text
stringlengths 2
97.5k
| meta
dict |
|---|---|
@namespace MatBlazor
@typeparam TValue
@inherits BaseMatRadioGroupInternal<TValue>
<CascadingValue Value="@this">
@if (Items != null)
{
foreach (var item in Items)
{
if (ItemTemplate != null)
{
@ItemTemplate(item)
}
else
{
<MatRadioButton T="T" Value="@item">@item</MatRadioButton>
}
}
}
@ChildContent
</CascadingValue>
|
{
"pile_set_name": "Github"
}
|
package session
import (
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/corehandlers"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/csm"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
)
// A Session provides a central location to create service clients from and
// store configurations and request handlers for those services.
//
// Sessions are safe to create service clients concurrently, but it is not safe
// to mutate the Session concurrently.
//
// The Session satisfies the service client's client.ConfigProvider.
type Session struct {
Config *aws.Config
Handlers request.Handlers
}
// New creates a new instance of the handlers merging in the provided configs
// on top of the SDK's default configurations. Once the Session is created it
// can be mutated to modify the Config or Handlers. The Session is safe to be
// read concurrently, but it should not be written to concurrently.
//
// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New
// method could now encounter an error when loading the configuration. When
// The environment variable is set, and an error occurs, New will return a
// session that will fail all requests reporting the error that occurred while
// loading the session. Use NewSession to get the error when creating the
// session.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded, in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file.
//
// Deprecated: Use NewSession functions to create sessions instead. NewSession
// has the same functionality as New except an error can be returned when the
// func is called instead of waiting to receive an error until a request is made.
func New(cfgs ...*aws.Config) *Session {
// load initial config from environment
envCfg := loadEnvConfig()
if envCfg.EnableSharedConfig {
var cfg aws.Config
cfg.MergeIn(cfgs...)
s, err := NewSessionWithOptions(Options{
Config: cfg,
SharedConfigState: SharedConfigEnable,
})
if err != nil {
// Old session.New expected all errors to be discovered when
// a request is made, and would report the errors then. This
// needs to be replicated if an error occurs while creating
// the session.
msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " +
"Use session.NewSession to handle errors occurring during session creation."
// Session creation failed, need to report the error and prevent
// any requests from succeeding.
s = &Session{Config: defaults.Config()}
s.Config.MergeIn(cfgs...)
s.Config.Logger.Log("ERROR:", msg, "Error:", err)
s.Handlers.Validate.PushBack(func(r *request.Request) {
r.Error = err
})
}
return s
}
s := deprecatedNewSession(cfgs...)
if envCfg.CSMEnabled {
enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger)
}
return s
}
// NewSession returns a new Session created from SDK defaults, config files,
// environment, and user provided config files. Once the Session is created
// it can be mutated to modify the Config or Handlers. The Session is safe to
// be read concurrently, but it should not be written to concurrently.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file. Enabling the Shared Config will also allow the Session
// to be built with retrieving credentials with AssumeRole set in the config.
//
// See the NewSessionWithOptions func for information on how to override or
// control through code how the Session will be created. Such as specifying the
// config profile, and controlling if shared config is enabled or not.
func NewSession(cfgs ...*aws.Config) (*Session, error) {
opts := Options{}
opts.Config.MergeIn(cfgs...)
return NewSessionWithOptions(opts)
}
// SharedConfigState provides the ability to optionally override the state
// of the session's creation based on the shared config being enabled or
// disabled.
type SharedConfigState int
const (
// SharedConfigStateFromEnv does not override any state of the
// AWS_SDK_LOAD_CONFIG env var. It is the default value of the
// SharedConfigState type.
SharedConfigStateFromEnv SharedConfigState = iota
// SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value
// and disables the shared config functionality.
SharedConfigDisable
// SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value
// and enables the shared config functionality.
SharedConfigEnable
)
// Options provides the means to control how a Session is created and what
// configuration values will be loaded.
//
type Options struct {
// Provides config values for the SDK to use when creating service clients
// and making API requests to services. Any value set in with this field
// will override the associated value provided by the SDK defaults,
// environment or config files where relevant.
//
// If not set, configuration values from from SDK defaults, environment,
// config will be used.
Config aws.Config
// Overrides the config profile the Session should be created from. If not
// set the value of the environment variable will be loaded (AWS_PROFILE,
// or AWS_DEFAULT_PROFILE if the Shared Config is enabled).
//
// If not set and environment variables are not set the "default"
// (DefaultSharedConfigProfile) will be used as the profile to load the
// session config from.
Profile string
// Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG
// environment variable. By default a Session will be created using the
// value provided by the AWS_SDK_LOAD_CONFIG environment variable.
//
// Setting this value to SharedConfigEnable or SharedConfigDisable
// will allow you to override the AWS_SDK_LOAD_CONFIG environment variable
// and enable or disable the shared config functionality.
SharedConfigState SharedConfigState
// Ordered list of files the session will load configuration from.
// It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE.
SharedConfigFiles []string
// When the SDK's shared config is configured to assume a role with MFA
// this option is required in order to provide the mechanism that will
// retrieve the MFA token. There is no default value for this field. If
// it is not set an error will be returned when creating the session.
//
// This token provider will be called when ever the assumed role's
// credentials need to be refreshed. Within the context of service clients
// all sharing the same session the SDK will ensure calls to the token
// provider are atomic. When sharing a token provider across multiple
// sessions additional synchronization logic is needed to ensure the
// token providers do not introduce race conditions. It is recommend to
// share the session where possible.
//
// stscreds.StdinTokenProvider is a basic implementation that will prompt
// from stdin for the MFA token code.
//
// This field is only used if the shared configuration is enabled, and
// the config enables assume role wit MFA via the mfa_serial field.
AssumeRoleTokenProvider func() (string, error)
// Reader for a custom Credentials Authority (CA) bundle in PEM format that
// the SDK will use instead of the default system's root CA bundle. Use this
// only if you want to replace the CA bundle the SDK uses for TLS requests.
//
// Enabling this option will attempt to merge the Transport into the SDK's HTTP
// client. If the client's Transport is not a http.Transport an error will be
// returned. If the Transport's TLS config is set this option will cause the SDK
// to overwrite the Transport's TLS config's RootCAs value. If the CA
// bundle reader contains multiple certificates all of them will be loaded.
//
// The Session option CustomCABundle is also available when creating sessions
// to also enable this feature. CustomCABundle session option field has priority
// over the AWS_CA_BUNDLE environment variable, and will be used if both are set.
CustomCABundle io.Reader
}
// NewSessionWithOptions returns a new Session created from SDK defaults, config files,
// environment, and user provided config files. This func uses the Options
// values to configure how the Session is created.
//
// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value
// the shared config file (~/.aws/config) will also be loaded in addition to
// the shared credentials file (~/.aws/credentials). Values set in both the
// shared config, and shared credentials will be taken from the shared
// credentials file. Enabling the Shared Config will also allow the Session
// to be built with retrieving credentials with AssumeRole set in the config.
//
// // Equivalent to session.New
// sess := session.Must(session.NewSessionWithOptions(session.Options{}))
//
// // Specify profile to load for the session's config
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// Profile: "profile_name",
// }))
//
// // Specify profile for config and region for requests
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// Config: aws.Config{Region: aws.String("us-east-1")},
// Profile: "profile_name",
// }))
//
// // Force enable Shared Config support
// sess := session.Must(session.NewSessionWithOptions(session.Options{
// SharedConfigState: session.SharedConfigEnable,
// }))
func NewSessionWithOptions(opts Options) (*Session, error) {
var envCfg envConfig
if opts.SharedConfigState == SharedConfigEnable {
envCfg = loadSharedEnvConfig()
} else {
envCfg = loadEnvConfig()
}
if len(opts.Profile) > 0 {
envCfg.Profile = opts.Profile
}
switch opts.SharedConfigState {
case SharedConfigDisable:
envCfg.EnableSharedConfig = false
case SharedConfigEnable:
envCfg.EnableSharedConfig = true
}
// Only use AWS_CA_BUNDLE if session option is not provided.
if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil {
f, err := os.Open(envCfg.CustomCABundle)
if err != nil {
return nil, awserr.New("LoadCustomCABundleError",
"failed to open custom CA bundle PEM file", err)
}
defer f.Close()
opts.CustomCABundle = f
}
return newSession(opts, envCfg, &opts.Config)
}
// Must is a helper function to ensure the Session is valid and there was no
// error when calling a NewSession function.
//
// This helper is intended to be used in variable initialization to load the
// Session and configuration at startup. Such as:
//
// var sess = session.Must(session.NewSession())
func Must(sess *Session, err error) *Session {
if err != nil {
panic(err)
}
return sess
}
func deprecatedNewSession(cfgs ...*aws.Config) *Session {
cfg := defaults.Config()
handlers := defaults.Handlers()
// Apply the passed in configs so the configuration can be applied to the
// default credential chain
cfg.MergeIn(cfgs...)
if cfg.EndpointResolver == nil {
// An endpoint resolver is required for a session to be able to provide
// endpoints for service client configurations.
cfg.EndpointResolver = endpoints.DefaultResolver()
}
cfg.Credentials = defaults.CredChain(cfg, handlers)
// Reapply any passed in configs to override credentials if set
cfg.MergeIn(cfgs...)
s := &Session{
Config: cfg,
Handlers: handlers,
}
initHandlers(s)
return s
}
func enableCSM(handlers *request.Handlers, clientID string, port string, logger aws.Logger) {
logger.Log("Enabling CSM")
if len(port) == 0 {
port = csm.DefaultPort
}
r, err := csm.Start(clientID, "127.0.0.1:"+port)
if err != nil {
return
}
r.InjectHandlers(handlers)
}
func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) {
cfg := defaults.Config()
handlers := defaults.Handlers()
// Get a merged version of the user provided config to determine if
// credentials were.
userCfg := &aws.Config{}
userCfg.MergeIn(cfgs...)
// Ordered config files will be loaded in with later files overwriting
// previous config file values.
var cfgFiles []string
if opts.SharedConfigFiles != nil {
cfgFiles = opts.SharedConfigFiles
} else {
cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile}
if !envCfg.EnableSharedConfig {
// The shared config file (~/.aws/config) is only loaded if instructed
// to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG).
cfgFiles = cfgFiles[1:]
}
}
// Load additional config from file(s)
sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles)
if err != nil {
return nil, err
}
if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil {
return nil, err
}
s := &Session{
Config: cfg,
Handlers: handlers,
}
initHandlers(s)
if envCfg.CSMEnabled {
enableCSM(&s.Handlers, envCfg.CSMClientID, envCfg.CSMPort, s.Config.Logger)
}
// Setup HTTP client with custom cert bundle if enabled
if opts.CustomCABundle != nil {
if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil {
return nil, err
}
}
return s, nil
}
func loadCustomCABundle(s *Session, bundle io.Reader) error {
var t *http.Transport
switch v := s.Config.HTTPClient.Transport.(type) {
case *http.Transport:
t = v
default:
if s.Config.HTTPClient.Transport != nil {
return awserr.New("LoadCustomCABundleError",
"unable to load custom CA bundle, HTTPClient's transport unsupported type", nil)
}
}
if t == nil {
t = &http.Transport{}
}
p, err := loadCertPool(bundle)
if err != nil {
return err
}
if t.TLSClientConfig == nil {
t.TLSClientConfig = &tls.Config{}
}
t.TLSClientConfig.RootCAs = p
s.Config.HTTPClient.Transport = t
return nil
}
func loadCertPool(r io.Reader) (*x509.CertPool, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, awserr.New("LoadCustomCABundleError",
"failed to read custom CA bundle PEM file", err)
}
p := x509.NewCertPool()
if !p.AppendCertsFromPEM(b) {
return nil, awserr.New("LoadCustomCABundleError",
"failed to load custom CA bundle PEM file", err)
}
return p, nil
}
func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error {
// Merge in user provided configuration
cfg.MergeIn(userCfg)
// Region if not already set by user
if len(aws.StringValue(cfg.Region)) == 0 {
if len(envCfg.Region) > 0 {
cfg.WithRegion(envCfg.Region)
} else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 {
cfg.WithRegion(sharedCfg.Region)
}
}
// Configure credentials if not already set
if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil {
if len(envCfg.Creds.AccessKeyID) > 0 {
cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
envCfg.Creds,
)
} else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil {
cfgCp := *cfg
cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds(
sharedCfg.AssumeRoleSource.Creds,
)
if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil {
// AssumeRole Token provider is required if doing Assume Role
// with MFA.
return AssumeRoleTokenProviderNotSetError{}
}
cfg.Credentials = stscreds.NewCredentials(
&Session{
Config: &cfgCp,
Handlers: handlers.Copy(),
},
sharedCfg.AssumeRole.RoleARN,
func(opt *stscreds.AssumeRoleProvider) {
opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName
// Assume role with external ID
if len(sharedCfg.AssumeRole.ExternalID) > 0 {
opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID)
}
// Assume role with MFA
if len(sharedCfg.AssumeRole.MFASerial) > 0 {
opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial)
opt.TokenProvider = sessOpts.AssumeRoleTokenProvider
}
},
)
} else if len(sharedCfg.Creds.AccessKeyID) > 0 {
cfg.Credentials = credentials.NewStaticCredentialsFromCreds(
sharedCfg.Creds,
)
} else {
// Fallback to default credentials provider, include mock errors
// for the credential chain so user can identify why credentials
// failed to be retrieved.
cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{
VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors),
Providers: []credentials.Provider{
&credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)},
&credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)},
defaults.RemoteCredProvider(*cfg, handlers),
},
})
}
}
return nil
}
// AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the
// MFAToken option is not set when shared config is configured load assume a
// role with an MFA token.
type AssumeRoleTokenProviderNotSetError struct{}
// Code is the short id of the error.
func (e AssumeRoleTokenProviderNotSetError) Code() string {
return "AssumeRoleTokenProviderNotSetError"
}
// Message is the description of the error
func (e AssumeRoleTokenProviderNotSetError) Message() string {
return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.")
}
// OrigErr is the underlying error that caused the failure.
func (e AssumeRoleTokenProviderNotSetError) OrigErr() error {
return nil
}
// Error satisfies the error interface.
func (e AssumeRoleTokenProviderNotSetError) Error() string {
return awserr.SprintError(e.Code(), e.Message(), "", nil)
}
type credProviderError struct {
Err error
}
var emptyCreds = credentials.Value{}
func (c credProviderError) Retrieve() (credentials.Value, error) {
return credentials.Value{}, c.Err
}
func (c credProviderError) IsExpired() bool {
return true
}
func initHandlers(s *Session) {
// Add the Validate parameter handler if it is not disabled.
s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler)
if !aws.BoolValue(s.Config.DisableParamValidation) {
s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler)
}
}
// Copy creates and returns a copy of the current Session, coping the config
// and handlers. If any additional configs are provided they will be merged
// on top of the Session's copied config.
//
// // Create a copy of the current Session, configured for the us-west-2 region.
// sess.Copy(&aws.Config{Region: aws.String("us-west-2")})
func (s *Session) Copy(cfgs ...*aws.Config) *Session {
newSession := &Session{
Config: s.Config.Copy(cfgs...),
Handlers: s.Handlers.Copy(),
}
initHandlers(newSession)
return newSession
}
// ClientConfig satisfies the client.ConfigProvider interface and is used to
// configure the service client instances. Passing the Session to the service
// client's constructor (New) will use this method to configure the client.
func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config {
// Backwards compatibility, the error will be eaten if user calls ClientConfig
// directly. All SDK services will use ClientconfigWithError.
cfg, _ := s.clientConfigWithErr(serviceName, cfgs...)
return cfg
}
func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) {
s = s.Copy(cfgs...)
var resolved endpoints.ResolvedEndpoint
var err error
region := aws.StringValue(s.Config.Region)
if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 {
resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL))
resolved.SigningRegion = region
} else {
resolved, err = s.Config.EndpointResolver.EndpointFor(
serviceName, region,
func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL)
opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack)
// Support the condition where the service is modeled but its
// endpoint metadata is not available.
opt.ResolveUnknownService = true
},
)
}
return client.Config{
Config: s.Config,
Handlers: s.Handlers,
Endpoint: resolved.URL,
SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
}, err
}
// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception
// that the EndpointResolver will not be used to resolve the endpoint. The only
// endpoint set must come from the aws.Config.Endpoint field.
func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config {
s = s.Copy(cfgs...)
var resolved endpoints.ResolvedEndpoint
region := aws.StringValue(s.Config.Region)
if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 {
resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL))
resolved.SigningRegion = region
}
return client.Config{
Config: s.Config,
Handlers: s.Handlers,
Endpoint: resolved.URL,
SigningRegion: resolved.SigningRegion,
SigningNameDerived: resolved.SigningNameDerived,
SigningName: resolved.SigningName,
}
}
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* XHTML 1.1 Image Module provides basic image embedding.
* @note There is specialized code for removing empty images in
* HTMLPurifier_Strategy_RemoveForeignElements
*/
class HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule
{
/**
* @type string
*/
public $name = 'Image';
/**
* @param HTMLPurifier_Config $config
*/
public function setup($config)
{
$max = $config->get('HTML.MaxImgLength');
$img = $this->addElement(
'img',
'Inline',
'Empty',
'Common',
array(
'alt*' => 'Text',
// According to the spec, it's Length, but percents can
// be abused, so we allow only Pixels.
'height' => 'Pixels#' . $max,
'width' => 'Pixels#' . $max,
'longdesc' => 'URI',
'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded
)
);
if ($max === null || $config->get('HTML.Trusted')) {
$img->attr['height'] =
$img->attr['width'] = 'Length';
}
// kind of strange, but splitting things up would be inefficient
$img->attr_transform_pre[] =
$img->attr_transform_post[] =
new HTMLPurifier_AttrTransform_ImgRequired();
}
}
// vim: et sw=4 sts=4
|
{
"pile_set_name": "Github"
}
|
/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package responsewriters
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apiserver/pkg/audit"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/metrics"
"k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/apiserver/pkg/registry/rest"
"k8s.io/apiserver/pkg/util/flushwriter"
"k8s.io/apiserver/pkg/util/wsstream"
)
// WriteObject renders a returned runtime.Object to the response as a stream or an encoded object. If the object
// returned by the response implements rest.ResourceStreamer that interface will be used to render the
// response. The Accept header and current API version will be passed in, and the output will be copied
// directly to the response body. If content type is returned it is used, otherwise the content type will
// be "application/octet-stream". All other objects are sent to standard JSON serialization.
func WriteObject(ctx request.Context, statusCode int, gv schema.GroupVersion, s runtime.NegotiatedSerializer, object runtime.Object, w http.ResponseWriter, req *http.Request) {
stream, ok := object.(rest.ResourceStreamer)
if ok {
requestInfo, _ := request.RequestInfoFrom(ctx)
metrics.RecordLongRunning(req, requestInfo, func() {
StreamObject(ctx, statusCode, gv, s, stream, w, req)
})
return
}
WriteObjectNegotiated(ctx, s, gv, w, req, statusCode, object)
}
// StreamObject performs input stream negotiation from a ResourceStreamer and writes that to the response.
// If the client requests a websocket upgrade, negotiate for a websocket reader protocol (because many
// browser clients cannot easily handle binary streaming protocols).
func StreamObject(ctx request.Context, statusCode int, gv schema.GroupVersion, s runtime.NegotiatedSerializer, stream rest.ResourceStreamer, w http.ResponseWriter, req *http.Request) {
out, flush, contentType, err := stream.InputStream(gv.String(), req.Header.Get("Accept"))
if err != nil {
ErrorNegotiated(ctx, err, s, gv, w, req)
return
}
if out == nil {
// No output provided - return StatusNoContent
w.WriteHeader(http.StatusNoContent)
return
}
defer out.Close()
if wsstream.IsWebSocketRequest(req) {
r := wsstream.NewReader(out, true, wsstream.NewDefaultReaderProtocols())
if err := r.Copy(w, req); err != nil {
utilruntime.HandleError(fmt.Errorf("error encountered while streaming results via websocket: %v", err))
}
return
}
if len(contentType) == 0 {
contentType = "application/octet-stream"
}
w.Header().Set("Content-Type", contentType)
w.WriteHeader(statusCode)
writer := w.(io.Writer)
if flush {
writer = flushwriter.Wrap(w)
}
io.Copy(writer, out)
}
// SerializeObject renders an object in the content type negotiated by the client using the provided encoder.
// The context is optional and can be nil.
func SerializeObject(mediaType string, encoder runtime.Encoder, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {
w.Header().Set("Content-Type", mediaType)
w.WriteHeader(statusCode)
if err := encoder.Encode(object, w); err != nil {
errorJSONFatal(err, encoder, w)
}
}
// WriteObjectNegotiated renders an object in the content type negotiated by the client.
// The context is optional and can be nil.
func WriteObjectNegotiated(ctx request.Context, s runtime.NegotiatedSerializer, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request, statusCode int, object runtime.Object) {
serializer, err := negotiation.NegotiateOutputSerializer(req, s)
if err != nil {
// if original statusCode was not successful we need to return the original error
// we cannot hide it behind negotiation problems
if statusCode < http.StatusOK || statusCode >= http.StatusBadRequest {
WriteRawJSON(int(statusCode), object, w)
return
}
status := ErrorToAPIStatus(err)
WriteRawJSON(int(status.Code), status, w)
return
}
if ae := request.AuditEventFrom(ctx); ae != nil {
audit.LogResponseObject(ae, object, gv, s)
}
encoder := s.EncoderForVersion(serializer.Serializer, gv)
SerializeObject(serializer.MediaType, encoder, w, req, statusCode, object)
}
// ErrorNegotiated renders an error to the response. Returns the HTTP status code of the error.
// The context is optional and may be nil.
func ErrorNegotiated(ctx request.Context, err error, s runtime.NegotiatedSerializer, gv schema.GroupVersion, w http.ResponseWriter, req *http.Request) int {
status := ErrorToAPIStatus(err)
code := int(status.Code)
// when writing an error, check to see if the status indicates a retry after period
if status.Details != nil && status.Details.RetryAfterSeconds > 0 {
delay := strconv.Itoa(int(status.Details.RetryAfterSeconds))
w.Header().Set("Retry-After", delay)
}
if code == http.StatusNoContent {
w.WriteHeader(code)
return code
}
WriteObjectNegotiated(ctx, s, gv, w, req, code, status)
return code
}
// errorJSONFatal renders an error to the response, and if codec fails will render plaintext.
// Returns the HTTP status code of the error.
func errorJSONFatal(err error, codec runtime.Encoder, w http.ResponseWriter) int {
utilruntime.HandleError(fmt.Errorf("apiserver was unable to write a JSON response: %v", err))
status := ErrorToAPIStatus(err)
code := int(status.Code)
output, err := runtime.Encode(codec, status)
if err != nil {
w.WriteHeader(code)
fmt.Fprintf(w, "%s: %s", status.Reason, status.Message)
return code
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(output)
return code
}
// WriteRawJSON writes a non-API object in JSON.
func WriteRawJSON(statusCode int, object interface{}, w http.ResponseWriter) {
output, err := json.MarshalIndent(object, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
w.Write(output)
}
|
{
"pile_set_name": "Github"
}
|
import * as React from 'react';
import expect from 'expect';
import { render, cleanup, getNodeText } from '@testing-library/react';
import TextField from './TextField';
describe('<TextField />', () => {
afterEach(cleanup);
it('should display record specific value as plain text', () => {
const record = {
id: 123,
title: "I'm sorry, Dave. I'm afraid I can't do that.",
};
const { queryByText } = render(
<TextField record={record} source="title" />
);
expect(
queryByText("I'm sorry, Dave. I'm afraid I can't do that.")
).not.toBeNull();
});
it.each([null, undefined])(
'should display emptyText prop if provided for %s value',
value => {
const record = { id: 123, title: value };
render(
<TextField
emptyText="Sorry, there's nothing here"
record={record}
source="title"
/>
);
expect("Sorry, there's nothing here").not.toBeNull();
}
);
it.each([null, undefined])(
'should display nothing for %s value without emptyText prop',
value => {
const record = { id: 123, title: value };
const { container } = render(
<TextField record={record} source="title" />
);
expect(getNodeText(container)).toStrictEqual('');
}
);
it('should handle deep fields', () => {
const record = {
id: 123,
foo: { title: "I'm sorry, Dave. I'm afraid I can't do that." },
};
const { queryByText } = render(
<TextField record={record} source="foo.title" />
);
expect(
queryByText("I'm sorry, Dave. I'm afraid I can't do that.")
).not.toBeNull();
});
it('should render the emptyText when value is null', () => {
const record = { id: 123, title: null };
const { queryByText } = render(
<TextField record={record} source="title" emptyText="NA" />
);
expect(queryByText('NA')).not.toBeNull();
});
});
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<resourceExtensions />
<wildcardResourcePatterns>
<entry name="!?*.java" />
<entry name="!?*.form" />
<entry name="!?*.class" />
<entry name="!?*.groovy" />
<entry name="!?*.scala" />
<entry name="!?*.flex" />
<entry name="!?*.kt" />
<entry name="!?*.clj" />
<entry name="!?*.aj" />
</wildcardResourcePatterns>
<annotationProcessing>
<profile default="true" name="Default" enabled="false">
<processorPath useClasspath="true" />
</profile>
</annotationProcessing>
</component>
</project>
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="PGInstrument|Win32">
<Configuration>PGInstrument</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="PGInstrument|x64">
<Configuration>PGInstrument</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="PGUpdate|Win32">
<Configuration>PGUpdate</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="PGUpdate|x64">
<Configuration>PGUpdate</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{17E1E049-C309-4D79-843F-AE483C264AEA}</ProjectGuid>
<RootNamespace>_elementtree</RootNamespace>
<Keyword>Win32Proj</Keyword>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
<WholeProgramOptimization>true</WholeProgramOptimization>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<CharacterSet>NotSet</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
<Import Project="pgupdate.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
<Import Project="pginstrument.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd_d.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
<Import Project="x64.props" />
<Import Project="pgupdate.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
<Import Project="x64.props" />
<Import Project="pginstrument.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd.props" />
<Import Project="x64.props" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
<Import Project="pyd_d.props" />
<Import Project="x64.props" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup>
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='PGInstrument|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|Win32'">
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='PGUpdate|x64'">
<Midl>
<TargetEnvironment>X64</TargetEnvironment>
</Midl>
<ClCompile>
<AdditionalIncludeDirectories>..\Modules\expat;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>XML_NS;XML_DTD;BYTEORDER=1234;XML_CONTEXT_BYTES=1024;USE_PYEXPAT_CAPI;XML_STATIC;HAVE_MEMMOVE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<BaseAddress>0x1D100000</BaseAddress>
<TargetMachine>MachineX64</TargetMachine>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="..\Modules\expat\ascii.h" />
<ClInclude Include="..\Modules\expat\asciitab.h" />
<ClInclude Include="..\Modules\expat\expat.h" />
<ClInclude Include="..\Modules\expat\expat_config.h" />
<ClInclude Include="..\Modules\expat\expat_external.h" />
<ClInclude Include="..\Modules\expat\iasciitab.h" />
<ClInclude Include="..\Modules\expat\internal.h" />
<ClInclude Include="..\Modules\expat\latin1tab.h" />
<ClInclude Include="..\Modules\expat\macconfig.h" />
<ClInclude Include="..\Modules\expat\nametab.h" />
<ClInclude Include="..\Modules\expat\pyexpatns.h" />
<ClInclude Include="..\Modules\expat\utf8tab.h" />
<ClInclude Include="..\Modules\expat\winconfig.h" />
<ClInclude Include="..\Modules\expat\xmlrole.h" />
<ClInclude Include="..\Modules\expat\xmltok.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\Modules\_elementtree.c" />
<ClCompile Include="..\Modules\expat\xmlparse.c" />
<ClCompile Include="..\Modules\expat\xmlrole.c" />
<ClCompile Include="..\Modules\expat\xmltok.c" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="pythoncore.vcxproj">
<Project>{cf7ac3d1-e2df-41d2-bea6-1e2556cdea26}</Project>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
|
{
"pile_set_name": "Github"
}
|
# $FreeBSD$
PORTNAME= File-FcntlLock
PORTVERSION= 0.22
CATEGORIES= devel perl5
MASTER_SITES= CPAN
PKGNAMEPREFIX= p5-
MAINTAINER= perl@FreeBSD.org
COMMENT= Perl5 module for file locking with fcntl
USES= perl5
USE_PERL5= configure
.include <bsd.port.mk>
|
{
"pile_set_name": "Github"
}
|
require('../../modules/core.object.make');
module.exports = require('../../modules/_core').Object.make;
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2007-2017 Xplenty, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cascading.flow.planner;
import cascading.flow.FlowElement;
import cascading.flow.FlowException;
import cascading.pipe.Pipe;
import cascading.tap.Tap;
import cascading.util.TraceUtil;
/**
* Class ElementGraphException is thrown during rendering of a pipe assembly to
* the Cascading internal "graph" representation.
*/
public class ElementGraphException extends FlowException
{
/** Field flowElement */
private FlowElement flowElement;
/** Constructor ElementGraphException creates a new ElementGraphException instance. */
public ElementGraphException()
{
}
public ElementGraphException( Pipe pipe, String message )
{
this( (FlowElement) pipe, TraceUtil.formatTrace( pipe, message ) );
}
public ElementGraphException( Tap tap, String message )
{
this( (FlowElement) tap, TraceUtil.formatTrace( tap, message ) );
}
/**
* Constructor ElementGraphException creates a new ElementGraphException instance.
*
* @param flowElement of type FlowElement
* @param message of type String
*/
public ElementGraphException( FlowElement flowElement, String message )
{
super( message );
this.flowElement = flowElement;
}
/**
* Constructor ElementGraphException creates a new ElementGraphException instance.
*
* @param flowElement of type FlowElement
* @param message of type String
* @param throwable of type Throwable
*/
public ElementGraphException( FlowElement flowElement, String message, Throwable throwable )
{
super( message, throwable );
this.flowElement = flowElement;
}
/**
* Constructor ElementGraphException creates a new ElementGraphException instance.
*
* @param string of type String
*/
public ElementGraphException( String string )
{
super( string );
}
/**
* Constructor ElementGraphException creates a new ElementGraphException instance.
*
* @param string of type String
* @param throwable of type Throwable
*/
public ElementGraphException( String string, Throwable throwable )
{
super( string, throwable );
}
/**
* Constructor ElementGraphException creates a new ElementGraphException instance.
*
* @param throwable of type Throwable
*/
public ElementGraphException( Throwable throwable )
{
super( throwable );
}
/**
* Method getFlowElement returns the flowElement of this ElementGraphException object.
*
* @return the flowElement (type FlowElement) of this ElementGraphException object.
*/
public FlowElement getFlowElement()
{
return flowElement;
}
Pipe getPipe()
{
if( flowElement instanceof Pipe )
return (Pipe) flowElement;
return null;
}
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<html>
<!--
https://bugzilla.mozilla.org/show_bug.cgi?id=606729
-->
<head>
<title>Test for Bug 606729</title>
<script type="text/javascript" src="/MochiKit/MochiKit.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=606729">Mozilla Bug 606729</a>
<p id="display"></p>
<div id="content" style="display: none">
</div>
<pre id="test">
<script>
SimpleTest.waitForExplicitFinish();
var events = 0;
var expectedEvents = 2;
function eventFired() {
++events;
if (events == expectedEvents) {
SimpleTest.finish();
}
}
</script>
<script
src="data:"
onerror="ok(true, 'Script with src=data: should fire onerror.');
eventFired();"
onload="ok(false, 'Script with src=data: should not fire onload.');
eventFired();"
>
ok(false, "Script with src=data: should not run textContent.");
</script>
<script
src="bogus:"
onerror="ok(true, 'Script with src=bogus: should fire onerror.');
eventFired();"
onload="ok(false, 'Script with src=bogus: should not fire onload.');
eventFired();"
>
ok(false, "Script with src=bogus: should not run textContent.");
</script>
</pre>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
# Comment
DELETE
# Comment
WHERE
# Comment
{ GRAPH <G> { <s> <p> 123 ; <q> 4567.0 . } }
|
{
"pile_set_name": "Github"
}
|
common/info.cpp
common/config.cpp
common/convert.cpp
common/errors.cpp
common/posib_err.cpp
lib/new_fmode.cpp
prog/aspell.cpp
prog/check_funs.cpp
modules/speller/default/language.cpp
modules/speller/default/affix.cpp
modules/speller/default/readonly_ws.cpp
modules/speller/default/multi_ws.cpp
modules/speller/default/suggest.cpp
modules/speller/default/data.cpp
modules/speller/default/speller_impl.cpp
modules/filter/tex.cpp
gen/filter.pot
|
{
"pile_set_name": "Github"
}
|
<?xml version='1.0' encoding='utf-8'?>
<section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code">
<num>38-828.02</num>
<heading>Applicability.</heading>
<para>
<num>(a)</num>
<text><cite path="38|8A|II">Subchapter II of this chapter</cite> shall apply as of August 1, 2010.</text>
</para>
<para>
<num>(b)</num>
<text>Repealed.</text>
</para>
<annotations>
<annotation doc="D.C. Law 18-209" type="History" path="§802">July 27, 2010, D.C. Law 18-209, § 802, 57 DCR 4779</annotation>
<annotation doc="D.C. Law 18-223" type="History">Sept. 24, 2010, D.C. Law 18-223, § 7005, 57 DCR 6242</annotation>
<annotation type="Emergency Legislation">For temporary (90 day) repeal of section 802(b) of <cite doc="D.C. Law 18-209">D.C. Law 18-209</cite>, see § 7005 of Fiscal Year 2011 Budget Support Emergency Act of 2010 (D.C. Act 18-463, July 2, 2010, 57 DCR 6542).</annotation>
<annotation type="Effect of Amendments"><cite doc="D.C. Law 18-223">D.C. Law 18-223</cite> repealed subsec. (b), which had read as follows: “(b) This chapter shall apply upon the inclusion of its fiscal effect in an approved budget and financial plan.”</annotation>
</annotations>
</section>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Test for PhpMyAdmin\Gis\GisGeometry
*/
declare(strict_types=1);
namespace PhpMyAdmin\Tests\Gis;
use PhpMyAdmin\Gis\GisGeometryCollection;
use PhpMyAdmin\Tests\AbstractTestCase;
use TCPDF;
use function function_exists;
use function imagecreatetruecolor;
use function imagesx;
use function imagesy;
use function preg_match;
/**
* Tests for PhpMyAdmin\Gis\GisGeometryCollection class
*/
class GisGeometryCollectionTest extends AbstractTestCase
{
/** @var GisGeometryCollection */
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*
* @access protected
*/
protected function setUp(): void
{
parent::setUp();
$this->object = GisGeometryCollection::singleton();
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*
* @access protected
*/
protected function tearDown(): void
{
parent::tearDown();
unset($this->object);
}
/**
* Test for scaleRow
*
* @param string $spatial string to parse
* @param array $output expected parsed output
*
* @dataProvider providerForScaleRow
*/
public function testScaleRow(string $spatial, array $output): void
{
$this->assertEquals($output, $this->object->scaleRow($spatial));
}
/**
* Data provider for testScaleRow() test case
*
* @return array test data for testScaleRow() test case
*/
public function providerForScaleRow(): array
{
return [
[
'GEOMETRYCOLLECTION(POLYGON((35 10,10 20,15 40,45 45,35 10),'
. '(20 30,35 32,30 20,20 30)))',
[
'maxX' => 45.0,
'minX' => 10.0,
'maxY' => 45.0,
'minY' => 10.0,
],
],
];
}
/**
* Test for generateWkt
*
* @param array $gis_data array of GIS data
* @param int $index index in $gis_data
* @param string|null $empty empty parameter
* @param string $output expected output
*
* @dataProvider providerForGenerateWkt
*/
public function testGenerateWkt(array $gis_data, int $index, ?string $empty, string $output): void
{
$this->assertEquals(
$output,
$this->object->generateWkt($gis_data, $index, $empty)
);
}
/**
* Data provider for testGenerateWkt() test case
*
* @return array test data for testGenerateWkt() test case
*/
public function providerForGenerateWkt(): array
{
$temp1 = [
0 => [
'gis_type' => 'LINESTRING',
'LINESTRING' => [
'no_of_points' => 2,
0 => [
'x' => 5.02,
'y' => 8.45,
],
1 => [
'x' => 6.14,
'y' => 0.15,
],
],
],
];
return [
[
$temp1,
0,
null,
'GEOMETRYCOLLECTION(LINESTRING(5.02 8.45,6.14 0.15))',
],
];
}
/**
* Test for generateParams
*
* @param string $value string to parse
* @param array $output expected parsed output
*
* @dataProvider providerForGenerateParams
*/
public function testGenerateParams(string $value, array $output): void
{
$this->assertEquals($output, $this->object->generateParams($value));
}
/**
* Data provider for testGenerateParams() test case
*
* @return array test data for testGenerateParams() test case
*/
public function providerForGenerateParams(): array
{
return [
[
'GEOMETRYCOLLECTION(LINESTRING(5.02 8.45,6.14 0.15))',
[
'srid' => 0,
'GEOMETRYCOLLECTION' => ['geom_count' => 1],
'0' => [
'gis_type' => 'LINESTRING',
'LINESTRING' => [
'no_of_points' => 2,
'0' => [
'x' => 5.02,
'y' => 8.45,
],
'1' => [
'x' => 6.14,
'y' => 0.15,
],
],
],
],
],
];
}
/**
* Test for prepareRowAsPng
*
* @param string $spatial string to parse
* @param string $label field label
* @param string $line_color line color
* @param array $scale_data scaling parameters
* @param resource $image initial image
*
* @dataProvider providerForPrepareRowAsPng
*/
public function testPrepareRowAsPng(
string $spatial,
string $label,
string $line_color,
array $scale_data,
$image
): void {
$return = $this->object->prepareRowAsPng(
$spatial,
$label,
$line_color,
$scale_data,
$image
);
$this->assertEquals(120, imagesx($return));
$this->assertEquals(150, imagesy($return));
}
/**
* Data provider for testPrepareRowAsPng() test case
*
* @return array test data for testPrepareRowAsPng() test case
*/
public function providerForPrepareRowAsPng(): array
{
if (! function_exists('imagecreatetruecolor')) {
$this->markTestSkipped('GD extension missing!');
}
return [
[
'GEOMETRYCOLLECTION(POLYGON((35 10,10 20,15 40,45 45,35 10),'
. '(20 30,35 32,30 20,20 30)))',
'image',
'#B02EE0',
[
'x' => 12,
'y' => 69,
'scale' => 2,
'height' => 150,
],
imagecreatetruecolor(120, 150),
],
];
}
/**
* Test for prepareRowAsPdf
*
* @param string $spatial string to parse
* @param string $label field label
* @param string $line_color line color
* @param array $scale_data scaling parameters
* @param TCPDF $pdf expected output
*
* @dataProvider providerForPrepareRowAsPdf
*/
public function testPrepareRowAsPdf(
string $spatial,
string $label,
string $line_color,
array $scale_data,
TCPDF $pdf
): void {
$return = $this->object->prepareRowAsPdf(
$spatial,
$label,
$line_color,
$scale_data,
$pdf
);
$this->assertInstanceOf('TCPDF', $return);
}
/**
* Data provider for testPrepareRowAsPdf() test case
*
* @return array test data for testPrepareRowAsPdf() test case
*/
public function providerForPrepareRowAsPdf(): array
{
return [
[
'GEOMETRYCOLLECTION(POLYGON((35 10,10 20,15 40,45 45,35 10),'
. '(20 30,35 32,30 20,20 30)))',
'pdf',
'#B02EE0',
[
'x' => 12,
'y' => 69,
'scale' => 2,
'height' => 150,
],
new TCPDF(),
],
];
}
/**
* Test for prepareRowAsSvg
*
* @param string $spatial string to parse
* @param string $label field label
* @param string $lineColor line color
* @param array $scaleData scaling parameters
* @param string $output expected output
*
* @dataProvider providerForPrepareRowAsSvg
*/
public function testPrepareRowAsSvg(
string $spatial,
string $label,
string $lineColor,
array $scaleData,
string $output
): void {
$string = $this->object->prepareRowAsSvg(
$spatial,
$label,
$lineColor,
$scaleData
);
$this->assertEquals(1, preg_match($output, $string));
// assertMatchesRegularExpression added in 9.1
$this->assertRegExp(
$output,
$this->object->prepareRowAsSvg(
$spatial,
$label,
$lineColor,
$scaleData
)
);
}
/**
* Data provider for testPrepareRowAsSvg() test case
*
* @return array test data for testPrepareRowAsSvg() test case
*/
public function providerForPrepareRowAsSvg(): array
{
return [
[
'GEOMETRYCOLLECTION(POLYGON((35 10,10 20,15 40,45 45,35 10),'
. '(20 30,35 32,30 20,20 30)))',
'svg',
'#B02EE0',
[
'x' => 12,
'y' => 69,
'scale' => 2,
'height' => 150,
],
'/^(<path d=" M 46, 268 L -4, 248 L 6, 208 L 66, 198 Z M 16,'
. ' 228 L 46, 224 L 36, 248 Z " name="svg" id="svg)(\d+)'
. '(" class="polygon vector" stroke="black" stroke-width="0.5"'
. ' fill="#B02EE0" fill-rule="evenodd" fill-opacity="0.8"\/>)$/',
],
];
}
/**
* Test for prepareRowAsOl
*
* @param string $spatial string to parse
* @param int $srid SRID
* @param string $label field label
* @param array $line_color line color
* @param array $scale_data scaling parameters
* @param string $output expected output
*
* @dataProvider providerForPrepareRowAsOl
*/
public function testPrepareRowAsOl(
string $spatial,
int $srid,
string $label,
array $line_color,
array $scale_data,
string $output
): void {
$this->assertEquals(
$output,
$this->object->prepareRowAsOl(
$spatial,
$srid,
$label,
$line_color,
$scale_data
)
);
}
/**
* Data provider for testPrepareRowAsOl() test case
*
* @return array test data for testPrepareRowAsOl() test case
*/
public function providerForPrepareRowAsOl(): array
{
return [
[
'GEOMETRYCOLLECTION(POLYGON((35 10,10 20,15 40,45 45,35 10),'
. '(20 30,35 32,30 20,20 30)))',
4326,
'Ol',
[176, 46, 224],
[
'minX' => '0',
'minY' => '0',
'maxX' => '1',
'maxY' => '1',
],
'var style = new ol.style.Style({fill: new ol.style.Fill({"c'
. 'olor":[176,46,224,0.8]}),stroke: new ol.style.Stroke({"co'
. 'lor":[0,0,0],"width":0.5}),text: new ol.style.Text({"text'
. '":"Ol"})});var minLoc = [0, 0];var maxLoc = [1, 1];var ex'
. 't = ol.extent.boundingExtent([minLoc, maxLoc]);ext = ol.p'
. 'roj.transformExtent(ext, ol.proj.get("EPSG:4326"), ol.pro'
. 'j.get(\'EPSG:3857\'));map.getView().fit(ext, map.getSize('
. '));var arr = [];var lineArr = [];var line = new ol.geom.L'
. 'inearRing(new Array((new ol.geom.Point([35,10]).transform'
. '(ol.proj.get("EPSG:4326"), ol.proj.get(\'EPSG:3857\'))).g'
. 'etCoordinates(), (new ol.geom.Point([10,20]).transform(ol'
. '.proj.get("EPSG:4326"), ol.proj.get(\'EPSG:3857\'))).getC'
. 'oordinates(), (new ol.geom.Point([15,40]).transform(ol.pr'
. 'oj.get("EPSG:4326"), ol.proj.get(\'EPSG:3857\'))).getCoor'
. 'dinates(), (new ol.geom.Point([45,45]).transform(ol.proj.'
. 'get("EPSG:4326"), ol.proj.get(\'EPSG:3857\'))).getCoordin'
. 'ates(), (new ol.geom.Point([35,10]).transform(ol.proj.get'
. '("EPSG:4326"), ol.proj.get(\'EPSG:3857\'))).getCoordinate'
. 's()));var coord = line.getCoordinates();for (var i = 0; i < coord.length; '
. 'index++) lineArr.push(coord[i]);arr.push(lineArr);var lineArr = '
. '[];var line = new ol.geom.LinearRing(new Array((new ol.ge'
. 'om.Point([20,30]).transform(ol.proj.get("EPSG:4326"), ol.'
. 'proj.get(\'EPSG:3857\'))).getCoordinates(), (new ol.geom.'
. 'Point([35,32]).transform(ol.proj.get("EPSG:4326"), ol.pro'
. 'j.get(\'EPSG:3857\'))).getCoordinates(), (new ol.geom.Poi'
. 'nt([30,20]).transform(ol.proj.get("EPSG:4326"), ol.proj.g'
. 'et(\'EPSG:3857\'))).getCoordinates(), (new ol.geom.Point('
. '[20,30]).transform(ol.proj.get("EPSG:4326"), ol.proj.get('
. '\'EPSG:3857\'))).getCoordinates()));var coord = line.getC'
. 'oordinates();for (var i = 0; i < coord.length; index++) lineArr.push(coord[i]);ar'
. 'r.push(lineArr);var polygon = new ol.geom.Polygon(arr);va'
. 'r feature = new ol.Feature({geometry: polygon});feature.s'
. 'etStyle(style);vectorLayer.addFeature(feature);',
],
];
}
}
|
{
"pile_set_name": "Github"
}
|
# Copyright 2012 - 2015 Aaron Jensen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
function Assert-FileDoesNotExist
{
<#
.SYNOPSIS
Asserts that a file does not exist.
.DESCRIPTION
Uses PowerShell's `Test-Path` cmdlet to check if a file doesn't exist.
.EXAMPLE
Assert-FileDoesNotExist 'C:\foobar.txt'
Demonstrates how to assert that a does not exist.
.EXAMPLE
Assert-FileDoesNotExist 'C:\foobar.txt' 'foobar.txt not removed.'
Demonstrates how to describe why an assertion might fail.
#>
[CmdletBinding()]
param(
[Parameter(Position=0)]
[string]
# The path to the file to check.
$Path,
[Parameter(Position=1)]
[string]
# A description of why the assertion might fail.
$Message
)
Set-StrictMode -Version 'Latest'
if( Test-Path -Path $Path -PathType Leaf )
{
Fail "File $Path exists: $Message"
}
}
|
{
"pile_set_name": "Github"
}
|
/* eslint-disable @typescript-eslint/no-var-requires */
// @ts-check
'use strict'
const path = require('path')
const FilterWarningsPlugin = require('webpack-filter-warnings-plugin')
/** @type {import('webpack').Configuration} */
const config = {
target: 'node',
entry: './src/extension.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'extension.js',
libraryTarget: 'commonjs2',
devtoolModuleFilenameTemplate: '../[resource-path]',
},
// devtool: 'source-map',
externals: {
vscode: 'commonjs vscode',
nodejieba: 'nodejieba',
esm: 'esm',
'ts-node': 'ts-node',
consolidate: 'consolidate',
less: '_',
sass: '_',
stylus: '_',
prettier: 'prettier',
'@microsoft/typescript-etw': '_',
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'ts-loader',
},
],
},
],
},
plugins: [
// @ts-ignore
new FilterWarningsPlugin({
exclude: /Critical dependency: the request of a dependency is an expression/,
}),
],
}
module.exports = config
|
{
"pile_set_name": "Github"
}
|
package org.succlz123.blueboard.view.adapter.recyclerview.content;
import com.facebook.drawee.view.SimpleDraweeView;
import org.succlz123.blueboard.MyApplication;
import org.succlz123.blueboard.R;
import org.succlz123.blueboard.base.BaseRvViewHolder;
import org.succlz123.blueboard.model.bean.acfun.AcContentInfo;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by succlz123 on 15/8/4.
*/
public class AcContentInfoRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIDEO_INFO = 0;
private static final int VIDEO_ITEM = 1;
private static final int VIDEO_DOWNLOAD = 2;
private AcContentInfo mAcContentInfo;
private OnVideoPlayClickListener mOnVideoPlayClickListener;
private OnDownLoadClickListener mOnDownLoadClickListener;
private List<AcContentInfo.DataEntity.FullContentEntity.VideosEntity> mVideoList = new ArrayList<>();
private boolean mIsShowDlCheckBox;
private boolean mIsDlCheckBoxSelectAll;
private HashMap<Integer, Boolean> mCheckBoxCheckedArray = new HashMap();
private List<Integer> mCheckedList = new ArrayList<>();
private ArrayList<AcContentInfo.DataEntity.FullContentEntity.VideosEntity> mDownLoadList = new ArrayList<>();
public void setIsShowDlCheckBox(boolean isShowDlCheckBox, boolean isDlCheckBoxSelectAll) {
this.mIsShowDlCheckBox = isShowDlCheckBox;
mIsDlCheckBoxSelectAll = isDlCheckBoxSelectAll;
notifyDataSetChanged();
}
public boolean isShowDlCheckBox() {
return mIsShowDlCheckBox;
}
public AcContentInfo getAcContentInfo() {
return mAcContentInfo;
}
public interface OnVideoPlayClickListener {
void onClick(View view, int position, String userId, String videoId, String sourceId, String sourceType, String sourceTitle);
}
public interface OnDownLoadClickListener {
void onClick(View view, int position, ArrayList<AcContentInfo.DataEntity.FullContentEntity.VideosEntity> downLoadList);
}
public OnDownLoadClickListener getOnDownLoadClickListener() {
return mOnDownLoadClickListener;
}
public void setOnDownLoadClickListener(OnDownLoadClickListener onDownLoadClickListener) {
mOnDownLoadClickListener = onDownLoadClickListener;
}
public void setOnVideoPlayClickListener(OnVideoPlayClickListener onVideoPlayClickListener) {
this.mOnVideoPlayClickListener = onVideoPlayClickListener;
}
public void setContentInfo(AcContentInfo acContentInfo) {
this.mAcContentInfo = acContentInfo;
mVideoList = acContentInfo.getData().getFullContent().getVideos();
notifyDataSetChanged();
}
public class VideoInfoVH extends BaseRvViewHolder {
private TextView tvTitle;
private TextView tvDescription;
private TextView tvClick;
private TextView tvStows;
private SimpleDraweeView simpleDraweeView;
private TextView tvName;
private TextView tvUid;
private FrameLayout frameLayout;
public VideoInfoVH(View itemView) {
super(itemView);
tvTitle = f(itemView, R.id.ac_rv_content_info_title);
tvDescription = f(itemView, R.id.ac_rv_content_info_description);
tvClick = f(itemView, R.id.ac_rv_content_info_click);
tvStows = f(itemView, R.id.ac_rv_content_info_stows);
simpleDraweeView = f(itemView, R.id.ac_rv_content_info_up_img);
tvName = f(itemView, R.id.ac_rv_content_info_up_name);
tvUid = f(itemView, R.id.ac_rv_content_info_up_level);
frameLayout = f(itemView, R.id.cv_content_title_info_frame_layout);
}
}
public class VideoItemVH extends BaseRvViewHolder {
private TextView tvVideo;
private CheckBox cbVideo;
private CardView cardView;
public VideoItemVH(View itemView) {
super(itemView);
tvVideo = f(itemView, R.id.ac_rv_content_info_video_tv);
cbVideo = f(itemView, R.id.ac_rv_content_info_video_cb);
cardView = f(itemView, R.id.cv_content_video_item);
}
}
public class DownLoadItemVH extends BaseRvViewHolder {
private CardView cardView;
public DownLoadItemVH(View itemView) {
super(itemView);
cardView = f(itemView, R.id.ac_rv_content_download_cv);
}
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return VIDEO_INFO;
} else if (getItemCount() - position == 1 && mIsShowDlCheckBox) {
return VIDEO_DOWNLOAD;
} else {
return VIDEO_ITEM;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View titleInfoView = inflater.inflate(R.layout.ac_rv_cardview_content_title_info, parent, false);
View videoItemView = inflater.inflate(R.layout.ac_rv_cardview_content_video_item, parent, false);
View downLoadItemView = inflater.inflate(R.layout.ac_rv_content_download, parent, false);
if (viewType == VIDEO_INFO) {
return new VideoInfoVH(titleInfoView);
} else if (viewType == VIDEO_ITEM) {
return new VideoItemVH(videoItemView);
} else if (viewType == VIDEO_DOWNLOAD) {
return new DownLoadItemVH(downLoadItemView);
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if (holder instanceof VideoInfoVH) {
if (mAcContentInfo != null) {
final AcContentInfo.DataEntity.FullContentEntity contentEntity
= mAcContentInfo.getData().getFullContent();
((VideoInfoVH) holder).tvTitle
.setText(contentEntity.getTitle());
((VideoInfoVH) holder).tvDescription
.setText(Html.fromHtml(contentEntity.getDescription()));
((VideoInfoVH) holder).tvClick
.setText(MyApplication.getInstance().getApplicationContext().getString(R.string.click) + " " + contentEntity.getViews());
((VideoInfoVH) holder).tvStows
.setText(MyApplication.getInstance().getApplicationContext().getString(R.string.stows) + " " + contentEntity.getStows());
((VideoInfoVH) holder).simpleDraweeView
.setImageURI(Uri.parse(contentEntity.getUser().getUserImg()));
((VideoInfoVH) holder).tvName
.setText(contentEntity.getUser().getUsername());
((VideoInfoVH) holder).tvUid
.setText(MyApplication.getInstance().getApplicationContext().getString(R.string.uid) + " " + contentEntity.getUser().getUserId());
if (mOnVideoPlayClickListener != null) {
((VideoInfoVH) holder).frameLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnVideoPlayClickListener.onClick(v,
position,
String.valueOf(contentEntity.getUser().getUserId()),
null, null, null, null);
}
});
}
}
} else if (holder instanceof VideoItemVH) {
if (mVideoList.size() != 0) {
final AcContentInfo.DataEntity.FullContentEntity.VideosEntity videosEntity
= mVideoList.get(position - 1);
((VideoItemVH) holder).tvVideo
.setText((position) + ". " + videosEntity.getName());
if (!mIsShowDlCheckBox && mOnVideoPlayClickListener != null) {
((VideoItemVH) holder).cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mOnVideoPlayClickListener.onClick(v,
position,
null,
videosEntity.getVideoId(),
videosEntity.getSourceId(),
videosEntity.getType(),
videosEntity.getName());
}
});
((VideoItemVH) holder).cbVideo.setVisibility(View.GONE);
if (!mIsDlCheckBoxSelectAll) {
((VideoItemVH) holder).cbVideo.setChecked(false);
}
} else {
((VideoItemVH) holder).cbVideo.setVisibility(View.VISIBLE);
((VideoItemVH) holder).cbVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
boolean checked = cb.isChecked();
mCheckBoxCheckedArray.put(position, checked);
}
});
if (mIsDlCheckBoxSelectAll) {
((VideoItemVH) holder).cbVideo.setChecked(true);
mCheckBoxCheckedArray.put(position, ((VideoItemVH) holder).cbVideo.isChecked());
} else {
((VideoItemVH) holder).cbVideo.setChecked(false);
}
}
}
} else if (holder instanceof DownLoadItemVH) {
if (mVideoList.size() != 0 && mCheckBoxCheckedArray != null) {
((DownLoadItemVH) holder).cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCheckedList.clear();
for (Object obj : mCheckBoxCheckedArray.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
Integer key = (Integer) entry.getKey();
Boolean value = (Boolean) entry.getValue();
if (value == true) {
mCheckedList.add(key);
}
}
if (mCheckedList.size() != 0) {
mDownLoadList.clear();
for (int position : mCheckedList) {
AcContentInfo.DataEntity.FullContentEntity.VideosEntity videosEntity
= mVideoList.get(position - 1);
videosEntity.setVideoTitle(mAcContentInfo.getData().getFullContent().getTitle());
mDownLoadList.add(videosEntity);
}
if (mOnDownLoadClickListener != null && mDownLoadList.size() != 0) {
mOnDownLoadClickListener.onClick(v, position, mDownLoadList);
mIsShowDlCheckBox = false;
notifyDataSetChanged();
}
}
}
});
}
}
}
@Override
public int getItemCount() {
if (mIsShowDlCheckBox) {
return mVideoList.size() + 2;
} else if (mVideoList.size() != 0) {
return mVideoList.size() + 1;
}
return 0;
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.datafactory.v2018_06_01;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* A copy activity Hubspot Service source.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = HubspotSource.class)
@JsonTypeName("HubspotSource")
public class HubspotSource extends TabularSource {
/**
* A query to retrieve data from source. Type: string (or Expression with
* resultType string).
*/
@JsonProperty(value = "query")
private Object query;
/**
* Get a query to retrieve data from source. Type: string (or Expression with resultType string).
*
* @return the query value
*/
public Object query() {
return this.query;
}
/**
* Set a query to retrieve data from source. Type: string (or Expression with resultType string).
*
* @param query the query value to set
* @return the HubspotSource object itself.
*/
public HubspotSource withQuery(Object query) {
this.query = query;
return this;
}
}
|
{
"pile_set_name": "Github"
}
|
Certificate:
Data:
Version: 3 (0x2)
Serial Number:
3e:2c:9d:be:b0:42:c8:cf:fc:99:42:d5:4d:41:6a:be
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=California, L=Mountain View, O=Test CA, CN=Test Root CA
Validity
Not Before: Dec 20 00:00:00 2017 GMT
Not After : Dec 20 00:00:00 2020 GMT
Subject: C=US, ST=California, L=Mountain View, O=Test CA, CN=127.0.0.1
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public-Key: (2048 bit)
Modulus:
00:d2:eb:f5:8f:40:9e:0a:5a:c9:42:20:d0:ec:6d:
1b:6b:2f:e6:fc:67:0d:ef:ac:4f:23:94:70:28:2d:
ca:38:47:d9:c6:7e:6d:20:90:e6:89:8c:cb:60:02:
5c:94:06:26:12:19:36:59:f3:ba:d6:3e:7e:39:da:
4c:ea:69:ef:21:de:ce:6d:cc:c4:29:c6:b4:2e:c8:
13:6b:f5:bd:b7:93:92:09:cd:de:11:b7:cf:fa:04:
6d:b7:74:88:c3:60:ff:36:f2:df:5a:3a:ee:e7:96:
7c:43:dd:9d:2d:dd:87:b1:d7:4e:8e:a8:31:72:47:
aa:46:0b:5b:bc:54:1e:ef:c4:fb:f7:d1:66:37:75:
56:b3:e7:19:51:7c:c4:0d:6b:ab:f1:ae:89:e1:87:
9c:26:e6:21:f5:6a:73:8e:23:4b:86:1b:80:c5:a3:
27:52:1c:dd:35:68:d2:fc:35:2c:0c:f0:6f:67:fb:
b4:d5:84:e8:56:4e:3d:09:ad:b9:f2:fc:f7:84:d9:
83:7f:c9:1b:f4:3d:f3:f4:f8:03:e6:fe:bd:17:09:
57:cf:81:b1:ed:75:09:40:0e:36:7a:96:85:1d:a1:
ae:43:86:2b:c5:ee:30:66:ff:60:05:5e:f5:76:a7:
c7:eb:1e:65:8f:e6:88:b6:42:6b:78:86:a3:c6:7a:
be:73
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Subject Key Identifier:
AF:5E:73:1B:EC:71:82:4F:A6:44:B2:11:27:57:AE:91:11:A0:50:1C
X509v3 Authority Key Identifier:
keyid:9B:26:0B:8A:98:A9:BB:1D:B9:1F:1C:E3:1A:40:33:ED:8E:17:88:AB
X509v3 Extended Key Usage:
TLS Web Server Authentication, TLS Web Client Authentication
X509v3 Subject Alternative Name:
IP Address:127.0.0.1
Signature Algorithm: sha256WithRSAEncryption
b1:92:16:b1:ec:a2:8a:d2:43:e6:5e:f5:a9:91:7b:1e:82:33:
7f:bd:ef:5d:6c:d5:75:29:02:e9:7b:dc:cf:00:05:9e:cd:2c:
ff:d3:74:d0:1d:88:b6:c6:08:11:af:90:be:d6:96:e5:1a:35:
18:1c:c7:ff:33:52:6e:07:65:2a:8d:8e:a4:66:d4:47:d5:74:
79:9e:9f:59:10:53:23:11:40:be:9e:ae:67:c2:cb:bd:7d:f2:
e6:f9:00:45:23:22:2b:48:82:1d:53:19:b6:7c:c9:3b:67:8a:
70:23:c6:43:c0:20:74:38:01:9f:35:95:c9:3c:09:b8:61:d8:
78:d2:44:0c:ea:fe:47:ff:b8:77:f6:ca:c0:ef:4f:5f:27:22:
34:8e:d0:a7:cd:7a:70:e4:4d:d1:d8:1a:b7:a3:90:06:17:46:
90:4f:0e:92:28:5e:64:d4:54:84:69:6f:b8:4a:e9:06:82:f3:
58:67:80:80:45:f7:26:a8:80:3c:35:e3:cb:b5:c1:9c:46:64:
a9:d5:b6:06:a3:30:81:d0:ea:45:75:da:36:1a:d6:c6:1c:38:
a2:d9:e3:37:71:84:e9:47:ed:5e:f4:1b:a3:cc:a2:ba:19:30:
f5:c7:18:31:b3:3e:86:3d:33:41:a9:2f:91:25:63:54:fe:3a:
aa:b3:24:61
-----BEGIN CERTIFICATE-----
MIIDzjCCAragAwIBAgIQPiydvrBCyM/8mULVTUFqvjANBgkqhkiG9w0BAQsFADBj
MQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91
bnRhaW4gVmlldzEQMA4GA1UECgwHVGVzdCBDQTEVMBMGA1UEAwwMVGVzdCBSb290
IENBMB4XDTE3MTIyMDAwMDAwMFoXDTIwMTIyMDAwMDAwMFowYDELMAkGA1UEBhMC
VVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcx
EDAOBgNVBAoMB1Rlc3QgQ0ExEjAQBgNVBAMMCTEyNy4wLjAuMTCCASIwDQYJKoZI
hvcNAQEBBQADggEPADCCAQoCggEBANLr9Y9AngpayUIg0OxtG2sv5vxnDe+sTyOU
cCgtyjhH2cZ+bSCQ5omMy2ACXJQGJhIZNlnzutY+fjnaTOpp7yHezm3MxCnGtC7I
E2v1vbeTkgnN3hG3z/oEbbd0iMNg/zby31o67ueWfEPdnS3dh7HXTo6oMXJHqkYL
W7xUHu/E+/fRZjd1VrPnGVF8xA1rq/GuieGHnCbmIfVqc44jS4YbgMWjJ1Ic3TVo
0vw1LAzwb2f7tNWE6FZOPQmtufL894TZg3/JG/Q98/T4A+b+vRcJV8+Bse11CUAO
NnqWhR2hrkOGK8XuMGb/YAVe9Xanx+seZY/miLZCa3iGo8Z6vnMCAwEAAaOBgDB+
MAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFK9ecxvscYJPpkSyESdXrpERoFAcMB8G
A1UdIwQYMBaAFJsmC4qYqbsduR8c4xpAM+2OF4irMB0GA1UdJQQWMBQGCCsGAQUF
BwMBBggrBgEFBQcDAjAPBgNVHREECDAGhwR/AAABMA0GCSqGSIb3DQEBCwUAA4IB
AQCxkhax7KKK0kPmXvWpkXsegjN/ve9dbNV1KQLpe9zPAAWezSz/03TQHYi2xggR
r5C+1pblGjUYHMf/M1JuB2UqjY6kZtRH1XR5np9ZEFMjEUC+nq5nwsu9ffLm+QBF
IyIrSIIdUxm2fMk7Z4pwI8ZDwCB0OAGfNZXJPAm4Ydh40kQM6v5H/7h39srA709f
JyI0jtCnzXpw5E3R2Bq3o5AGF0aQTw6SKF5k1FSEaW+4SukGgvNYZ4CARfcmqIA8
NePLtcGcRmSp1bYGozCB0OpFddo2GtbGHDii2eM3cYTpR+1e9BujzKK6GTD1xxgx
sz6GPTNBqS+RJWNU/jqqsyRh
-----END CERTIFICATE-----
|
{
"pile_set_name": "Github"
}
|
// Copyright 2016 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"github.com/la5nta/pat/cfg"
)
func LoadConfig(path string, fallback cfg.Config) (config cfg.Config, err error) {
config, err = ReadConfig(path)
if os.IsNotExist(err) {
return fallback, WriteConfig(fallback, path)
} else if err != nil {
return config, err
}
// Ensure the alias "telnet" exists
if config.ConnectAliases == nil {
config.ConnectAliases = make(map[string]string)
}
if _, exists := config.ConnectAliases["telnet"]; !exists {
config.ConnectAliases["telnet"] = cfg.DefaultConfig.ConnectAliases["telnet"]
}
// Ensure ServiceCodes has a default value
if len(config.ServiceCodes) == 0 {
config.ServiceCodes = cfg.DefaultConfig.ServiceCodes
}
// Ensure Pactor has a default value
if config.Pactor == (cfg.PactorConfig{}) {
config.Pactor = cfg.DefaultConfig.Pactor
}
//TODO: Remove after some release cycles (2019-09-29)
if config.GPSdAddrLegacy != "" {
config.GPSd.Addr = config.GPSdAddrLegacy
}
return config, nil
}
func replaceDeprecatedCMSHostname(path string, data []byte) ([]byte, error) {
const o = "@server.winlink.org:8772/wl2k"
const n = "@cms.winlink.org:8772/wl2k"
if !bytes.Contains(data, []byte(o)) {
return data, nil
}
data = bytes.Replace(data, []byte(o), []byte(n), -1)
f, err := os.Open(path)
if err != nil {
return data, err
}
stat, err := f.Stat()
f.Close()
if err != nil {
return data, err
}
return data, ioutil.WriteFile(path, data, stat.Mode())
}
func ReadConfig(path string) (config cfg.Config, err error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return
}
//TODO: Remove after some release cycles (2017-11-09)
data, err = replaceDeprecatedCMSHostname(path, data)
if err != nil {
fmt.Println("Failed to rewrite deprecated CMS hostname:", err)
fmt.Println("Please update your config's 'telnet' connect alias manually to:")
fmt.Println(cfg.DefaultConfig.ConnectAliases["telnet"])
fmt.Println("")
}
err = json.Unmarshal(data, &config)
return
}
func WriteConfig(config cfg.Config, filePath string) error {
b, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
// Add trailing new-line
b = append(b, '\n')
// Ensure path dir is available
os.Mkdir(path.Dir(filePath), os.ModePerm|os.ModeDir)
return ioutil.WriteFile(filePath, b, 0600)
}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright 2011-2019 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dmdl.java;
import static com.asakusafw.dmdl.util.CommandLineUtils.*;
import java.io.File;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Locale;
import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asakusafw.dmdl.source.DmdlSourceRepository;
import com.asakusafw.utils.java.model.syntax.ModelFactory;
import com.asakusafw.utils.java.model.util.Filer;
import com.asakusafw.utils.java.model.util.Models;
/**
* Asakusa DMDL Compiler Command Line Interface.
*/
public final class Main {
static final Logger LOG = LoggerFactory.getLogger(Main.class);
private static final Option OPT_OUTPUT;
private static final Option OPT_PACKAGE;
private static final Option OPT_SOURCE_ENCODING;
private static final Option OPT_TARGET_ENCODING;
private static final Option OPT_SOURCE_PATH;
private static final Option OPT_PLUGIN;
private static final Options OPTIONS;
static {
OPT_OUTPUT = new Option("output", true, //$NON-NLS-1$
Messages.getString("Main.optOutput")); //$NON-NLS-1$
OPT_OUTPUT.setArgName("/path/to/output"); //$NON-NLS-1$
OPT_OUTPUT.setRequired(true);
OPT_SOURCE_PATH = new Option("source", true, //$NON-NLS-1$
Messages.getString("Main.optSource")); //$NON-NLS-1$
OPT_SOURCE_PATH.setArgName(
"source-file.dmdl" + File.pathSeparatorChar + "/path/to/source"); //$NON-NLS-1$ //$NON-NLS-2$
OPT_SOURCE_PATH.setRequired(true);
OPT_PACKAGE = new Option("package", true, //$NON-NLS-1$
Messages.getString("Main.optPackage")); //$NON-NLS-1$
OPT_PACKAGE.setArgName("pkg.name"); //$NON-NLS-1$
OPT_PACKAGE.setRequired(true);
OPT_SOURCE_ENCODING = new Option("sourceencoding", true, //$NON-NLS-1$
Messages.getString("Main.optSourceencoding")); //$NON-NLS-1$
OPT_SOURCE_ENCODING.setArgName("source-encoding"); //$NON-NLS-1$
OPT_SOURCE_ENCODING.setRequired(false);
OPT_TARGET_ENCODING = new Option("targetencoding", true, //$NON-NLS-1$
Messages.getString("Main.optTargetencoding")); //$NON-NLS-1$
OPT_TARGET_ENCODING.setArgName("target-encoding"); //$NON-NLS-1$
OPT_TARGET_ENCODING.setRequired(false);
OPT_PLUGIN = new Option("plugin", true, //$NON-NLS-1$
Messages.getString("Main.optPlugin")); //$NON-NLS-1$
OPT_PLUGIN.setArgName("plugin-1.jar" + File.pathSeparatorChar + "plugin-2.jar"); //$NON-NLS-1$ //$NON-NLS-2$
OPT_PLUGIN.setValueSeparator(File.pathSeparatorChar);
OPT_PLUGIN.setRequired(false);
OPTIONS = new Options();
OPTIONS.addOption(OPT_OUTPUT);
OPTIONS.addOption(OPT_PACKAGE);
OPTIONS.addOption(OPT_SOURCE_ENCODING);
OPTIONS.addOption(OPT_TARGET_ENCODING);
OPTIONS.addOption(OPT_SOURCE_PATH);
OPTIONS.addOption(OPT_PLUGIN);
}
private Main() {
return;
}
/**
* Program entry.
* @param args program arguments
*/
public static void main(String... args) {
GenerateTask task;
try {
Configuration conf = configure(args);
task = new GenerateTask(conf);
} catch (Exception e) {
HelpFormatter formatter = new HelpFormatter();
formatter.setWidth(Integer.MAX_VALUE);
formatter.printHelp(
MessageFormat.format(
"java -classpath ... {0}", //$NON-NLS-1$
Main.class.getName()),
OPTIONS,
true);
e.printStackTrace(System.out);
System.exit(1);
return;
}
try {
task.process();
} catch (Exception e) {
e.printStackTrace(System.out);
System.exit(1);
return;
}
}
static Configuration configure(String[] args) throws ParseException {
assert args != null;
CommandLineParser parser = new BasicParser();
CommandLine cmd = parser.parse(OPTIONS, args);
String output = cmd.getOptionValue(OPT_OUTPUT.getOpt());
String packageName = cmd.getOptionValue(OPT_PACKAGE.getOpt());
Charset sourceEnc = parseCharset(cmd.getOptionValue(OPT_SOURCE_ENCODING.getOpt()));
Charset targetEnc = parseCharset(cmd.getOptionValue(OPT_TARGET_ENCODING.getOpt()));
String sourcePaths = cmd.getOptionValue(OPT_SOURCE_PATH.getOpt());
String plugin = cmd.getOptionValue(OPT_PLUGIN.getOpt());
File outputDirectory = new File(output);
DmdlSourceRepository source = buildRepository(parseFileList(sourcePaths), sourceEnc);
ClassLoader serviceLoader = buildPluginLoader(Main.class.getClassLoader(), parseFileList(plugin));
ModelFactory factory = Models.getModelFactory();
return new Configuration(
factory,
source,
Models.toName(factory, packageName),
new Filer(outputDirectory, targetEnc),
serviceLoader,
Locale.getDefault());
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.components.impl.stores
import com.intellij.configurationStore.SaveSession
import com.intellij.configurationStore.StateStorageManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.messages.MessageBus
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.TestOnly
import java.nio.file.Path
@ApiStatus.Internal
interface IComponentStore {
val storageManager: StateStorageManager
fun setPath(path: Path)
fun initComponent(component: Any, serviceDescriptor: ServiceDescriptor?, pluginId: PluginId?)
@JvmDefault
fun unloadComponent(component: Any) {
}
fun initPersistencePlainComponent(component: Any, @NlsSafe key: String)
fun reloadStates(componentNames: Set<String>, messageBus: MessageBus)
fun reloadState(componentClass: Class<out PersistentStateComponent<*>>)
fun isReloadPossible(componentNames: Set<String>): Boolean
suspend fun save(forceSavingAllSettings: Boolean = false)
@TestOnly
fun saveComponent(component: PersistentStateComponent<*>)
@TestOnly
fun removeComponent(name: String)
@TestOnly
@JvmDefault
fun clearCaches() {}
@JvmDefault
fun release() {}
}
data class SaveSessionAndFile(val session: SaveSession, val file: VirtualFile)
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2012 Google 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 Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @constructor
* @extends {WebInspector.SplitWidget}
* @param {!WebInspector.FileSystemModel.FileSystem} fileSystem
*/
WebInspector.FileSystemView = function(fileSystem)
{
WebInspector.SplitWidget.call(this, true, false, "fileSystemViewSplitViewState");
this.element.classList.add("file-system-view", "storage-view");
var vbox = new WebInspector.VBox();
vbox.element.classList.add("sidebar");
this._directoryTree = new TreeOutline();
this._directoryTree.element.classList.add("outline-disclosure", "filesystem-directory-tree");
vbox.element.appendChild(this._directoryTree.element);
this.setSidebarWidget(vbox);
var rootItem = new WebInspector.FileSystemView.EntryTreeElement(this, fileSystem.root);
rootItem.expanded = true;
this._directoryTree.appendChild(rootItem);
this._visibleView = null;
this._refreshButton = new WebInspector.ToolbarButton(WebInspector.UIString("Refresh"), "refresh-toolbar-item");
this._refreshButton.setVisible(true);
this._refreshButton.addEventListener("click", this._refresh, this);
this._deleteButton = new WebInspector.ToolbarButton(WebInspector.UIString("Delete"), "delete-toolbar-item");
this._deleteButton.setVisible(true);
this._deleteButton.addEventListener("click", this._confirmDelete, this);
}
WebInspector.FileSystemView.prototype = {
/**
* @return {!Array.<!WebInspector.ToolbarItem>}
*/
toolbarItems: function()
{
return [this._refreshButton, this._deleteButton];
},
/**
* @type {!WebInspector.Widget}
*/
get visibleView()
{
return this._visibleView;
},
/**
* @param {!WebInspector.Widget} view
*/
showView: function(view)
{
if (this._visibleView === view)
return;
if (this._visibleView)
this._visibleView.detach();
this._visibleView = view;
this.setMainWidget(view);
},
_refresh: function()
{
this._directoryTree.firstChild().refresh();
},
_confirmDelete: function()
{
if (confirm(WebInspector.UIString("Are you sure you want to delete the selected entry?")))
this._delete();
},
_delete: function()
{
this._directoryTree.selectedTreeElement.deleteEntry();
},
__proto__: WebInspector.SplitWidget.prototype
}
/**
* @constructor
* @extends {TreeElement}
* @param {!WebInspector.FileSystemView} fileSystemView
* @param {!WebInspector.FileSystemModel.Entry} entry
*/
WebInspector.FileSystemView.EntryTreeElement = function(fileSystemView, entry)
{
TreeElement.call(this, entry.name, entry.isDirectory);
this._entry = entry;
this._fileSystemView = fileSystemView;
}
WebInspector.FileSystemView.EntryTreeElement.prototype = {
/**
* @override
*/
onattach: function()
{
var selection = this.listItemElement.createChild("div", "selection fill");
this.listItemElement.insertBefore(selection, this.listItemElement.firstChild);
},
/**
* @override
* @return {boolean}
*/
onselect: function()
{
if (!this._view) {
if (this._entry.isDirectory)
this._view = new WebInspector.DirectoryContentView();
else {
var file = /** @type {!WebInspector.FileSystemModel.File} */ (this._entry);
this._view = new WebInspector.FileContentView(file);
}
}
this._fileSystemView.showView(this._view);
this.refresh();
return false;
},
/**
* @override
*/
onpopulate: function()
{
this.refresh();
},
/**
* @param {number} errorCode
* @param {!Array.<!WebInspector.FileSystemModel.Entry>=} entries
*/
_directoryContentReceived: function(errorCode, entries)
{
WebInspector.userMetrics.actionTaken(WebInspector.UserMetrics.Action.FileSystemDirectoryContentReceived);
if (errorCode === FileError.NOT_FOUND_ERR) {
if (this.parent)
this.parent.refresh();
return;
}
if (errorCode !== 0 || !entries) {
console.error("Failed to read directory: " + errorCode);
return;
}
entries.sort(WebInspector.FileSystemModel.Entry.compare);
if (this._view)
this._view.showEntries(entries);
var oldChildren = this.children().slice(0);
var newEntryIndex = 0;
var oldChildIndex = 0;
var currentTreeItem = 0;
while (newEntryIndex < entries.length && oldChildIndex < oldChildren.length) {
var newEntry = entries[newEntryIndex];
var oldChild = oldChildren[oldChildIndex];
var order = newEntry.name.compareTo(oldChild._entry.name);
if (order === 0) {
if (oldChild._entry.isDirectory)
oldChild.invalidateChildren();
else
oldChild.refresh();
++newEntryIndex;
++oldChildIndex;
++currentTreeItem;
continue;
}
if (order < 0) {
this.insertChild(new WebInspector.FileSystemView.EntryTreeElement(this._fileSystemView, newEntry), currentTreeItem);
++newEntryIndex;
++currentTreeItem;
continue;
}
this.removeChildAtIndex(currentTreeItem);
++oldChildIndex;
}
for (; newEntryIndex < entries.length; ++newEntryIndex)
this.appendChild(new WebInspector.FileSystemView.EntryTreeElement(this._fileSystemView, entries[newEntryIndex]));
for (; oldChildIndex < oldChildren.length; ++oldChildIndex)
this.removeChild(oldChildren[oldChildIndex]);
},
refresh: function()
{
if (!this._entry.isDirectory) {
if (this._view && this._view === this._fileSystemView.visibleView) {
var fileContentView = /** @type {!WebInspector.FileContentView} */ (this._view);
fileContentView.refresh();
}
} else
this._entry.requestDirectoryContent(this._directoryContentReceived.bind(this));
},
deleteEntry: function()
{
this._entry.deleteEntry(this._deletionCompleted.bind(this));
},
_deletionCompleted: function()
{
if (this._entry != this._entry.fileSystem.root)
this.parent.refresh();
},
__proto__: TreeElement.prototype
}
|
{
"pile_set_name": "Github"
}
|
function varargout = covMaterniso(d,varargin)
% Wrapper for Matern covariance function covMatern.m.
%
% Matern covariance function with nu = d/2 and isotropic distance measure. For
% d=1 the function is also known as the exponential covariance function or the
% Ornstein-Uhlenbeck covariance in 1d. The covariance function is:
%
% k(x,z) = sf^2 * f( sqrt(d)*r ) * exp(-sqrt(d)*r)
%
% with f(t)=1 for d=1, f(t)=1+t for d=3 and f(t)=1+t+t^2/3 for d=5.
% Here r is the distance sqrt((x-z)'*inv(P)*(x-z)), P is ell times
% the unit matrix and sf2 is the signal variance. The hyperparameters are:
%
% hyp = [ log(ell)
% log(sf) ]
%
% Copyright (c) by Carl Edward Rasmussen and Hannes Nickisch, 2016-04-27.
%
% See also COVFUNCTIONS.M.
varargout = cell(max(1,nargout),1);
[varargout{:}] = covScale({'covMatern','iso',[],d},varargin{:});
|
{
"pile_set_name": "Github"
}
|
// SPDX-License-Identifier: GPL-2.0
#ifndef TESTPARSEPERFORMANCE_H
#define TESTPARSEPERFORMANCE_H
#include <QtTest>
class TestParsePerformance : public QObject {
Q_OBJECT
private slots:
void initTestCase();
void init();
void cleanup();
void parseSsrf();
void parseGit();
};
#endif
|
{
"pile_set_name": "Github"
}
|
// RUN: %clang_cc1 -triple=x86_64-linux-gnu -emit-llvm -o - %s | FileCheck %s
// PR8839
extern "C" char memmove();
int main() {
// CHECK: call {{signext i8|i8}} @memmove()
return memmove();
}
struct S;
// CHECK: define {{.*}} @_Z9addressofbR1SS0_(
S *addressof(bool b, S &s, S &t) {
// CHECK: %[[LVALUE:.*]] = phi
// CHECK: ret {{.*}}* %[[LVALUE]]
return __builtin_addressof(b ? s : t);
}
extern "C" int __builtin_abs(int); // #1
long __builtin_abs(long); // #2
extern "C" int __builtin_abs(int); // #3
int x = __builtin_abs(-2);
// CHECK: store i32 2, i32* @x, align 4
long y = __builtin_abs(-2l);
// CHECK: [[Y:%.+]] = call i64 @_Z13__builtin_absl(i64 -2)
// CHECK: store i64 [[Y]], i64* @y, align 8
extern const char char_memchr_arg[32];
char *memchr_result = __builtin_char_memchr(char_memchr_arg, 123, 32);
// CHECK: call i8* @memchr(i8* getelementptr inbounds ([32 x i8], [32 x i8]* @char_memchr_arg, i32 0, i32 0), i32 123, i64 32)
int constexpr_overflow_result() {
constexpr int x = 1;
// CHECK: alloca i32
constexpr int y = 2;
// CHECK: alloca i32
int z;
// CHECK: [[Z:%.+]] = alloca i32
__builtin_sadd_overflow(x, y, &z);
return z;
// CHECK: [[RET_PTR:%.+]] = extractvalue { i32, i1 } %0, 0
// CHECK: store i32 [[RET_PTR]], i32* [[Z]]
// CHECK: [[RET_VAL:%.+]] = load i32, i32* [[Z]]
// CHECK: ret i32 [[RET_VAL]]
}
|
{
"pile_set_name": "Github"
}
|
# 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.
'''Count number of occurrences of a given message ID.'''
from __future__ import print_function
import getopt
import sys
from grit import grd_reader
from grit.tool import interface
class CountMessage(interface.Tool):
'''Count the number of times a given message ID is used.'''
def __init__(self):
pass
def ShortDescription(self):
return 'Count the number of times a given message ID is used.'
def ParseOptions(self, args):
"""Set this objects and return all non-option arguments."""
own_opts, args = getopt.getopt(args, '', ('help',))
for key, val in own_opts:
if key == '--help':
self.ShowUsage()
sys.exit(0)
return args
def Run(self, opts, args):
args = self.ParseOptions(args)
if len(args) != 1:
print('This tool takes a single tool-specific argument, the message '
'ID to count.')
return 2
self.SetOptions(opts)
id = args[0]
res_tree = grd_reader.Parse(opts.input, debug=opts.extra_verbose)
res_tree.OnlyTheseTranslations([])
res_tree.RunGatherers()
count = 0
for c in res_tree.UberClique().AllCliques():
if c.GetId() == id:
count += 1
print("There are %d occurrences of message %s." % (count, id))
|
{
"pile_set_name": "Github"
}
|
#ifndef BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
#define BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/contains_fwd.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/map/aux_/at_impl.hpp>
#include <boost/mpl/map/aux_/tag.hpp>
#include <boost/type_traits/is_same.hpp>
namespace boost { namespace mpl {
template<>
struct contains_impl< aux::map_tag >
{
template< typename Map, typename Pair > struct apply
: is_same<
typename at_impl<aux::map_tag>::apply<
Map
, typename Pair::first
>::type
, typename Pair::second
>
{
};
};
}}
#endif // BOOST_MPL_MAP_AUX_CONTAINS_IMPL_HPP_INCLUDED
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>arm_lms_q15.d File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="cmsis.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 46px;">
<td id="proglogo"><img alt="CMSIS Logo" src="CMSIS_Logo_Final.png"></td>
<td style="padding-left: 0.5em;">
<div id="projectname">CMSIS-DSP
 <span id="projectnumber">Verison 1.1.0</span>
</div>
<div id="projectbrief">CMSIS DSP Software Library</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="CMSISnav" class="tabs1">
<ul class="tablist">
<li><a href="../../General/html/index.html"><span>CMSIS</span></a></li>
<li><a href="../../Core/html/index.html"><span>CORE</span></a></li>
<li class="current"><a href="../../DSP/html/index.html"><span>DSP</span></a></li>
<li><a href="../../RTOS/html/index.html"><span>RTOS API</span></a></li>
<li><a href="../../SVD/html/index.html"><span>SVD</span></a></li>
</ul>
</div>
<!-- Generated by Doxygen 1.7.5.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Reference</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('arm__lms__q15_8d.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="headertitle">
<div class="title">arm_lms_q15.d File Reference</div> </div>
</div>
<div class="contents">
</div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="arm__lms__q15_8d.html">arm_lms_q15.d</a> </li>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<li class="footer">Generated on Wed Mar 28 2012 15:38:07 for CMSIS-DSP by ARM Ltd. All rights reserved.
<!--
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.5.1 </li>
-->
</li>
</ul>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
--TEST--
ReflectionMethod class __toString() and export() methods
--FILE--
<?php
function reflectMethod($class, $method) {
$methodInfo = new ReflectionMethod($class, $method);
echo "**********************************\n";
echo "Reflecting on method $class::$method()\n\n";
echo "__toString():\n";
var_dump($methodInfo->__toString());
echo "\nexport():\n";
var_dump(ReflectionMethod::export($class, $method, true));
echo "\n**********************************\n";
}
class TestClass
{
public function foo() {
echo "Called foo()\n";
}
static function stat() {
echo "Called stat()\n";
}
private function priv() {
echo "Called priv()\n";
}
protected function prot() {}
public function __destruct() {}
}
class DerivedClass extends TestClass {}
interface TestInterface {
public function int();
}
reflectMethod("DerivedClass", "foo");
reflectMethod("TestClass", "stat");
reflectMethod("TestClass", "priv");
reflectMethod("TestClass", "prot");
reflectMethod("DerivedClass", "prot");
reflectMethod("TestInterface", "int");
reflectMethod("ReflectionProperty", "__construct");
reflectMethod("TestClass", "__destruct");
?>
--EXPECTF--
**********************************
Reflecting on method DerivedClass::foo()
__toString():
string(%d) "Method [ <user, inherits TestClass> public method foo ] {
@@ %s 16 - 18
}
"
export():
string(%d) "Method [ <user, inherits TestClass> public method foo ] {
@@ %s 16 - 18
}
"
**********************************
**********************************
Reflecting on method TestClass::stat()
__toString():
string(%d) "Method [ <user> static public method stat ] {
@@ %s 20 - 22
}
"
export():
string(%d) "Method [ <user> static public method stat ] {
@@ %s 20 - 22
}
"
**********************************
**********************************
Reflecting on method TestClass::priv()
__toString():
string(%d) "Method [ <user> private method priv ] {
@@ %s 24 - 26
}
"
export():
string(%d) "Method [ <user> private method priv ] {
@@ %s 24 - 26
}
"
**********************************
**********************************
Reflecting on method TestClass::prot()
__toString():
string(%d) "Method [ <user> protected method prot ] {
@@ %s 28 - 28
}
"
export():
string(%d) "Method [ <user> protected method prot ] {
@@ %s 28 - 28
}
"
**********************************
**********************************
Reflecting on method DerivedClass::prot()
__toString():
string(%d) "Method [ <user, inherits TestClass> protected method prot ] {
@@ %s 28 - 28
}
"
export():
string(%d) "Method [ <user, inherits TestClass> protected method prot ] {
@@ %s 28 - 28
}
"
**********************************
**********************************
Reflecting on method TestInterface::int()
__toString():
string(%d) "Method [ <user> abstract public method int ] {
@@ %s 36 - 36
}
"
export():
string(%d) "Method [ <user> abstract public method int ] {
@@ %s 36 - 36
}
"
**********************************
**********************************
Reflecting on method ReflectionProperty::__construct()
__toString():
string(%d) "Method [ <internal:Reflection, ctor> public method __construct ] {
- Parameters [2] {
Parameter #0 [ <required> $class ]
Parameter #1 [ <required> $name ]
}
}
"
export():
string(%d) "Method [ <internal:Reflection, ctor> public method __construct ] {
- Parameters [2] {
Parameter #0 [ <required> $class ]
Parameter #1 [ <required> $name ]
}
}
"
**********************************
**********************************
Reflecting on method TestClass::__destruct()
__toString():
string(%d) "Method [ <user, dtor> public method __destruct ] {
@@ %s 30 - 30
}
"
export():
string(%d) "Method [ <user, dtor> public method __destruct ] {
@@ %s 30 - 30
}
"
**********************************
|
{
"pile_set_name": "Github"
}
|
<Workflow xmlns="urn:wexflow-schema" id="161" name="Workflow_Tar" description="Workflow_Tar">
<Settings>
<Setting name="launchType" value="trigger" />
<Setting name="enabled" value="true" />
</Settings>
<Tasks>
<Task id="1" name="FilesLoader" description="Loading files" enabled="true">
<Setting name="folder" value="/opt/wexflow/WexflowTesting/Watchfolder1/" />
</Task>
<Task id="2" name="Tar" description="Creating Tar" enabled="true">
<Setting name="selectFiles" value="1" />
<Setting name="tarFileName" value="output.tar" />
</Task>
<Task id="3" name="FilesMover" description="Moving tars to Tar folder" enabled="true">
<Setting name="selectFiles" value="2" />
<Setting name="destFolder" value="/opt/wexflow/WexflowTesting/Tar/" />
</Task>
</Tasks>
</Workflow>
|
{
"pile_set_name": "Github"
}
|
a.in / b;
|
{
"pile_set_name": "Github"
}
|
{
"parent": "computercraft:block/monitor_base",
"textures": {
"front": "computercraft:blocks/adv_monitor29",
"side": "computercraft:blocks/adv_monitor7",
"top": "computercraft:blocks/adv_monitor3",
"back": "computercraft:blocks/adv_monitor47"
}
}
|
{
"pile_set_name": "Github"
}
|
// Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
desc: >
Extension not observed when creation of variable binding would produce an
early error (for-of statement)
template: func
info: |
B.3.3.1 Changes to FunctionDeclarationInstantiation
[...]
ii. If replacing the FunctionDeclaration f with a VariableStatement that
has F as a BindingIdentifier would not produce any Early Errors for
func and F is not an element of BoundNames of argumentsList, then
[...]
---*/
//- before
assert.throws(ReferenceError, function() {
f;
}, 'An initialized binding is not created prior to evaluation');
assert.sameValue(
typeof f,
'undefined',
'An uninitialized binding is not created prior to evaluation'
);
for (let f in { key: 0 }) {
//- after
}
assert.throws(ReferenceError, function() {
f;
}, 'An initialized binding is not created following evaluation');
assert.sameValue(
typeof f,
'undefined',
'An uninitialized binding is not created following evaluation'
);
|
{
"pile_set_name": "Github"
}
|
-------------------------------------
Exceptionless Readme
-------------------------------------
Exceptionless provides real-time error reporting for your apps. It organizes the
gathered information into simple actionable data that will help your app become
exceptionless!
Learn more at http://exceptionless.io.
-------------------------------------
How to get an api key
-------------------------------------
The Exceptionless client requires an api key to use the Exceptionless service.
You can get your Exceptionless api key by logging into http://exceptionless.io
and viewing your project configuration page.
-------------------------------------
General Data Protection Regulation
-------------------------------------
By default the Exceptionless Client will report all available metadata including potential PII data.
You can fine tune the collection of information via Data Exclusions or turning off collection completely.
Please visit the wiki https://github.com/exceptionless/Exceptionless.Net/wiki/Configuration#general-data-protection-regulation
for detailed information on how to configure the client to meet your requirements.
-------------------------------------
ASP.NET Web Api Integration
-------------------------------------
The Exceptionless.WebApi package will automatically configure your web.config.
All you need to do is open the web.config and add your Exceptionless api key to
the web.config Exceptionless section.
<exceptionless apiKey="API_KEY_HERE" />
Next, you must import the "Exceptionless" namespace and call the following line
of code to start reporting unhandled exceptions. You will need to run code during
application startup and pass it an HttpConfiguration instance. Please note that this
code is normally placed inside of the WebApiConfig classes Register method.
Exceptionless.ExceptionlessClient.Default.RegisterWebApi(config)
If you are hosting Web API inside of ASP.NET, you would register Exceptionless like:
Exceptionless.ExceptionlessClient.Default.RegisterWebApi(GlobalConfiguration.Configuration)
Please visit the wiki https://github.com/exceptionless/Exceptionless.Net/wiki/Sending-Events
for examples on sending events to Exceptionless.
-------------------------------------
Manually reporting an exception
-------------------------------------
By default the Exceptionless Client will report all unhandled exceptions. You can
also manually send an exception by importing the Exceptionless namespace and calling
the following method.
exception.ToExceptionless().Submit()
Please note that Web Api doesn't have a static http context. If possible, it is recommended
that you set the HttpActionContext when submitting events. Doing so will allow the request and
user information to be populated. You can do this by calling the SetHttpActionContext EventBuilder
extension method.
exception.ToExceptionless().SetHttpActionContext(ActionContext).Submit()
-------------------------------------
Documentation and Support
-------------------------------------
Please visit http://exceptionless.io for documentation and support.
|
{
"pile_set_name": "Github"
}
|
/*
Copyright (C) 1994-1995 Apogee Software, Ltd.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/**********************************************************************
module: SNDCARDS.H
author: James R. Dose
date: March 31, 1994
Contains enumerated type definitions for sound cards.
(c) Copyright 1994 James R. Dose. All Rights Reserved.
**********************************************************************/
#ifndef __SNDCARDS_H
#define __SNDCARDS_H
#define ASS_VERSION_STRING "1.12"
typedef enum
{
// ASS_NoSound,
SoundBlaster,
ProAudioSpectrum,
SoundMan16,
Adlib,
GenMidi,
SoundCanvas,
Awe32,
WaveBlaster,
SoundScape,
UltraSound,
SoundSource,
TandySoundSource,
PC,
NumSoundCards
} soundcardnames;
#endif
|
{
"pile_set_name": "Github"
}
|
/**
*
* TableRow
*
*/
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import { isEmpty, isNull, isObject, toLower, toString } from 'lodash';
import cn from 'classnames';
import CustomInputCheckbox from 'components/CustomInputCheckbox';
import IcoContainer from 'components/IcoContainer';
import styles from './styles.scss';
class TableRow extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
/**
* Return a formatted value according to the
* data type and value stored in database
*
* @param type {String} Data type
* @param value {*} Value stored in database
* @returns {*}
*/
getDisplayedValue(type, value, name) {
switch (toLower(type)) {
case 'string':
case 'text':
case 'email':
case 'enumeration':
return (value && !isEmpty(toString(value))) || name === 'id' ? toString(value) : '-';
case 'float':
case 'integer':
case 'biginteger':
case 'decimal':
return !isNull(value) ? toString(value) : '-';
case 'boolean':
return value !== null ? toString(value) : '-';
case 'date':
case 'time':
case 'datetime':
case 'timestamp': {
if (value === null) {
return '-';
}
const date = value && isObject(value) && value._isAMomentObject === true ?
value :
moment.utc(value);
return date.format('YYYY-MM-DD HH:mm:ss');
}
case 'password':
return '••••••••';
default:
return '-';
}
}
// Redirect to the edit page
handleClick() {
this.context.router.history.push(`${this.props.destination}${this.props.redirectUrl}`);
}
renderAction = () => (
<td key='action' className={styles.actions}>
<IcoContainer
icons={[
{ icoType: 'pencil', onClick: this.handleClick },
{ id: this.props.record.id, icoType: 'trash', onClick: this.props.onDelete },
]}
/>
</td>
);
renderCells = () => {
const { headers } = this.props;
return [this.renderDelete()]
.concat(
headers.map((header, i) => (
<td key={i}>
<div className={styles.truncate}>
<div className={styles.truncated}>
{this.getDisplayedValue(
header.type,
this.props.record[header.name],
header.name,
)}
</div>
</div>
</td>
)))
.concat([this.renderAction()]);
}
renderDelete = () => {
if (this.props.enableBulkActions) {
return (
<td onClick={(e) => e.stopPropagation()} key="i">
<CustomInputCheckbox
name={this.props.record.id}
onChange={this.props.onChange}
value={this.props.value}
/>
</td>
);
}
return null;
}
render() {
return (
<tr className={cn(styles.tableRow, this.props.enableBulkActions && styles.tableRowWithBulk)} onClick={this.handleClick}>
{this.renderCells()}
</tr>
);
}
}
TableRow.contextTypes = {
router: PropTypes.object.isRequired,
};
TableRow.propTypes = {
destination: PropTypes.string.isRequired,
enableBulkActions: PropTypes.bool,
headers: PropTypes.array.isRequired,
onChange: PropTypes.func.isRequired,
onDelete: PropTypes.func,
record: PropTypes.object.isRequired,
redirectUrl: PropTypes.string.isRequired,
value: PropTypes.bool,
};
TableRow.defaultProps = {
enableBulkActions: true,
onDelete: () => {},
value: false,
};
export default TableRow;
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<unit xmlns="http://www.sdml.info/srcML/src" xmlns:cpp="http://www.sdml.info/srcML/cpp" language="C++" dir="./core" filename="RNonCopyable.h"><comment type="block">/**
* Copyright (c) 2011-2018 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QCAD is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QCAD.
*/</comment>
<cpp:ifndef>#<cpp:directive>ifndef</cpp:directive> <name>RNONCOPYABLE_H</name></cpp:ifndef>
<cpp:define>#<cpp:directive>define</cpp:directive> <name>RNONCOPYABLE_H</name></cpp:define>
<cpp:include>#<cpp:directive>include</cpp:directive> <cpp:file>"core_global.h"</cpp:file></cpp:include>
<comment type="block">/**
* Instances of classes derived from this base class cannot be copied.
*
* \ingroup core
*/</comment>
<class>class <macro><name>QCADCORE_EXPORT</name></macro> <name>RNonCopyable</name> <block>{<private type="default">
</private><protected>protected:
<constructor><name>RNonCopyable</name><parameter_list>()</parameter_list> <block>{}</block></constructor>
<destructor><name>~RNonCopyable</name><parameter_list>()</parameter_list> <block>{}</block></destructor>
</protected><private>private:
<constructor_decl><name>RNonCopyable</name><parameter_list>(<param><decl><type><name>const</name> <name>RNonCopyable</name>&</type></decl></param>)</parameter_list>;</constructor_decl>
<function_decl><type><name>const</name> <name>RNonCopyable</name>&</type> <name>operator=</name><parameter_list>(<param><decl><type><name>const</name> <name>RNonCopyable</name>&</type></decl></param>)</parameter_list>;</function_decl>
</private>}</block>;</class>
<macro><name>Q_DECLARE_METATYPE</name><argument_list>(<argument>RNonCopyable*</argument>)</argument_list></macro>
<cpp:endif>#<cpp:directive>endif</cpp:directive></cpp:endif>
</unit>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2020-07-07 11:24:43 AM CDT
*/
namespace NetSuite\Classes;
class BinTransferInventory {
/**
* @var integer
*/
public $line;
/**
* @var \NetSuite\Classes\RecordRef
*/
public $item;
/**
* @var string
*/
public $description;
/**
* @var string
*/
public $preferredBin;
/**
* @var float
*/
public $quantity;
/**
* @var string
*/
public $itemUnitsLabel;
/**
* @var \NetSuite\Classes\InventoryDetail
*/
public $inventoryDetail;
/**
* @var string
*/
public $fromBins;
/**
* @var string
*/
public $toBins;
static $paramtypesmap = array(
"line" => "integer",
"item" => "RecordRef",
"description" => "string",
"preferredBin" => "string",
"quantity" => "float",
"itemUnitsLabel" => "string",
"inventoryDetail" => "InventoryDetail",
"fromBins" => "string",
"toBins" => "string",
);
}
|
{
"pile_set_name": "Github"
}
|
package stanford.spl;
import acm.graphics.GObject;
import acm.util.TokenScanner;
class GObject_rotate
extends JBECommand
{
public void execute(TokenScanner paramTokenScanner, JavaBackEnd paramJavaBackEnd)
{
paramTokenScanner.verifyToken("(");
String str = nextString(paramTokenScanner);
GObject localGObject = paramJavaBackEnd.getGObject(str);
paramTokenScanner.verifyToken(",");
double d = nextDouble(paramTokenScanner);
paramTokenScanner.verifyToken(")");
if (localGObject != null) {
localGObject.rotate(d);
}
}
}
|
{
"pile_set_name": "Github"
}
|
.TH LIFEREA "1" "Luty 1, 2005"
.SH NAME
Liferea \- Czytnik wiadomo¶ci RSS/RDF i Atom
.SH SK£ADNIA
.B liferea
.RI [\fIOPCJE\fR]
.SH OPIS
\fBLiferea\fP (Linuksowy Czytnik Wiadomo¶ci) to przegl±darka kana³ów
RSS/RDF oraz Atom obs³uguj±ca równie¿ kana³y CDF, OCS i katalogi OPML.
Z za³o¿enia jest klonem Windowsowego czytnika FeedReader.
Umo¿liwia zarz±dzanie list± subskrypcji, przegl±danie, wyszukiwanie w
elementach oraz wy¶wietlanie ich zawarto¶ci z wykorzystaniem bibliotek
GtkHTML lub Mozilli.
.SH OPCJE
.TP
.B \-\-version
Wy¶wietl informacjê o wersji i wyjd¼
.TP
.B \-\-help
Wy¶wietl podsumowanie opcji i wyjd¼
.TP
.B \-\-mainwindow\-state=\fISTAN\fR
Uruchom g³ówne okno Liferea w jednym ze STANów: shown, iconified, hidden
.TP
.B \-\-debug\-cache
Wy¶wietl informacje debugowania obs³ugi pamiêci podrêcznej
.TP
.B \-\-debug\-conf
Wy¶wietl informacje debugowania obs³ugi konfiguracji
.TP
.B \-\-debug\-update
Wy¶wietl informacje debugowania procesu uaktualniania subskrypcji
.TP
.B \-\-debug\-parsing
Wy¶wietl informacje debugowania funkcji przetwarzaj±cych
.TP
.B \-\-debug\-gui
Wy¶wietl informacje debugowania wszystkich funkcji interfejsu
graficznego
.TP
.B \-\-debug\-trace
Wy¶wietl informacje debugowania wykonywania funkcji
.TP
.B \-\-debug\-all
Wy¶wietl wszelkie mo¿liwe informacje debugowania
.TP
.B \-\-debug\-verbose
Wy¶wietl szczegó³owe informacje debugowania
.SH ZMIENNE ¦RODOWISKOWE
.TP
.B http_proxy
Je¶li po¶rednik sieciowy (proxy) nie zosta³ podany w Preferencjach
Liferea (pobierany z konfiguracji Gconf), u¿ywany bêdzie serwer podany w
zmiennej $http_proxy. Warto¶æ zmiennej $http_proxy powinna zawieraæ URI
¿±danego serwera proxy, na przyk³ad
.RB \(oqhttp://proxy.example.com:3128/\(cq.
.SH PLIKI
.TP
\fI/usr/lib/liferea/\fR
Wtyczki Liferea
.TP
\fI/usr/share/liferea/css/\fR
Arkusze stylów u¿ywane do modyfikowania wygl±du przegl±darki artyku³ów
.TP
\fI/usr/share/liferea/opml/\fR
Przyk³adowe listy subskrypcji
.TP
\fI~/.liferea/\fR
Listy subskrypcji u¿ytkownika oraz pliki pamiêci podrêcznej
.SH AUTORZY
Lars Windolf <lars.windolf@gmx.de>
.br
Nathan J. Conrad <t98502@users.sourceforge.net>
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/codedeploy/model/TimeBasedLinear.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CodeDeploy
{
namespace Model
{
TimeBasedLinear::TimeBasedLinear() :
m_linearPercentage(0),
m_linearPercentageHasBeenSet(false),
m_linearInterval(0),
m_linearIntervalHasBeenSet(false)
{
}
TimeBasedLinear::TimeBasedLinear(JsonView jsonValue) :
m_linearPercentage(0),
m_linearPercentageHasBeenSet(false),
m_linearInterval(0),
m_linearIntervalHasBeenSet(false)
{
*this = jsonValue;
}
TimeBasedLinear& TimeBasedLinear::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("linearPercentage"))
{
m_linearPercentage = jsonValue.GetInteger("linearPercentage");
m_linearPercentageHasBeenSet = true;
}
if(jsonValue.ValueExists("linearInterval"))
{
m_linearInterval = jsonValue.GetInteger("linearInterval");
m_linearIntervalHasBeenSet = true;
}
return *this;
}
JsonValue TimeBasedLinear::Jsonize() const
{
JsonValue payload;
if(m_linearPercentageHasBeenSet)
{
payload.WithInteger("linearPercentage", m_linearPercentage);
}
if(m_linearIntervalHasBeenSet)
{
payload.WithInteger("linearInterval", m_linearInterval);
}
return payload;
}
} // namespace Model
} // namespace CodeDeploy
} // namespace Aws
|
{
"pile_set_name": "Github"
}
|
/**
* NullPad
*
* A padding class that doesn't pad.
* Copyright (c) 2007 Henri Torgemane
*
* See LICENSE.txt for full license information.
*/
package com.hurlant.crypto.symmetric
{
import flash.utils.ByteArray;
/**
* A pad that does nothing.
* Useful when you don't want padding in your Mode.
*/
public class NullPad implements IPad
{
public function unpad(a:ByteArray):void
{
return;
}
public function pad(a:ByteArray):void
{
return;
}
public function setBlockSize(bs:uint):void {
return;
}
}
}
|
{
"pile_set_name": "Github"
}
|
/**
* Removes `key` and its value from the hash.
*
* @private
* @name delete
* @memberOf Hash
* @param {Object} hash The hash to modify.
* @param {string} key The key of the value to remove.
* @returns {boolean} Returns `true` if the entry was removed, else `false`.
*/
function hashDelete(key) {
var result = this.has(key) && delete this.__data__[key];
this.size -= result ? 1 : 0;
return result;
}
module.exports = hashDelete;
|
{
"pile_set_name": "Github"
}
|
unsigned long testPixel() {
tft.clearScreen();
start = micros();
tft.drawPixel(0, 0, WHITE);
t_end = micros() - start;
return t_end;
}
unsigned long testPixels() {
int green = 0;
tft.clearScreen();
start = micros();
for (int16_t i = 0; i < tft.width(); i++) {
if (green > 255) green = 0;
tft.drawPixel(i, 0, tft.Color565(0, green, 0));
green++;
}
t_end = micros() - start;
return t_end;
}
unsigned long testFillScreen() {
tft.clearScreen();
start = micros();
tft.fillScreen(0xF800);
t_end = micros() - start;
return t_end;
}
unsigned long testText() {
tft.clearScreen();
tft.setTextColor(WHITE);
tft.setTextScale(0);
start = micros();
tft.println("Hello World!");
tft.setTextColor(0xFFE0);
tft.setTextScale(1);
tft.println(1234.56);
tft.setTextColor(0xF800);
tft.println(0xFFFF, HEX);
tft.println();
tft.setTextColor(0x07E0);
tft.setTextScale(3);
tft.println("Hello");
tft.setTextScale(0);
tft.println("I implore thee, my foonting turlingdromes.");
tft.println("And hooptiously drangle me");
tft.println("with crinkly bindlewurdles, Or I will rend thee");
t_end = micros() - start;
return t_end;
}
unsigned long testLines(uint16_t color) {
int16_t i;
tft.clearScreen();
t_end = 0;
start = micros();
for (i = 0; i < tft.width(); i += 6) tft.drawLine(0, 0, i, tft.height() - 1, color);
for (i = 0; i < tft.height(); i += 6) tft.drawLine(0, 0, tft.width() - 1, i, color);
t_end = micros() - start;//exclude clear screen from count
tft.clearScreen();
start = micros();
for (i = 0; i < tft.width(); i += 6) tft.drawLine(tft.width() - 1, 0, i, tft.height() - 1, color);
for (i = 0; i < tft.height(); i += 6) tft.drawLine(tft.width() - 1, 0, 0, i, color);
t_end += micros() - start;
tft.clearScreen();
start = micros();
for (i = 0; i < tft.width(); i += 6) tft.drawLine(0, tft.height() - 1, i, 0, color);
for (i = 0; i < tft.height(); i += 6) tft.drawLine(0, tft.height() - 1, tft.width() - 1, i, color);
t_end += micros() - start;
tft.clearScreen();
start = micros();
for (i = 0; i < tft.width(); i += 6) tft.drawLine(tft.width() - 1, tft.height() - 1, i, 0, color);
for (i = 0; i < tft.height(); i += 6) tft.drawLine(tft.width() - 1, tft.height() - 1, 0, i, color);
t_end += micros() - start;
return t_end;
}
#if !defined(__AVR_ATmega32U4__) && defined(_ILI9163C_DRAWARC)
unsigned long testArc(uint16_t color) {
uint16_t i, cx = tft.width()/2,cy = tft.height()/2;
tft.clearScreen();
start = micros();
for (i = 0; i < 360; i += 5) {
tft.drawArc(cx, cy, 40, 2, 0, i, color);
}
t_end = micros() - start;
return t_end;
}
#endif
unsigned long testFastLines(uint16_t color1, uint16_t color2) {
int16_t i;
tft.clearScreen();
start = micros();
for (i = 0; i < tft.height(); i += 5) tft.drawFastHLine(0, i, tft.width() - 1, color1);
for (i = 0; i < tft.width(); i += 5) tft.drawFastVLine(i, 0, tft.height() - 1, color2);
t_end = micros() - start;
return t_end;
}
unsigned long testRects(uint16_t color) {
int16_t i;
int16_t i2;
int16_t cx = tft.width() / 2;
int16_t cy = tft.height() / 2;
int16_t n = min(tft.width(), tft.height());
tft.clearScreen();
start = micros();
for (i = 2; i < n; i += 6) {
i2 = i / 2;
tft.drawRect(cx - i2, cy - i2, i, i, color);
}
t_end = micros() - start;
return t_end;
}
unsigned long testFilledRects(uint16_t color1, uint16_t color2) {
int n, i, i2,
cx = tft.width() / 2,
cy = tft.height() / 2;
tft.clearScreen();
n = min(tft.width(), tft.height());
t_end = 0;
start = micros();
for (i = 2; i < n; i += 6) {
i2 = i / 2;
tft.fillRect(cx - i2, cy - i2, i, i, color1);
}
t_end = micros() - start;
for (i = 2; i < n; i += 6) {
i2 = i / 2;
tft.drawRect(cx - i2, cy - i2, i, i, color2);
}
return t_end;
}
unsigned long testFilledCircles(uint8_t radius, uint16_t color1) {
int16_t x;
int16_t y;
int16_t r2 = radius * 2;
tft.clearScreen();
start = micros();
for (x = radius; x < tft.width(); x += r2) {
for (y = radius; y < tft.height(); y += r2) {
tft.fillCircle(x, y, radius, color1);
}
}
t_end = micros() - start;
return t_end;
}
unsigned long testCircles(uint8_t radius, uint16_t color) {
int16_t x;
int16_t y;
int16_t r2 = radius * 2;
start = micros();
for (x = 0; x < (tft.width() - radius); x += r2) {
for (y = 0; y < (tft.height() - radius); y += r2) {
tft.drawCircle(x, y, radius, color);
}
}
t_end = micros() - start;
return t_end;
}
unsigned long testTriangles(uint16_t color) {
uint16_t i;
uint16_t cx = (tft.width() / 2) - 1;
uint16_t cy = (tft.height() / 2) - 1;
uint16_t n = min(cx, cy);
tft.clearScreen();
start = micros();
for (i = 0; i < n; i += 5) {
// peak,bottom left,bottom right
tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i, color);
}
t_end = micros() - start;
return t_end;
}
unsigned long testFilledTriangles(uint16_t color1, uint16_t color2) {
uint16_t i;
uint16_t cx = (tft.width() / 2) - 1;
uint16_t cy = (tft.height() / 2) - 1;
uint16_t n = min(cx, cy);
tft.clearScreen();
t_end = 0;
start = micros();
for (i = n; i > 10; i -= 5) {
start = micros();
tft.fillTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i, color1);
t_end += micros() - start;
tft.drawTriangle(cx, cy - i, cx - i, cy + i, cx + i, cy + i, color2);
}
return t_end;
}
unsigned long testFilledRoundRects() {
uint16_t i, d;
tft.clearScreen();
if (tft.getRotation() != 1 && tft.getRotation() != 3) {
d = tft.height() - 1;
} else {
d = tft.width() - 1;
}
start = micros();
for (i = d; i >= 10; i--) {
tft.fillRoundRect(tft.width() / 2 - (i / 2), tft.height() / 2 - (i / 2), i, i, i / 4, tft.htmlTo565(0xFF0000 + i));
}
t_end = micros() - start;
return t_end;
}
unsigned long testRoundRects() {
uint16_t i, d;
tft.clearScreen();
if (tft.getRotation() != 1 && tft.getRotation() != 3) {
d = tft.height() - 1;
} else {
d = tft.width() - 1;
}
start = micros();
for (i = d; i >= 10; i--) {
tft.drawRoundRect(tft.width() / 2 - (i / 2), tft.height() / 2 - (i / 2), i, i, i / 4, random(0xFFFF));
}
t_end = micros() - start;
return t_end;
}
void test(uint8_t rot) {
tft.setRotation(rot);
tft.clearScreen();
tft.setCursor(CENTER,CENTER);
tft.setTextColor(WHITE);
tft.setTextScale(2);
tft.print("Rot:");
tft.print(rot);
tft.setCursor(0, 0);
delay(1000);
Serial.print(F("screen:"));
Serial.print(tft.width());
Serial.print("x");
Serial.print(tft.height());
Serial.print(" - rotation:");
Serial.print(rot);
Serial.println(F("\nBenchmark Time (microseconds)"));
Serial.print(F("Screen fill "));
Serial.println(testFillScreen());
delay(DELAY_BETWEEN);
Serial.print(F("Test Pixel "));
Serial.println(testPixel());
delay(DELAY_BETWEEN);
Serial.print(F("Test Pixels "));
Serial.println(testPixels());
delay(DELAY_BETWEEN);
Serial.print(F("Text "));
Serial.println(testText());
delay(DELAY_BETWEEN);
Serial.print(F("Lines "));
Serial.println(testLines(0x07FF));
delay(DELAY_BETWEEN);
Serial.print(F("Horiz/Vert Lines "));
Serial.println(testFastLines(0xF800, 0x001F));
delay(DELAY_BETWEEN);
Serial.print(F("Rectangles (outline) "));
Serial.println(testRects(0x07E0));
delay(DELAY_BETWEEN);
Serial.print(F("Rectangles (filled) "));
Serial.println(testFilledRects(0xFFE0, 0xF81F));
delay(DELAY_BETWEEN);
#if !defined(__AVR_ATmega32U4__) && defined(_ILI9163C_DRAWARC)
Serial.print(F("Arc "));
Serial.println(testArc(0xF81F));
delay(DELAY_BETWEEN);
#endif
Serial.print(F("Circles (filled) "));
Serial.println(testFilledCircles(10, 0xF81F));
delay(DELAY_BETWEEN);
Serial.print(F("Circles (outline) "));
Serial.println(testCircles(10, WHITE));
delay(DELAY_BETWEEN);
Serial.print(F("Triangles (outline) "));
Serial.println(testTriangles(0x07FF));
delay(DELAY_BETWEEN);
Serial.print(F("Triangles (filled) "));
Serial.println(testFilledTriangles(0xF800, 0x07FF));
delay(DELAY_BETWEEN);
Serial.print(F("Rounded rects (outline) "));
Serial.println(testRoundRects());
delay(DELAY_BETWEEN);
Serial.print(F("Rounded rects (filled) "));
Serial.println(testFilledRoundRects());
delay(DELAY_BETWEEN);
Serial.println(F("--------------------------------\n"));
}
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>VisIdeal2D</title>
<!-- <script type="text/javascript" src="js/d3.v3.js"></script>-->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/BootSideMenu.css" rel="stylesheet">
<link href="css/nouislider.min.css" rel="stylesheet">
<style>
#svgMain {margin-left:auto; margin-right: auto; display:block}
.axis path,
.axis line {
fill: none;
stroke: black;
stroke-width: 2;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
a { cursor: pointer; cursor: hand; }
#canvasElement2d {
background-color: #FFF;
cursor: default;
display:inline;
z-index:2;
padding-bottom: 10px;
}
#canvasElement2d:not(.active):not(.shift) {
cursor: crosshair;
}
/* CSS for sliders */
#charge-slider{
margin: 10px;
display: inline-block;
height: 10px;
width: 120px;
}
#linkdist-slider{
margin: 10px;
display: inline-block;
height: 10px;
width: 120px;
}
.noUi-horizontal .noUi-handle {
width: 24px;
height: 18px;
left: -17px;
top: -6px;
}
.noUi-horizontal {
height: 14px;
}
/* Vertical lines on the handles */
.noUi-handle:before,
.noUi-handle:after {
content: "";
display: block;
position: absolute;
height: 10px;
width: 1px;
background: #E8E7E6;
left: 10px;
top: 3px;
}
.noUi-handle:after {
left: 12px;
}
.noUi-horizontal.noUi-extended {
padding-right: 20px;
}
.noUi-horizontal.noUi-extended .noUi-handle {
left: -2px;
}
.noUi-horizontal.noUi-extended .noUi-origin {
right: -32px;
}
path.link {
fill: none;
stroke: #B6B6B6;
stroke-width: 2px;
cursor: default;
}
#canvasElement2d:not(.active):not(.shift) path.link {
cursor: pointer;
}
path.link.selected {
stroke-dasharray: 10,2;
}
path.link.highlighted {
fill: none;
/* stroke: #B6B6B6; */
stroke: #FF0000;
stroke-width: 4px;
cursor: default;
}
path.link.dragline {
pointer-events: none;
}
path.link.hidden {
stroke-width: 0;
}
circle.node {
stroke-width: 0px;
cursor: pointer;
}
circle.node.reflexive {
stroke: #000 !important;
stroke-width: 2.5px;
}
circle.node.highlighted {
stroke: #000 !important;
stroke-width: 2.5px;
}
text {
font: 12px sans-serif;
pointer-events: none;
}
text.id {
text-anchor: middle;
font-weight: bold;
}
#canvasElement3d {
background-color: #FFF;
cursor: default;
display:none;
z-index: 0;
padding-bottom: 10px;
}
#constructorString {
-o-user-select: text;
-moz-user-select: text;
-webkit-user-select: text;
user-select: text;
z-index: 100;
padding-bottom: 5px;
}
#incString {
-o-user-select: text;
-moz-user-select: text;
-webkit-user-select: text;
user-select: text;
z-index: 100;
padding-bottom: 5px;
}
#adjString {
-o-user-select: text;
-moz-user-select: text;
-webkit-user-select: text;
user-select: text;
z-index: 100;
padding-bottom: 5px;
}
</style>
<script type="text/javascript">
//global variables
curConvex = true;
h = window.innerHeight-10;//600;
w = window.innerWidth-10;//900;
dataset = [[1, 3], [4, 0], [0, 5]];
</script>
</head>
<body>
<div id="side">
<h2>  Menu</h2>
<div class="list-group" id="menuList">
</div>
<a id="convexToggle" href="#" class="list-group-item">Convex Hull: off</a>
<a id="idealGens" href="#" class="list-group-item">Ideal Generators</a>
<!-- we can put these options in later
<a id="exportTikz" href="#" class="list-group-item">Generate TikZ code</a>
<a id="endSession" href="#" class="list-group-item">End session</a>
-->
</div>
</div>
<div class="container">
<div id="canvasElement2d"></div>
</div>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/BootSideMenu.js"></script>
<script src="js/d3.v3.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<!-- <script src="js/clipboard.min.js"></script>
<script src="js/nouislider.min.js"></script>
-->
<script type="text/javascript">
$('#side').BootSideMenu({side:"right", closeOnClick: false, width: "230px"});
$(document).ready(function(){
// display convex hull when clicked
$("#convexToggle").on("click", function(){
if(curConvex) {
$(this).html("Convex Hull: on");
curConvex = !curConvex;
hull.attr("opacity",1);
} else {
$(this).html("Convex Hull: off");
curConvex = !curConvex;
hull.attr("opacity",0);
}
});
// show the ideal generators when clicked
$("#idealGens").on("click", function(){
$(this).html("Ideal Generators: " + labels);
});
});
dataset.sort(function(a,b) {return a[0]-b[0]});
svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w)
.attr("id", "svgMain");
// find largest x and y exponents
xMax = 0;
yMax = 0;
for (i = 0; i < dataset.length; i++) {
if (dataset[i][0] > xMax) {
xMax = dataset[i][0];
}
if (dataset[i][1] > yMax) {
yMax = dataset[i][1];
}
}
// make the lattice go one unit beyond max x and y values
// looks like chart is an array of arrays of 1's
chart = [];
for (i = 0; i < yMax+1; i++) {
chart.push([]);
for (j = 0; j < xMax+1; j++) {
chart[i].push(1);
}
}
// determine the size of each unit square
sq = Math.ceil(Math.min(h/(yMax+2), w/(xMax+2)));
// datum will be a coordinate in the plane and blankout will
// put a 0 in every lattice point above and to the right
var blankOut = function(datum, chart) {
for (i = 0; i < chart.length; i++) {
if (i >= datum[1]) {
for (j = 0; j < chart[0].length; j++) {
if (j >= datum[0]) {
chart[i][j] = 0;
}
}
}
}
return chart;
}
// put 0 in coordinates for elements of ideal
for (k = 0; k < dataset.length; k++) {
chart = blankOut(dataset[k], chart);
}
// the lattice points not in the ideal
var makeDatFromChart = function(chart) {
dat = [];
for (i = 0; i < chart.length; i++) {
for (j = 0; j < chart[0].length; j++) {
if (chart[i][j] === 1) {
dat.push([i, j]);
}
}
}
return dat;
}
// the coordinates of the points not in the ideal
dat = makeDatFromChart(chart);
// i'm not sure but i think the lines we get when switching
// between convex hull are coming from the scale
var xScale = d3.scale.linear();
xScale.domain([0,xMax+1]);
xScale.range([sq/2, (xMax+1.5)*sq]);
var yScale = d3.scale.linear();
yScale.domain([0, yMax+1]);
yScale.range([h-1.5*sq, h-(yMax+2.5)*sq]);
// list of triangles from generator to another generator to
// the point with (x max, y max)
tri = [];
for (i = 0; i < dataset.length-1; i++) {
for(j = i+1; j < dataset.length; j++) {
tri.push(xScale(dataset[i][0]+.01).toString() + "," +
yScale(dataset[i][1]-1).toString() + " " +
xScale(dataset[j][0]+.01).toString() + "," +
yScale(dataset[j][1]-1).toString() + " " +
xScale(Math.max(dataset[i][0]+.01,
dataset[j][0]+.01)).toString() + "," +
yScale(Math.max(dataset[i][1],
dataset[j][1])-1).toString());
}
}
console.log(tri);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(xMax)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.ticks(yMax)
.orient("left");
var latticePoints= [];
for (i = 0; i <= yMax; i++) {
for (j = 1; j <= xMax+1; j++) {
latticePoints.push([i,j]);
}
}
// shades all the squares not in the ideal
ideal = svg.selectAll("rect")
.data(dat)
.enter()
.append("rect")
.attr("x", function(d) { return Math.ceil(xScale(d[1])); })
.attr("y", function(d) { return Math.ceil(yScale(d[0])); })
.attr("width", sq)
.attr("height", sq)
.attr("fill", "#f5deb3");
// shades all the triangles. default is transparent
hull = svg.selectAll("polygon")
.data(tri)
.enter()
.append("polygon")
.attr("points", function(d) { return d; })
.attr("fill", "#FFFFFF")
.attr("opacity", 0);
// shades all the lattice points
lattice = svg.selectAll("circle.lattice")
.data(latticePoints)
.enter()
.append("circle")
.attr("cx", function(d) { return Math.floor(xScale(d[1])); })
.attr("cy", function(d) { return Math.floor(yScale(d[0])); })
.attr("r", 4)
.attr("fill", "#b3caf5");
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h-sq/2) + ")")
.call(xAxis);
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + sq/2 + "," + sq + ")")
.call(yAxis);
var makeXYstring = function(x,y) {
if (x === 0) { xstr = ""; }
else if (x === 1) { xstr = "x"; }
else { xstr = "x<sup>" + x.toString() + "</sup>"; }
if (y === 0) { ystr = ""; }
else if (y === 1) { ystr = "y"; }
else { ystr = "y<sup>" + y.toString() + "</sup>"; }
xystr = xstr + ystr;
return xystr;
}
var labels = []
for (i = 0; i < dataset.length; i++) {
labels.push(makeXYstring(dataset[i][0],dataset[i][1]));
}
var pointsBelow = function (point1, point2, extX, extY) {
if (point1[0] < point2[0]) {
first = point1;
second = point2;
}
else { first = point2; second = point1; }
xMin = first[0];
xMax = second[0];
yMin = 0;
yMax = Math.max(point1[1], point2[1]);
points = []
for (x = xMin; x <= xMax; x++) {
for (y = yMin; y <= yMax; y++) {
t = (x - xMin)/(xMax - xMin);
l = first[1]*(1-t) + second[1]*(t);
if (y < l) { points.push([x,y]); }
}
}
for (x = 0; x < xMin; x++) {
for (y = 0; y <= extY; y++) {
points.push([x,y]);
}
}
for (x = xMax+1; x <= extX; x++) {
for (y = 0; y <= extY; y++) {
points.push([x,y]);
}
}
return points;
}
var comparePoints = function(point1, point2) {
if (point1[0] === point2[0] && point1[1] === point2[1]) { return true; }
else { return false; }
}
extX = 0
extY = 0
for (i = 0; i < dataset.length; i++) {
if (dataset[i][0] > extX) { extX = dataset[i][0]; }
if (dataset[i][1] > extY) { extY = dataset[i][1]; }
}
pointList = []
for (i = 0; i <= extX; i++) {
for (j = 0; j <= extY; j++) {
pointList.push([i,j])
}
}
for (i = 0; i < dataset.length-1; i++) {
for (j = i+1; j < dataset.length; j++) {
pointsUnder = pointsBelow(dataset[i], dataset[j], extX, extY);
newPointList = []
for (a = 0; a < pointsUnder.length; a++) {
for (b = 0; b < pointList.length; b++) {
if (comparePoints(pointsUnder[a], pointList[b])) { newPointList.push(pointsUnder[a]); }
}
}
pointList = newPointList;
}
}
innerLattice = svg.selectAll("circle.inner")
.data(pointList)
.enter()
.append("circle")
.attr("cx", function(d) { return Math.floor(xScale(d[0])); })
.attr("cy", function(d) { return Math.floor(yScale(d[1]-1)); })
.attr("r", 2)
.attr("fill", "#FFFFFF");
</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
//
// RequestEnvironment.swift
// SwiftTalkServerLib
//
// Created by Florian Kugler on 08-02-2019.
//
import Foundation
import Base
import Database
import WebServer
private let sharedCSRF = CSRFToken(UUID(uuidString: "F5F6C2AE-85CB-4989-B0BF-F471CC92E3FF")!)
public struct STRequestEnvironment: RequestEnvironment {
var hashedAssetName: (String) -> String = { $0 }
var resourcePaths: [URL]
public var route: Route
public var session: Session? { return flatten(try? _session.get()) }
private let _connection: Lazy<ConnectionProtocol>
private let _session: Lazy<S?>
public init(route: Route, hashedAssetName: @escaping (String) -> String, buildSession: @escaping () -> S?, connection: Lazy<ConnectionProtocol>, resourcePaths: [URL]) {
self.hashedAssetName = hashedAssetName
self._session = Lazy(buildSession, cleanup: { _ in () })
self.route = route
self._connection = connection
self.resourcePaths = resourcePaths
}
public var csrf: CSRFToken {
return session?.user.data.csrfToken ?? sharedCSRF
}
public func execute<A>(_ query: Query<A>) -> Either<A, Error> {
do {
return try .left(_connection.get().execute(query))
} catch {
return .right(error)
}
}
}
|
{
"pile_set_name": "Github"
}
|
package org.solovyev.common;
import org.junit.Before;
import org.junit.Test;
import java.math.BigInteger;
import static java.lang.Math.pow;
import static java.math.BigInteger.TEN;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.solovyev.common.NumberFormatter.DEFAULT_MAGNITUDE;
import static org.solovyev.common.NumberFormatter.NO_ROUNDING;
public class NumberFormatterTest {
private NumberFormatter numberFormatter;
@Before
public void setUp() throws Exception {
numberFormatter = new NumberFormatter();
}
@Test
public void testEngineeringFormat() throws Exception {
numberFormatter.useEngineeringFormat(5);
assertEquals("0.1", numberFormatter.format(0.1d));
assertEquals("0.01", numberFormatter.format(0.01d));
assertEquals("0.001", numberFormatter.format(0.001d));
assertEquals("5", numberFormatter.format(5d));
assertEquals("5000", numberFormatter.format(5000d));
}
@Test
public void testScientificFormatNoRounding() throws Exception {
numberFormatter.useScientificFormat(DEFAULT_MAGNITUDE);
numberFormatter.setPrecision(NO_ROUNDING);
assertEquals("1", numberFormatter.format(1d));
assertEquals("0.333333333333333", numberFormatter.format(1d / 3));
assertEquals("3.333333333333333E-19", numberFormatter.format(pow(10, -18) / 3));
assertEquals("1.23456789E18", numberFormatter.format(123456789 * pow(10, 10)));
assertEquals("1E-16", numberFormatter.format(pow(10, -16)));
assertEquals("5.999999999999995E18", numberFormatter.format(5999999999999994999d));
testScientificFormat();
}
@Test
public void testScientificFormatWithRounding() throws Exception {
numberFormatter.useScientificFormat(DEFAULT_MAGNITUDE);
numberFormatter.setPrecision(5);
assertEquals("1", numberFormatter.format(1d));
assertEquals("0.33333", numberFormatter.format(1d / 3));
assertEquals("3.33333E-19", numberFormatter.format(pow(10, -18) / 3));
assertEquals("1.23457E18", numberFormatter.format(123456789 * pow(10, 10)));
assertEquals("1E-16", numberFormatter.format(pow(10, -16)));
assertEquals("6E18", numberFormatter.format(5999999999999994999d));
testScientificFormat();
}
@Test
public void testSimpleFormatNoRounding() throws Exception {
numberFormatter.useSimpleFormat();
numberFormatter.setPrecision(NO_ROUNDING);
assertEquals("1", numberFormatter.format(1d));
assertEquals("0.000001", numberFormatter.format(pow(10, -6)));
assertEquals("0.333333333333333", numberFormatter.format(1d / 3));
assertEquals("3.333333333333333E-19", numberFormatter.format(pow(10, -18) / 3));
assertEquals("1234567890000000000", numberFormatter.format(123456789 * pow(10, 10)));
assertEquals("1E-16", numberFormatter.format(pow(10, -16)));
assertEquals("1E-17", numberFormatter.format(pow(10, -17)));
assertEquals("1E-18", numberFormatter.format(pow(10, -18)));
assertEquals("1.5E-18", numberFormatter.format(1.5 * pow(10, -18)));
assertEquals("1E-100", numberFormatter.format(pow(10, -100)));
testSimpleFormat();
}
@Test
public void testSimpleFormatWithRounding() throws Exception {
numberFormatter.useSimpleFormat();
numberFormatter.setPrecision(5);
assertEquals("1", numberFormatter.format(1d));
assertEquals("0", numberFormatter.format(pow(10, -6)));
assertEquals("0.33333", numberFormatter.format(1d / 3));
assertEquals("0", numberFormatter.format(pow(10, -18) / 3));
assertEquals("1234567890000000000", numberFormatter.format(123456789 * pow(10, 10)));
assertEquals("0", numberFormatter.format(pow(10, -16)));
assertEquals("0", numberFormatter.format(pow(10, -17)));
assertEquals("0", numberFormatter.format(pow(10, -18)));
assertEquals("0", numberFormatter.format(1.5 * pow(10, -18)));
assertEquals("0", numberFormatter.format(pow(10, -100)));
testSimpleFormat();
}
// testing simple format with and without rounding
private void testSimpleFormat() {
assertEquals("0.00001", numberFormatter.format(pow(10, -5)));
assertEquals("0.01", numberFormatter.format(3.11 - 3.1));
assertEquals("100", numberFormatter.format(pow(10, 2)));
assertEquals("1", numberFormatter.format(BigInteger.ONE));
assertEquals("1000", numberFormatter.format(BigInteger.valueOf(1000)));
assertEquals("1000000000000000000", numberFormatter.format(pow(10, 18)));
assertEquals("1000000000000000000", numberFormatter.format(BigInteger.valueOf(10).pow(18)));
assertEquals("1E19", numberFormatter.format(pow(10, 19)));
assertEquals("1E19", numberFormatter.format(BigInteger.valueOf(10).pow(19)));
assertEquals("1E20", numberFormatter.format(pow(10, 20)));
assertEquals("1E20", numberFormatter.format(BigInteger.valueOf(10).pow(20)));
assertEquals("1E100", numberFormatter.format(pow(10, 100)));
assertEquals("1E100", numberFormatter.format(BigInteger.valueOf(10).pow(100)));
assertEquals("0.01", numberFormatter.format(pow(10, -2)));
assertEquals("5000000000000000000", numberFormatter.format(5000000000000000000d));
assertEquals("5000000000000000000", numberFormatter.format(BigInteger.valueOf(5000000000000000000L)));
assertEquals("5000000000000000000", numberFormatter.format(5000000000000000001d));
assertEquals("5000000000000000001", numberFormatter.format(BigInteger.valueOf(5000000000000000001L)));
assertEquals("5999999999999994900", numberFormatter.format(5999999999999994999d));
assertEquals("5999999999999994999", numberFormatter.format(BigInteger.valueOf(5999999999999994999L)));
assertEquals("5E19", numberFormatter.format(50000000000000000000d));
assertEquals("5E19", numberFormatter.format(BigInteger.valueOf(5L).multiply(TEN.pow(19))));
assertEquals("5E40", numberFormatter.format(50000000000000000000000000000000000000000d));
assertEquals("5E40", numberFormatter.format(BigInteger.valueOf(5L).multiply(TEN.pow(40))));
}
// testing scientific format with and without rounding
private void testScientificFormat() {
assertEquals("0.00001", numberFormatter.format(pow(10, -5)));
assertEquals("1E-6", numberFormatter.format(pow(10, -6)));
assertEquals("100", numberFormatter.format(pow(10, 2)));
assertEquals("100", numberFormatter.format(TEN.pow(2)));
assertEquals("10000", numberFormatter.format(pow(10, 4)));
assertEquals("10000", numberFormatter.format(TEN.pow(4)));
assertEquals("1E5", numberFormatter.format(pow(10, 5)));
assertEquals("1E5", numberFormatter.format(TEN.pow(5)));
assertEquals("1E18", numberFormatter.format(pow(10, 18)));
assertEquals("1E18", numberFormatter.format(TEN.pow(18)));
assertEquals("1E19", numberFormatter.format(pow(10, 19)));
assertEquals("1E19", numberFormatter.format(TEN.pow( 19)));
assertEquals("1E20", numberFormatter.format(pow(10, 20)));
assertEquals("1E20", numberFormatter.format(TEN.pow(20)));
assertEquals("1E100", numberFormatter.format(pow(10, 100)));
assertEquals("1E100", numberFormatter.format(TEN.pow(100)));
assertEquals("0.01", numberFormatter.format(pow(10, -2)));
assertEquals("1E-17", numberFormatter.format(pow(10, -17)));
assertEquals("1E-18", numberFormatter.format(pow(10, -18)));
assertEquals("1.5E-18", numberFormatter.format(1.5 * pow(10, -18)));
assertEquals("1E-100", numberFormatter.format(pow(10, -100)));
assertEquals("5E18", numberFormatter.format(5000000000000000000d));
assertEquals("5E18", numberFormatter.format(5000000000000000001d));
assertEquals("5E19", numberFormatter.format(50000000000000000000d));
assertEquals("5E40", numberFormatter.format(50000000000000000000000000000000000000000d));
}
@Test
public void testMaximumPrecision() throws Exception {
numberFormatter.useSimpleFormat();
numberFormatter.setPrecision(10);
for (int i = 0; i < 1000; i++) {
for (int j = 2; j < 1000; j += j - 1) {
for (int k = 2; k < 1000; k += k - 1) {
final double first = makeDouble(i, j);
final double second = makeDouble(i, 1000 - k);
checkMaximumPrecision(first + "-" + second, numberFormatter.format(first - second));
checkMaximumPrecision(second + "-" + first, numberFormatter.format(second - first));
checkMaximumPrecision(second + "+" + first, numberFormatter.format(first + second));
}
}
}
}
private void checkMaximumPrecision(String expression, CharSequence value) {
assertTrue(expression + "=" + value, value.length() <= 8);
}
private static double makeDouble(int integerPart, int fractionalPart) {
return Double.parseDouble(integerPart + "." + fractionalPart);
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_selected="true" android:drawable="@drawable/icon_close_mic"/>
<item android:drawable="@drawable/icon_open_mic"/>
</selector>
|
{
"pile_set_name": "Github"
}
|
package template
import (
"fmt"
"reflect"
)
// Tag is a CloudFormation tag
type Tag struct {
Key interface{}
Value interface{}
PropagateAtLaunch string
}
// maybeSetNameTag adds a Name tag to any resource that supports tags
// it calls makeAutoNameTag to format the tag value
func maybeSetNameTag(name string, resource interface{}) {
e := reflect.ValueOf(resource).Elem()
if e.Kind() == reflect.Struct {
f := e.FieldByName("Tags")
if f.IsValid() && f.CanSet() {
tag := reflect.ValueOf(makeAutoNameTag(name))
if f.Type() == reflect.ValueOf([]Tag{}).Type() {
f.Set(reflect.Append(f, tag))
}
}
}
}
// makeAutoNameTag create a new Name tag in the following format:
// {Key: "Name", Value: !Sub "${AWS::StackName}/<logicalResourceName>"}
func makeAutoNameTag(suffix string) Tag {
return Tag{
Key: NewString("Name"),
Value: MakeFnSubString(fmt.Sprintf("${%s}/%s", StackName, suffix)),
}
}
|
{
"pile_set_name": "Github"
}
|
---
- name: Check status of monkeysphere-host
command: monkeysphere-host diagnostics
register: monkeysphere_host_status
changed_when: monkeysphere_host_status.rc != 0
- name: Import SSH host key
command: monkeysphere-host import-key /etc/ssh/ssh_host_rsa_key ssh://{{ ansible_fqdn }}
when: monkeysphere_host_status is defined and
monkeysphere_host_status.stdout.startswith('No host OpenPGP certificates file found!')
# Publish host key at the time of first generation
- name: Publish GPG host certificate to Web of Trust
shell: yes | monkeysphere-host publish-keys
when: monkeysphere_autopublish is defined and
monkeysphere_autopublish and
monkeysphere_host_status is defined and
monkeysphere_host_status.stdout.startswith('No host OpenPGP certificates file found!')
|
{
"pile_set_name": "Github"
}
|
package com.automatak.render.dnp3.objects.groups
import com.automatak.render.dnp3.objects.{ClassData, AnyVariation, ObjectGroup}
object Group60 extends ObjectGroup {
def objects = List(Group60Var1, Group60Var2, Group60Var3, Group60Var4)
def group: Byte = 60
def desc: String = "Class Data"
def isEventGroup: Boolean = false
}
object Group60Var1 extends ClassData(Group60, 1, "Class 0")
object Group60Var2 extends ClassData(Group60, 2, "Class 1")
object Group60Var3 extends ClassData(Group60, 3, "Class 2")
object Group60Var4 extends ClassData(Group60, 4, "Class 3")
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSArray;
@protocol MSPublisher <NSObject>
@property(nonatomic) int publishBatchSize;
@property(nonatomic) id <MSPublisherDelegate> delegate;
- (void)publish;
- (void)stop;
- (void)abort;
- (void)submitAssetCollectionsForPublication:(NSArray *)arg1 skipAssetCollections:(NSArray *)arg2;
- (void)submitAssetCollectionsForPublication:(NSArray *)arg1;
@end
|
{
"pile_set_name": "Github"
}
|
@page
@model SettingsGeneralModel
@{
ViewData["Title"] = "";
}
@section Styles {
<link href="@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)assets/plugins/switchery/css/switchery.min.css" rel="stylesheet" />
}
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">General Settings</h4>
<p>
In this area you may change the settings of your <b>settings.general.json</b> file. Please use this with caution as all settings you saved here will directly affect your PT Magic bot.
</p>
<p class="text-danger">Please note: When you save your settings using this interface, all existing comments will be removed from your settings.general.json!</p>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">Restore Backup<span></span></h4>
<p>
PT Magic automatically creates a backup when you save your settings.general.json file using this interface. In case you notice some suspicious behaviour or just want to go back to your previous settings, you may restore the most recent backup here.
</p>
<button class="btn btn-ptmagic text-uppercase waves-effect waves-light" data-toggle="modal" data-target="#modalRestoreBackup" type="submit">
Restore Backup
</button>
</div>
</div>
</div>
<form class="form-horizontal m-t-20" method="post">
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">Application</h4>
<div class="form-group row">
<label class="col-md-4 col-form-label">Is Enabled <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Enables the PTMagic bot."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Application_IsEnabled" checked="@(Model.PTMagicConfiguration.GeneralSettings.Application.IsEnabled)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Test Mode <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="If TestMode is active, no properties files will be changed"></i></label>
<div class="col-md-8">
<input type="checkbox" name="Application_TestMode" checked="@(Model.PTMagicConfiguration.GeneralSettings.Application.TestMode)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Profit Trailer Major Version <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Major version of your Profit Trailer."></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerMajorVersion
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Profit Trailer Path <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Path to your Profit Trailer main directory."></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerPath
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Profit Trailer License <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Your Profit Trailer license key (needed to change your settings for PT 2.0 and above)"></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GetProfitTrailerLicenseKeyMasked()
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Profit Trailer Monitor URL <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The URL to your profit trailer monitor (needed to change your settings for PT 2.0 and above)"></i></label>
<div class="col-md-8">
<a href="@Model.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerMonitorURL" target="_blank">@Model.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerMonitorURL</a>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Profit Trailer Default Setting Name <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Your Profit Trailer default setting name (needed to change your settings for PT 2.0 and above)"></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GeneralSettings.Application.ProfitTrailerDefaultSettingName
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Exchange <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The exchange your are running Profit Trailer on."></i></label>
<div class="col-md-8">
<select name="Application_Exchange" class="form-control">
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Application.Exchange.Equals("Binance", StringComparison.InvariantCultureIgnoreCase))">Binance</option>
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Application.Exchange.Equals("Bittrex", StringComparison.InvariantCultureIgnoreCase))">Bittrex</option>
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Application.Exchange.Equals("Poloniex", StringComparison.InvariantCultureIgnoreCase))">Poloniex</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Start Balance <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The balance you had in your wallet when you started working with Profit Trailer."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Application_StartBalance" value="@Model.PTMagicConfiguration.GeneralSettings.Application.StartBalance.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Timezone Offset <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Your timezone offset from GMT."></i></label>
<div class="col-md-8">
<select name="Application_TimezoneOffset" class="form-control">
@Html.Raw(Model.GetTimezoneSelection())
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Always Load Default Before Switch <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="If this is enabled, PTMagic will always load default settings before switching to another setting."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Application_AlwaysLoadDefaultBeforeSwitch" checked="@(Model.PTMagicConfiguration.GeneralSettings.Application.AlwaysLoadDefaultBeforeSwitch)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Flood Protection Minutes <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="If a price trend is just zig-zagging around its trigger, you may want to protect your settings from getting switched back and forth every minute."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Application_FloodProtectionMinutes" value="@Model.PTMagicConfiguration.GeneralSettings.Application.FloodProtectionMinutes.ToString()">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Instance Name <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The name of the instance of this bot. This will be used in your monitor and your Telegram messages. In case you are running more than one bot, you may set different names to separate them."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Application_InstanceName" value="@Model.PTMagicConfiguration.GeneralSettings.Application.InstanceName">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">Monitor</h4>
<div class="form-group row">
<label class="col-md-4 col-form-label">Is Password Protected <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Defines if your monitor will be asking to setup a password on its first start."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Monitor_IsPasswordProtected" checked="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.IsPasswordProtected)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Open Browser On Start <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="If active, a browser window will open as soon as you start the monitor."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Monitor_OpenBrowserOnStart" checked="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.OpenBrowserOnStart)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Port <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The port you want to run your monitor on"></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GeneralSettings.Monitor.Port
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">RootUrl <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The root URL of your monitor website"></i></label>
<div class="col-md-8">
@Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Graph Interval Minutes <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The interval for the monitor market trend graph to draw points."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_GraphIntervalMinutes" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.GraphIntervalMinutes.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Graph Max Timeframe Hours <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="This defines the timeframe that your graph for market trends covers."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_GraphMaxTimeframeHours" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.GraphMaxTimeframeHours.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Refresh Seconds <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The refresh interval of your monitor main page."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_RefreshSeconds" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.RefreshSeconds.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Bag AnalyzerRefresh Seconds <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The refresh interval of your monitor bag analyzer page."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_BagAnalyzerRefreshSeconds" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.BagAnalyzerRefreshSeconds.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Buy AnalyzerRefresh Seconds <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The refresh interval of your monitor buy analyzer page."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_BuyAnalyzerRefreshSeconds" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.BuyAnalyzerRefreshSeconds.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Link Platform <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The platform to which the pair name will link if you click on it."></i></label>
<div class="col-md-8">
<select name="Monitor_LinkPlatform" class="form-control">
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.LinkPlatform.Equals("TradingView", StringComparison.InvariantCultureIgnoreCase))">TradingView</option>
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.LinkPlatform.Equals("Exchange", StringComparison.InvariantCultureIgnoreCase))">Exchange</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Top Markets <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The amount of top markets being show in your Sales Analyzer."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxTopMarkets" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxTopMarkets.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Daily Summaries <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The amount of Last Days being shown in your Sales Analyzer."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxDailySummaries" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxDailySummaries.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Monthly Summaries <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The amount of Last Months being shown in your Sales Analyzer."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxMonthlySummaries" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxMonthlySummaries.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Dashboard Buy Entries <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The amount of entries being shown in your dashboard for possible buys."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxDashboardBuyEntries" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBuyEntries.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Dashboard Bag Entries <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The amount of top markets being shown in your dashboard for pairs and dca."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxDashboardBagEntries" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxDashboardBagEntries.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max DCA Pairs <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="The number of pairs (rows) to be shown in your DCA calculator."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Monitor_MaxDCAPairs" value="@Model.PTMagicConfiguration.GeneralSettings.Monitor.MaxDCAPairs.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Default DCA Mode <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Set the default mode of your DCA calculator.."></i></label>
<div class="col-md-8">
<select name="Monitor_DefaultDCAMode" class="form-control">
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.DefaultDCAMode.Equals("Simple", StringComparison.InvariantCultureIgnoreCase))">Simple</option>
<option selected="@(Model.PTMagicConfiguration.GeneralSettings.Monitor.DefaultDCAMode.Equals("Advanced", StringComparison.InvariantCultureIgnoreCase))">Advanced</option>
</select>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">Backup</h4>
<div class="form-group row">
<label class="col-md-4 col-form-label">Is Enabled <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Enables a backup procedure for your properties files. Before every switch PTMagic will backup the current properties."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Backup_IsEnabled" checked="@(Model.PTMagicConfiguration.GeneralSettings.Backup.IsEnabled)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Max Hours <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Max number of hours to keep backup files."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Backup_MaxHours" value="@Model.PTMagicConfiguration.GeneralSettings.Backup.MaxHours.ToString(new System.Globalization.CultureInfo("en-US"))">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="card-box">
<h4 class="m-t-0 header-title">Telegram</h4>
<div class="form-group row">
<label class="col-md-4 col-form-label">Is Enabled <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Enables PT Magic to send Telegram messages."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Telegram_IsEnabled" checked="@(Model.PTMagicConfiguration.GeneralSettings.Telegram.IsEnabled)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Bot Token <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Your Telegram bot token."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Telegram_BotToken" id="Telegram_BotToken" value="@Model.PTMagicConfiguration.GeneralSettings.Telegram.BotToken">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Chat Id <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="Your Telegram Chat ID."></i></label>
<div class="col-md-8">
<input type="text" class="form-control" name="Telegram_ChatId" id="Telegram_ChatId" value="@Model.PTMagicConfiguration.GeneralSettings.Telegram.ChatId">
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label">Silent Mode <i class="fa fa-info-circle text-muted" data-toggle="tooltip" data-placement="top" title="If SilentMode is active, no notification sound or vibration will happen when the bot sends a Telegram message."></i></label>
<div class="col-md-8">
<input type="checkbox" name="Telegram_SilentMode" id="Telegram_SilentMode" checked="@(Model.PTMagicConfiguration.GeneralSettings.Telegram.SilentMode)" data-plugin="switchery" data-color="#81c868" data-size="small" />
</div>
</div>
<div class="form-group row">
<label class="col-md-4 col-form-label"></label>
<div class="col-md-8">
<button id="btn-test-telegram" class="btn btn-ptmagic btn-block text-uppercase waves-effect waves-light">
Send Telegram Test Message
</button>
</div>
</div>
</div>
</div>
</div>
@if (!Model.ValidationMessage.Equals("")) {
<div class="row">
<div class="col-md-12">
<div class="card-box text-danger">
@Model.ValidationMessage
</div>
</div>
</div>
}
<div class="row">
<div class="col-md-12">
<div class="card-box">
<a class="btn btn-ptmagic btn-block text-uppercase waves-effect waves-light" data-toggle="modal" data-target="#modalSaveSettings" href="#">
Save Settings
</a>
</div>
</div>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="modalRestoreBackup" tabindex="-1" role="dialog" aria-labelledby="modalRestoreBackupTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalRestoreBackupTitle">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you really want to restore a backup of your settings.general.json and overwrite all current settings?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-ptmagic text-uppercase waves-effect waves-light btn-restorebackup" data-datatarget="settings.general.json">Yes, do it!</button>
<button type="button" class="btn btn-secondary text-uppercase" data-dismiss="modal">No...</button>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="modalSaveSettings" tabindex="-1" role="dialog" aria-labelledby="modalSaveSettingsTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalSaveSettingsTitle">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you really want to save the current settings?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-ptmagic text-uppercase waves-effect waves-light btn-savesettings">Yes, do it!</button>
<button type="button" class="btn btn-secondary text-uppercase" data-dismiss="modal">No...</button>
</div>
</div>
</div>
</div>
@section Scripts {
<script src="@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)assets/plugins/switchery/js/switchery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
$('.text-autocolor').autocolor(false);
$('#btn-test-telegram').click(function () {
var telegramSettings = { Telegram_BotToken: $('#Telegram_BotToken').val(), Telegram_ChatId: $('#Telegram_ChatId').val(), Telegram_SilentMode: $('#Telegram_SilentMode').val() };
$.ajax({
type: 'POST',
url: "@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)_post/TestTelegram",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(telegramSettings),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
$.Notification.notify('success', 'top left', 'Telegram message sent!', 'Telegram test message sent successfully.');
},
error: function (jqxhr, errorText, thrownError) {
$.Notification.notify('error', 'top left', 'Error sending Telegram message!', 'Error message: ' + errorText);
}
});
return false;
});
$(document).on('click', '.btn-savesettings', function () {
$('form').submit();
});
$('.btn-restorebackup').click(function () {
var dataTarget = $(this).data('datatarget');
var postValues = { File: dataTarget };
$.ajax({
type: 'POST',
url: "@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)_post/RestoreBackup",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(postValues),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
window.location.replace("@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)SettingsGeneral?n=BackupRestored");
},
error: function (jqxhr, errorText, thrownError) {
$.Notification.notify('error', 'top left', 'Error restoring backup!', 'Error message: ' + errorText);
}
});
return false;
});
@if (!Model.NotifyType.Equals("") && !Model.NotifyHeadline.Equals("") && !Model.NotifyMessage.Equals("")) {
<text>
$.Notification.notify('@Model.NotifyType', 'top left', '@Model.NotifyHeadline', '@Model.NotifyMessage');
window.history.pushState('@Model.PTMagicConfiguration.GeneralSettings.Application.InstanceName Monitor', '@Model.PTMagicConfiguration.GeneralSettings.Application.InstanceName Monitor', '@Html.Raw(Model.PTMagicConfiguration.GeneralSettings.Monitor.RootUrl)SettingsGeneral');
</text>
}
});
</script>
}
|
{
"pile_set_name": "Github"
}
|
{
"description": "ClusterRole is a cluster level, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding or ClusterRoleBinding.",
"required": [
"rules"
],
"properties": {
"aggregationRule": {
"description": "AggregationRule is an optional field that describes how to build the Rules for this ClusterRole. If AggregationRule is set, then the Rules are controller managed and direct changes to Rules will be stomped by the controller.",
"$ref": "_definitions.json#/definitions/io.k8s.api.rbac.v1alpha1.AggregationRule"
},
"apiVersion": {
"description": "APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources",
"type": [
"string",
"null"
],
"enum": [
"rbac.authorization.k8s.io/v1alpha1"
]
},
"kind": {
"description": "Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
"type": [
"string",
"null"
],
"enum": [
"ClusterRole"
]
},
"metadata": {
"description": "Standard object's metadata.",
"$ref": "_definitions.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta"
},
"rules": {
"description": "Rules holds all the PolicyRules for this ClusterRole",
"type": [
"array",
"null"
],
"items": {
"$ref": "_definitions.json#/definitions/io.k8s.api.rbac.v1alpha1.PolicyRule"
}
}
},
"x-kubernetes-group-version-kind": [
{
"group": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"version": "v1alpha1"
}
],
"$schema": "http://json-schema.org/schema#",
"type": "object"
}
|
{
"pile_set_name": "Github"
}
|
-- Test basic TRUNCATE functionality.
CREATE TABLE truncate_a (col1 integer primary key);
INSERT INTO truncate_a VALUES (1);
INSERT INTO truncate_a VALUES (2);
SELECT * FROM truncate_a;
col1
------
1
2
(2 rows)
-- Roll truncate back
BEGIN;
TRUNCATE truncate_a;
ROLLBACK;
SELECT * FROM truncate_a;
col1
------
1
2
(2 rows)
-- Commit the truncate this time
BEGIN;
TRUNCATE truncate_a;
COMMIT;
SELECT * FROM truncate_a;
col1
------
(0 rows)
-- Test foreign-key checks
CREATE TABLE trunc_b (a int REFERENCES truncate_a);
CREATE TABLE trunc_c (a serial PRIMARY KEY);
CREATE TABLE trunc_d (a int REFERENCES trunc_c);
CREATE TABLE trunc_e (a int REFERENCES truncate_a, b int REFERENCES trunc_c);
TRUNCATE TABLE truncate_a; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_b" references "truncate_a".
HINT: Truncate table "trunc_b" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE truncate_a,trunc_b; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_e" references "truncate_a".
HINT: Truncate table "trunc_e" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE truncate_a,trunc_b,trunc_e; -- ok
TRUNCATE TABLE truncate_a,trunc_e; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_b" references "truncate_a".
HINT: Truncate table "trunc_b" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_d" references "trunc_c".
HINT: Truncate table "trunc_d" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,trunc_d; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_e" references "trunc_c".
HINT: Truncate table "trunc_e" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,trunc_d,trunc_e; -- ok
TRUNCATE TABLE trunc_c,trunc_d,trunc_e,truncate_a; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_b" references "truncate_a".
HINT: Truncate table "trunc_b" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,trunc_d,trunc_e,truncate_a,trunc_b; -- ok
TRUNCATE TABLE truncate_a RESTRICT; -- fail
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_b" references "truncate_a".
HINT: Truncate table "trunc_b" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE truncate_a CASCADE; -- ok
NOTICE: truncate cascades to table "trunc_b"
NOTICE: truncate cascades to table "trunc_e"
-- circular references
ALTER TABLE truncate_a ADD FOREIGN KEY (col1) REFERENCES trunc_c;
-- Add some data to verify that truncating actually works ...
INSERT INTO trunc_c VALUES (1);
INSERT INTO truncate_a VALUES (1);
INSERT INTO trunc_b VALUES (1);
INSERT INTO trunc_d VALUES (1);
INSERT INTO trunc_e VALUES (1,1);
TRUNCATE TABLE trunc_c;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "truncate_a" references "trunc_c".
HINT: Truncate table "truncate_a" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,truncate_a;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_d" references "trunc_c".
HINT: Truncate table "trunc_d" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,truncate_a,trunc_d;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_e" references "trunc_c".
HINT: Truncate table "trunc_e" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,truncate_a,trunc_d,trunc_e;
ERROR: cannot truncate a table referenced in a foreign key constraint
DETAIL: Table "trunc_b" references "truncate_a".
HINT: Truncate table "trunc_b" at the same time, or use TRUNCATE ... CASCADE.
TRUNCATE TABLE trunc_c,truncate_a,trunc_d,trunc_e,trunc_b;
-- Verify that truncating did actually work
SELECT * FROM truncate_a
UNION ALL
SELECT * FROM trunc_c
UNION ALL
SELECT * FROM trunc_b
UNION ALL
SELECT * FROM trunc_d;
col1
------
(0 rows)
SELECT * FROM trunc_e;
a | b
---+---
(0 rows)
-- Add data again to test TRUNCATE ... CASCADE
INSERT INTO trunc_c VALUES (1);
INSERT INTO truncate_a VALUES (1);
INSERT INTO trunc_b VALUES (1);
INSERT INTO trunc_d VALUES (1);
INSERT INTO trunc_e VALUES (1,1);
TRUNCATE TABLE trunc_c CASCADE; -- ok
NOTICE: truncate cascades to table "truncate_a"
NOTICE: truncate cascades to table "trunc_d"
NOTICE: truncate cascades to table "trunc_e"
NOTICE: truncate cascades to table "trunc_b"
SELECT * FROM truncate_a
UNION ALL
SELECT * FROM trunc_c
UNION ALL
SELECT * FROM trunc_b
UNION ALL
SELECT * FROM trunc_d;
col1
------
(0 rows)
SELECT * FROM trunc_e;
a | b
---+---
(0 rows)
DROP TABLE truncate_a,trunc_c,trunc_b,trunc_d,trunc_e CASCADE;
-- Test TRUNCATE with inheritance
CREATE TABLE trunc_f (col1 integer primary key);
INSERT INTO trunc_f VALUES (1);
INSERT INTO trunc_f VALUES (2);
CREATE TABLE trunc_fa (col2a text) INHERITS (trunc_f);
INSERT INTO trunc_fa VALUES (3, 'three');
CREATE TABLE trunc_fb (col2b int) INHERITS (trunc_f);
INSERT INTO trunc_fb VALUES (4, 444);
CREATE TABLE trunc_faa (col3 text) INHERITS (trunc_fa);
INSERT INTO trunc_faa VALUES (5, 'five', 'FIVE');
BEGIN;
SELECT * FROM trunc_f;
col1
------
1
2
3
4
5
(5 rows)
TRUNCATE trunc_f;
SELECT * FROM trunc_f;
col1
------
(0 rows)
ROLLBACK;
BEGIN;
SELECT * FROM trunc_f;
col1
------
1
2
3
4
5
(5 rows)
TRUNCATE ONLY trunc_f;
SELECT * FROM trunc_f;
col1
------
3
4
5
(3 rows)
ROLLBACK;
BEGIN;
SELECT * FROM trunc_f;
col1
------
1
2
3
4
5
(5 rows)
SELECT * FROM trunc_fa;
col1 | col2a
------+-------
3 | three
5 | five
(2 rows)
SELECT * FROM trunc_faa;
col1 | col2a | col3
------+-------+------
5 | five | FIVE
(1 row)
TRUNCATE ONLY trunc_fb, ONLY trunc_fa;
SELECT * FROM trunc_f;
col1
------
1
2
5
(3 rows)
SELECT * FROM trunc_fa;
col1 | col2a
------+-------
5 | five
(1 row)
SELECT * FROM trunc_faa;
col1 | col2a | col3
------+-------+------
5 | five | FIVE
(1 row)
ROLLBACK;
BEGIN;
SELECT * FROM trunc_f;
col1
------
1
2
3
4
5
(5 rows)
SELECT * FROM trunc_fa;
col1 | col2a
------+-------
3 | three
5 | five
(2 rows)
SELECT * FROM trunc_faa;
col1 | col2a | col3
------+-------+------
5 | five | FIVE
(1 row)
TRUNCATE ONLY trunc_fb, trunc_fa;
SELECT * FROM trunc_f;
col1
------
1
2
(2 rows)
SELECT * FROM trunc_fa;
col1 | col2a
------+-------
(0 rows)
SELECT * FROM trunc_faa;
col1 | col2a | col3
------+-------+------
(0 rows)
ROLLBACK;
DROP TABLE trunc_f CASCADE;
NOTICE: drop cascades to 3 other objects
DETAIL: drop cascades to table trunc_fa
drop cascades to table trunc_faa
drop cascades to table trunc_fb
-- Test ON TRUNCATE triggers
CREATE TABLE trunc_trigger_test (f1 int, f2 text, f3 text);
CREATE TABLE trunc_trigger_log (tgop text, tglevel text, tgwhen text,
tgargv text, tgtable name, rowcount bigint);
CREATE FUNCTION trunctrigger() RETURNS trigger as $$
declare c bigint;
begin
execute 'select count(*) from ' || quote_ident(tg_table_name) into c;
insert into trunc_trigger_log values
(TG_OP, TG_LEVEL, TG_WHEN, TG_ARGV[0], tg_table_name, c);
return null;
end;
$$ LANGUAGE plpgsql;
-- basic before trigger
INSERT INTO trunc_trigger_test VALUES(1, 'foo', 'bar'), (2, 'baz', 'quux');
CREATE TRIGGER t
BEFORE TRUNCATE ON trunc_trigger_test
FOR EACH STATEMENT
EXECUTE PROCEDURE trunctrigger('before trigger truncate');
SELECT count(*) as "Row count in test table" FROM trunc_trigger_test;
Row count in test table
-------------------------
2
(1 row)
SELECT * FROM trunc_trigger_log;
tgop | tglevel | tgwhen | tgargv | tgtable | rowcount
------+---------+--------+--------+---------+----------
(0 rows)
TRUNCATE trunc_trigger_test;
SELECT count(*) as "Row count in test table" FROM trunc_trigger_test;
Row count in test table
-------------------------
0
(1 row)
SELECT * FROM trunc_trigger_log;
tgop | tglevel | tgwhen | tgargv | tgtable | rowcount
----------+-----------+--------+-------------------------+--------------------+----------
TRUNCATE | STATEMENT | BEFORE | before trigger truncate | trunc_trigger_test | 2
(1 row)
DROP TRIGGER t ON trunc_trigger_test;
truncate trunc_trigger_log;
-- same test with an after trigger
INSERT INTO trunc_trigger_test VALUES(1, 'foo', 'bar'), (2, 'baz', 'quux');
CREATE TRIGGER tt
AFTER TRUNCATE ON trunc_trigger_test
FOR EACH STATEMENT
EXECUTE PROCEDURE trunctrigger('after trigger truncate');
SELECT count(*) as "Row count in test table" FROM trunc_trigger_test;
Row count in test table
-------------------------
2
(1 row)
SELECT * FROM trunc_trigger_log;
tgop | tglevel | tgwhen | tgargv | tgtable | rowcount
------+---------+--------+--------+---------+----------
(0 rows)
TRUNCATE trunc_trigger_test;
SELECT count(*) as "Row count in test table" FROM trunc_trigger_test;
Row count in test table
-------------------------
0
(1 row)
SELECT * FROM trunc_trigger_log;
tgop | tglevel | tgwhen | tgargv | tgtable | rowcount
----------+-----------+--------+------------------------+--------------------+----------
TRUNCATE | STATEMENT | AFTER | after trigger truncate | trunc_trigger_test | 0
(1 row)
DROP TABLE trunc_trigger_test;
DROP TABLE trunc_trigger_log;
DROP FUNCTION trunctrigger();
-- test TRUNCATE ... RESTART IDENTITY
CREATE SEQUENCE truncate_a_id1 START WITH 33;
CREATE TABLE truncate_a (id serial,
id1 integer default nextval('truncate_a_id1'));
ALTER SEQUENCE truncate_a_id1 OWNED BY truncate_a.id1;
INSERT INTO truncate_a DEFAULT VALUES;
INSERT INTO truncate_a DEFAULT VALUES;
SELECT * FROM truncate_a;
id | id1
----+-----
1 | 33
2 | 34
(2 rows)
TRUNCATE truncate_a;
INSERT INTO truncate_a DEFAULT VALUES;
INSERT INTO truncate_a DEFAULT VALUES;
SELECT * FROM truncate_a;
id | id1
----+-----
3 | 35
4 | 36
(2 rows)
TRUNCATE truncate_a RESTART IDENTITY;
INSERT INTO truncate_a DEFAULT VALUES;
INSERT INTO truncate_a DEFAULT VALUES;
SELECT * FROM truncate_a;
id | id1
----+-----
1 | 33
2 | 34
(2 rows)
-- check rollback of a RESTART IDENTITY operation
BEGIN;
TRUNCATE truncate_a RESTART IDENTITY;
INSERT INTO truncate_a DEFAULT VALUES;
SELECT * FROM truncate_a;
id | id1
----+-----
1 | 33
(1 row)
ROLLBACK;
INSERT INTO truncate_a DEFAULT VALUES;
INSERT INTO truncate_a DEFAULT VALUES;
SELECT * FROM truncate_a;
id | id1
----+-----
1 | 33
2 | 34
3 | 35
4 | 36
(4 rows)
DROP TABLE truncate_a;
SELECT nextval('truncate_a_id1'); -- fail, seq should have been dropped
ERROR: relation "truncate_a_id1" does not exist
LINE 1: SELECT nextval('truncate_a_id1');
^
|
{
"pile_set_name": "Github"
}
|
<workspace name="spi_slave">
<project device="EFM32LG990F256"
name="EFM32LG_spi_slave_polled">
<targets>
<name>slsproj</name>
<name>iar</name>
</targets>
<directories>
<cmsis>$PROJ_DIR$\..\..\..\..\..\platform\CMSIS</cmsis>
<device>$PROJ_DIR$\..\..\..\..\..\platform\Device\SiliconLabs</device>
<emlib>$PROJ_DIR$\..\..\..\..\..\platform\emlib</emlib>
<drivers>$PROJ_DIR$\..\..\..\..\..\hardware\kit\common\drivers</drivers>
<bsp>$PROJ_DIR$\..\..\..\..\..\hardware\kit\common\bsp</bsp>
<kitconfig>$PROJ_DIR$\..\..\..\..\..\hardware\kit\EFM32LG_STK3600\config</kitconfig>
</directories>
<includepaths>
<path>##em-path-cmsis##\Include</path>
<path>##em-path-device##\EFM32LG\Include</path>
<path>##em-path-emlib##\inc</path>
<path>##em-path-kitconfig##</path>
<path>##em-path-bsp##</path>
<path>##em-path-drivers##</path>
</includepaths>
<group name="CMSIS">
<source>##em-path-device##\EFM32LG\Source\$IDE$\startup_efm32lg.s</source>
<source>##em-path-device##\EFM32LG\Source\system_efm32lg.c</source>
</group>
<group name="emlib">
<source>##em-path-emlib##\src\em_system.c</source>
<source>##em-path-emlib##\src\em_core.c</source>
<source>##em-path-emlib##\src\em_cmu.c</source>
<source>##em-path-emlib##\src\em_gpio.c</source>
<source>##em-path-emlib##\src\em_usart.c</source>
</group>
<group name="Source">
<source>$PROJ_DIR$\..\src\main_s0_g_gg_wg_lg.c</source>
<source>$PROJ_DIR$\..\readme_g_gg_wg_lg.txt</source>
</group>
</project>
</workspace>
|
{
"pile_set_name": "Github"
}
|
require('../../modules/es7.object.define-getter');
module.exports = require('../../modules/_core').Object.__defineGetter__;
|
{
"pile_set_name": "Github"
}
|
package xgb
// Sync sends a round trip request and waits for the response.
// This forces all pending cookies to be dealt with.
// You actually shouldn't need to use this like you might with Xlib. Namely,
// buffers are automatically flushed using Go's channels and round trip requests
// are forced where appropriate automatically.
func (c *Conn) Sync() {
cookie := c.NewCookie(true, true)
c.NewRequest(c.getInputFocusRequest(), cookie)
cookie.Reply() // wait for the buffer to clear
}
// getInputFocusRequest writes the raw bytes to a buffer.
// It is duplicated from xproto/xproto.go.
func (c *Conn) getInputFocusRequest() []byte {
size := 4
b := 0
buf := make([]byte, size)
buf[b] = 43 // request opcode
b += 1
b += 1 // padding
Put16(buf[b:], uint16(size/4)) // write request size in 4-byte units
b += 2
return buf
}
|
{
"pile_set_name": "Github"
}
|
(ns garden.def-test
(:require [garden.def :refer [defcssfn defkeyframes defrule]]
[clojure.test :refer :all])
(:import garden.types.CSSFunction
garden.types.CSSAtRule))
(defrule a)
(defrule sub-headings :h4 :h5 :h6)
(deftest defrule-test
(testing "defrule"
(is (= (a {:font-weight "bold"})
[:a {:font-weight "bold"}]))
(is (= (sub-headings {:font-weight "normal"})
[:h4 :h5 :h6 {:font-weight "normal"}]))))
(defcssfn bar)
(defcssfn foo
"LOL"
([x] x)
([x y] [x y]))
(deftest defcssfn-test
(is (instance? CSSFunction (bar 1)))
(is (= (:args (bar 1))
'(1)))
(is (= (:args (foo 1))
1))
(is (= (:args (foo 1 2))
[1 2]))
(is (= (:doc (meta #'foo))
"LOL"))
(is (= (:arglists (meta #'foo))
'([x] [x y]))))
(defkeyframes fade-out
[:from {:opacity 1}]
[:to {:opacity 0}])
(deftest defkeyframes-test
(is (instance? CSSAtRule fade-out))
(is (= :keyframes (:identifier fade-out)))
(is (= "fade-out" (get-in fade-out [:value :identifier]))))
|
{
"pile_set_name": "Github"
}
|
/* SCTP kernel implementation
* (C) Copyright 2007 Hewlett-Packard Development Company, L.P.
*
* This file is part of the SCTP kernel implementation
*
* This SCTP implementation is free software;
* you can redistribute it and/or modify it under the terms of
* the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This SCTP implementation is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied
* ************************
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU CC; see the file COPYING. If not, write to
* the Free Software Foundation, 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Please send any bug reports or fixes you make to the
* email address(es):
* lksctp developers <lksctp-developers@lists.sourceforge.net>
*
* Or submit a bug report through the following website:
* http://www.sf.net/projects/lksctp
*
* Written or modified by:
* Vlad Yasevich <vladislav.yasevich@hp.com>
*
* Any bugs reported given to us we will try to fix... any fixes shared will
* be incorporated into the next SCTP release.
*/
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/crypto.h>
#include <linux/scatterlist.h>
#include <net/sctp/sctp.h>
#include <net/sctp/auth.h>
static struct sctp_hmac sctp_hmac_list[SCTP_AUTH_NUM_HMACS] = {
{
/* id 0 is reserved. as all 0 */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_0,
},
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA1,
.hmac_name="hmac(sha1)",
.hmac_len = SCTP_SHA1_SIG_SIZE,
},
{
/* id 2 is reserved as well */
.hmac_id = SCTP_AUTH_HMAC_ID_RESERVED_2,
},
#if defined (CONFIG_CRYPTO_SHA256) || defined (CONFIG_CRYPTO_SHA256_MODULE)
{
.hmac_id = SCTP_AUTH_HMAC_ID_SHA256,
.hmac_name="hmac(sha256)",
.hmac_len = SCTP_SHA256_SIG_SIZE,
}
#endif
};
void sctp_auth_key_put(struct sctp_auth_bytes *key)
{
if (!key)
return;
if (atomic_dec_and_test(&key->refcnt)) {
kfree(key);
SCTP_DBG_OBJCNT_DEC(keys);
}
}
/* Create a new key structure of a given length */
static struct sctp_auth_bytes *sctp_auth_create_key(__u32 key_len, gfp_t gfp)
{
struct sctp_auth_bytes *key;
/* Verify that we are not going to overflow INT_MAX */
if ((INT_MAX - key_len) < sizeof(struct sctp_auth_bytes))
return NULL;
/* Allocate the shared key */
key = kmalloc(sizeof(struct sctp_auth_bytes) + key_len, gfp);
if (!key)
return NULL;
key->len = key_len;
atomic_set(&key->refcnt, 1);
SCTP_DBG_OBJCNT_INC(keys);
return key;
}
/* Create a new shared key container with a give key id */
struct sctp_shared_key *sctp_auth_shkey_create(__u16 key_id, gfp_t gfp)
{
struct sctp_shared_key *new;
/* Allocate the shared key container */
new = kzalloc(sizeof(struct sctp_shared_key), gfp);
if (!new)
return NULL;
INIT_LIST_HEAD(&new->key_list);
new->key_id = key_id;
return new;
}
/* Free the shared key stucture */
static void sctp_auth_shkey_free(struct sctp_shared_key *sh_key)
{
BUG_ON(!list_empty(&sh_key->key_list));
sctp_auth_key_put(sh_key->key);
sh_key->key = NULL;
kfree(sh_key);
}
/* Destory the entire key list. This is done during the
* associon and endpoint free process.
*/
void sctp_auth_destroy_keys(struct list_head *keys)
{
struct sctp_shared_key *ep_key;
struct sctp_shared_key *tmp;
if (list_empty(keys))
return;
key_for_each_safe(ep_key, tmp, keys) {
list_del_init(&ep_key->key_list);
sctp_auth_shkey_free(ep_key);
}
}
/* Compare two byte vectors as numbers. Return values
* are:
* 0 - vectors are equal
* < 0 - vector 1 is smaller than vector2
* > 0 - vector 1 is greater than vector2
*
* Algorithm is:
* This is performed by selecting the numerically smaller key vector...
* If the key vectors are equal as numbers but differ in length ...
* the shorter vector is considered smaller
*
* Examples (with small values):
* 000123456789 > 123456789 (first number is longer)
* 000123456789 < 234567891 (second number is larger numerically)
* 123456789 > 2345678 (first number is both larger & longer)
*/
static int sctp_auth_compare_vectors(struct sctp_auth_bytes *vector1,
struct sctp_auth_bytes *vector2)
{
int diff;
int i;
const __u8 *longer;
diff = vector1->len - vector2->len;
if (diff) {
longer = (diff > 0) ? vector1->data : vector2->data;
/* Check to see if the longer number is
* lead-zero padded. If it is not, it
* is automatically larger numerically.
*/
for (i = 0; i < abs(diff); i++ ) {
if (longer[i] != 0)
return diff;
}
}
/* lengths are the same, compare numbers */
return memcmp(vector1->data, vector2->data, vector1->len);
}
/*
* Create a key vector as described in SCTP-AUTH, Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
static struct sctp_auth_bytes *sctp_auth_make_key_vector(
sctp_random_param_t *random,
sctp_chunks_param_t *chunks,
sctp_hmac_algo_param_t *hmacs,
gfp_t gfp)
{
struct sctp_auth_bytes *new;
__u32 len;
__u32 offset = 0;
len = ntohs(random->param_hdr.length) + ntohs(hmacs->param_hdr.length);
if (chunks)
len += ntohs(chunks->param_hdr.length);
new = kmalloc(sizeof(struct sctp_auth_bytes) + len, gfp);
if (!new)
return NULL;
new->len = len;
memcpy(new->data, random, ntohs(random->param_hdr.length));
offset += ntohs(random->param_hdr.length);
if (chunks) {
memcpy(new->data + offset, chunks,
ntohs(chunks->param_hdr.length));
offset += ntohs(chunks->param_hdr.length);
}
memcpy(new->data + offset, hmacs, ntohs(hmacs->param_hdr.length));
return new;
}
/* Make a key vector based on our local parameters */
static struct sctp_auth_bytes *sctp_auth_make_local_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(
(sctp_random_param_t*)asoc->c.auth_random,
(sctp_chunks_param_t*)asoc->c.auth_chunks,
(sctp_hmac_algo_param_t*)asoc->c.auth_hmacs,
gfp);
}
/* Make a key vector based on peer's parameters */
static struct sctp_auth_bytes *sctp_auth_make_peer_vector(
const struct sctp_association *asoc,
gfp_t gfp)
{
return sctp_auth_make_key_vector(asoc->peer.peer_random,
asoc->peer.peer_chunks,
asoc->peer.peer_hmacs,
gfp);
}
/* Set the value of the association shared key base on the parameters
* given. The algorithm is:
* From the endpoint pair shared keys and the key vectors the
* association shared keys are computed. This is performed by selecting
* the numerically smaller key vector and concatenating it to the
* endpoint pair shared key, and then concatenating the numerically
* larger key vector to that. The result of the concatenation is the
* association shared key.
*/
static struct sctp_auth_bytes *sctp_auth_asoc_set_secret(
struct sctp_shared_key *ep_key,
struct sctp_auth_bytes *first_vector,
struct sctp_auth_bytes *last_vector,
gfp_t gfp)
{
struct sctp_auth_bytes *secret;
__u32 offset = 0;
__u32 auth_len;
auth_len = first_vector->len + last_vector->len;
if (ep_key->key)
auth_len += ep_key->key->len;
secret = sctp_auth_create_key(auth_len, gfp);
if (!secret)
return NULL;
if (ep_key->key) {
memcpy(secret->data, ep_key->key->data, ep_key->key->len);
offset += ep_key->key->len;
}
memcpy(secret->data + offset, first_vector->data, first_vector->len);
offset += first_vector->len;
memcpy(secret->data + offset, last_vector->data, last_vector->len);
return secret;
}
/* Create an association shared key. Follow the algorithm
* described in SCTP-AUTH, Section 6.1
*/
static struct sctp_auth_bytes *sctp_auth_asoc_create_secret(
const struct sctp_association *asoc,
struct sctp_shared_key *ep_key,
gfp_t gfp)
{
struct sctp_auth_bytes *local_key_vector;
struct sctp_auth_bytes *peer_key_vector;
struct sctp_auth_bytes *first_vector,
*last_vector;
struct sctp_auth_bytes *secret = NULL;
int cmp;
/* Now we need to build the key vectors
* SCTP-AUTH , Section 6.1
* The RANDOM parameter, the CHUNKS parameter and the HMAC-ALGO
* parameter sent by each endpoint are concatenated as byte vectors.
* These parameters include the parameter type, parameter length, and
* the parameter value, but padding is omitted; all padding MUST be
* removed from this concatenation before proceeding with further
* computation of keys. Parameters which were not sent are simply
* omitted from the concatenation process. The resulting two vectors
* are called the two key vectors.
*/
local_key_vector = sctp_auth_make_local_vector(asoc, gfp);
peer_key_vector = sctp_auth_make_peer_vector(asoc, gfp);
if (!peer_key_vector || !local_key_vector)
goto out;
/* Figure out the order in wich the key_vectors will be
* added to the endpoint shared key.
* SCTP-AUTH, Section 6.1:
* This is performed by selecting the numerically smaller key
* vector and concatenating it to the endpoint pair shared
* key, and then concatenating the numerically larger key
* vector to that. If the key vectors are equal as numbers
* but differ in length, then the concatenation order is the
* endpoint shared key, followed by the shorter key vector,
* followed by the longer key vector. Otherwise, the key
* vectors are identical, and may be concatenated to the
* endpoint pair key in any order.
*/
cmp = sctp_auth_compare_vectors(local_key_vector,
peer_key_vector);
if (cmp < 0) {
first_vector = local_key_vector;
last_vector = peer_key_vector;
} else {
first_vector = peer_key_vector;
last_vector = local_key_vector;
}
secret = sctp_auth_asoc_set_secret(ep_key, first_vector, last_vector,
gfp);
out:
kfree(local_key_vector);
kfree(peer_key_vector);
return secret;
}
/*
* Populate the association overlay list with the list
* from the endpoint.
*/
int sctp_auth_asoc_copy_shkeys(const struct sctp_endpoint *ep,
struct sctp_association *asoc,
gfp_t gfp)
{
struct sctp_shared_key *sh_key;
struct sctp_shared_key *new;
BUG_ON(!list_empty(&asoc->endpoint_shared_keys));
key_for_each(sh_key, &ep->endpoint_shared_keys) {
new = sctp_auth_shkey_create(sh_key->key_id, gfp);
if (!new)
goto nomem;
new->key = sh_key->key;
sctp_auth_key_hold(new->key);
list_add(&new->key_list, &asoc->endpoint_shared_keys);
}
return 0;
nomem:
sctp_auth_destroy_keys(&asoc->endpoint_shared_keys);
return -ENOMEM;
}
/* Public interface to creat the association shared key.
* See code above for the algorithm.
*/
int sctp_auth_asoc_init_active_key(struct sctp_association *asoc, gfp_t gfp)
{
struct sctp_auth_bytes *secret;
struct sctp_shared_key *ep_key;
/* If we don't support AUTH, or peer is not capable
* we don't need to do anything.
*/
if (!sctp_auth_enable || !asoc->peer.auth_capable)
return 0;
/* If the key_id is non-zero and we couldn't find an
* endpoint pair shared key, we can't compute the
* secret.
* For key_id 0, endpoint pair shared key is a NULL key.
*/
ep_key = sctp_auth_get_shkey(asoc, asoc->active_key_id);
BUG_ON(!ep_key);
secret = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!secret)
return -ENOMEM;
sctp_auth_key_put(asoc->asoc_shared_key);
asoc->asoc_shared_key = secret;
return 0;
}
/* Find the endpoint pair shared key based on the key_id */
struct sctp_shared_key *sctp_auth_get_shkey(
const struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
/* First search associations set of endpoint pair shared keys */
key_for_each(key, &asoc->endpoint_shared_keys) {
if (key->key_id == key_id)
return key;
}
return NULL;
}
/*
* Initialize all the possible digest transforms that we can use. Right now
* now, the supported digests are SHA1 and SHA256. We do this here once
* because of the restrictiong that transforms may only be allocated in
* user context. This forces us to pre-allocated all possible transforms
* at the endpoint init time.
*/
int sctp_auth_init_hmacs(struct sctp_endpoint *ep, gfp_t gfp)
{
struct crypto_hash *tfm = NULL;
__u16 id;
/* if the transforms are already allocted, we are done */
if (!sctp_auth_enable) {
ep->auth_hmacs = NULL;
return 0;
}
if (ep->auth_hmacs)
return 0;
/* Allocated the array of pointers to transorms */
ep->auth_hmacs = kzalloc(
sizeof(struct crypto_hash *) * SCTP_AUTH_NUM_HMACS,
gfp);
if (!ep->auth_hmacs)
return -ENOMEM;
for (id = 0; id < SCTP_AUTH_NUM_HMACS; id++) {
/* See is we support the id. Supported IDs have name and
* length fields set, so that we can allocated and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (!sctp_hmac_list[id].hmac_name)
continue;
/* If this TFM has been allocated, we are all set */
if (ep->auth_hmacs[id])
continue;
/* Allocate the ID */
tfm = crypto_alloc_hash(sctp_hmac_list[id].hmac_name, 0,
CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm))
goto out_err;
ep->auth_hmacs[id] = tfm;
}
return 0;
out_err:
/* Clean up any successful allocations */
sctp_auth_destroy_hmacs(ep->auth_hmacs);
return -ENOMEM;
}
/* Destroy the hmac tfm array */
void sctp_auth_destroy_hmacs(struct crypto_hash *auth_hmacs[])
{
int i;
if (!auth_hmacs)
return;
for (i = 0; i < SCTP_AUTH_NUM_HMACS; i++)
{
if (auth_hmacs[i])
crypto_free_hash(auth_hmacs[i]);
}
kfree(auth_hmacs);
}
struct sctp_hmac *sctp_auth_get_hmac(__u16 hmac_id)
{
return &sctp_hmac_list[hmac_id];
}
/* Get an hmac description information that we can use to build
* the AUTH chunk
*/
struct sctp_hmac *sctp_auth_asoc_get_hmac(const struct sctp_association *asoc)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
__u16 id = 0;
int i;
/* If we have a default entry, use it */
if (asoc->default_hmac_id)
return &sctp_hmac_list[asoc->default_hmac_id];
/* Since we do not have a default entry, find the first entry
* we support and return that. Do not cache that id.
*/
hmacs = asoc->peer.peer_hmacs;
if (!hmacs)
return NULL;
n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;
for (i = 0; i < n_elt; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range */
if (id > SCTP_AUTH_HMAC_ID_MAX) {
id = 0;
continue;
}
/* See is we support the id. Supported IDs have name and
* length fields set, so that we can allocated and use
* them. We can safely just check for name, for without the
* name, we can't allocate the TFM.
*/
if (!sctp_hmac_list[id].hmac_name) {
id = 0;
continue;
}
break;
}
if (id == 0)
return NULL;
return &sctp_hmac_list[id];
}
static int __sctp_auth_find_hmacid(__be16 *hmacs, int n_elts, __be16 hmac_id)
{
int found = 0;
int i;
for (i = 0; i < n_elts; i++) {
if (hmac_id == hmacs[i]) {
found = 1;
break;
}
}
return found;
}
/* See if the HMAC_ID is one that we claim as supported */
int sctp_auth_asoc_verify_hmac_id(const struct sctp_association *asoc,
__be16 hmac_id)
{
struct sctp_hmac_algo_param *hmacs;
__u16 n_elt;
if (!asoc)
return 0;
hmacs = (struct sctp_hmac_algo_param *)asoc->c.auth_hmacs;
n_elt = (ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t)) >> 1;
return __sctp_auth_find_hmacid(hmacs->hmac_ids, n_elt, hmac_id);
}
/* Cache the default HMAC id. This to follow this text from SCTP-AUTH:
* Section 6.1:
* The receiver of a HMAC-ALGO parameter SHOULD use the first listed
* algorithm it supports.
*/
void sctp_auth_asoc_set_default_hmac(struct sctp_association *asoc,
struct sctp_hmac_algo_param *hmacs)
{
struct sctp_endpoint *ep;
__u16 id;
int i;
int n_params;
/* if the default id is already set, use it */
if (asoc->default_hmac_id)
return;
n_params = (ntohs(hmacs->param_hdr.length)
- sizeof(sctp_paramhdr_t)) >> 1;
ep = asoc->ep;
for (i = 0; i < n_params; i++) {
id = ntohs(hmacs->hmac_ids[i]);
/* Check the id is in the supported range */
if (id > SCTP_AUTH_HMAC_ID_MAX)
continue;
/* If this TFM has been allocated, use this id */
if (ep->auth_hmacs[id]) {
asoc->default_hmac_id = id;
break;
}
}
}
/* Check to see if the given chunk is supposed to be authenticated */
static int __sctp_auth_cid(sctp_cid_t chunk, struct sctp_chunks_param *param)
{
unsigned short len;
int found = 0;
int i;
if (!param || param->param_hdr.length == 0)
return 0;
len = ntohs(param->param_hdr.length) - sizeof(sctp_paramhdr_t);
/* SCTP-AUTH, Section 3.2
* The chunk types for INIT, INIT-ACK, SHUTDOWN-COMPLETE and AUTH
* chunks MUST NOT be listed in the CHUNKS parameter. However, if
* a CHUNKS parameter is received then the types for INIT, INIT-ACK,
* SHUTDOWN-COMPLETE and AUTH chunks MUST be ignored.
*/
for (i = 0; !found && i < len; i++) {
switch (param->chunks[i]) {
case SCTP_CID_INIT:
case SCTP_CID_INIT_ACK:
case SCTP_CID_SHUTDOWN_COMPLETE:
case SCTP_CID_AUTH:
break;
default:
if (param->chunks[i] == chunk)
found = 1;
break;
}
}
return found;
}
/* Check if peer requested that this chunk is authenticated */
int sctp_auth_send_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
if (!sctp_auth_enable || !asoc || !asoc->peer.auth_capable)
return 0;
return __sctp_auth_cid(chunk, asoc->peer.peer_chunks);
}
/* Check if we requested that peer authenticate this chunk. */
int sctp_auth_recv_cid(sctp_cid_t chunk, const struct sctp_association *asoc)
{
if (!sctp_auth_enable || !asoc)
return 0;
return __sctp_auth_cid(chunk,
(struct sctp_chunks_param *)asoc->c.auth_chunks);
}
/* SCTP-AUTH: Section 6.2:
* The sender MUST calculate the MAC as described in RFC2104 [2] using
* the hash function H as described by the MAC Identifier and the shared
* association key K based on the endpoint pair shared key described by
* the shared key identifier. The 'data' used for the computation of
* the AUTH-chunk is given by the AUTH chunk with its HMAC field set to
* zero (as shown in Figure 6) followed by all chunks that are placed
* after the AUTH chunk in the SCTP packet.
*/
void sctp_auth_calculate_hmac(const struct sctp_association *asoc,
struct sk_buff *skb,
struct sctp_auth_chunk *auth,
gfp_t gfp)
{
struct scatterlist sg;
struct hash_desc desc;
struct sctp_auth_bytes *asoc_key;
__u16 key_id, hmac_id;
__u8 *digest;
unsigned char *end;
int free_key = 0;
/* Extract the info we need:
* - hmac id
* - key id
*/
key_id = ntohs(auth->auth_hdr.shkey_id);
hmac_id = ntohs(auth->auth_hdr.hmac_id);
if (key_id == asoc->active_key_id)
asoc_key = asoc->asoc_shared_key;
else {
struct sctp_shared_key *ep_key;
ep_key = sctp_auth_get_shkey(asoc, key_id);
if (!ep_key)
return;
asoc_key = sctp_auth_asoc_create_secret(asoc, ep_key, gfp);
if (!asoc_key)
return;
free_key = 1;
}
/* set up scatter list */
end = skb_tail_pointer(skb);
sg_init_one(&sg, auth, end - (unsigned char *)auth);
desc.tfm = asoc->ep->auth_hmacs[hmac_id];
desc.flags = 0;
digest = auth->auth_hdr.hmac;
if (crypto_hash_setkey(desc.tfm, &asoc_key->data[0], asoc_key->len))
goto free;
crypto_hash_digest(&desc, &sg, sg.length, digest);
free:
if (free_key)
sctp_auth_key_put(asoc_key);
}
/* API Helpers */
/* Add a chunk to the endpoint authenticated chunk list */
int sctp_auth_ep_add_chunkid(struct sctp_endpoint *ep, __u8 chunk_id)
{
struct sctp_chunks_param *p = ep->auth_chunk_list;
__u16 nchunks;
__u16 param_len;
/* If this chunk is already specified, we are done */
if (__sctp_auth_cid(chunk_id, p))
return 0;
/* Check if we can add this chunk to the array */
param_len = ntohs(p->param_hdr.length);
nchunks = param_len - sizeof(sctp_paramhdr_t);
if (nchunks == SCTP_NUM_CHUNK_TYPES)
return -EINVAL;
p->chunks[nchunks] = chunk_id;
p->param_hdr.length = htons(param_len + 1);
return 0;
}
/* Add hmac identifires to the endpoint list of supported hmac ids */
int sctp_auth_ep_set_hmacs(struct sctp_endpoint *ep,
struct sctp_hmacalgo *hmacs)
{
int has_sha1 = 0;
__u16 id;
int i;
/* Scan the list looking for unsupported id. Also make sure that
* SHA1 is specified.
*/
for (i = 0; i < hmacs->shmac_num_idents; i++) {
id = hmacs->shmac_idents[i];
if (id > SCTP_AUTH_HMAC_ID_MAX)
return -EOPNOTSUPP;
if (SCTP_AUTH_HMAC_ID_SHA1 == id)
has_sha1 = 1;
if (!sctp_hmac_list[id].hmac_name)
return -EOPNOTSUPP;
}
if (!has_sha1)
return -EINVAL;
memcpy(ep->auth_hmacs_list->hmac_ids, &hmacs->shmac_idents[0],
hmacs->shmac_num_idents * sizeof(__u16));
ep->auth_hmacs_list->param_hdr.length = htons(sizeof(sctp_paramhdr_t) +
hmacs->shmac_num_idents * sizeof(__u16));
return 0;
}
/* Set a new shared key on either endpoint or association. If the
* the key with a same ID already exists, replace the key (remove the
* old key and add a new one).
*/
int sctp_auth_set_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
struct sctp_authkey *auth_key)
{
struct sctp_shared_key *cur_key = NULL;
struct sctp_auth_bytes *key;
struct list_head *sh_keys;
int replace = 0;
/* Try to find the given key id to see if
* we are doing a replace, or adding a new key
*/
if (asoc)
sh_keys = &asoc->endpoint_shared_keys;
else
sh_keys = &ep->endpoint_shared_keys;
key_for_each(cur_key, sh_keys) {
if (cur_key->key_id == auth_key->sca_keynumber) {
replace = 1;
break;
}
}
/* If we are not replacing a key id, we need to allocate
* a shared key.
*/
if (!replace) {
cur_key = sctp_auth_shkey_create(auth_key->sca_keynumber,
GFP_KERNEL);
if (!cur_key)
return -ENOMEM;
}
/* Create a new key data based on the info passed in */
key = sctp_auth_create_key(auth_key->sca_keylength, GFP_KERNEL);
if (!key)
goto nomem;
memcpy(key->data, &auth_key->sca_key[0], auth_key->sca_keylength);
/* If we are replacing, remove the old keys data from the
* key id. If we are adding new key id, add it to the
* list.
*/
if (replace)
sctp_auth_key_put(cur_key->key);
else
list_add(&cur_key->key_list, sh_keys);
cur_key->key = key;
sctp_auth_key_hold(key);
return 0;
nomem:
if (!replace)
sctp_auth_shkey_free(cur_key);
return -ENOMEM;
}
int sctp_auth_set_active_key(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST correst to an existing key */
if (asoc)
sh_keys = &asoc->endpoint_shared_keys;
else
sh_keys = &ep->endpoint_shared_keys;
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
if (asoc) {
asoc->active_key_id = key_id;
sctp_auth_asoc_init_active_key(asoc, GFP_KERNEL);
} else
ep->active_key_id = key_id;
return 0;
}
int sctp_auth_del_key_id(struct sctp_endpoint *ep,
struct sctp_association *asoc,
__u16 key_id)
{
struct sctp_shared_key *key;
struct list_head *sh_keys;
int found = 0;
/* The key identifier MUST NOT be the current active key
* The key identifier MUST correst to an existing key
*/
if (asoc) {
if (asoc->active_key_id == key_id)
return -EINVAL;
sh_keys = &asoc->endpoint_shared_keys;
} else {
if (ep->active_key_id == key_id)
return -EINVAL;
sh_keys = &ep->endpoint_shared_keys;
}
key_for_each(key, sh_keys) {
if (key->key_id == key_id) {
found = 1;
break;
}
}
if (!found)
return -EINVAL;
/* Delete the shared key */
list_del_init(&key->key_list);
sctp_auth_shkey_free(key);
return 0;
}
|
{
"pile_set_name": "Github"
}
|
#define _FILE_OFFSET_BITS 64
#include <linux/kernel.h>
#include <byteswap.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include "evlist.h"
#include "evsel.h"
#include "session.h"
#include "sort.h"
#include "util.h"
static int perf_session__open(struct perf_session *self, bool force)
{
struct stat input_stat;
if (!strcmp(self->filename, "-")) {
self->fd_pipe = true;
self->fd = STDIN_FILENO;
if (perf_session__read_header(self, self->fd) < 0)
pr_err("incompatible file format");
return 0;
}
self->fd = open(self->filename, O_RDONLY);
if (self->fd < 0) {
int err = errno;
pr_err("failed to open %s: %s", self->filename, strerror(err));
if (err == ENOENT && !strcmp(self->filename, "perf.data"))
pr_err(" (try 'perf record' first)");
pr_err("\n");
return -errno;
}
if (fstat(self->fd, &input_stat) < 0)
goto out_close;
if (!force && input_stat.st_uid && (input_stat.st_uid != geteuid())) {
pr_err("file %s not owned by current user or root\n",
self->filename);
goto out_close;
}
if (!input_stat.st_size) {
pr_info("zero-sized file (%s), nothing to do!\n",
self->filename);
goto out_close;
}
if (perf_session__read_header(self, self->fd) < 0) {
pr_err("incompatible file format");
goto out_close;
}
if (!perf_evlist__valid_sample_type(self->evlist)) {
pr_err("non matching sample_type");
goto out_close;
}
if (!perf_evlist__valid_sample_id_all(self->evlist)) {
pr_err("non matching sample_id_all");
goto out_close;
}
self->size = input_stat.st_size;
return 0;
out_close:
close(self->fd);
self->fd = -1;
return -1;
}
static void perf_session__id_header_size(struct perf_session *session)
{
struct perf_sample *data;
u64 sample_type = session->sample_type;
u16 size = 0;
if (!session->sample_id_all)
goto out;
if (sample_type & PERF_SAMPLE_TID)
size += sizeof(data->tid) * 2;
if (sample_type & PERF_SAMPLE_TIME)
size += sizeof(data->time);
if (sample_type & PERF_SAMPLE_ID)
size += sizeof(data->id);
if (sample_type & PERF_SAMPLE_STREAM_ID)
size += sizeof(data->stream_id);
if (sample_type & PERF_SAMPLE_CPU)
size += sizeof(data->cpu) * 2;
out:
session->id_hdr_size = size;
}
void perf_session__update_sample_type(struct perf_session *self)
{
self->sample_type = perf_evlist__sample_type(self->evlist);
self->sample_size = __perf_evsel__sample_size(self->sample_type);
self->sample_id_all = perf_evlist__sample_id_all(self->evlist);
perf_session__id_header_size(self);
}
int perf_session__create_kernel_maps(struct perf_session *self)
{
int ret = machine__create_kernel_maps(&self->host_machine);
if (ret >= 0)
ret = machines__create_guest_kernel_maps(&self->machines);
return ret;
}
static void perf_session__destroy_kernel_maps(struct perf_session *self)
{
machine__destroy_kernel_maps(&self->host_machine);
machines__destroy_guest_kernel_maps(&self->machines);
}
struct perf_session *perf_session__new(const char *filename, int mode,
bool force, bool repipe,
struct perf_event_ops *ops)
{
size_t len = filename ? strlen(filename) + 1 : 0;
struct perf_session *self = zalloc(sizeof(*self) + len);
if (self == NULL)
goto out;
memcpy(self->filename, filename, len);
self->threads = RB_ROOT;
INIT_LIST_HEAD(&self->dead_threads);
self->last_match = NULL;
/*
* On 64bit we can mmap the data file in one go. No need for tiny mmap
* slices. On 32bit we use 32MB.
*/
#if BITS_PER_LONG == 64
self->mmap_window = ULLONG_MAX;
#else
self->mmap_window = 32 * 1024 * 1024ULL;
#endif
self->machines = RB_ROOT;
self->repipe = repipe;
INIT_LIST_HEAD(&self->ordered_samples.samples);
INIT_LIST_HEAD(&self->ordered_samples.sample_cache);
INIT_LIST_HEAD(&self->ordered_samples.to_free);
machine__init(&self->host_machine, "", HOST_KERNEL_ID);
if (mode == O_RDONLY) {
if (perf_session__open(self, force) < 0)
goto out_delete;
perf_session__update_sample_type(self);
} else if (mode == O_WRONLY) {
/*
* In O_RDONLY mode this will be performed when reading the
* kernel MMAP event, in perf_event__process_mmap().
*/
if (perf_session__create_kernel_maps(self) < 0)
goto out_delete;
}
if (ops && ops->ordering_requires_timestamps &&
ops->ordered_samples && !self->sample_id_all) {
dump_printf("WARNING: No sample_id_all support, falling back to unordered processing\n");
ops->ordered_samples = false;
}
out:
return self;
out_delete:
perf_session__delete(self);
return NULL;
}
static void perf_session__delete_dead_threads(struct perf_session *self)
{
struct thread *n, *t;
list_for_each_entry_safe(t, n, &self->dead_threads, node) {
list_del(&t->node);
thread__delete(t);
}
}
static void perf_session__delete_threads(struct perf_session *self)
{
struct rb_node *nd = rb_first(&self->threads);
while (nd) {
struct thread *t = rb_entry(nd, struct thread, rb_node);
rb_erase(&t->rb_node, &self->threads);
nd = rb_next(nd);
thread__delete(t);
}
}
void perf_session__delete(struct perf_session *self)
{
perf_session__destroy_kernel_maps(self);
perf_session__delete_dead_threads(self);
perf_session__delete_threads(self);
machine__exit(&self->host_machine);
close(self->fd);
free(self);
}
void perf_session__remove_thread(struct perf_session *self, struct thread *th)
{
self->last_match = NULL;
rb_erase(&th->rb_node, &self->threads);
/*
* We may have references to this thread, for instance in some hist_entry
* instances, so just move them to a separate list.
*/
list_add_tail(&th->node, &self->dead_threads);
}
static bool symbol__match_parent_regex(struct symbol *sym)
{
if (sym->name && !regexec(&parent_regex, sym->name, 0, NULL, 0))
return 1;
return 0;
}
int perf_session__resolve_callchain(struct perf_session *self,
struct thread *thread,
struct ip_callchain *chain,
struct symbol **parent)
{
u8 cpumode = PERF_RECORD_MISC_USER;
unsigned int i;
int err;
callchain_cursor_reset(&self->callchain_cursor);
for (i = 0; i < chain->nr; i++) {
u64 ip = chain->ips[i];
struct addr_location al;
if (ip >= PERF_CONTEXT_MAX) {
switch (ip) {
case PERF_CONTEXT_HV:
cpumode = PERF_RECORD_MISC_HYPERVISOR; break;
case PERF_CONTEXT_KERNEL:
cpumode = PERF_RECORD_MISC_KERNEL; break;
case PERF_CONTEXT_USER:
cpumode = PERF_RECORD_MISC_USER; break;
default:
break;
}
continue;
}
al.filtered = false;
thread__find_addr_location(thread, self, cpumode,
MAP__FUNCTION, thread->pid, ip, &al, NULL);
if (al.sym != NULL) {
if (sort__has_parent && !*parent &&
symbol__match_parent_regex(al.sym))
*parent = al.sym;
if (!symbol_conf.use_callchain)
break;
}
err = callchain_cursor_append(&self->callchain_cursor,
ip, al.map, al.sym);
if (err)
return err;
}
return 0;
}
static int process_event_synth_stub(union perf_event *event __used,
struct perf_session *session __used)
{
dump_printf(": unhandled!\n");
return 0;
}
static int process_event_sample_stub(union perf_event *event __used,
struct perf_sample *sample __used,
struct perf_evsel *evsel __used,
struct perf_session *session __used)
{
dump_printf(": unhandled!\n");
return 0;
}
static int process_event_stub(union perf_event *event __used,
struct perf_sample *sample __used,
struct perf_session *session __used)
{
dump_printf(": unhandled!\n");
return 0;
}
static int process_finished_round_stub(union perf_event *event __used,
struct perf_session *session __used,
struct perf_event_ops *ops __used)
{
dump_printf(": unhandled!\n");
return 0;
}
static int process_finished_round(union perf_event *event,
struct perf_session *session,
struct perf_event_ops *ops);
static void perf_event_ops__fill_defaults(struct perf_event_ops *handler)
{
if (handler->sample == NULL)
handler->sample = process_event_sample_stub;
if (handler->mmap == NULL)
handler->mmap = process_event_stub;
if (handler->comm == NULL)
handler->comm = process_event_stub;
if (handler->fork == NULL)
handler->fork = process_event_stub;
if (handler->exit == NULL)
handler->exit = process_event_stub;
if (handler->lost == NULL)
handler->lost = perf_event__process_lost;
if (handler->read == NULL)
handler->read = process_event_stub;
if (handler->throttle == NULL)
handler->throttle = process_event_stub;
if (handler->unthrottle == NULL)
handler->unthrottle = process_event_stub;
if (handler->attr == NULL)
handler->attr = process_event_synth_stub;
if (handler->event_type == NULL)
handler->event_type = process_event_synth_stub;
if (handler->tracing_data == NULL)
handler->tracing_data = process_event_synth_stub;
if (handler->build_id == NULL)
handler->build_id = process_event_synth_stub;
if (handler->finished_round == NULL) {
if (handler->ordered_samples)
handler->finished_round = process_finished_round;
else
handler->finished_round = process_finished_round_stub;
}
}
void mem_bswap_64(void *src, int byte_size)
{
u64 *m = src;
while (byte_size > 0) {
*m = bswap_64(*m);
byte_size -= sizeof(u64);
++m;
}
}
static void perf_event__all64_swap(union perf_event *event)
{
struct perf_event_header *hdr = &event->header;
mem_bswap_64(hdr + 1, event->header.size - sizeof(*hdr));
}
static void perf_event__comm_swap(union perf_event *event)
{
event->comm.pid = bswap_32(event->comm.pid);
event->comm.tid = bswap_32(event->comm.tid);
}
static void perf_event__mmap_swap(union perf_event *event)
{
event->mmap.pid = bswap_32(event->mmap.pid);
event->mmap.tid = bswap_32(event->mmap.tid);
event->mmap.start = bswap_64(event->mmap.start);
event->mmap.len = bswap_64(event->mmap.len);
event->mmap.pgoff = bswap_64(event->mmap.pgoff);
}
static void perf_event__task_swap(union perf_event *event)
{
event->fork.pid = bswap_32(event->fork.pid);
event->fork.tid = bswap_32(event->fork.tid);
event->fork.ppid = bswap_32(event->fork.ppid);
event->fork.ptid = bswap_32(event->fork.ptid);
event->fork.time = bswap_64(event->fork.time);
}
static void perf_event__read_swap(union perf_event *event)
{
event->read.pid = bswap_32(event->read.pid);
event->read.tid = bswap_32(event->read.tid);
event->read.value = bswap_64(event->read.value);
event->read.time_enabled = bswap_64(event->read.time_enabled);
event->read.time_running = bswap_64(event->read.time_running);
event->read.id = bswap_64(event->read.id);
}
/* exported for swapping attributes in file header */
void perf_event__attr_swap(struct perf_event_attr *attr)
{
attr->type = bswap_32(attr->type);
attr->size = bswap_32(attr->size);
attr->config = bswap_64(attr->config);
attr->sample_period = bswap_64(attr->sample_period);
attr->sample_type = bswap_64(attr->sample_type);
attr->read_format = bswap_64(attr->read_format);
attr->wakeup_events = bswap_32(attr->wakeup_events);
attr->bp_type = bswap_32(attr->bp_type);
attr->bp_addr = bswap_64(attr->bp_addr);
attr->bp_len = bswap_64(attr->bp_len);
}
static void perf_event__hdr_attr_swap(union perf_event *event)
{
size_t size;
perf_event__attr_swap(&event->attr.attr);
size = event->header.size;
size -= (void *)&event->attr.id - (void *)event;
mem_bswap_64(event->attr.id, size);
}
static void perf_event__event_type_swap(union perf_event *event)
{
event->event_type.event_type.event_id =
bswap_64(event->event_type.event_type.event_id);
}
static void perf_event__tracing_data_swap(union perf_event *event)
{
event->tracing_data.size = bswap_32(event->tracing_data.size);
}
typedef void (*perf_event__swap_op)(union perf_event *event);
static perf_event__swap_op perf_event__swap_ops[] = {
[PERF_RECORD_MMAP] = perf_event__mmap_swap,
[PERF_RECORD_COMM] = perf_event__comm_swap,
[PERF_RECORD_FORK] = perf_event__task_swap,
[PERF_RECORD_EXIT] = perf_event__task_swap,
[PERF_RECORD_LOST] = perf_event__all64_swap,
[PERF_RECORD_READ] = perf_event__read_swap,
[PERF_RECORD_SAMPLE] = perf_event__all64_swap,
[PERF_RECORD_HEADER_ATTR] = perf_event__hdr_attr_swap,
[PERF_RECORD_HEADER_EVENT_TYPE] = perf_event__event_type_swap,
[PERF_RECORD_HEADER_TRACING_DATA] = perf_event__tracing_data_swap,
[PERF_RECORD_HEADER_BUILD_ID] = NULL,
[PERF_RECORD_HEADER_MAX] = NULL,
};
struct sample_queue {
u64 timestamp;
u64 file_offset;
union perf_event *event;
struct list_head list;
};
static void perf_session_free_sample_buffers(struct perf_session *session)
{
struct ordered_samples *os = &session->ordered_samples;
while (!list_empty(&os->to_free)) {
struct sample_queue *sq;
sq = list_entry(os->to_free.next, struct sample_queue, list);
list_del(&sq->list);
free(sq);
}
}
static int perf_session_deliver_event(struct perf_session *session,
union perf_event *event,
struct perf_sample *sample,
struct perf_event_ops *ops,
u64 file_offset);
static void flush_sample_queue(struct perf_session *s,
struct perf_event_ops *ops)
{
struct ordered_samples *os = &s->ordered_samples;
struct list_head *head = &os->samples;
struct sample_queue *tmp, *iter;
struct perf_sample sample;
u64 limit = os->next_flush;
u64 last_ts = os->last_sample ? os->last_sample->timestamp : 0ULL;
int ret;
if (!ops->ordered_samples || !limit)
return;
list_for_each_entry_safe(iter, tmp, head, list) {
if (iter->timestamp > limit)
break;
ret = perf_session__parse_sample(s, iter->event, &sample);
if (ret)
pr_err("Can't parse sample, err = %d\n", ret);
else
perf_session_deliver_event(s, iter->event, &sample, ops,
iter->file_offset);
os->last_flush = iter->timestamp;
list_del(&iter->list);
list_add(&iter->list, &os->sample_cache);
}
if (list_empty(head)) {
os->last_sample = NULL;
} else if (last_ts <= limit) {
os->last_sample =
list_entry(head->prev, struct sample_queue, list);
}
}
/*
* When perf record finishes a pass on every buffers, it records this pseudo
* event.
* We record the max timestamp t found in the pass n.
* Assuming these timestamps are monotonic across cpus, we know that if
* a buffer still has events with timestamps below t, they will be all
* available and then read in the pass n + 1.
* Hence when we start to read the pass n + 2, we can safely flush every
* events with timestamps below t.
*
* ============ PASS n =================
* CPU 0 | CPU 1
* |
* cnt1 timestamps | cnt2 timestamps
* 1 | 2
* 2 | 3
* - | 4 <--- max recorded
*
* ============ PASS n + 1 ==============
* CPU 0 | CPU 1
* |
* cnt1 timestamps | cnt2 timestamps
* 3 | 5
* 4 | 6
* 5 | 7 <---- max recorded
*
* Flush every events below timestamp 4
*
* ============ PASS n + 2 ==============
* CPU 0 | CPU 1
* |
* cnt1 timestamps | cnt2 timestamps
* 6 | 8
* 7 | 9
* - | 10
*
* Flush every events below timestamp 7
* etc...
*/
static int process_finished_round(union perf_event *event __used,
struct perf_session *session,
struct perf_event_ops *ops)
{
flush_sample_queue(session, ops);
session->ordered_samples.next_flush = session->ordered_samples.max_timestamp;
return 0;
}
/* The queue is ordered by time */
static void __queue_event(struct sample_queue *new, struct perf_session *s)
{
struct ordered_samples *os = &s->ordered_samples;
struct sample_queue *sample = os->last_sample;
u64 timestamp = new->timestamp;
struct list_head *p;
os->last_sample = new;
if (!sample) {
list_add(&new->list, &os->samples);
os->max_timestamp = timestamp;
return;
}
/*
* last_sample might point to some random place in the list as it's
* the last queued event. We expect that the new event is close to
* this.
*/
if (sample->timestamp <= timestamp) {
while (sample->timestamp <= timestamp) {
p = sample->list.next;
if (p == &os->samples) {
list_add_tail(&new->list, &os->samples);
os->max_timestamp = timestamp;
return;
}
sample = list_entry(p, struct sample_queue, list);
}
list_add_tail(&new->list, &sample->list);
} else {
while (sample->timestamp > timestamp) {
p = sample->list.prev;
if (p == &os->samples) {
list_add(&new->list, &os->samples);
return;
}
sample = list_entry(p, struct sample_queue, list);
}
list_add(&new->list, &sample->list);
}
}
#define MAX_SAMPLE_BUFFER (64 * 1024 / sizeof(struct sample_queue))
static int perf_session_queue_event(struct perf_session *s, union perf_event *event,
struct perf_sample *sample, u64 file_offset)
{
struct ordered_samples *os = &s->ordered_samples;
struct list_head *sc = &os->sample_cache;
u64 timestamp = sample->time;
struct sample_queue *new;
if (!timestamp || timestamp == ~0ULL)
return -ETIME;
if (timestamp < s->ordered_samples.last_flush) {
printf("Warning: Timestamp below last timeslice flush\n");
return -EINVAL;
}
if (!list_empty(sc)) {
new = list_entry(sc->next, struct sample_queue, list);
list_del(&new->list);
} else if (os->sample_buffer) {
new = os->sample_buffer + os->sample_buffer_idx;
if (++os->sample_buffer_idx == MAX_SAMPLE_BUFFER)
os->sample_buffer = NULL;
} else {
os->sample_buffer = malloc(MAX_SAMPLE_BUFFER * sizeof(*new));
if (!os->sample_buffer)
return -ENOMEM;
list_add(&os->sample_buffer->list, &os->to_free);
os->sample_buffer_idx = 2;
new = os->sample_buffer + 1;
}
new->timestamp = timestamp;
new->file_offset = file_offset;
new->event = event;
__queue_event(new, s);
return 0;
}
static void callchain__printf(struct perf_sample *sample)
{
unsigned int i;
printf("... chain: nr:%" PRIu64 "\n", sample->callchain->nr);
for (i = 0; i < sample->callchain->nr; i++)
printf("..... %2d: %016" PRIx64 "\n",
i, sample->callchain->ips[i]);
}
static void perf_session__print_tstamp(struct perf_session *session,
union perf_event *event,
struct perf_sample *sample)
{
if (event->header.type != PERF_RECORD_SAMPLE &&
!session->sample_id_all) {
fputs("-1 -1 ", stdout);
return;
}
if ((session->sample_type & PERF_SAMPLE_CPU))
printf("%u ", sample->cpu);
if (session->sample_type & PERF_SAMPLE_TIME)
printf("%" PRIu64 " ", sample->time);
}
static void dump_event(struct perf_session *session, union perf_event *event,
u64 file_offset, struct perf_sample *sample)
{
if (!dump_trace)
return;
printf("\n%#" PRIx64 " [%#x]: event: %d\n",
file_offset, event->header.size, event->header.type);
trace_event(event);
if (sample)
perf_session__print_tstamp(session, event, sample);
printf("%#" PRIx64 " [%#x]: PERF_RECORD_%s", file_offset,
event->header.size, perf_event__name(event->header.type));
}
static void dump_sample(struct perf_session *session, union perf_event *event,
struct perf_sample *sample)
{
if (!dump_trace)
return;
printf("(IP, %d): %d/%d: %#" PRIx64 " period: %" PRIu64 "\n",
event->header.misc, sample->pid, sample->tid, sample->ip,
sample->period);
if (session->sample_type & PERF_SAMPLE_CALLCHAIN)
callchain__printf(sample);
}
static int perf_session_deliver_event(struct perf_session *session,
union perf_event *event,
struct perf_sample *sample,
struct perf_event_ops *ops,
u64 file_offset)
{
struct perf_evsel *evsel;
dump_event(session, event, file_offset, sample);
switch (event->header.type) {
case PERF_RECORD_SAMPLE:
dump_sample(session, event, sample);
evsel = perf_evlist__id2evsel(session->evlist, sample->id);
if (evsel == NULL) {
++session->hists.stats.nr_unknown_id;
return -1;
}
return ops->sample(event, sample, evsel, session);
case PERF_RECORD_MMAP:
return ops->mmap(event, sample, session);
case PERF_RECORD_COMM:
return ops->comm(event, sample, session);
case PERF_RECORD_FORK:
return ops->fork(event, sample, session);
case PERF_RECORD_EXIT:
return ops->exit(event, sample, session);
case PERF_RECORD_LOST:
return ops->lost(event, sample, session);
case PERF_RECORD_READ:
return ops->read(event, sample, session);
case PERF_RECORD_THROTTLE:
return ops->throttle(event, sample, session);
case PERF_RECORD_UNTHROTTLE:
return ops->unthrottle(event, sample, session);
default:
++session->hists.stats.nr_unknown_events;
return -1;
}
}
static int perf_session__preprocess_sample(struct perf_session *session,
union perf_event *event, struct perf_sample *sample)
{
if (event->header.type != PERF_RECORD_SAMPLE ||
!(session->sample_type & PERF_SAMPLE_CALLCHAIN))
return 0;
if (!ip_callchain__valid(sample->callchain, event)) {
pr_debug("call-chain problem with event, skipping it.\n");
++session->hists.stats.nr_invalid_chains;
session->hists.stats.total_invalid_chains += sample->period;
return -EINVAL;
}
return 0;
}
static int perf_session__process_user_event(struct perf_session *session, union perf_event *event,
struct perf_event_ops *ops, u64 file_offset)
{
dump_event(session, event, file_offset, NULL);
/* These events are processed right away */
switch (event->header.type) {
case PERF_RECORD_HEADER_ATTR:
return ops->attr(event, session);
case PERF_RECORD_HEADER_EVENT_TYPE:
return ops->event_type(event, session);
case PERF_RECORD_HEADER_TRACING_DATA:
/* setup for reading amidst mmap */
lseek(session->fd, file_offset, SEEK_SET);
return ops->tracing_data(event, session);
case PERF_RECORD_HEADER_BUILD_ID:
return ops->build_id(event, session);
case PERF_RECORD_FINISHED_ROUND:
return ops->finished_round(event, session, ops);
default:
return -EINVAL;
}
}
static int perf_session__process_event(struct perf_session *session,
union perf_event *event,
struct perf_event_ops *ops,
u64 file_offset)
{
struct perf_sample sample;
int ret;
if (session->header.needs_swap &&
perf_event__swap_ops[event->header.type])
perf_event__swap_ops[event->header.type](event);
if (event->header.type >= PERF_RECORD_HEADER_MAX)
return -EINVAL;
hists__inc_nr_events(&session->hists, event->header.type);
if (event->header.type >= PERF_RECORD_USER_TYPE_START)
return perf_session__process_user_event(session, event, ops, file_offset);
/*
* For all kernel events we get the sample data
*/
ret = perf_session__parse_sample(session, event, &sample);
if (ret)
return ret;
/* Preprocess sample records - precheck callchains */
if (perf_session__preprocess_sample(session, event, &sample))
return 0;
if (ops->ordered_samples) {
ret = perf_session_queue_event(session, event, &sample,
file_offset);
if (ret != -ETIME)
return ret;
}
return perf_session_deliver_event(session, event, &sample, ops,
file_offset);
}
void perf_event_header__bswap(struct perf_event_header *self)
{
self->type = bswap_32(self->type);
self->misc = bswap_16(self->misc);
self->size = bswap_16(self->size);
}
static struct thread *perf_session__register_idle_thread(struct perf_session *self)
{
struct thread *thread = perf_session__findnew(self, 0);
if (thread == NULL || thread__set_comm(thread, "swapper")) {
pr_err("problem inserting idle task.\n");
thread = NULL;
}
return thread;
}
static void perf_session__warn_about_errors(const struct perf_session *session,
const struct perf_event_ops *ops)
{
if (ops->lost == perf_event__process_lost &&
session->hists.stats.total_lost != 0) {
ui__warning("Processed %" PRIu64 " events and LOST %" PRIu64
"!\n\nCheck IO/CPU overload!\n\n",
session->hists.stats.total_period,
session->hists.stats.total_lost);
}
if (session->hists.stats.nr_unknown_events != 0) {
ui__warning("Found %u unknown events!\n\n"
"Is this an older tool processing a perf.data "
"file generated by a more recent tool?\n\n"
"If that is not the case, consider "
"reporting to linux-kernel@vger.kernel.org.\n\n",
session->hists.stats.nr_unknown_events);
}
if (session->hists.stats.nr_unknown_id != 0) {
ui__warning("%u samples with id not present in the header\n",
session->hists.stats.nr_unknown_id);
}
if (session->hists.stats.nr_invalid_chains != 0) {
ui__warning("Found invalid callchains!\n\n"
"%u out of %u events were discarded for this reason.\n\n"
"Consider reporting to linux-kernel@vger.kernel.org.\n\n",
session->hists.stats.nr_invalid_chains,
session->hists.stats.nr_events[PERF_RECORD_SAMPLE]);
}
}
#define session_done() (*(volatile int *)(&session_done))
volatile int session_done;
static int __perf_session__process_pipe_events(struct perf_session *self,
struct perf_event_ops *ops)
{
union perf_event event;
uint32_t size;
int skip = 0;
u64 head;
int err;
void *p;
perf_event_ops__fill_defaults(ops);
head = 0;
more:
err = readn(self->fd, &event, sizeof(struct perf_event_header));
if (err <= 0) {
if (err == 0)
goto done;
pr_err("failed to read event header\n");
goto out_err;
}
if (self->header.needs_swap)
perf_event_header__bswap(&event.header);
size = event.header.size;
if (size == 0)
size = 8;
p = &event;
p += sizeof(struct perf_event_header);
if (size - sizeof(struct perf_event_header)) {
err = readn(self->fd, p, size - sizeof(struct perf_event_header));
if (err <= 0) {
if (err == 0) {
pr_err("unexpected end of event stream\n");
goto done;
}
pr_err("failed to read event data\n");
goto out_err;
}
}
if (size == 0 ||
(skip = perf_session__process_event(self, &event, ops, head)) < 0) {
dump_printf("%#" PRIx64 " [%#x]: skipping unknown header type: %d\n",
head, event.header.size, event.header.type);
/*
* assume we lost track of the stream, check alignment, and
* increment a single u64 in the hope to catch on again 'soon'.
*/
if (unlikely(head & 7))
head &= ~7ULL;
size = 8;
}
head += size;
if (skip > 0)
head += skip;
if (!session_done())
goto more;
done:
err = 0;
out_err:
perf_session__warn_about_errors(self, ops);
perf_session_free_sample_buffers(self);
return err;
}
static union perf_event *
fetch_mmaped_event(struct perf_session *session,
u64 head, size_t mmap_size, char *buf)
{
union perf_event *event;
/*
* Ensure we have enough space remaining to read
* the size of the event in the headers.
*/
if (head + sizeof(event->header) > mmap_size)
return NULL;
event = (union perf_event *)(buf + head);
if (session->header.needs_swap)
perf_event_header__bswap(&event->header);
if (head + event->header.size > mmap_size)
return NULL;
return event;
}
int __perf_session__process_events(struct perf_session *session,
u64 data_offset, u64 data_size,
u64 file_size, struct perf_event_ops *ops)
{
u64 head, page_offset, file_offset, file_pos, progress_next;
int err, mmap_prot, mmap_flags, map_idx = 0;
struct ui_progress *progress;
size_t page_size, mmap_size;
char *buf, *mmaps[8];
union perf_event *event;
uint32_t size;
perf_event_ops__fill_defaults(ops);
page_size = sysconf(_SC_PAGESIZE);
page_offset = page_size * (data_offset / page_size);
file_offset = page_offset;
head = data_offset - page_offset;
if (data_offset + data_size < file_size)
file_size = data_offset + data_size;
progress_next = file_size / 16;
progress = ui_progress__new("Processing events...", file_size);
if (progress == NULL)
return -1;
mmap_size = session->mmap_window;
if (mmap_size > file_size)
mmap_size = file_size;
memset(mmaps, 0, sizeof(mmaps));
mmap_prot = PROT_READ;
mmap_flags = MAP_SHARED;
if (session->header.needs_swap) {
mmap_prot |= PROT_WRITE;
mmap_flags = MAP_PRIVATE;
}
remap:
buf = mmap(NULL, mmap_size, mmap_prot, mmap_flags, session->fd,
file_offset);
if (buf == MAP_FAILED) {
pr_err("failed to mmap file\n");
err = -errno;
goto out_err;
}
mmaps[map_idx] = buf;
map_idx = (map_idx + 1) & (ARRAY_SIZE(mmaps) - 1);
file_pos = file_offset + head;
more:
event = fetch_mmaped_event(session, head, mmap_size, buf);
if (!event) {
if (mmaps[map_idx]) {
munmap(mmaps[map_idx], mmap_size);
mmaps[map_idx] = NULL;
}
page_offset = page_size * (head / page_size);
file_offset += page_offset;
head -= page_offset;
goto remap;
}
size = event->header.size;
if (size == 0 ||
perf_session__process_event(session, event, ops, file_pos) < 0) {
dump_printf("%#" PRIx64 " [%#x]: skipping unknown header type: %d\n",
file_offset + head, event->header.size,
event->header.type);
/*
* assume we lost track of the stream, check alignment, and
* increment a single u64 in the hope to catch on again 'soon'.
*/
if (unlikely(head & 7))
head &= ~7ULL;
size = 8;
}
head += size;
file_pos += size;
if (file_pos >= progress_next) {
progress_next += file_size / 16;
ui_progress__update(progress, file_pos);
}
if (file_pos < file_size)
goto more;
err = 0;
/* do the final flush for ordered samples */
session->ordered_samples.next_flush = ULLONG_MAX;
flush_sample_queue(session, ops);
out_err:
ui_progress__delete(progress);
perf_session__warn_about_errors(session, ops);
perf_session_free_sample_buffers(session);
return err;
}
int perf_session__process_events(struct perf_session *self,
struct perf_event_ops *ops)
{
int err;
if (perf_session__register_idle_thread(self) == NULL)
return -ENOMEM;
if (!self->fd_pipe)
err = __perf_session__process_events(self,
self->header.data_offset,
self->header.data_size,
self->size, ops);
else
err = __perf_session__process_pipe_events(self, ops);
return err;
}
bool perf_session__has_traces(struct perf_session *self, const char *msg)
{
if (!(self->sample_type & PERF_SAMPLE_RAW)) {
pr_err("No trace sample to read. Did you call 'perf %s'?\n", msg);
return false;
}
return true;
}
int perf_session__set_kallsyms_ref_reloc_sym(struct map **maps,
const char *symbol_name,
u64 addr)
{
char *bracket;
enum map_type i;
struct ref_reloc_sym *ref;
ref = zalloc(sizeof(struct ref_reloc_sym));
if (ref == NULL)
return -ENOMEM;
ref->name = strdup(symbol_name);
if (ref->name == NULL) {
free(ref);
return -ENOMEM;
}
bracket = strchr(ref->name, ']');
if (bracket)
*bracket = '\0';
ref->addr = addr;
for (i = 0; i < MAP__NR_TYPES; ++i) {
struct kmap *kmap = map__kmap(maps[i]);
kmap->ref_reloc_sym = ref;
}
return 0;
}
size_t perf_session__fprintf_dsos(struct perf_session *self, FILE *fp)
{
return __dsos__fprintf(&self->host_machine.kernel_dsos, fp) +
__dsos__fprintf(&self->host_machine.user_dsos, fp) +
machines__fprintf_dsos(&self->machines, fp);
}
size_t perf_session__fprintf_dsos_buildid(struct perf_session *self, FILE *fp,
bool with_hits)
{
size_t ret = machine__fprintf_dsos_buildid(&self->host_machine, fp, with_hits);
return ret + machines__fprintf_dsos_buildid(&self->machines, fp, with_hits);
}
size_t perf_session__fprintf_nr_events(struct perf_session *session, FILE *fp)
{
struct perf_evsel *pos;
size_t ret = fprintf(fp, "Aggregated stats:\n");
ret += hists__fprintf_nr_events(&session->hists, fp);
list_for_each_entry(pos, &session->evlist->entries, node) {
ret += fprintf(fp, "%s stats:\n", event_name(pos));
ret += hists__fprintf_nr_events(&pos->hists, fp);
}
return ret;
}
struct perf_evsel *perf_session__find_first_evtype(struct perf_session *session,
unsigned int type)
{
struct perf_evsel *pos;
list_for_each_entry(pos, &session->evlist->entries, node) {
if (pos->attr.type == type)
return pos;
}
return NULL;
}
void perf_session__print_symbols(union perf_event *event,
struct perf_sample *sample,
struct perf_session *session)
{
struct addr_location al;
const char *symname, *dsoname;
struct callchain_cursor *cursor = &session->callchain_cursor;
struct callchain_cursor_node *node;
if (perf_event__preprocess_sample(event, session, &al, sample,
NULL) < 0) {
error("problem processing %d event, skipping it.\n",
event->header.type);
return;
}
if (symbol_conf.use_callchain && sample->callchain) {
if (perf_session__resolve_callchain(session, al.thread,
sample->callchain, NULL) != 0) {
if (verbose)
error("Failed to resolve callchain. Skipping\n");
return;
}
callchain_cursor_commit(cursor);
while (1) {
node = callchain_cursor_current(cursor);
if (!node)
break;
if (node->sym && node->sym->name)
symname = node->sym->name;
else
symname = "";
if (node->map && node->map->dso && node->map->dso->name)
dsoname = node->map->dso->name;
else
dsoname = "";
printf("\t%16" PRIx64 " %s (%s)\n", node->ip, symname, dsoname);
callchain_cursor_advance(cursor);
}
} else {
if (al.sym && al.sym->name)
symname = al.sym->name;
else
symname = "";
if (al.map && al.map->dso && al.map->dso->name)
dsoname = al.map->dso->name;
else
dsoname = "";
printf("%16" PRIx64 " %s (%s)", al.addr, symname, dsoname);
}
}
|
{
"pile_set_name": "Github"
}
|
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2019, Alexandros Theodotou
# This file is distributed under the same license as the Zrythm package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2019.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Zrythm 0.4\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-05-04 08:01+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.7.0\n"
#: ../../control-surfaces/intro.rst:2
msgid "Control Surfaces"
msgstr ""
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0"?>
<ZopeData>
<record id="1" aka="AAAAAAAAAAE=">
<pickle>
<global name="PythonScript" module="Products.PythonScripts.PythonScript"/>
</pickle>
<pickle>
<dictionary>
<item>
<key> <string>Script_magic</string> </key>
<value> <int>3</int> </value>
</item>
<item>
<key> <string>_bind_names</string> </key>
<value>
<object>
<klass>
<global name="NameAssignments" module="Shared.DC.Scripts.Bindings"/>
</klass>
<tuple/>
<state>
<dictionary>
<item>
<key> <string>_asgns</string> </key>
<value>
<dictionary>
<item>
<key> <string>name_container</string> </key>
<value> <string>container</string> </value>
</item>
<item>
<key> <string>name_context</string> </key>
<value> <string>context</string> </value>
</item>
<item>
<key> <string>name_m_self</string> </key>
<value> <string>script</string> </value>
</item>
<item>
<key> <string>name_subpath</string> </key>
<value> <string>traverse_subpath</string> </value>
</item>
</dictionary>
</value>
</item>
</dictionary>
</state>
</object>
</value>
</item>
<item>
<key> <string>_params</string> </key>
<value> <string>**kw</string> </value>
</item>
<item>
<key> <string>id</string> </key>
<value> <string>ManufacturingOrderBuilder_selectSimulationMovement</string> </value>
</item>
<item>
<key> <string>title</string> </key>
<value> <string></string> </value>
</item>
</dictionary>
</pickle>
</record>
</ZopeData>
|
{
"pile_set_name": "Github"
}
|
/*!
* \file
*
* \brief Various routines with dealing with CSR matrices
*
* \author George Karypis
* \version\verbatim $Id: csr.c 13437 2013-01-11 21:54:10Z karypis $ \endverbatim
*/
#include <GKlib.h>
#define OMPMINOPS 50000
/*************************************************************************/
/*! Allocate memory for a CSR matrix and initializes it
\returns the allocated matrix. The various fields are set to NULL.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Create()
{
gk_csr_t *mat;
mat = (gk_csr_t *)gk_malloc(sizeof(gk_csr_t), "gk_csr_Create: mat");
gk_csr_Init(mat);
return mat;
}
/*************************************************************************/
/*! Initializes the matrix
\param mat is the matrix to be initialized.
*/
/*************************************************************************/
void gk_csr_Init(gk_csr_t *mat)
{
memset(mat, 0, sizeof(gk_csr_t));
mat->nrows = mat->ncols = -1;
}
/*************************************************************************/
/*! Frees all the memory allocated for matrix.
\param mat is the matrix to be freed.
*/
/*************************************************************************/
void gk_csr_Free(gk_csr_t **mat)
{
if (*mat == NULL)
return;
gk_csr_FreeContents(*mat);
gk_free((void **)mat, LTERM);
}
/*************************************************************************/
/*! Frees only the memory allocated for the matrix's different fields and
sets them to NULL.
\param mat is the matrix whose contents will be freed.
*/
/*************************************************************************/
void gk_csr_FreeContents(gk_csr_t *mat)
{
gk_free((void *)&mat->rowptr, &mat->rowind, &mat->rowval, &mat->rowids,
&mat->colptr, &mat->colind, &mat->colval, &mat->colids,
&mat->rnorms, &mat->cnorms, &mat->rsums, &mat->csums,
&mat->rsizes, &mat->csizes, &mat->rvols, &mat->cvols,
&mat->rwgts, &mat->cwgts,
LTERM);
}
/*************************************************************************/
/*! Returns a copy of a matrix.
\param mat is the matrix to be duplicated.
\returns the newly created copy of the matrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Dup(gk_csr_t *mat)
{
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = mat->nrows;
nmat->ncols = mat->ncols;
/* copy the row structure */
if (mat->rowptr)
nmat->rowptr = gk_zcopy(mat->nrows+1, mat->rowptr,
gk_zmalloc(mat->nrows+1, "gk_csr_Dup: rowptr"));
if (mat->rowids)
nmat->rowids = gk_icopy(mat->nrows, mat->rowids,
gk_imalloc(mat->nrows, "gk_csr_Dup: rowids"));
if (mat->rnorms)
nmat->rnorms = gk_fcopy(mat->nrows, mat->rnorms,
gk_fmalloc(mat->nrows, "gk_csr_Dup: rnorms"));
if (mat->rowind)
nmat->rowind = gk_icopy(mat->rowptr[mat->nrows], mat->rowind,
gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowind"));
if (mat->rowval)
nmat->rowval = gk_fcopy(mat->rowptr[mat->nrows], mat->rowval,
gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Dup: rowval"));
/* copy the col structure */
if (mat->colptr)
nmat->colptr = gk_zcopy(mat->ncols+1, mat->colptr,
gk_zmalloc(mat->ncols+1, "gk_csr_Dup: colptr"));
if (mat->colids)
nmat->colids = gk_icopy(mat->ncols, mat->colids,
gk_imalloc(mat->ncols, "gk_csr_Dup: colids"));
if (mat->cnorms)
nmat->cnorms = gk_fcopy(mat->ncols, mat->cnorms,
gk_fmalloc(mat->ncols, "gk_csr_Dup: cnorms"));
if (mat->colind)
nmat->colind = gk_icopy(mat->colptr[mat->ncols], mat->colind,
gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colind"));
if (mat->colval)
nmat->colval = gk_fcopy(mat->colptr[mat->ncols], mat->colval,
gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Dup: colval"));
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix containint a set of consecutive rows.
\param mat is the original matrix.
\param rstart is the starting row.
\param nrows is the number of rows from rstart to extract.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractSubmatrix(gk_csr_t *mat, int rstart, int nrows)
{
ssize_t i;
gk_csr_t *nmat;
if (rstart+nrows > mat->nrows)
return NULL;
nmat = gk_csr_Create();
nmat->nrows = nrows;
nmat->ncols = mat->ncols;
/* copy the row structure */
if (mat->rowptr)
nmat->rowptr = gk_zcopy(nrows+1, mat->rowptr+rstart,
gk_zmalloc(nrows+1, "gk_csr_ExtractSubmatrix: rowptr"));
for (i=nrows; i>=0; i--)
nmat->rowptr[i] -= nmat->rowptr[0];
ASSERT(nmat->rowptr[0] == 0);
if (mat->rowids)
nmat->rowids = gk_icopy(nrows, mat->rowids+rstart,
gk_imalloc(nrows, "gk_csr_ExtractSubmatrix: rowids"));
if (mat->rnorms)
nmat->rnorms = gk_fcopy(nrows, mat->rnorms+rstart,
gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rnorms"));
if (mat->rsums)
nmat->rsums = gk_fcopy(nrows, mat->rsums+rstart,
gk_fmalloc(nrows, "gk_csr_ExtractSubmatrix: rsums"));
ASSERT(nmat->rowptr[nrows] == mat->rowptr[rstart+nrows]-mat->rowptr[rstart]);
if (mat->rowind)
nmat->rowind = gk_icopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
mat->rowind+mat->rowptr[rstart],
gk_imalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
"gk_csr_ExtractSubmatrix: rowind"));
if (mat->rowval)
nmat->rowval = gk_fcopy(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
mat->rowval+mat->rowptr[rstart],
gk_fmalloc(mat->rowptr[rstart+nrows]-mat->rowptr[rstart],
"gk_csr_ExtractSubmatrix: rowval"));
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix containing a certain set of rows.
\param mat is the original matrix.
\param nrows is the number of rows to extract.
\param rind is the set of row numbers to extract.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractRows(gk_csr_t *mat, int nrows, int *rind)
{
ssize_t i, ii, j, nnz;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = nrows;
nmat->ncols = mat->ncols;
for (nnz=0, i=0; i<nrows; i++)
nnz += mat->rowptr[rind[i]+1]-mat->rowptr[rind[i]];
nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr");
nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind");
nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval");
nmat->rowptr[0] = 0;
for (nnz=0, j=0, ii=0; ii<nrows; ii++) {
i = rind[ii];
gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz);
gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz);
nnz += mat->rowptr[i+1]-mat->rowptr[i];
nmat->rowptr[++j] = nnz;
}
ASSERT(j == nmat->nrows);
return nmat;
}
/*************************************************************************/
/*! Returns a submatrix corresponding to a specified partitioning of rows.
\param mat is the original matrix.
\param part is the partitioning vector of the rows.
\param pid is the partition ID that will be extracted.
\returns the row structure of the newly created submatrix.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ExtractPartition(gk_csr_t *mat, int *part, int pid)
{
ssize_t i, j, nnz;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = 0;
nmat->ncols = mat->ncols;
for (nnz=0, i=0; i<mat->nrows; i++) {
if (part[i] == pid) {
nmat->nrows++;
nnz += mat->rowptr[i+1]-mat->rowptr[i];
}
}
nmat->rowptr = gk_zmalloc(nmat->nrows+1, "gk_csr_ExtractPartition: rowptr");
nmat->rowind = gk_imalloc(nnz, "gk_csr_ExtractPartition: rowind");
nmat->rowval = gk_fmalloc(nnz, "gk_csr_ExtractPartition: rowval");
nmat->rowptr[0] = 0;
for (nnz=0, j=0, i=0; i<mat->nrows; i++) {
if (part[i] == pid) {
gk_icopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowind+mat->rowptr[i], nmat->rowind+nnz);
gk_fcopy(mat->rowptr[i+1]-mat->rowptr[i], mat->rowval+mat->rowptr[i], nmat->rowval+nnz);
nnz += mat->rowptr[i+1]-mat->rowptr[i];
nmat->rowptr[++j] = nnz;
}
}
ASSERT(j == nmat->nrows);
return nmat;
}
/*************************************************************************/
/*! Splits the matrix into multiple sub-matrices based on the provided
color array.
\param mat is the original matrix.
\param color is an array of size equal to the number of non-zeros
in the matrix (row-wise structure). The matrix is split into
as many parts as the number of colors. For meaningfull results,
the colors should be numbered consecutively starting from 0.
\returns an array of matrices for each supplied color number.
*/
/**************************************************************************/
gk_csr_t **gk_csr_Split(gk_csr_t *mat, int *color)
{
ssize_t i, j;
int nrows, ncolors;
ssize_t *rowptr;
int *rowind;
float *rowval;
gk_csr_t **smats;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
ncolors = gk_imax(rowptr[nrows], color)+1;
smats = (gk_csr_t **)gk_malloc(sizeof(gk_csr_t *)*ncolors, "gk_csr_Split: smats");
for (i=0; i<ncolors; i++) {
smats[i] = gk_csr_Create();
smats[i]->nrows = mat->nrows;
smats[i]->ncols = mat->ncols;
smats[i]->rowptr = gk_zsmalloc(nrows+1, 0, "gk_csr_Split: smats[i]->rowptr");
}
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
smats[color[j]]->rowptr[i]++;
}
for (i=0; i<ncolors; i++)
MAKECSR(j, nrows, smats[i]->rowptr);
for (i=0; i<ncolors; i++) {
smats[i]->rowind = gk_imalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowind");
smats[i]->rowval = gk_fmalloc(smats[i]->rowptr[nrows], "gk_csr_Split: smats[i]->rowval");
}
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
smats[color[j]]->rowind[smats[color[j]]->rowptr[i]] = rowind[j];
smats[color[j]]->rowval[smats[color[j]]->rowptr[i]] = rowval[j];
smats[color[j]]->rowptr[i]++;
}
}
for (i=0; i<ncolors; i++)
SHIFTCSR(j, nrows, smats[i]->rowptr);
return smats;
}
/**************************************************************************/
/*! Reads a CSR matrix from the supplied file and stores it the matrix's
forward structure.
\param filename is the file that stores the data.
\param format is either GK_CSR_FMT_METIS, GK_CSR_FMT_CLUTO,
GK_CSR_FMT_CSR, GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL
specifying the type of the input format.
The GK_CSR_FMT_CSR does not contain a header
line, whereas the GK_CSR_FMT_BINROW is a binary format written
by gk_csr_Write() using the same format specifier.
\param readvals is either 1 or 0, indicating if the CSR file contains
values or it does not. It only applies when GK_CSR_FMT_CSR is
used.
\param numbering is either 1 or 0, indicating if the numbering of the
indices start from 1 or 0, respectively. If they start from 1,
they are automatically decreamented during input so that they
will start from 0. It only applies when GK_CSR_FMT_CSR is
used.
\returns the matrix that was read.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Read(char *filename, int format, int readvals, int numbering)
{
ssize_t i, k, l;
size_t nfields, nrows, ncols, nnz, fmt, ncon;
size_t lnlen;
ssize_t *rowptr;
int *rowind, ival;
float *rowval=NULL, fval;
int readsizes, readwgts;
char *line=NULL, *head, *tail, fmtstr[256];
FILE *fpin;
gk_csr_t *mat=NULL;
if (!gk_fexists(filename))
gk_errexit(SIGERR, "File %s does not exist!\n", filename);
if (format == GK_CSR_FMT_BINROW) {
mat = gk_csr_Create();
fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin");
if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename);
if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename);
mat->rowptr = gk_zmalloc(mat->nrows+1, "gk_csr_Read: rowptr");
if (fread(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpin) != mat->nrows+1)
gk_errexit(SIGERR, "Failed to read the rowptr from file %s!\n", filename);
mat->rowind = gk_imalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowind");
if (fread(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows])
gk_errexit(SIGERR, "Failed to read the rowind from file %s!\n", filename);
if (readvals == 1) {
mat->rowval = gk_fmalloc(mat->rowptr[mat->nrows], "gk_csr_Read: rowval");
if (fread(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpin) != mat->rowptr[mat->nrows])
gk_errexit(SIGERR, "Failed to read the rowval from file %s!\n", filename);
}
gk_fclose(fpin);
return mat;
}
if (format == GK_CSR_FMT_BINCOL) {
mat = gk_csr_Create();
fpin = gk_fopen(filename, "rb", "gk_csr_Read: fpin");
if (fread(&(mat->nrows), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the nrows from file %s!\n", filename);
if (fread(&(mat->ncols), sizeof(int32_t), 1, fpin) != 1)
gk_errexit(SIGERR, "Failed to read the ncols from file %s!\n", filename);
mat->colptr = gk_zmalloc(mat->ncols+1, "gk_csr_Read: colptr");
if (fread(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpin) != mat->ncols+1)
gk_errexit(SIGERR, "Failed to read the colptr from file %s!\n", filename);
mat->colind = gk_imalloc(mat->colptr[mat->ncols], "gk_csr_Read: colind");
if (fread(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols])
gk_errexit(SIGERR, "Failed to read the colind from file %s!\n", filename);
if (readvals) {
mat->colval = gk_fmalloc(mat->colptr[mat->ncols], "gk_csr_Read: colval");
if (fread(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpin) != mat->colptr[mat->ncols])
gk_errexit(SIGERR, "Failed to read the colval from file %s!\n", filename);
}
gk_fclose(fpin);
return mat;
}
if (format == GK_CSR_FMT_CLUTO) {
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
do {
if (gk_getline(&line, &lnlen, fpin) <= 0)
gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename);
} while (line[0] == '%');
if (sscanf(line, "%zu %zu %zu", &nrows, &ncols, &nnz) != 3)
gk_errexit(SIGERR, "Header line must contain 3 integers.\n");
readsizes = 0;
readwgts = 0;
readvals = 1;
numbering = 1;
}
else if (format == GK_CSR_FMT_METIS) {
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
do {
if (gk_getline(&line, &lnlen, fpin) <= 0)
gk_errexit(SIGERR, "Premature end of input file: file:%s\n", filename);
} while (line[0] == '%');
fmt = ncon = 0;
nfields = sscanf(line, "%zu %zu %zu %zu", &nrows, &nnz, &fmt, &ncon);
if (nfields < 2)
gk_errexit(SIGERR, "Header line must contain at least 2 integers (#vtxs and #edges).\n");
ncols = nrows;
nnz *= 2;
if (fmt > 111)
gk_errexit(SIGERR, "Cannot read this type of file format [fmt=%zu]!\n", fmt);
sprintf(fmtstr, "%03zu", fmt%1000);
readsizes = (fmtstr[0] == '1');
readwgts = (fmtstr[1] == '1');
readvals = (fmtstr[2] == '1');
numbering = 1;
ncon = (ncon == 0 ? 1 : ncon);
}
else {
readsizes = 0;
readwgts = 0;
gk_getfilestats(filename, &nrows, &nnz, NULL, NULL);
if (readvals == 1 && nnz%2 == 1)
gk_errexit(SIGERR, "Error: The number of numbers (%zd %d) in the input file is not even.\n", nnz, readvals);
if (readvals == 1)
nnz = nnz/2;
fpin = gk_fopen(filename, "r", "gk_csr_Read: fpin");
}
mat = gk_csr_Create();
mat->nrows = nrows;
rowptr = mat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Read: rowptr");
rowind = mat->rowind = gk_imalloc(nnz, "gk_csr_Read: rowind");
if (readvals != 2)
rowval = mat->rowval = gk_fsmalloc(nnz, 1.0, "gk_csr_Read: rowval");
if (readsizes)
mat->rsizes = gk_fsmalloc(nrows, 0.0, "gk_csr_Read: rsizes");
if (readwgts)
mat->rwgts = gk_fsmalloc(nrows*ncon, 0.0, "gk_csr_Read: rwgts");
/*----------------------------------------------------------------------
* Read the sparse matrix file
*---------------------------------------------------------------------*/
numbering = (numbering ? - 1 : 0);
for (ncols=0, rowptr[0]=0, k=0, i=0; i<nrows; i++) {
do {
if (gk_getline(&line, &lnlen, fpin) == -1)
gk_errexit(SIGERR, "Premature end of input file: file while reading row %d\n", i);
} while (line[0] == '%');
head = line;
tail = NULL;
/* Read vertex sizes */
if (readsizes) {
#ifdef __MSC__
mat->rsizes[i] = (float)strtod(head, &tail);
#else
mat->rsizes[i] = strtof(head, &tail);
#endif
if (tail == head)
gk_errexit(SIGERR, "The line for vertex %zd does not have size information\n", i+1);
if (mat->rsizes[i] < 0)
errexit("The size for vertex %zd must be >= 0\n", i+1);
head = tail;
}
/* Read vertex weights */
if (readwgts) {
for (l=0; l<ncon; l++) {
#ifdef __MSC__
mat->rwgts[i*ncon+l] = (float)strtod(head, &tail);
#else
mat->rwgts[i*ncon+l] = strtof(head, &tail);
#endif
if (tail == head)
errexit("The line for vertex %zd does not have enough weights "
"for the %d constraints.\n", i+1, ncon);
if (mat->rwgts[i*ncon+l] < 0)
errexit("The weight vertex %zd and constraint %zd must be >= 0\n", i+1, l);
head = tail;
}
}
/* Read the rest of the row */
while (1) {
ival = (int)strtol(head, &tail, 0);
if (tail == head)
break;
head = tail;
if ((rowind[k] = ival + numbering) < 0)
gk_errexit(SIGERR, "Error: Invalid column number %d at row %zd.\n", ival, i);
ncols = gk_max(rowind[k], ncols);
if (readvals == 1) {
#ifdef __MSC__
fval = (float)strtod(head, &tail);
#else
fval = strtof(head, &tail);
#endif
if (tail == head)
gk_errexit(SIGERR, "Value could not be found for column! Row:%zd, NNZ:%zd\n", i, k);
head = tail;
rowval[k] = fval;
}
k++;
}
rowptr[i+1] = k;
}
if (format == GK_CSR_FMT_METIS) {
ASSERT(ncols+1 == mat->nrows);
mat->ncols = mat->nrows;
}
else {
mat->ncols = ncols+1;
}
if (k != nnz)
gk_errexit(SIGERR, "gk_csr_Read: Something wrong with the number of nonzeros in "
"the input file. NNZ=%zd, ActualNNZ=%zd.\n", nnz, k);
gk_fclose(fpin);
gk_free((void **)&line, LTERM);
return mat;
}
/**************************************************************************/
/*! Writes the row-based structure of a matrix into a file.
\param mat is the matrix to be written,
\param filename is the name of the output file.
\param format is one of: GK_CSR_FMT_CLUTO, GK_CSR_FMT_CSR,
GK_CSR_FMT_BINROW, GK_CSR_FMT_BINCOL.
\param writevals is either 1 or 0 indicating if the values will be
written or not. This is only applicable when GK_CSR_FMT_CSR
is used.
\param numbering is either 1 or 0 indicating if the internal 0-based
numbering will be shifted by one or not during output. This
is only applicable when GK_CSR_FMT_CSR is used.
*/
/**************************************************************************/
void gk_csr_Write(gk_csr_t *mat, char *filename, int format, int writevals, int numbering)
{
ssize_t i, j;
FILE *fpout;
if (format == GK_CSR_FMT_BINROW) {
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout");
fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout);
fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout);
fwrite(mat->rowptr, sizeof(ssize_t), mat->nrows+1, fpout);
fwrite(mat->rowind, sizeof(int32_t), mat->rowptr[mat->nrows], fpout);
if (writevals)
fwrite(mat->rowval, sizeof(float), mat->rowptr[mat->nrows], fpout);
gk_fclose(fpout);
return;
}
if (format == GK_CSR_FMT_BINCOL) {
if (filename == NULL)
gk_errexit(SIGERR, "The filename parameter cannot be NULL.\n");
fpout = gk_fopen(filename, "wb", "gk_csr_Write: fpout");
fwrite(&(mat->nrows), sizeof(int32_t), 1, fpout);
fwrite(&(mat->ncols), sizeof(int32_t), 1, fpout);
fwrite(mat->colptr, sizeof(ssize_t), mat->ncols+1, fpout);
fwrite(mat->colind, sizeof(int32_t), mat->colptr[mat->ncols], fpout);
if (writevals)
fwrite(mat->colval, sizeof(float), mat->colptr[mat->ncols], fpout);
gk_fclose(fpout);
return;
}
if (filename)
fpout = gk_fopen(filename, "w", "gk_csr_Write: fpout");
else
fpout = stdout;
if (format == GK_CSR_FMT_CLUTO) {
fprintf(fpout, "%d %d %zd\n", mat->nrows, mat->ncols, mat->rowptr[mat->nrows]);
writevals = 1;
numbering = 1;
}
for (i=0; i<mat->nrows; i++) {
for (j=mat->rowptr[i]; j<mat->rowptr[i+1]; j++) {
fprintf(fpout, " %d", mat->rowind[j]+(numbering ? 1 : 0));
if (writevals)
fprintf(fpout, " %f", mat->rowval[j]);
}
fprintf(fpout, "\n");
}
if (filename)
gk_fclose(fpout);
}
/*************************************************************************/
/*! Prunes certain rows/columns of the matrix. The prunning takes place
by analyzing the row structure of the matrix. The prunning takes place
by removing rows/columns but it does not affect the numbering of the
remaining rows/columns.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param minf is the minimum number of rows (columns) that a column (row) must
be present in order to be kept,
\param maxf is the maximum number of rows (columns) that a column (row) must
be present at in order to be kept.
\returns the prunned matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_Prune(gk_csr_t *mat, int what, int minf, int maxf)
{
ssize_t i, j, nnz;
int nrows, ncols;
ssize_t *rowptr, *nrowptr;
int *rowind, *nrowind, *collen;
float *rowval, *nrowval;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_Prune: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_Prune: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_Prune: nrowval");
switch (what) {
case GK_CSR_COL:
collen = gk_ismalloc(ncols, 0, "gk_csr_Prune: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
ASSERT(rowind[j] < ncols);
collen[rowind[j]]++;
}
}
for (i=0; i<ncols; i++)
collen[i] = (collen[i] >= minf && collen[i] <= maxf ? 1 : 0);
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (collen[rowind[j]]) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
nnz++;
}
}
nrowptr[i+1] = nnz;
}
gk_free((void **)&collen, LTERM);
break;
case GK_CSR_ROW:
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
if (rowptr[i+1]-rowptr[i] >= minf && rowptr[i+1]-rowptr[i] <= maxf) {
for (j=rowptr[i]; j<rowptr[i+1]; j++, nnz++) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
}
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the highest weight entries whose
sum accounts for a certain fraction of the overall weight of the
row/column.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param norm indicates the norm that will be used to aggregate the weights
and possible values are 1 or 2,
\param fraction is the fraction of the overall norm that will be retained
by the kept entries.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_LowFilter(gk_csr_t *mat, int what, int norm, float fraction)
{
ssize_t i, j, nnz;
int nrows, ncols, ncand, maxlen=0;
ssize_t *rowptr, *colptr, *nrowptr;
int *rowind, *colind, *nrowind;
float *rowval, *colval, *nrowval, rsum, tsum;
gk_csr_t *nmat;
gk_fkv_t *cand;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval");
switch (what) {
case GK_CSR_COL:
if (mat->colptr == NULL)
gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n");
gk_zcopy(nrows+1, rowptr, nrowptr);
for (i=0; i<ncols; i++)
maxlen = gk_max(maxlen, colptr[i+1]-colptr[i]);
#pragma omp parallel private(i, j, ncand, rsum, tsum, cand)
{
cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand");
#pragma omp for schedule(static)
for (i=0; i<ncols; i++) {
for (tsum=0.0, ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) {
cand[ncand].val = colind[j];
cand[ncand].key = colval[j];
tsum += (norm == 1 ? colval[j] : colval[j]*colval[j]);
}
gk_fkvsortd(ncand, cand);
for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) {
rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key);
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
}
gk_free((void **)&cand, LTERM);
}
/* compact the nrowind/nrowval */
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i] = nnz;
}
SHIFTCSR(i, nrows, nrowptr);
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
for (i=0; i<nrows; i++)
maxlen = gk_max(maxlen, rowptr[i+1]-rowptr[i]);
#pragma omp parallel private(i, j, ncand, rsum, tsum, cand)
{
cand = gk_fkvmalloc(maxlen, "gk_csr_LowFilter: cand");
#pragma omp for schedule(static)
for (i=0; i<nrows; i++) {
for (tsum=0.0, ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) {
cand[ncand].val = rowind[j];
cand[ncand].key = rowval[j];
tsum += (norm == 1 ? rowval[j] : rowval[j]*rowval[j]);
}
gk_fkvsortd(ncand, cand);
for (rsum=0.0, j=0; j<ncand && rsum<=fraction*tsum; j++) {
rsum += (norm == 1 ? cand[j].key : cand[j].key*cand[j].key);
nrowind[rowptr[i]+j] = cand[j].val;
nrowval[rowptr[i]+j] = cand[j].key;
}
nrowptr[i+1] = rowptr[i]+j;
}
gk_free((void **)&cand, LTERM);
}
/* compact nrowind/nrowval */
nrowptr[0] = nnz = 0;
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i+1]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the highest weight top-K entries
along each row/column and those entries whose weight is greater than
a specified value.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param topk is the number of the highest weight entries to keep.
\param keepval is the weight of a term above which will be kept. This
is used to select additional terms past the first topk.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_TopKPlusFilter(gk_csr_t *mat, int what, int topk, float keepval)
{
ssize_t i, j, k, nnz;
int nrows, ncols, ncand;
ssize_t *rowptr, *colptr, *nrowptr;
int *rowind, *colind, *nrowind;
float *rowval, *colval, *nrowval;
gk_csr_t *nmat;
gk_fkv_t *cand;
nmat = gk_csr_Create();
nrows = nmat->nrows = mat->nrows;
ncols = nmat->ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_LowFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_LowFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_LowFilter: nrowval");
switch (what) {
case GK_CSR_COL:
if (mat->colptr == NULL)
gk_errexit(SIGERR, "Cannot filter columns when column-based structure has not been created.\n");
cand = gk_fkvmalloc(nrows, "gk_csr_LowFilter: cand");
gk_zcopy(nrows+1, rowptr, nrowptr);
for (i=0; i<ncols; i++) {
for (ncand=0, j=colptr[i]; j<colptr[i+1]; j++, ncand++) {
cand[ncand].val = colind[j];
cand[ncand].key = colval[j];
}
gk_fkvsortd(ncand, cand);
k = gk_min(topk, ncand);
for (j=0; j<k; j++) {
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
for (; j<ncand; j++) {
if (cand[j].key < keepval)
break;
nrowind[nrowptr[cand[j].val]] = i;
nrowval[nrowptr[cand[j].val]] = cand[j].key;
nrowptr[cand[j].val]++;
}
}
/* compact the nrowind/nrowval */
for (nnz=0, i=0; i<nrows; i++) {
for (j=rowptr[i]; j<nrowptr[i]; j++, nnz++) {
nrowind[nnz] = nrowind[j];
nrowval[nnz] = nrowval[j];
}
nrowptr[i] = nnz;
}
SHIFTCSR(i, nrows, nrowptr);
gk_free((void **)&cand, LTERM);
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
cand = gk_fkvmalloc(ncols, "gk_csr_LowFilter: cand");
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
for (ncand=0, j=rowptr[i]; j<rowptr[i+1]; j++, ncand++) {
cand[ncand].val = rowind[j];
cand[ncand].key = rowval[j];
}
gk_fkvsortd(ncand, cand);
k = gk_min(topk, ncand);
for (j=0; j<k; j++, nnz++) {
nrowind[nnz] = cand[j].val;
nrowval[nnz] = cand[j].key;
}
for (; j<ncand; j++, nnz++) {
if (cand[j].key < keepval)
break;
nrowind[nnz] = cand[j].val;
nrowval[nnz] = cand[j].key;
}
nrowptr[i+1] = nnz;
}
gk_free((void **)&cand, LTERM);
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Eliminates certain entries from the rows/columns of the matrix. The
filtering takes place by keeping only the terms whose contribution to
the total length of the document is greater than a user-splied multiple
over the average.
This routine assumes that the vectors are normalized to be unit length.
\param mat the matrix to be prunned,
\param what indicates if the rows (GK_CSR_ROW) or the columns (GK_CSR_COL)
of the matrix will be prunned,
\param zscore is the multiplicative factor over the average contribution
to the length of the document.
\returns the filtered matrix consisting only of its row-based structure.
The input matrix is not modified.
*/
/**************************************************************************/
gk_csr_t *gk_csr_ZScoreFilter(gk_csr_t *mat, int what, float zscore)
{
ssize_t i, j, nnz;
int nrows;
ssize_t *rowptr, *nrowptr;
int *rowind, *nrowind;
float *rowval, *nrowval, avgwgt;
gk_csr_t *nmat;
nmat = gk_csr_Create();
nmat->nrows = mat->nrows;
nmat->ncols = mat->ncols;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
nrowptr = nmat->rowptr = gk_zmalloc(nrows+1, "gk_csr_ZScoreFilter: nrowptr");
nrowind = nmat->rowind = gk_imalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowind");
nrowval = nmat->rowval = gk_fmalloc(rowptr[nrows], "gk_csr_ZScoreFilter: nrowval");
switch (what) {
case GK_CSR_COL:
gk_errexit(SIGERR, "This has not been implemented yet.\n");
break;
case GK_CSR_ROW:
if (mat->rowptr == NULL)
gk_errexit(SIGERR, "Cannot filter rows when row-based structure has not been created.\n");
nrowptr[0] = 0;
for (nnz=0, i=0; i<nrows; i++) {
avgwgt = zscore/(rowptr[i+1]-rowptr[i]);
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] > avgwgt) {
nrowind[nnz] = rowind[j];
nrowval[nnz] = rowval[j];
nnz++;
}
}
nrowptr[i+1] = nnz;
}
break;
default:
gk_csr_Free(&nmat);
gk_errexit(SIGERR, "Unknown prunning type of %d\n", what);
return NULL;
}
return nmat;
}
/*************************************************************************/
/*! Compacts the column-space of the matrix by removing empty columns.
As a result of the compaction, the column numbers are renumbered.
The compaction operation is done in place and only affects the row-based
representation of the matrix.
The new columns are ordered in decreasing frequency.
\param mat the matrix whose empty columns will be removed.
*/
/**************************************************************************/
void gk_csr_CompactColumns(gk_csr_t *mat)
{
ssize_t i;
int nrows, ncols, nncols;
ssize_t *rowptr;
int *rowind, *colmap;
gk_ikv_t *clens;
nrows = mat->nrows;
ncols = mat->ncols;
rowptr = mat->rowptr;
rowind = mat->rowind;
colmap = gk_imalloc(ncols, "gk_csr_CompactColumns: colmap");
clens = gk_ikvmalloc(ncols, "gk_csr_CompactColumns: clens");
for (i=0; i<ncols; i++) {
clens[i].key = 0;
clens[i].val = i;
}
for (i=0; i<rowptr[nrows]; i++)
clens[rowind[i]].key++;
gk_ikvsortd(ncols, clens);
for (nncols=0, i=0; i<ncols; i++) {
if (clens[i].key > 0)
colmap[clens[i].val] = nncols++;
else
break;
}
for (i=0; i<rowptr[nrows]; i++)
rowind[i] = colmap[rowind[i]];
mat->ncols = nncols;
gk_free((void **)&colmap, &clens, LTERM);
}
/*************************************************************************/
/*! Sorts the indices in increasing order
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which set of
indices to sort.
*/
/**************************************************************************/
void gk_csr_SortIndices(gk_csr_t *mat, int what)
{
int n, nn=0;
ssize_t *ptr;
int *ind;
float *val;
switch (what) {
case GK_CSR_ROW:
if (!mat->rowptr)
gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n");
n = mat->nrows;
ptr = mat->rowptr;
ind = mat->rowind;
val = mat->rowval;
break;
case GK_CSR_COL:
if (!mat->colptr)
gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n");
n = mat->ncols;
ptr = mat->colptr;
ind = mat->colind;
val = mat->colval;
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return;
}
#pragma omp parallel if (n > 100)
{
ssize_t i, j, k;
gk_ikv_t *cand;
float *tval;
#pragma omp single
for (i=0; i<n; i++)
nn = gk_max(nn, ptr[i+1]-ptr[i]);
cand = gk_ikvmalloc(nn, "gk_csr_SortIndices: cand");
tval = gk_fmalloc(nn, "gk_csr_SortIndices: tval");
#pragma omp for schedule(static)
for (i=0; i<n; i++) {
for (k=0, j=ptr[i]; j<ptr[i+1]; j++) {
if (j > ptr[i] && ind[j] < ind[j-1])
k = 1; /* an inversion */
cand[j-ptr[i]].val = j-ptr[i];
cand[j-ptr[i]].key = ind[j];
tval[j-ptr[i]] = val[j];
}
if (k) {
gk_ikvsorti(ptr[i+1]-ptr[i], cand);
for (j=ptr[i]; j<ptr[i+1]; j++) {
ind[j] = cand[j-ptr[i]].key;
val[j] = tval[cand[j-ptr[i]].val];
}
}
}
gk_free((void **)&cand, &tval, LTERM);
}
}
/*************************************************************************/
/*! Creates a row/column index from the column/row data.
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which index
will be created.
*/
/**************************************************************************/
void gk_csr_CreateIndex(gk_csr_t *mat, int what)
{
/* 'f' stands for forward, 'r' stands for reverse */
ssize_t i, j, k, nf, nr;
ssize_t *fptr, *rptr;
int *find, *rind;
float *fval, *rval;
switch (what) {
case GK_CSR_COL:
nf = mat->nrows;
fptr = mat->rowptr;
find = mat->rowind;
fval = mat->rowval;
if (mat->colptr) gk_free((void **)&mat->colptr, LTERM);
if (mat->colind) gk_free((void **)&mat->colind, LTERM);
if (mat->colval) gk_free((void **)&mat->colval, LTERM);
nr = mat->ncols;
rptr = mat->colptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr");
rind = mat->colind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind");
rval = mat->colval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL);
break;
case GK_CSR_ROW:
nf = mat->ncols;
fptr = mat->colptr;
find = mat->colind;
fval = mat->colval;
if (mat->rowptr) gk_free((void **)&mat->rowptr, LTERM);
if (mat->rowind) gk_free((void **)&mat->rowind, LTERM);
if (mat->rowval) gk_free((void **)&mat->rowval, LTERM);
nr = mat->nrows;
rptr = mat->rowptr = gk_zsmalloc(nr+1, 0, "gk_csr_CreateIndex: rptr");
rind = mat->rowind = gk_imalloc(fptr[nf], "gk_csr_CreateIndex: rind");
rval = mat->rowval = (fval ? gk_fmalloc(fptr[nf], "gk_csr_CreateIndex: rval") : NULL);
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return;
}
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rptr[find[j]]++;
}
MAKECSR(i, nr, rptr);
if (rptr[nr] > 6*nr) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rind[rptr[find[j]]++] = i;
}
SHIFTCSR(i, nr, rptr);
if (fval) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rval[rptr[find[j]]++] = fval[j];
}
SHIFTCSR(i, nr, rptr);
}
}
else {
if (fval) {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++) {
k = find[j];
rind[rptr[k]] = i;
rval[rptr[k]++] = fval[j];
}
}
}
else {
for (i=0; i<nf; i++) {
for (j=fptr[i]; j<fptr[i+1]; j++)
rind[rptr[find[j]]++] = i;
}
}
SHIFTCSR(i, nr, rptr);
}
}
/*************************************************************************/
/*! Normalizes the rows/columns of the matrix to be unit
length.
\param mat the matrix itself,
\param what indicates what will be normalized and is obtained by
specifying GK_CSR_ROW, GK_CSR_COL, GK_CSR_ROW|GK_CSR_COL.
\param norm indicates what norm is to normalize to, 1: 1-norm, 2: 2-norm
*/
/**************************************************************************/
void gk_csr_Normalize(gk_csr_t *mat, int what, int norm)
{
ssize_t i, j;
int n;
ssize_t *ptr;
float *val, sum;
if (what&GK_CSR_ROW && mat->rowval) {
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
#pragma omp parallel if (ptr[n] > OMPMINOPS)
{
#pragma omp for private(j,sum) schedule(static)
for (i=0; i<n; i++) {
for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++){
if (norm == 2)
sum += val[j]*val[j];
else if (norm == 1)
sum += val[j]; /* assume val[j] > 0 */
}
if (sum > 0) {
if (norm == 2)
sum=1.0/sqrt(sum);
else if (norm == 1)
sum=1.0/sum;
for (j=ptr[i]; j<ptr[i+1]; j++)
val[j] *= sum;
}
}
}
}
if (what&GK_CSR_COL && mat->colval) {
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
#pragma omp parallel if (ptr[n] > OMPMINOPS)
{
#pragma omp for private(j,sum) schedule(static)
for (i=0; i<n; i++) {
for (sum=0.0, j=ptr[i]; j<ptr[i+1]; j++)
if (norm == 2)
sum += val[j]*val[j];
else if (norm == 1)
sum += val[j];
if (sum > 0) {
if (norm == 2)
sum=1.0/sqrt(sum);
else if (norm == 1)
sum=1.0/sum;
for (j=ptr[i]; j<ptr[i+1]; j++)
val[j] *= sum;
}
}
}
}
}
/*************************************************************************/
/*! Applies different row scaling methods.
\param mat the matrix itself,
\param type indicates the type of row scaling. Possible values are:
GK_CSR_MAXTF, GK_CSR_SQRT, GK_CSR_LOG, GK_CSR_IDF, GK_CSR_MAXTF2.
*/
/**************************************************************************/
void gk_csr_Scale(gk_csr_t *mat, int type)
{
ssize_t i, j;
int nrows, ncols, nnzcols, bgfreq;
ssize_t *rowptr;
int *rowind, *collen;
float *rowval, *cscale, maxtf;
nrows = mat->nrows;
rowptr = mat->rowptr;
rowind = mat->rowind;
rowval = mat->rowval;
switch (type) {
case GK_CSR_MAXTF: /* TF' = .5 + .5*TF/MAX(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j, maxtf) schedule(static)
for (i=0; i<nrows; i++) {
maxtf = fabs(rowval[rowptr[i]]);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] = .5 + .5*rowval[j]/maxtf;
}
}
break;
case GK_CSR_MAXTF2: /* TF' = .1 + .9*TF/MAX(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j, maxtf) schedule(static)
for (i=0; i<nrows; i++) {
maxtf = fabs(rowval[rowptr[i]]);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
maxtf = (maxtf < fabs(rowval[j]) ? fabs(rowval[j]) : maxtf);
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] = .1 + .9*rowval[j]/maxtf;
}
}
break;
case GK_CSR_SQRT: /* TF' = .1+SQRT(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], sqrt(fabs(rowval[j])));
}
}
}
break;
case GK_CSR_POW25: /* TF' = .1+POW(TF,.25) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], sqrt(sqrt(fabs(rowval[j]))));
}
}
}
break;
case GK_CSR_POW65: /* TF' = .1+POW(TF,.65) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .65));
}
}
}
break;
case GK_CSR_POW75: /* TF' = .1+POW(TF,.75) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .75));
}
}
}
break;
case GK_CSR_POW85: /* TF' = .1+POW(TF,.85) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = .1+sign(rowval[j], powf(fabs(rowval[j]), .85));
}
}
}
break;
case GK_CSR_LOG: /* TF' = 1+log_2(TF) */
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
double logscale = 1.0/log(2.0);
#pragma omp for schedule(static,32)
for (i=0; i<rowptr[nrows]; i++) {
if (rowval[i] != 0.0)
rowval[i] = 1+(rowval[i]>0.0 ? log(rowval[i]) : -log(-rowval[i]))*logscale;
}
#ifdef XXX
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++) {
if (rowval[j] != 0.0)
rowval[j] = 1+(rowval[j]>0.0 ? log(rowval[j]) : -log(-rowval[j]))*logscale;
//rowval[j] = 1+sign(rowval[j], log(fabs(rowval[j]))*logscale);
}
}
#endif
}
break;
case GK_CSR_IDF: /* TF' = TF*IDF */
ncols = mat->ncols;
cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale");
collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
collen[rowind[j]]++;
}
#pragma omp parallel if (ncols > OMPMINOPS)
{
#pragma omp for schedule(static)
for (i=0; i<ncols; i++)
cscale[i] = (collen[i] > 0 ? log(1.0*nrows/collen[i]) : 0.0);
}
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] *= cscale[rowind[j]];
}
}
gk_free((void **)&cscale, &collen, LTERM);
break;
case GK_CSR_IDF2: /* TF' = TF*IDF */
ncols = mat->ncols;
cscale = gk_fmalloc(ncols, "gk_csr_Scale: cscale");
collen = gk_ismalloc(ncols, 0, "gk_csr_Scale: collen");
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
collen[rowind[j]]++;
}
nnzcols = 0;
#pragma omp parallel if (ncols > OMPMINOPS)
{
#pragma omp for schedule(static) reduction(+:nnzcols)
for (i=0; i<ncols; i++)
nnzcols += (collen[i] > 0 ? 1 : 0);
bgfreq = gk_max(10, (ssize_t)(.5*rowptr[nrows]/nnzcols));
printf("nnz: %zd, nnzcols: %d, bgfreq: %d\n", rowptr[nrows], nnzcols, bgfreq);
#pragma omp for schedule(static)
for (i=0; i<ncols; i++)
cscale[i] = (collen[i] > 0 ? log(1.0*(nrows+2*bgfreq)/(bgfreq+collen[i])) : 0.0);
}
#pragma omp parallel if (rowptr[nrows] > OMPMINOPS)
{
#pragma omp for private(j) schedule(static)
for (i=0; i<nrows; i++) {
for (j=rowptr[i]; j<rowptr[i+1]; j++)
rowval[j] *= cscale[rowind[j]];
}
}
gk_free((void **)&cscale, &collen, LTERM);
break;
default:
gk_errexit(SIGERR, "Unknown scaling type of %d\n", type);
}
}
/*************************************************************************/
/*! Computes the sums of the rows/columns
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which
sums to compute.
*/
/**************************************************************************/
void gk_csr_ComputeSums(gk_csr_t *mat, int what)
{
ssize_t i;
int n;
ssize_t *ptr;
float *val, *sums;
switch (what) {
case GK_CSR_ROW:
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
if (mat->rsums)
gk_free((void **)&mat->rsums, LTERM);
sums = mat->rsums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums");
break;
case GK_CSR_COL:
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
if (mat->csums)
gk_free((void **)&mat->csums, LTERM);
sums = mat->csums = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: sums");
break;
default:
gk_errexit(SIGERR, "Invalid sum type of %d.\n", what);
return;
}
#pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static)
for (i=0; i<n; i++)
sums[i] = gk_fsum(ptr[i+1]-ptr[i], val+ptr[i], 1);
}
/*************************************************************************/
/*! Computes the squared of the norms of the rows/columns
\param mat the matrix itself,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating which
squared norms to compute.
*/
/**************************************************************************/
void gk_csr_ComputeSquaredNorms(gk_csr_t *mat, int what)
{
ssize_t i;
int n;
ssize_t *ptr;
float *val, *norms;
switch (what) {
case GK_CSR_ROW:
n = mat->nrows;
ptr = mat->rowptr;
val = mat->rowval;
if (mat->rnorms) gk_free((void **)&mat->rnorms, LTERM);
norms = mat->rnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms");
break;
case GK_CSR_COL:
n = mat->ncols;
ptr = mat->colptr;
val = mat->colval;
if (mat->cnorms) gk_free((void **)&mat->cnorms, LTERM);
norms = mat->cnorms = gk_fsmalloc(n, 0, "gk_csr_ComputeSums: norms");
break;
default:
gk_errexit(SIGERR, "Invalid norm type of %d.\n", what);
return;
}
#pragma omp parallel for if (ptr[n] > OMPMINOPS) schedule(static)
for (i=0; i<n; i++)
norms[i] = gk_fdot(ptr[i+1]-ptr[i], val+ptr[i], 1, val+ptr[i], 1);
}
/*************************************************************************/
/*! Computes the similarity between two rows/columns
\param mat the matrix itself. The routine assumes that the indices
are sorted in increasing order.
\param i1 is the first row/column,
\param i2 is the second row/column,
\param what is either GK_CSR_ROW or GK_CSR_COL indicating the type of
objects between the similarity will be computed,
\param simtype is the type of similarity and is one of GK_CSR_COS,
GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN
\returns the similarity between the two rows/columns.
*/
/**************************************************************************/
float gk_csr_ComputeSimilarity(gk_csr_t *mat, int i1, int i2, int what, int simtype)
{
int nind1, nind2;
int *ind1, *ind2;
float *val1, *val2, stat1, stat2, sim;
switch (what) {
case GK_CSR_ROW:
if (!mat->rowptr)
gk_errexit(SIGERR, "Row-based view of the matrix does not exists.\n");
nind1 = mat->rowptr[i1+1]-mat->rowptr[i1];
nind2 = mat->rowptr[i2+1]-mat->rowptr[i2];
ind1 = mat->rowind + mat->rowptr[i1];
ind2 = mat->rowind + mat->rowptr[i2];
val1 = mat->rowval + mat->rowptr[i1];
val2 = mat->rowval + mat->rowptr[i2];
break;
case GK_CSR_COL:
if (!mat->colptr)
gk_errexit(SIGERR, "Column-based view of the matrix does not exists.\n");
nind1 = mat->colptr[i1+1]-mat->colptr[i1];
nind2 = mat->colptr[i2+1]-mat->colptr[i2];
ind1 = mat->colind + mat->colptr[i1];
ind2 = mat->colind + mat->colptr[i2];
val1 = mat->colval + mat->colptr[i1];
val2 = mat->colval + mat->colptr[i2];
break;
default:
gk_errexit(SIGERR, "Invalid index type of %d.\n", what);
return 0.0;
}
switch (simtype) {
case GK_CSR_COS:
case GK_CSR_JAC:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2]*val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1]*val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1]*val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2]*val2[i2];
i2++;
}
else {
sim += val1[i1]*val2[i2];
stat1 += val1[i1]*val1[i1];
stat2 += val2[i2]*val2[i2];
i1++;
i2++;
}
}
if (simtype == GK_CSR_COS)
sim = (stat1*stat2 > 0.0 ? sim/sqrt(stat1*stat2) : 0.0);
else
sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0);
break;
case GK_CSR_MIN:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2];
i2++;
}
else {
sim += gk_min(val1[i1],val2[i2]);
stat1 += val1[i1];
stat2 += val2[i2];
i1++;
i2++;
}
}
sim = (stat1+stat2-sim > 0.0 ? sim/(stat1+stat2-sim) : 0.0);
break;
case GK_CSR_AMIN:
sim = stat1 = stat2 = 0.0;
i1 = i2 = 0;
while (i1<nind1 && i2<nind2) {
if (i1 == nind1) {
stat2 += val2[i2];
i2++;
}
else if (i2 == nind2) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] < ind2[i2]) {
stat1 += val1[i1];
i1++;
}
else if (ind1[i1] > ind2[i2]) {
stat2 += val2[i2];
i2++;
}
else {
sim += gk_min(val1[i1],val2[i2]);
stat1 += val1[i1];
stat2 += val2[i2];
i1++;
i2++;
}
}
sim = (stat1 > 0.0 ? sim/stat1 : 0.0);
break;
default:
gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype);
return -1;
}
return sim;
}
/*************************************************************************/
/*! Finds the n most similar rows (neighbors) to the query using cosine
similarity.
\param mat the matrix itself
\param nqterms is the number of columns in the query
\param qind is the list of query columns
\param qval is the list of correspodning query weights
\param simtype is the type of similarity and is one of GK_CSR_COS,
GK_CSR_JAC, GK_CSR_MIN, GK_CSR_AMIN
\param nsim is the maximum number of requested most similar rows.
If -1 is provided, then everything is returned unsorted.
\param minsim is the minimum similarity of the requested most
similar rows
\param hits is the result set. This array should be at least
of length nsim.
\param i_marker is an array of size equal to the number of rows
whose values are initialized to -1. If NULL is provided
then this array is allocated and freed internally.
\param i_cand is an array of size equal to the number of rows.
If NULL is provided then this array is allocated and freed
internally.
\returns the number of identified most similar rows, which can be
smaller than the requested number of nnbrs in those cases
in which there are no sufficiently many neighbors.
*/
/**************************************************************************/
int gk_csr_GetSimilarRows(gk_csr_t *mat, int nqterms, int *qind,
float *qval, int simtype, int nsim, float minsim, gk_fkv_t *hits,
int *i_marker, gk_fkv_t *i_cand)
{
ssize_t i, ii, j, k;
int nrows, ncols, ncand;
ssize_t *colptr;
int *colind, *marker;
float *colval, *rnorms, mynorm, *rsums, mysum;
gk_fkv_t *cand;
if (nqterms == 0)
return 0;
nrows = mat->nrows;
ncols = mat->ncols;
colptr = mat->colptr;
colind = mat->colind;
colval = mat->colval;
marker = (i_marker ? i_marker : gk_ismalloc(nrows, -1, "gk_csr_SimilarRows: marker"));
cand = (i_cand ? i_cand : gk_fkvmalloc(nrows, "gk_csr_SimilarRows: cand"));
switch (simtype) {
case GK_CSR_COS:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += colval[j]*qval[ii];
}
}
}
break;
case GK_CSR_JAC:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += colval[j]*qval[ii];
}
}
}
rnorms = mat->rnorms;
mynorm = gk_fdot(nqterms, qval, 1, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/(rnorms[cand[i].val]+mynorm-cand[i].key);
break;
case GK_CSR_MIN:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += gk_min(colval[j], qval[ii]);
}
}
}
rsums = mat->rsums;
mysum = gk_fsum(nqterms, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/(rsums[cand[i].val]+mysum-cand[i].key);
break;
/* Assymetric MIN similarity */
case GK_CSR_AMIN:
for (ncand=0, ii=0; ii<nqterms; ii++) {
i = qind[ii];
if (i < ncols) {
for (j=colptr[i]; j<colptr[i+1]; j++) {
k = colind[j];
if (marker[k] == -1) {
cand[ncand].val = k;
cand[ncand].key = 0;
marker[k] = ncand++;
}
cand[marker[k]].key += gk_min(colval[j], qval[ii]);
}
}
}
mysum = gk_fsum(nqterms, qval, 1);
for (i=0; i<ncand; i++)
cand[i].key = cand[i].key/mysum;
break;
default:
gk_errexit(SIGERR, "Unknown similarity measure %d\n", simtype);
return -1;
}
/* go and prune the hits that are bellow minsim */
for (j=0, i=0; i<ncand; i++) {
marker[cand[i].val] = -1;
if (cand[i].key >= minsim)
cand[j++] = cand[i];
}
ncand = j;
if (nsim == -1 || nsim >= ncand) {
nsim = ncand;
}
else {
nsim = gk_min(nsim, ncand);
gk_dfkvkselect(ncand, nsim, cand);
gk_fkvsortd(nsim, cand);
}
gk_fkvcopy(nsim, cand, hits);
if (i_marker == NULL)
gk_free((void **)&marker, LTERM);
if (i_cand == NULL)
gk_free((void **)&cand, LTERM);
return nsim;
}
|
{
"pile_set_name": "Github"
}
|
# This is an automatically generated fragment file
#
$HDH
15 1 1 0
HDH
1 C1 C 3 1 0 1 1 0.597879 0.000000
2 O1 O 0 0 0 1 1 -0.656819 0.000000
3 C2 CT 0 0 0 1 1 -0.065272 0.000000
42H2 HC 0 0 0 1 1 0.032636 0.000000
53H2 HC 0 0 0 1 1 0.032636 0.000000
6 C3 CT 0 0 0 1 1 0.378592 0.000000
7 H3 H1 0 0 0 1 1 -0.030998 0.000000
8 O3 OH 0 0 0 1 1 -0.686049 0.000000
9 HO3 HO 0 0 0 1 1 0.397395 0.000000
10 C4 CT 0 0 0 1 1 0.001626 0.000000
112H4 HC 0 0 0 1 1 -0.000813 0.000000
123H4 HC 0 0 0 1 1 -0.000813 0.000000
13 C5 CT 4 0 0 1 1 -0.021174 0.000000
142H5 HC 0 0 0 1 1 0.010587 0.000000
153H5 HC 0 0 0 1 1 0.010587 0.000000
1 2
1 3
3 4
3 5
3 6
6 7
6 8
6 10
8 9
10 11
10 12
10 13
13 14
13 15
|
{
"pile_set_name": "Github"
}
|
//-----------------------------------------------------------------------------
// boost variant/detail/apply_visitor_binary.hpp header file
// See http://www.boost.org for updates, documentation, and revision history.
//-----------------------------------------------------------------------------
//
// Copyright (c) 2002-2003 Eric Friedman
// Copyright (c) 2014 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_VARIANT_DETAIL_APPLY_VISITOR_BINARY_HPP
#define BOOST_VARIANT_DETAIL_APPLY_VISITOR_BINARY_HPP
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#include <boost/variant/detail/generic_result_type.hpp>
#include <boost/variant/detail/apply_visitor_unary.hpp>
#if BOOST_WORKAROUND(__EDG__, BOOST_TESTED_AT(302))
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/not.hpp>
#include <boost/type_traits/is_const.hpp>
#endif
#if !defined(BOOST_NO_CXX14_DECLTYPE_AUTO) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276)
# include <boost/variant/detail/has_result_type.hpp>
#endif
namespace boost {
//////////////////////////////////////////////////////////////////////////
// function template apply_visitor(visitor, visitable1, visitable2)
//
// Visits visitable1 and visitable2 such that their values (which we
// shall call x and y, respectively) are used as arguments in the
// expression visitor(x, y).
//
namespace detail { namespace variant {
template <typename Visitor, typename Value1>
class apply_visitor_binary_invoke
{
public: // visitor typedefs
typedef typename Visitor::result_type
result_type;
private: // representation
Visitor& visitor_;
Value1& value1_;
public: // structors
apply_visitor_binary_invoke(Visitor& visitor, Value1& value1) BOOST_NOEXCEPT
: visitor_(visitor)
, value1_(value1)
{
}
public: // visitor interfaces
template <typename Value2>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
operator()(Value2& value2)
{
return visitor_(value1_, value2);
}
private:
apply_visitor_binary_invoke& operator=(const apply_visitor_binary_invoke&);
};
template <typename Visitor, typename Visitable2>
class apply_visitor_binary_unwrap
{
public: // visitor typedefs
typedef typename Visitor::result_type
result_type;
private: // representation
Visitor& visitor_;
Visitable2& visitable2_;
public: // structors
apply_visitor_binary_unwrap(Visitor& visitor, Visitable2& visitable2) BOOST_NOEXCEPT
: visitor_(visitor)
, visitable2_(visitable2)
{
}
public: // visitor interfaces
template <typename Value1>
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(result_type)
operator()(Value1& value1)
{
apply_visitor_binary_invoke<
Visitor
, Value1
> invoker(visitor_, value1);
return boost::apply_visitor(invoker, visitable2_);
}
private:
apply_visitor_binary_unwrap& operator=(const apply_visitor_binary_unwrap&);
};
}} // namespace detail::variant
//
// nonconst-visitor version:
//
#if !BOOST_WORKAROUND(__EDG__, BOOST_TESTED_AT(302))
# define BOOST_VARIANT_AUX_APPLY_VISITOR_NON_CONST_RESULT_TYPE(V) \
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(typename V::result_type) \
/**/
#else // EDG-based compilers
# define BOOST_VARIANT_AUX_APPLY_VISITOR_NON_CONST_RESULT_TYPE(V) \
typename enable_if< \
mpl::not_< is_const< V > > \
, BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(typename V::result_type) \
>::type \
/**/
#endif // EDG-based compilers workaround
template <typename Visitor, typename Visitable1, typename Visitable2>
inline
BOOST_VARIANT_AUX_APPLY_VISITOR_NON_CONST_RESULT_TYPE(Visitor)
apply_visitor(
Visitor& visitor
, Visitable1& visitable1, Visitable2& visitable2
)
{
::boost::detail::variant::apply_visitor_binary_unwrap<
Visitor, Visitable2
> unwrapper(visitor, visitable2);
return boost::apply_visitor(unwrapper, visitable1);
}
#undef BOOST_VARIANT_AUX_APPLY_VISITOR_NON_CONST_RESULT_TYPE
//
// const-visitor version:
//
template <typename Visitor, typename Visitable1, typename Visitable2>
inline
BOOST_VARIANT_AUX_GENERIC_RESULT_TYPE(
typename Visitor::result_type
)
apply_visitor(
const Visitor& visitor
, Visitable1& visitable1, Visitable2& visitable2
)
{
::boost::detail::variant::apply_visitor_binary_unwrap<
const Visitor, Visitable2
> unwrapper(visitor, visitable2);
return boost::apply_visitor(unwrapper, visitable1);
}
#if !defined(BOOST_NO_CXX14_DECLTYPE_AUTO) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276)
//////////////////////////////////////////////////////////////////////////
// function template apply_visitor(visitor, visitable1, visitable2)
//
// C++14 part.
//
namespace detail { namespace variant {
template <typename Visitor, typename Value1>
class apply_visitor_binary_invoke_cpp14
{
Visitor& visitor_;
Value1& value1_;
public: // structors
apply_visitor_binary_invoke_cpp14(Visitor& visitor, Value1& value1) BOOST_NOEXCEPT
: visitor_(visitor)
, value1_(value1)
{
}
public: // visitor interfaces
template <typename Value2>
decltype(auto) operator()(Value2& value2)
{
return visitor_(value1_, value2);
}
private:
apply_visitor_binary_invoke_cpp14& operator=(const apply_visitor_binary_invoke_cpp14&);
};
template <typename Visitor, typename Visitable2>
class apply_visitor_binary_unwrap_cpp14
{
Visitor& visitor_;
Visitable2& visitable2_;
public: // structors
apply_visitor_binary_unwrap_cpp14(Visitor& visitor, Visitable2& visitable2) BOOST_NOEXCEPT
: visitor_(visitor)
, visitable2_(visitable2)
{
}
public: // visitor interfaces
template <typename Value1>
decltype(auto) operator()(Value1& value1)
{
apply_visitor_binary_invoke_cpp14<
Visitor
, Value1
> invoker(visitor_, value1);
return boost::apply_visitor(invoker, visitable2_);
}
private:
apply_visitor_binary_unwrap_cpp14& operator=(const apply_visitor_binary_unwrap_cpp14&);
};
}} // namespace detail::variant
template <typename Visitor, typename Visitable1, typename Visitable2>
inline decltype(auto) apply_visitor(Visitor& visitor, Visitable1& visitable1, Visitable2& visitable2,
typename boost::disable_if<
boost::detail::variant::has_result_type<Visitor>
>::type* = 0)
{
::boost::detail::variant::apply_visitor_binary_unwrap_cpp14<
Visitor, Visitable2
> unwrapper(visitor, visitable2);
return boost::apply_visitor(unwrapper, visitable1);
}
template <typename Visitor, typename Visitable1, typename Visitable2>
inline decltype(auto) apply_visitor(const Visitor& visitor, Visitable1& visitable1, Visitable2& visitable2,
typename boost::disable_if<
boost::detail::variant::has_result_type<Visitor>
>::type* = 0)
{
::boost::detail::variant::apply_visitor_binary_unwrap_cpp14<
const Visitor, Visitable2
> unwrapper(visitor, visitable2);
return boost::apply_visitor(unwrapper, visitable1);
}
#endif // !defined(BOOST_NO_CXX14_DECLTYPE_AUTO) && !defined(BOOST_NO_CXX11_DECLTYPE_N3276)
} // namespace boost
#endif // BOOST_VARIANT_DETAIL_APPLY_VISITOR_BINARY_HPP
|
{
"pile_set_name": "Github"
}
|
Development Release (Auto-Generated)
====================================
This release was auto-generated by [Travis-CI](https://travis-ci.org/forkineye/ESPixelStick). ESP8266 Arduino and all required libraries were pulled from their current github repositories. This release is meant for testing purposes and **is not** considered stable. The latest stable release can be found on the [GitHub Release Page](https://github.com/forkineye/ESPixelStick/releases/latest). EFU files for updating are not included, however you can create them yourself within ESPSFlashTool.
|
{
"pile_set_name": "Github"
}
|
<#--
/**
$id:checkbox$
$author:sl
#date:2013.08.22
**/
-->
<#if (parameters.queryType!"SELECT" == "CHECKBOX")>
<input type="checkbox" id="${parameters.id!'x'}"
<#lt> dataattribute="${parameters.dataattribute!''}" cause="${parameters.cause!''}"<#rt>
<#lt> class="checkbox_td_query" changed="0" inputmode="${parameters.inputmode!''}" <#rt/>
<#if (parameters.queryValue!'0') == (parameters.checked!'1')>
<#lt> checked="checked" <#rt>
</#if>
<#lt> value="${parameters.queryValue!(parameters.notChecked!'0')}" <#rt>
<#lt> chk="${parameters.checked!'1'}" notchk="${parameters.notChecked!'0'}" <#rt>
<#if !(parameters.readonly!false)>
<#lt> onchange="checkOnChange(this, event)" <#rt>
<#else>
<#lt> disabled="disabled" <#rt>
</#if>
<#include "/${parameters.templateDir}/simple/scripting-events.ftl" /><#rt/>
<#include "/${parameters.templateDir}/simple/common-attributes.ftl" /><#rt/>
<#include "/${parameters.templateDir}/simple/dynamic-attributes.ftl" /><#rt/>
/><#t>
<#else>
<select onChange="selectChange(this,event)" id="${parameters.id}" <#rt>
<#lt> inputmode="${parameters.inputmode}" changed="0" dataattribute="${parameters.dataattribute!}" <#rt>
<#lt> cause="=?" class="checkbox_td_query"><#t>
<option value="">ALL</option>
<option value="${parameters.checked!'1'}">True</option>
<option value="${parameters.notChecked!'0'}">False</option>
</select>
</#if>
|
{
"pile_set_name": "Github"
}
|
function merge(target) {
console.dir(target, arguments);
var objects = Array.prototype.slice.call(arguments, 1),
keys = [],
log = console.log;
objects.forEach(function (val, idx) {
keys = Object.keys(val);
keys.forEach(function (val) {
target[val] = objects[idx][val];
App.logger.warn("Hello World");
console.log(keys);
debugger;
//<development>
clean('this').developmentPragma;
//</development>
});
});
App.logger.log("Hello World");
console.log('all duplicates, get more');
console.log("loadImageInCache():::::", index+1, index+1 % 2);
console.log("external() open()", url, scrollee);
//<validation>
clean('this').validationPragma;
//</validation>
}
|
{
"pile_set_name": "Github"
}
|
/**
@license
Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import { Action } from 'redux';
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
export interface CounterActionIncrement extends Action<'INCREMENT'> {};
export interface CounterActionDecrement extends Action<'DECREMENT'> {};
export type CounterAction = CounterActionIncrement | CounterActionDecrement;
export const increment = (): CounterActionIncrement => {
return {
type: INCREMENT
};
};
export const decrement = (): CounterActionDecrement => {
return {
type: DECREMENT
};
};
|
{
"pile_set_name": "Github"
}
|
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /home/mikel/developer/android-studio/sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
|
{
"pile_set_name": "Github"
}
|
// META: global=jsshell
// META: script=/wasm/jsapi/assertions.js
function assert_Memory(memory, expected) {
assert_equals(Object.getPrototypeOf(memory), WebAssembly.Memory.prototype,
"prototype");
assert_true(Object.isExtensible(memory), "extensible");
// https://github.com/WebAssembly/spec/issues/840
assert_equals(memory.buffer, memory.buffer, "buffer should be idempotent");
const isShared = !!expected.shared;
const bufferType = isShared ? self.SharedArrayBuffer : ArrayBuffer;
assert_equals(Object.getPrototypeOf(memory.buffer), bufferType.prototype,
'prototype of buffer');
assert_equals(memory.buffer.byteLength, 0x10000 * expected.size, "size of buffer");
if (expected.size > 0) {
const array = new Uint8Array(memory.buffer);
assert_equals(array[0], 0, "first element of buffer");
assert_equals(array[array.byteLength - 1], 0, "last element of buffer");
}
assert_equals(isShared, Object.isFrozen(memory.buffer), "buffer frozen");
assert_not_equals(Object.isExtensible(memory.buffer), isShared, "buffer extensibility");
}
test(() => {
assert_function_name(WebAssembly.Memory, "Memory", "WebAssembly.Memory");
}, "name");
test(() => {
assert_function_length(WebAssembly.Memory, 1, "WebAssembly.Memory");
}, "length");
test(() => {
assert_throws(new TypeError(), () => new WebAssembly.Memory());
}, "No arguments");
test(() => {
const argument = { "initial": 0 };
assert_throws(new TypeError(), () => WebAssembly.Memory(argument));
}, "Calling");
test(() => {
const invalidArguments = [
undefined,
null,
false,
true,
"",
"test",
Symbol(),
1,
NaN,
{},
];
for (const invalidArgument of invalidArguments) {
assert_throws(new TypeError(),
() => new WebAssembly.Memory(invalidArgument),
`new Memory(${format_value(invalidArgument)})`);
}
}, "Invalid descriptor argument");
test(() => {
assert_throws(new TypeError(), () => new WebAssembly.Memory({ "initial": undefined }));
}, "Undefined initial value in descriptor");
const outOfRangeValues = [
NaN,
Infinity,
-Infinity,
-1,
0x100000000,
0x1000000000,
];
for (const value of outOfRangeValues) {
test(() => {
assert_throws(new TypeError(), () => new WebAssembly.Memory({ "initial": value }));
}, `Out-of-range initial value in descriptor: ${format_value(value)}`);
test(() => {
assert_throws(new TypeError(), () => new WebAssembly.Memory({ "initial": 0, "maximum": value }));
}, `Out-of-range maximum value in descriptor: ${format_value(value)}`);
}
test(() => {
assert_throws(new RangeError(), () => new WebAssembly.Memory({ "initial": 10, "maximum": 9 }));
}, "Initial value exceeds maximum");
test(() => {
assert_throws(new TypeError(), () => new WebAssembly.Memory({ "initial": 10, "shared": true }));
}, "Shared memory without maximum");
test(() => {
const proxy = new Proxy({}, {
has(o, x) {
assert_unreached(`Should not call [[HasProperty]] with ${x}`);
},
get(o, x) {
return 0;
},
});
new WebAssembly.Memory(proxy);
}, "Proxy descriptor");
test(() => {
const order = [];
new WebAssembly.Memory({
get maximum() {
order.push("maximum");
return {
valueOf() {
order.push("maximum valueOf");
return 1;
},
};
},
get initial() {
order.push("initial");
return {
valueOf() {
order.push("initial valueOf");
return 1;
},
};
},
});
assert_array_equals(order, [
"initial",
"initial valueOf",
"maximum",
"maximum valueOf",
]);
}, "Order of evaluation for descriptor");
test(t => {
const order = [];
new WebAssembly.Memory({
get maximum() {
order.push("maximum");
return {
valueOf() {
order.push("maximum valueOf");
return 1;
},
};
},
get initial() {
order.push("initial");
return {
valueOf() {
order.push("initial valueOf");
return 1;
},
};
},
get shared() {
order.push("shared");
return {
valueOf: t.unreached_func("should not call shared valueOf"),
};
},
});
assert_array_equals(order, [
"initial",
"initial valueOf",
"maximum",
"maximum valueOf",
"shared",
]);
}, "Order of evaluation for descriptor (with shared)");
test(() => {
const argument = { "initial": 0 };
const memory = new WebAssembly.Memory(argument);
assert_Memory(memory, { "size": 0 });
}, "Zero initial");
test(() => {
const argument = { "initial": 4 };
const memory = new WebAssembly.Memory(argument);
assert_Memory(memory, { "size": 4 });
}, "Non-zero initial");
test(() => {
const argument = { "initial": 0 };
const memory = new WebAssembly.Memory(argument, {});
assert_Memory(memory, { "size": 0 });
}, "Stray argument");
test(() => {
const argument = { "initial": 4, "maximum": 10, shared: true };
const memory = new WebAssembly.Memory(argument);
assert_Memory(memory, { "size": 4, "shared": true });
}, "Shared memory");
|
{
"pile_set_name": "Github"
}
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: Trd_GetOrderList.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
import Common_pb2 as Common__pb2
import Trd_Common_pb2 as Trd__Common__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='Trd_GetOrderList.proto',
package='Trd_GetOrderList',
syntax='proto2',
serialized_pb=_b('\n\x16Trd_GetOrderList.proto\x12\x10Trd_GetOrderList\x1a\x0c\x43ommon.proto\x1a\x10Trd_Common.proto\"\x81\x01\n\x03\x43\x32S\x12%\n\x06header\x18\x01 \x02(\x0b\x32\x15.Trd_Common.TrdHeader\x12\x39\n\x10\x66ilterConditions\x18\x02 \x01(\x0b\x32\x1f.Trd_Common.TrdFilterConditions\x12\x18\n\x10\x66ilterStatusList\x18\x03 \x03(\x05\"R\n\x03S2C\x12%\n\x06header\x18\x01 \x02(\x0b\x32\x15.Trd_Common.TrdHeader\x12$\n\torderList\x18\x02 \x03(\x0b\x32\x11.Trd_Common.Order\"-\n\x07Request\x12\"\n\x03\x63\x32s\x18\x01 \x02(\x0b\x32\x15.Trd_GetOrderList.C2S\"f\n\x08Response\x12\x15\n\x07retType\x18\x01 \x02(\x05:\x04-400\x12\x0e\n\x06retMsg\x18\x02 \x01(\t\x12\x0f\n\x07\x65rrCode\x18\x03 \x01(\x05\x12\"\n\x03s2c\x18\x04 \x01(\x0b\x32\x15.Trd_GetOrderList.S2C')
,
dependencies=[Common__pb2.DESCRIPTOR,Trd__Common__pb2.DESCRIPTOR,])
_C2S = _descriptor.Descriptor(
name='C2S',
full_name='Trd_GetOrderList.C2S',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='header', full_name='Trd_GetOrderList.C2S.header', index=0,
number=1, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='filterConditions', full_name='Trd_GetOrderList.C2S.filterConditions', index=1,
number=2, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='filterStatusList', full_name='Trd_GetOrderList.C2S.filterStatusList', index=2,
number=3, type=5, cpp_type=1, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=77,
serialized_end=206,
)
_S2C = _descriptor.Descriptor(
name='S2C',
full_name='Trd_GetOrderList.S2C',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='header', full_name='Trd_GetOrderList.S2C.header', index=0,
number=1, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='orderList', full_name='Trd_GetOrderList.S2C.orderList', index=1,
number=2, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=208,
serialized_end=290,
)
_REQUEST = _descriptor.Descriptor(
name='Request',
full_name='Trd_GetOrderList.Request',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='c2s', full_name='Trd_GetOrderList.Request.c2s', index=0,
number=1, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=292,
serialized_end=337,
)
_RESPONSE = _descriptor.Descriptor(
name='Response',
full_name='Trd_GetOrderList.Response',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='retType', full_name='Trd_GetOrderList.Response.retType', index=0,
number=1, type=5, cpp_type=1, label=2,
has_default_value=True, default_value=-400,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='retMsg', full_name='Trd_GetOrderList.Response.retMsg', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='errCode', full_name='Trd_GetOrderList.Response.errCode', index=2,
number=3, type=5, cpp_type=1, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='s2c', full_name='Trd_GetOrderList.Response.s2c', index=3,
number=4, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto2',
extension_ranges=[],
oneofs=[
],
serialized_start=339,
serialized_end=441,
)
_C2S.fields_by_name['header'].message_type = Trd__Common__pb2._TRDHEADER
_C2S.fields_by_name['filterConditions'].message_type = Trd__Common__pb2._TRDFILTERCONDITIONS
_S2C.fields_by_name['header'].message_type = Trd__Common__pb2._TRDHEADER
_S2C.fields_by_name['orderList'].message_type = Trd__Common__pb2._ORDER
_REQUEST.fields_by_name['c2s'].message_type = _C2S
_RESPONSE.fields_by_name['s2c'].message_type = _S2C
DESCRIPTOR.message_types_by_name['C2S'] = _C2S
DESCRIPTOR.message_types_by_name['S2C'] = _S2C
DESCRIPTOR.message_types_by_name['Request'] = _REQUEST
DESCRIPTOR.message_types_by_name['Response'] = _RESPONSE
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
C2S = _reflection.GeneratedProtocolMessageType('C2S', (_message.Message,), dict(
DESCRIPTOR = _C2S,
__module__ = 'Trd_GetOrderList_pb2'
# @@protoc_insertion_point(class_scope:Trd_GetOrderList.C2S)
))
_sym_db.RegisterMessage(C2S)
S2C = _reflection.GeneratedProtocolMessageType('S2C', (_message.Message,), dict(
DESCRIPTOR = _S2C,
__module__ = 'Trd_GetOrderList_pb2'
# @@protoc_insertion_point(class_scope:Trd_GetOrderList.S2C)
))
_sym_db.RegisterMessage(S2C)
Request = _reflection.GeneratedProtocolMessageType('Request', (_message.Message,), dict(
DESCRIPTOR = _REQUEST,
__module__ = 'Trd_GetOrderList_pb2'
# @@protoc_insertion_point(class_scope:Trd_GetOrderList.Request)
))
_sym_db.RegisterMessage(Request)
Response = _reflection.GeneratedProtocolMessageType('Response', (_message.Message,), dict(
DESCRIPTOR = _RESPONSE,
__module__ = 'Trd_GetOrderList_pb2'
# @@protoc_insertion_point(class_scope:Trd_GetOrderList.Response)
))
_sym_db.RegisterMessage(Response)
# @@protoc_insertion_point(module_scope)
|
{
"pile_set_name": "Github"
}
|
.page
.subttl 'tstflg.src'
;*
;*
;**********************************
;*
;* scflg
;* setflg
;* clrflg
;* tstflg
;*
;*********************************
;*
;*
scflg bcc clrflg
setflg ldx lindx
ora filtyp,x
bne clrf10
clrflg ldx lindx
eor #$ff
and filtyp,x
clrf10 sta filtyp,x
rts
tstflg ldx lindx
and filtyp,x
rts
;*
;*
;******************************
;*
;*
;* tstwrt
;*
;******************************
;*
;*
tstwrt jsr getact
tax
lda lstjob,x
and #$f0
cmp #$90
rts
;*
;*
.page
; test for active files from
; lindx table
; c=1 file not active x=18,y=?,a=?
; c=0 file active x=entfnd,y=lindx,a=?
tstchn ldx #0 ; start search at top
tstc20 stx temp+2 ; save to look on
lda lintab,x ; get lindx
cmp #$ff
bne tstc40 ; if plus test it
tstc30 ldx temp+2 ; not active
inx
cpx #maxsa-2 ; searched all
bcc tstc20 ; no
tstrts rts ; yes
tstc40 stx temp+2 ; save x
and #$3f
tay ; use lindx as index
lda filtyp,y ; right drive # ?
and #1
sta temp+1
ldx entfnd ; index entry found
lda fildrv,x
and #1
cmp temp+1 ; same drive # ?
bne tstc30 ; no
lda dsec,y ; yes - same dir. entry ?
cmp entsec,x
bne tstc30 ; no
lda dind,y
cmp entind,x
bne tstc30 ; no
clc ; set flag
rts
|
{
"pile_set_name": "Github"
}
|
namespace NHSE.Core
{
public enum Hemisphere
{
Northern = 0,
Southern = 1,
}
}
|
{
"pile_set_name": "Github"
}
|
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace DynamicSample
{
class Program
{
static void Main()
{
dynamic dyn;
dyn = 100;
Console.WriteLine(dyn.GetType());
Console.WriteLine(dyn);
dyn = "This is a string";
Console.WriteLine(dyn.GetType());
Console.WriteLine(dyn);
dyn = new Person() { FirstName = "Bugs", LastName = "Bunny" };
Console.WriteLine(dyn.GetType());
Console.WriteLine($"{dyn.FirstName} {dyn.LastName}");
dyn = new WroxDynamicObject();
dyn.FirstName = "Bugs";
dyn.LastName = "Bunny";
Console.WriteLine(dyn.GetType());
Console.WriteLine($"{dyn.FirstName} {dyn.LastName}");
dyn.MiddleName = "Rabbit";
Console.WriteLine(dyn.MiddleName);
Console.WriteLine(dyn.GetType());
Console.WriteLine($"{dyn.FirstName} {dyn.MiddleName} {dyn.LastName}");
List<Person> friends = new List<Person>();
friends.Add(new Person() { FirstName = "Daffy", LastName = "Duck" });
friends.Add(new Person() { FirstName = "Porky", LastName = "Pig" });
friends.Add(new Person() { FirstName = "Tweety", LastName = "Bird" });
dyn.Friends = friends;
foreach (Person friend in dyn.Friends)
{
Console.WriteLine($"{friend.FirstName} {friend.LastName}");
}
Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToString("d");
dyn.GetTomorrowDate = GetTomorrow;
Console.WriteLine("Tomorrow is {0}", dyn.GetTomorrowDate(DateTime.Now));
DoExpando();
Console.Read();
}
static void DoExpando()
{
dynamic expObj = new ExpandoObject();
expObj.FirstName = "Daffy";
expObj.LastName = "Duck";
Console.WriteLine(expObj.FirstName + " " + expObj.LastName);
Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToString("d");
expObj.GetTomorrowDate = GetTomorrow;
Console.WriteLine($"Tomorrow is {expObj.GetTomorrowDate(DateTime.Now)}");
expObj.Friends = new List<Person>();
expObj.Friends.Add(new Person() { FirstName = "Bob", LastName = "Jones" });
expObj.Friends.Add(new Person() { FirstName = "Robert", LastName = "Jones" });
expObj.Friends.Add(new Person() { FirstName = "Bobby", LastName = "Jones" });
foreach (Person friend in expObj.Friends)
{
Console.WriteLine($"{friend.FirstName} {friend.LastName}");
}
}
}
}
|
{
"pile_set_name": "Github"
}
|
/// @ref core
/// @file glm/ext/vector_int3_precision.hpp
#pragma once
#include "../detail/type_vec3.hpp"
namespace glm
{
/// @addtogroup core_vector_precision
/// @{
/// 3 components vector of high qualifier signed integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<3, int, highp> highp_ivec3;
/// 3 components vector of medium qualifier signed integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<3, int, mediump> mediump_ivec3;
/// 3 components vector of low qualifier signed integer numbers.
///
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.5 Vectors</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a>
typedef vec<3, int, lowp> lowp_ivec3;
/// @}
}//namespace glm
|
{
"pile_set_name": "Github"
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\EventDispatcher\Debug;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
interface TraceableEventDispatcherInterface extends EventDispatcherInterface
{
/**
* Gets the called listeners.
*
* @return array An array of called listeners
*/
public function getCalledListeners();
/**
* Gets the not called listeners.
*
* @return array An array of not called listeners
*/
public function getNotCalledListeners();
}
|
{
"pile_set_name": "Github"
}
|
Organization: Central Michigan University
From: <34NIGS2@CMUVM.CSV.CMICH.EDU>
Subject: Help Needed w/ DOS Apps and Windows
Lines: 21
Since loading Windows, two of my DOS applications have been
acting strangely. It appears that font changes and page
orientation changes (so far) are not being recognized in
WordPerfect/DOS and QuattroPro/DOS. Another DOS application
does accept font and page orientation changes, so I don't
think the problem is with the printer.
I reloaded QuattroPro, and these changes are still not
accepted whether launching from Windows or the DOS prompt.
Does anyone have any suggestions as to where to look or how to
correct this problem? I've ordered QuattroPro for Windows,
but need a landscape application printed immediately. Please e-mail.
Thanks in advance!
*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*
| SUE BITTNER Internet: 34nigs2@cmuvm.csv.cmich.edu |
|Central Michigan University BITNET: 34nigs2@cmuvm |
| Mt. Pleasant, MI 48859 |
*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*==*
|
{
"pile_set_name": "Github"
}
|
{
"created_at": "2015-02-27T22:28:12.146069",
"description": "Standalone sdoc generator",
"fork": false,
"full_name": "voloko/sdoc",
"language": "CSS",
"updated_at": "2015-02-27T23:42:16.004487"
}
|
{
"pile_set_name": "Github"
}
|
<!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_171) on Tue Jun 05 13:03:15 NZST 2018 -->
<title>LossMSLE</title>
<meta name="date" content="2018-06-05">
<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="LossMSLE";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</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="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../weka/dl4j/lossfunctions/LossMSE.html" title="class in weka.dl4j.lossfunctions"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../weka/dl4j/lossfunctions/LossNegativeLogLikelihood.html" title="class in weka.dl4j.lossfunctions"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?weka/dl4j/lossfunctions/LossMSLE.html" target="_top">Frames</a></li>
<li><a href="LossMSLE.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All 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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">weka.dl4j.lossfunctions</div>
<h2 title="Class LossMSLE" class="title">Class LossMSLE</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">weka.dl4j.lossfunctions.LossFunction</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></li>
<li>
<ul class="inheritance">
<li>weka.dl4j.lossfunctions.LossMSLE</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, <a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true" title="class or interface in weka.core">OptionHandler</a>, <a href="../../../weka/dl4j/ApiWrapper.html" title="interface in weka.dl4j">ApiWrapper</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></dd>
</dl>
<hr>
<br>
<pre>public class <span class="typeNameLabel">LossMSLE</span>
extends <a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">LossFunction</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE>
implements <a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true" title="class or interface in weka.core">OptionHandler</a></pre>
<div class="block">A version of DeepLearning4j's LossMSLE that implements WEKA option handling.</div>
<dl>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Eibe Frank</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../serialized-form.html#weka.dl4j.lossfunctions.LossMSLE">Serialized Form</a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../weka/dl4j/lossfunctions/LossMSLE.html#LossMSLE--">LossMSLE</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String[]</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../weka/dl4j/lossfunctions/LossMSLE.html#getOptions--">getOptions</a></span>()</code>
<div class="block">Gets the current settings of the Classifier.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../weka/dl4j/lossfunctions/LossMSLE.html#initializeBackend--">initializeBackend</a></span>()</code> </td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>java.util.Enumeration<<a href="http://weka.sourceforge.net/doc.dev/weka/core/Option.html?is-external=true" title="class or interface in weka.core">Option</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../weka/dl4j/lossfunctions/LossMSLE.html#listOptions--">listOptions</a></span>()</code>
<div class="block">Returns an enumeration describing the available options.</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../weka/dl4j/lossfunctions/LossMSLE.html#setOptions-java.lang.String:A-">setOptions</a></span>(java.lang.String[] options)</code>
<div class="block">Parses a given list of options.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.weka.dl4j.lossfunctions.LossFunction">
<!-- -->
</a>
<h3>Methods inherited from class weka.dl4j.lossfunctions.<a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">LossFunction</a></h3>
<code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html#create-org.nd4j.linalg.lossfunctions.ILossFunction-">create</a>, <a href="../../../weka/dl4j/lossfunctions/LossFunction.html#getBackend--">getBackend</a>, <a href="../../../weka/dl4j/lossfunctions/LossFunction.html#setBackend-T-">setBackend</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="LossMSLE--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>LossMSLE</h4>
<pre>public LossMSLE()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="listOptions--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>listOptions</h4>
<pre>public java.util.Enumeration<<a href="http://weka.sourceforge.net/doc.dev/weka/core/Option.html?is-external=true" title="class or interface in weka.core">Option</a>> listOptions()</pre>
<div class="block">Returns an enumeration describing the available options.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true#listOptions--" title="class or interface in weka.core">listOptions</a></code> in interface <code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true" title="class or interface in weka.core">OptionHandler</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html#listOptions--">listOptions</a></code> in class <code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">LossFunction</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an enumeration of all the available options.</dd>
</dl>
</li>
</ul>
<a name="getOptions--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getOptions</h4>
<pre>public java.lang.String[] getOptions()</pre>
<div class="block">Gets the current settings of the Classifier.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true#getOptions--" title="class or interface in weka.core">getOptions</a></code> in interface <code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true" title="class or interface in weka.core">OptionHandler</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html#getOptions--">getOptions</a></code> in class <code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">LossFunction</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></code></dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>an array of strings suitable for passing to setOptions</dd>
</dl>
</li>
</ul>
<a name="setOptions-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setOptions</h4>
<pre>public void setOptions(java.lang.String[] options)
throws java.lang.Exception</pre>
<div class="block">Parses a given list of options.</div>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true#setOptions-java.lang.String:A-" title="class or interface in weka.core">setOptions</a></code> in interface <code><a href="http://weka.sourceforge.net/doc.dev/weka/core/OptionHandler.html?is-external=true" title="class or interface in weka.core">OptionHandler</a></code></dd>
<dt><span class="overrideSpecifyLabel">Overrides:</span></dt>
<dd><code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html#setOptions-java.lang.String:A-">setOptions</a></code> in class <code><a href="../../../weka/dl4j/lossfunctions/LossFunction.html" title="class in weka.dl4j.lossfunctions">LossFunction</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></code></dd>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>options</code> - the list of options as an array of strings</dd>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code> - if an option is not supported</dd>
</dl>
</li>
</ul>
<a name="initializeBackend--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>initializeBackend</h4>
<pre>public void initializeBackend()</pre>
<dl>
<dt><span class="overrideSpecifyLabel">Specified by:</span></dt>
<dd><code><a href="../../../weka/dl4j/ApiWrapper.html#initializeBackend--">initializeBackend</a></code> in interface <code><a href="../../../weka/dl4j/ApiWrapper.html" title="interface in weka.dl4j">ApiWrapper</a><org.nd4j.linalg.lossfunctions.impl.LossMSLE></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-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><a href="../../../weka/dl4j/lossfunctions/LossMSE.html" title="class in weka.dl4j.lossfunctions"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../weka/dl4j/lossfunctions/LossNegativeLogLikelihood.html" title="class in weka.dl4j.lossfunctions"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?weka/dl4j/lossfunctions/LossMSLE.html" target="_top">Frames</a></li>
<li><a href="LossMSLE.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All 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>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2010,
* Gavriloaie Eugen-Andrei (shiretu@gmail.com)
*
* This file is part of crtmpserver.
* crtmpserver is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* crtmpserver is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with crtmpserver. If not, see <http://www.gnu.org/licenses/>.
*/
#include "protocols/protocolmanager.h"
#include "protocols/baseprotocol.h"
#include "netio/netio.h"
map<uint32_t, BaseProtocol *> ProtocolManager::_activeProtocols;
map<uint32_t, BaseProtocol *> ProtocolManager::_deadProtocols;
void ProtocolManager::RegisterProtocol(BaseProtocol *pProtocol) {
if (MAP_HAS1(_activeProtocols, pProtocol->GetId()))
return;
if (MAP_HAS1(_deadProtocols, pProtocol->GetId()))
return;
_activeProtocols[pProtocol->GetId()] = pProtocol;
}
void ProtocolManager::UnRegisterProtocol(BaseProtocol *pProtocol) {
if (MAP_HAS1(_activeProtocols, pProtocol->GetId()))
_activeProtocols.erase(pProtocol->GetId());
if (MAP_HAS1(_deadProtocols, pProtocol->GetId()))
_deadProtocols.erase(pProtocol->GetId());
}
void ProtocolManager::EnqueueForDelete(BaseProtocol *pProtocol) {
if (pProtocol->GetNearProtocol() == NULL) {
FINEST("Enqueue for delete for protocol %s", STR(*pProtocol));
}
pProtocol->SetApplication(NULL);
if (MAP_HAS1(_activeProtocols, pProtocol->GetId()))
_activeProtocols.erase(pProtocol->GetId());
if (!MAP_HAS1(_deadProtocols, pProtocol->GetId()))
_deadProtocols[pProtocol->GetId()] = pProtocol;
}
uint32_t ProtocolManager::CleanupDeadProtocols() {
uint32_t result = 0;
while (_deadProtocols.size() > 0) {
BaseProtocol *pBaseProtocol = MAP_VAL(_deadProtocols.begin());
delete pBaseProtocol;
result++;
}
return result;
}
void ProtocolManager::Shutdown() {
while (_activeProtocols.size() > 0) {
EnqueueForDelete(MAP_VAL(_activeProtocols.begin()));
}
}
BaseProtocol * ProtocolManager::GetProtocol(uint32_t id,
bool includeDeadProtocols) {
if (!includeDeadProtocols && MAP_HAS1(_deadProtocols, id))
return NULL;
if (MAP_HAS1(_activeProtocols, id))
return _activeProtocols[id];
if (MAP_HAS1(_deadProtocols, id))
return _deadProtocols[id];
return NULL;
}
const map<uint32_t, BaseProtocol *> & ProtocolManager::GetActiveProtocols() {
return _activeProtocols;
}
void ProtocolManager::GetActiveProtocols(map<uint32_t, BaseProtocol *> &result,
protocolManagerFilter_f filter) {
result.clear();
if (filter == NULL) {
result = _activeProtocols;
return;
}
FOR_MAP(_activeProtocols, uint32_t, BaseProtocol *, i) {
if (!filter(MAP_VAL(i)))
continue;
result[MAP_VAL(i)->GetId()] = MAP_VAL(i);
}
}
bool protocolManagerNetworkedProtocolsFilter(BaseProtocol *pProtocol) {
IOHandler *pIOHandler = pProtocol->GetIOHandler();
if ((pIOHandler == NULL)
|| ((pIOHandler->GetType() != IOHT_TCP_CARRIER)
&& (pIOHandler->GetType() != IOHT_UDP_CARRIER)))
return false;
return true;
}
bool protocolManagerNearProtocolsFilter(BaseProtocol *pProtocol) {
return pProtocol->GetNearProtocol() == NULL;
}
|
{
"pile_set_name": "Github"
}
|
---
title: Conferences (Unified Communications Managed API 5.0)
TOCTitle: Conferences
ms:assetid: 29e5a8ed-3e14-4ed4-9b0a-a311725ee121
ms:mtpsurl: https://msdn.microsoft.com/en-us/library/Dn466009(v=office.16)
ms:contentKeyID: 65239937
ms.date: 07/27/2015
mtps_version: v=office.16
---
# Conferences
**Applies to**: Skype for Business 2015
This section discusses concepts related to conferences:
- [ConferenceSession state transitions](conferencesession-state-transitions.md)
- [Conference lobby](conference-lobby.md)
- [Conference operations](conference-operations.md)
- [Joining a conference](joining-a-conference.md)
- [Inviting a new participant](inviting-a-new-participant.md)
- [Conference invitation state transitions](conference-invitation-state-transitions.md)
- [Receiving a conference invitation](receiving-a-conference-invitation.md)
|
{
"pile_set_name": "Github"
}
|
set(NAME glm_dummy)
file(GLOB ROOT_SOURCE *.cpp)
file(GLOB ROOT_INLINE *.inl)
file(GLOB ROOT_HEADER *.hpp)
file(GLOB ROOT_TEXT ../*.txt)
file(GLOB ROOT_NAT ../util/glm.natvis)
file(GLOB_RECURSE CORE_SOURCE ./detail/*.cpp)
file(GLOB_RECURSE CORE_INLINE ./detail/*.inl)
file(GLOB_RECURSE CORE_HEADER ./detail/*.hpp)
file(GLOB_RECURSE GTC_SOURCE ./gtc/*.cpp)
file(GLOB_RECURSE GTC_INLINE ./gtc/*.inl)
file(GLOB_RECURSE GTC_HEADER ./gtc/*.hpp)
file(GLOB_RECURSE GTX_SOURCE ./gtx/*.cpp)
file(GLOB_RECURSE GTX_INLINE ./gtx/*.inl)
file(GLOB_RECURSE GTX_HEADER ./gtx/*.hpp)
source_group("Text Files" FILES ${ROOT_TEXT})
source_group("Core Files" FILES ${CORE_SOURCE})
source_group("Core Files" FILES ${CORE_INLINE})
source_group("Core Files" FILES ${CORE_HEADER})
source_group("GTC Files" FILES ${GTC_SOURCE})
source_group("GTC Files" FILES ${GTC_INLINE})
source_group("GTC Files" FILES ${GTC_HEADER})
source_group("GTX Files" FILES ${GTX_SOURCE})
source_group("GTX Files" FILES ${GTX_INLINE})
source_group("GTX Files" FILES ${GTX_HEADER})
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/..)
if(GLM_TEST_ENABLE)
add_executable(${NAME} ${ROOT_TEXT} ${ROOT_NAT}
${ROOT_SOURCE} ${ROOT_INLINE} ${ROOT_HEADER}
${CORE_SOURCE} ${CORE_INLINE} ${CORE_HEADER}
${GTC_SOURCE} ${GTC_INLINE} ${GTC_HEADER}
${GTX_SOURCE} ${GTX_INLINE} ${GTX_HEADER})
endif(GLM_TEST_ENABLE)
#add_library(glm STATIC glm.cpp)
#add_library(glm_shared SHARED glm.cpp)
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html>
<head>
<title>Bug 1086883</title>
<!-- writing mode of #inner div should not affect its position within #outer -->
<style>
#outer {
width:400px;
height:300px;
padding:50px;
border:1px solid black;
}
#inner {
width:200px;
height:100px;
background:red;
writing-mode:vertical-lr;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// Copyright 2014 OneOfOne
// https://github.com/OneOfOne/go-utils
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package util
import (
"runtime"
"sync/atomic"
)
// SpinLock implements a simple atomic spin lock, the zero value for a SpinLock is an unlocked spinlock.
type SpinLock struct {
f uint32
}
// Lock locks sl. If the lock is already in use, the caller blocks until Unlock is called
func (sl *SpinLock) Lock() {
for !sl.TryLock() {
runtime.Gosched() //allow other goroutines to do stuff.
}
}
// Unlock unlocks sl, unlike [Mutex.Unlock](http://golang.org/pkg/sync/#Mutex.Unlock),
// there's no harm calling it on an unlocked SpinLock
func (sl *SpinLock) Unlock() {
atomic.StoreUint32(&sl.f, 0)
}
// TryLock will try to lock sl and return whether it succeed or not without blocking.
func (sl *SpinLock) TryLock() bool {
return atomic.CompareAndSwapUint32(&sl.f, 0, 1)
}
func (sl *SpinLock) String() string {
if atomic.LoadUint32(&sl.f) == 1 {
return "Locked"
}
return "Unlocked"
}
|
{
"pile_set_name": "Github"
}
|
**Are you the copyright owner or authorized to act on the copyright owner's behalf?**
Yes
**Please provide a detailed description of the original copyrighted work that has allegedly been infringed. If possible, include a URL to where it is posted online.**
The link below contains a forked repository to all my school work. I did not realize soon enough that putting all my school work at a public repository was a bad idea. It could lead to possible plagiarism and it is a huge deal.
https://github.com/LynDeng/school-work
**What files should be taken down? Please provide URLs for each file, or if the entire repository, the repository's URL:**
https://github.com/LynDeng/school-work
The entire repository.
**Have you searched for any forks of the allegedly infringing files or repositories? Each fork is a distinct repository and must be identified separately if you believe it is infringing and wish to have it taken down.**
Yes. Above is the link to the repository I want to take down.
**Is the work licensed under an open source license? If so, which open source license? Are the allegedly infringing files being used under the open source license, or are they in violation of the license?**
No it isn't under any license.
**What would be the best solution for the alleged infringement? Are there specific changes the other person can make other than removal?**
Removal would be the best option.
**Do you have the alleged infringer's contact information? If so, please provide it:**
I do not have his/her contact information but I have the link to the profile.
**Type (or copy and paste) the following statement: "I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law. I have taken fair use into consideration."**
I have a good faith belief that use of the copyrighted materials described above on the infringing web pages is not authorized by the copyright owner, or its agent, or the law. I have taken fair use into consideration.
**Type (or copy and paste) the following statement: "I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed."**
I swear, under penalty of perjury, that the information in this notification is accurate and that I am the copyright owner, or am authorized to act on behalf of the owner, of an exclusive right that is allegedly infringed.
**Please confirm that you have you have read our Guide to Submitting a DMCA Takedown Notice: https://help.github.com/articles/guide-to-submitting-a-dmca-takedown-notice/**
confirmed
**So that we can get back to you, please provide either your telephone number or physical address:**
[Private]
**Please type your full legal name below to sign this request:**
[Private]
|
{
"pile_set_name": "Github"
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Diagnostics.EventFlow.TestHelpers
{
public class UnitTestInput : IObservable<EventData>, IDisposable
{
private EventFlowSubject<EventData> subject;
public UnitTestInput()
{
subject = new EventFlowSubject<EventData>();
}
public void Dispose()
{
if (subject != null)
{
this.subject.Dispose();
this.subject = null;
}
}
public void SendMessage(string message)
{
var e = new EventData();
e.Payload["Message"] = message;
subject.OnNext(e);
}
public void SendData(IEnumerable<KeyValuePair<string, object>> data)
{
var e = new EventData();
foreach (var kvPair in data)
{
e.Payload.Add(kvPair.Key, kvPair.Value);
}
subject.OnNext(e);
}
public IDisposable Subscribe(IObserver<EventData> observer)
{
return this.subject.Subscribe(observer);
}
}
internal class UnitTestInputFactory : IPipelineItemFactory<UnitTestInput>
{
public UnitTestInput CreateItem(IConfiguration configuration, IHealthReporter healthReporter)
{
return new UnitTestInput();
}
}
}
|
{
"pile_set_name": "Github"
}
|
import { writable } from '../../../../store';
export const count = writable(0);
|
{
"pile_set_name": "Github"
}
|
#<< toaster/toast
fs = require 'fs'
path = require 'path'
exec = (require "child_process").exec
class InjectNS
constructor:( @builders )->
console.log "Declaring namespaces for files..."
for builder in @builders
for f in builder.files
f.getinfo true
fs.writeFileSync f.realpath, f.raw
f.getinfo false
console.log f.realpath
console.log "...done."
|
{
"pile_set_name": "Github"
}
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@interface WCWatchDefine : NSObject
{
}
+ (id)exceptionFilePath;
+ (id)watchLogFilePath;
+ (id)watchLogFolderPath;
+ (id)getWatchCrashReportFilePath;
+ (id)getWatchCrashReportFolderPath;
@end
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
# Use is subject to license terms.
#
# Desktop entry for the automatic execution of jnlp files identified as
# the x-java-jnlp-file mime type.
#
# Note: This file may be installed under both "control-center-2.0" and
# "applications". Depending upon the version of GNOME, the copy in
# "applications" may take precedence.
#
[Desktop Entry]
Encoding=UTF-8
Name=JavaWS
Comment=Java Web Start
Exec=javaws
Icon=sun-javaws.png
Terminal=false
Type=Application
NoDisplay=true
Categories=Java;Applications;
MimeType=application/x-java-jnlp-file;
|
{
"pile_set_name": "Github"
}
|
/*
* Driver for Atmel Flexcom
*
* Copyright (C) 2015 Atmel Corporation
*
* Author: Cyrille Pitchen <cyrille.pitchen@atmel.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <dt-bindings/mfd/atmel-flexcom.h>
/* I/O register offsets */
#define FLEX_MR 0x0 /* Mode Register */
#define FLEX_VERSION 0xfc /* Version Register */
/* Mode Register bit fields */
#define FLEX_MR_OPMODE_OFFSET (0) /* Operating Mode */
#define FLEX_MR_OPMODE_MASK (0x3 << FLEX_MR_OPMODE_OFFSET)
#define FLEX_MR_OPMODE(opmode) (((opmode) << FLEX_MR_OPMODE_OFFSET) & \
FLEX_MR_OPMODE_MASK)
struct atmel_flexcom {
void __iomem *base;
u32 opmode;
struct clk *clk;
};
static int atmel_flexcom_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct resource *res;
struct atmel_flexcom *ddata;
int err;
ddata = devm_kzalloc(&pdev->dev, sizeof(*ddata), GFP_KERNEL);
if (!ddata)
return -ENOMEM;
platform_set_drvdata(pdev, ddata);
err = of_property_read_u32(np, "atmel,flexcom-mode", &ddata->opmode);
if (err)
return err;
if (ddata->opmode < ATMEL_FLEXCOM_MODE_USART ||
ddata->opmode > ATMEL_FLEXCOM_MODE_TWI)
return -EINVAL;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ddata->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(ddata->base))
return PTR_ERR(ddata->base);
ddata->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(ddata->clk))
return PTR_ERR(ddata->clk);
err = clk_prepare_enable(ddata->clk);
if (err)
return err;
/*
* Set the Operating Mode in the Mode Register: only the selected device
* is clocked. Hence, registers of the other serial devices remain
* inaccessible and are read as zero. Also the external I/O lines of the
* Flexcom are muxed to reach the selected device.
*/
writel(FLEX_MR_OPMODE(ddata->opmode), ddata->base + FLEX_MR);
clk_disable_unprepare(ddata->clk);
return devm_of_platform_populate(&pdev->dev);
}
static const struct of_device_id atmel_flexcom_of_match[] = {
{ .compatible = "atmel,sama5d2-flexcom" },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, atmel_flexcom_of_match);
#ifdef CONFIG_PM_SLEEP
static int atmel_flexcom_resume(struct device *dev)
{
struct atmel_flexcom *ddata = dev_get_drvdata(dev);
int err;
u32 val;
err = clk_prepare_enable(ddata->clk);
if (err)
return err;
val = FLEX_MR_OPMODE(ddata->opmode),
writel(val, ddata->base + FLEX_MR);
clk_disable_unprepare(ddata->clk);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(atmel_flexcom_pm_ops, NULL,
atmel_flexcom_resume);
static struct platform_driver atmel_flexcom_driver = {
.probe = atmel_flexcom_probe,
.driver = {
.name = "atmel_flexcom",
.pm = &atmel_flexcom_pm_ops,
.of_match_table = atmel_flexcom_of_match,
},
};
module_platform_driver(atmel_flexcom_driver);
MODULE_AUTHOR("Cyrille Pitchen <cyrille.pitchen@atmel.com>");
MODULE_DESCRIPTION("Atmel Flexcom MFD driver");
MODULE_LICENSE("GPL v2");
|
{
"pile_set_name": "Github"
}
|
---
layout: default
---
本书是 [The Linux Command Line](http://linuxcommand.org/) 的中文版,
* [在线阅读](book)
* [下载pdf](https://github.com/billie66/TLCL/releases/download/v1/tlcl-cn.pdf)
翻译由 <a href="https://haoqicat.com/">好奇猫工作室</a> 发起, 翻译者是:<a href="https://github.com/happypeter">happypeter</a> , <a href="http://github.com/billie66">billie66</a> 和最最可爱的社区
( <a href="https://github.com/billie66/TLCL/graphs/contributors">Github 贡献者名单</a> )
想要参与翻译的朋友可以直接 fork [github 书稿源码](https://github.com/billie66/TLCL) ,然后给我们发 Pull Request 即可。想要点赞支持的朋友,[点这里](https://github.com/billie66/TLCL) star 一下项目,多谢!
欢迎添加 happypeter 的微信进行讨论:
<blockquote>
happypeter1983
</blockquote>
|
{
"pile_set_name": "Github"
}
|
<annotation>
<folder>widerface</folder>
<filename>33--Running_33_Running_Running_33_889.jpg</filename>
<source>
<database>wider face Database</database>
<annotation>PASCAL VOC2007</annotation>
<image>flickr</image>
<flickrid>-1</flickrid>
</source>
<owner>
<flickrid>yanyu</flickrid>
<name>yanyu</name>
</owner>
<size>
<width>1024</width>
<height>716</height>
<depth>3</depth>
</size>
<segmented>0</segmented>
<object>
<name>face</name>
<pose>Unspecified</pose>
<truncated>1</truncated>
<difficult>0</difficult>
<bndbox>
<xmin>300</xmin>
<ymin>48</ymin>
<xmax>672</xmax>
<ymax>554</ymax>
</bndbox>
<lm>
<x1>424.094</x1>
<y1>251.473</y1>
<x2>605.388</x2>
<y2>266.094</y2>
<x3>505.969</x3>
<y3>388.906</y3>
<x4>397.777</x4>
<y4>429.844</y4>
<x5>543.982</x5>
<y5>438.616</y5>
<visible>0</visible>
<blur>0.92</blur>
</lm>
<has_lm>1</has_lm>
</object>
</annotation>
|
{
"pile_set_name": "Github"
}
|
/*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __BPY_RNA_CALLBACK_H__
#define __BPY_RNA_CALLBACK_H__
/** \file
* \ingroup pythonintern
*/
struct BPy_StructRNA;
struct PyObject;
#if 0
PyObject *pyrna_callback_add(BPy_StructRNA *self, PyObject *args);
PyObject *pyrna_callback_remove(BPy_StructRNA *self, PyObject *args);
#endif
PyObject *pyrna_callback_classmethod_add(PyObject *cls, PyObject *args);
PyObject *pyrna_callback_classmethod_remove(PyObject *cls, PyObject *args);
#endif /* __BPY_RNA_CALLBACK_H__ */
|
{
"pile_set_name": "Github"
}
|
var download = require("./index");
var fs = require("fs-extra");
var urls = {
bad: "foo",
terrible: null,
"200": "http://i.imgur.com/A5Apd1a.jpg",
"404": "http://imgur.com/fhsdjkfhsjkdfhkjsadhfjksdahfkjahsdkjfads.jpg"
};
var url = urls["404"];
require("shelljs/global");
console.log();
console.log("Downloading", url);
download(url, {}, function(err, path, headers) {
console.log();
if (err) console.log(err);
if (path) {
console.log("Downloaded", path);
exec("open " + path);
// rm(path);
}
if (!path) console.log("DIDNT DOWNLOAD", url);
if (headers) console.log(headers);
console.log();
console.log("Re-downloading", url);
download(url, headers, function(err, path, headers) {
console.log();
if (err) console.log(err);
if (path) console.log("Downloaded", path);
if (!path) console.log("DIDNT DOWNLOAD", url);
if (headers) console.log(headers);
});
});
|
{
"pile_set_name": "Github"
}
|
/* mbed Microcontroller Library
* CMSIS-style functionality to support dynamic vectors
*******************************************************************************
* Copyright (c) 2014, STMicroelectronics
* 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 STMicroelectronics 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.
*******************************************************************************
*/
#include "cmsis_nvic.h"
#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM
#define NVIC_FLASH_VECTOR_ADDRESS (0x08000000) // Initial vector position in flash
static unsigned char vtor_remap = 0; // To keep track that the vectors remap is done
void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) {
int i;
// Space for dynamic vectors, initialised to allocate in R/W
static volatile uint32_t *vectors = (uint32_t *)NVIC_RAM_VECTOR_ADDRESS;
// Copy and switch to dynamic vectors if first time called
if (vtor_remap == 0) {
uint32_t *old_vectors = (uint32_t *)NVIC_FLASH_VECTOR_ADDRESS;
for (i = 0; i < NVIC_NUM_VECTORS; i++) {
vectors[i] = old_vectors[i];
}
SYSCFG->CFGR1 |= 0x03; // Embedded SRAM mapped at 0x00000000
vtor_remap = 1; // The vectors remap is done
}
// Set the vector
vectors[IRQn + 16] = vector;
}
uint32_t NVIC_GetVector(IRQn_Type IRQn) {
uint32_t *vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS;
// Return the vector
return vectors[IRQn + 16];
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.