text:
# ember-myth
[![NPM](https://nodei.co/npm/ember-myth.png)](https://npmjs.org/package/ember-myth)

Preprocess your CSS using Myth.

> Myth is a preprocessor that lets you write pure CSS without having to worry about slow browser support, or even slow spec approval. It's like a CSS polyfill.

## Installation

```
npm install --save-dev ember-myth
```

## Usage

By default, this addon will compile `app/styles/<app-name>.css` into `dist/assets/<app-name>.css`.  To change this,  use the configuration object (explained below) and set the property: `outputFile`.

Options can be configured within your `Brocfile.js` or from within `config/environment.js`:

```javascript
// Brocfile.js
var app = new EmberApp({
	mythOptions: {...}
	...
});
```

```javascript
module.exports = function (/* env */) {
	return  {
		mythOptions: {...}
		...
	}
};
```

## Myth Example

```css
/* app.css */
:root {
	--purple: #847AD1;
	--large: 10px;
}

a {
	color: var(--purple);
	transition: color .2s;
}

a:hover {
	color: color(var(--purple) tint(20%));
}

pre {
	padding: var(--large);
	margin: calc(var(--large) * 2);
}
```

## Available Options
- `browsers` - `Array` - an array of [browsers and versions to support](https://github.com/postcss/autoprefixer#browsers).
- `compress` - `Boolean` - whether to compress the CSS output.
- `source` - `String` - the full path to the source CSS file. This is necessary if you want Myth to concatenate `@import` rules in your CSS. Default: `<project-path>/app/styles/app.css`
- `features` - `Object` - any features you'd like to disable. All features are enabled by default. For example:
```js
features: {
	import: false,
	variables: false,
	customMedia: false,
	hexAlpha: false,
	color: false,
	calc: false,
	fontVariant: false,
	rebeccapurple: false,
	prefixes: false
}
```

## Why Myth?

> Myth lets you write pure CSS while still giving you the benefits of tools like LESS and Sass. You can still use variables and math functions, just like you do in preprocessors. It's like a polyfill for future versions of the spec.

> Some of the features in CSS require runtime calculations, which neither Myth nor preprocessors handle, but what Myth does is let you write your code today in the future syntax, so that your code is future-proof. When browsers finally support these features you won't need to rewrite anything, just start using the cascade!

> Taking plain CSS as an input also means you can use Myth to re-process anyone else's CSS (or another preprocessors output), adding the browser support you need, without having to re-write the code in a completely different syntax.

> Myth is built with Rework so it's incredibly fast, and has a nice Javascript API in addition to the CLI.

(Credits: [myth#why](https://github.com/segmentio/myth#why))

## References

- [myth](https://github.com/segmentio/myth)


text:
<!DOCTYPE html>

    <meta charset="utf-8" />

    <title>User agent detail - Links 2.0 (http://gossamer-threads.com/scripts/links/)</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link href="../circle.css" rel="stylesheet">

User agent detail

            Links 2.0 (http://gossamer-threads.com/scripts/links/)

	General	Device	Bot

Provider	Browser	Engine	OS	Brand	Model	Type	Is mobile	Is touch	Is bot	Name	Type	Parse time	Actions

Test suite

Zsxsoft
1.3
vendor/zsxsoft/php-useragent/tests/UserAgentList.php	Links 	close	 			close	close	close	close		close	0

Detail

Zsxsoft result detail

Array
(
    [0] => img/16/browser/null.png
    [1] => img/16/browser/null.png
    [2] => Links
    [3] =>
    [4] => Links
    [5] =>
    [6] =>
    [7] =>
    [8] => Unknown
    [9] => os
)

        close

Providers

BrowscapFull
6014

                        No result found

BrowscapLite
6014

                        No result found

BrowscapPhp
6014

                        No result found

DonatjUAParser
v0.5.1
	Links 	close	close	close	close	close	close	close	close	close	close	0

Detail

DonatjUAParser result detail

Array
(
    [platform] =>
    [browser] => Links
    [version] =>
)

        close

JenssegersAgent
v2.3.3

                        No result found

NeutrinoApiCom

                        No result found

PiwikDeviceDetector
3.6.1
	Links 	Text-based 	 									0.008

Detail

PiwikDeviceDetector result detail

Array
(
    [client] => Array
        (
            [type] => browser
            [name] => Links
            [short_name] => LI
            [version] =>
            [engine] => Text-based
        )

    [operatingSystem] => Array
        (
        )

    [device] => Array
        (
            [brand] =>
            [brandName] =>
            [model] =>
            [device] =>
            [deviceName] =>
        )

    [bot] =>
    [extra] => Array
        (
            [isBot] =>
            [isBrowser] => 1
            [isFeedReader] =>
            [isMobileApp] =>
            [isPIM] =>
            [isLibrary] =>
            [isMediaPlayer] =>
            [isCamera] =>
            [isCarBrowser] =>
            [isConsole] =>
            [isFeaturePhone] =>
            [isPhablet] =>
            [isPortableMediaPlayer] =>
            [isSmartDisplay] =>
            [isSmartphone] =>
            [isTablet] =>
            [isTV] =>
            [isDesktop] =>
            [isMobile] =>
            [isTouchEnabled] =>
        )

)

        close

SinergiBrowserDetector
6.0.1

                        No result found

UAParser
v3.4.5

                        No result found

UserAgentApiCom

                        No result found

UserAgentStringCom

	Links 2.0	close	 	close	close	close	close	close				0.08101

Detail

UserAgentStringCom result detail

stdClass Object
(
    [agent_type] => Browser
    [agent_name] => Links
    [agent_version] => 2.0
    [os_type] => unknown
    [os_name] => unknown
    [os_versionName] =>
    [os_versionNumber] =>
    [os_producer] =>
    [os_producerURL] =>
    [linux_distibution] => Null
    [agent_language] =>
    [agent_languageTag] =>
)

        close

WhatIsMyBrowserCom

	Links 	 	 			close	close	close	close	close	close	0.23501

Detail

WhatIsMyBrowserCom result detail

stdClass Object
(
    [operating_system_name] =>
    [simple_sub_description_string] =>
    [simple_browser_string] => Links
    [browser_version] =>
    [extra_info] => Array
        (
        )

    [operating_platform] =>
    [extra_info_table] => Array
        (
        )

    [layout_engine_name] =>
    [detected_addons] => Array
        (
        )

    [operating_system_flavour_code] =>
    [hardware_architecture] =>
    [operating_system_flavour] =>
    [operating_system_frameworks] => Array
        (
        )

    [browser_name_code] => links
    [operating_system_version] =>
    [simple_operating_platform_string] =>
    [is_abusive] =>
    [layout_engine_version] =>
    [browser_capabilities] => Array
        (
        )

    [operating_platform_vendor_name] =>
    [operating_system] =>
    [operating_system_version_full] =>
    [operating_platform_code] =>
    [browser_name] => Links
    [operating_system_name_code] =>
    [user_agent] => Links 2.0 (http://gossamer-threads.com/scripts/links/)
    [browser_version_full] =>
    [browser] => Links
)

        close

WhichBrowser
v2.0.18

                        No result found

Woothee
v1.2.0

                        No result found

Wurfl
1.7.1.0

                        No result found

Zsxsoft
1.3
	Links 	close	 			close	close	close	close	close	close	0

Detail

Zsxsoft result detail

Array
(
    [browser] => Array
        (
            [link] => http://links.twibright.com/
            [title] => Links
            [code] => null
            [version] =>
            [name] => Links
            [image] => img/16/browser/null.png
        )

    [os] => Array
        (
            [link] =>
            [name] =>
            [version] =>
            [code] => null
            [x64] =>
            [title] =>
            [type] => os
            [dir] => os
            [image] => img/16/os/null.png
        )

    [device] => Array
        (
            [link] => #
            [title] => Unknown
            [code] => null
            [dir] => browser
            [type] => os
            [image] => img/16/browser/null.png
        )

    [platform] => Array
        (
            [link] => #
            [title] => Unknown
            [code] => null
            [dir] => browser
            [type] => os
            [image] => img/16/browser/null.png
        )

)

        close

About this comparison

                The primary goal of this project is simple

                I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...

                The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.

                You can also improve this further, by suggesting ideas at ThaDafinser/UserAgentParserComparison

                The comparison is based on the abstraction by ThaDafinser/UserAgentParser

			Comparison created 2016-05-10 08:00:54 | by
            ThaDafinser

redpajama_set_name: RedPajamaGithub


text:
package pl.touk.nussknacker.k8s.manager.deployment

import com.typesafe.scalalogging.LazyLogging
import io.circe.syntax.EncoderOps
import monocle.Iso
import monocle.macros.GenLens
import monocle.std.option._
import pl.touk.nussknacker.engine.api.{LiteStreamMetaData, ProcessVersion, RequestResponseMetaData, TypeSpecificData}
import pl.touk.nussknacker.k8s.manager.K8sDeploymentManager.{labelsForScenario, objectNameForScenario, scenarioIdLabel, scenarioVersionAnnotation, versionAnnotationForScenario}
import pl.touk.nussknacker.k8s.manager.K8sDeploymentManagerConfig
import skuber.EnvVar.FieldRef
import skuber.LabelSelector.IsEqualRequirement
import skuber.apps.v1.Deployment
import skuber.apps.v1.Deployment.Strategy
import skuber.{Container, EnvVar, HTTPGetAction, LabelSelector, Pod, Probe, Volume}

case class MountableResources(commonConfigConfigMap: String,
                              loggingConfigConfigMap: String,
                              runtimeConfigSecret: String)

class DeploymentPreparer(config: K8sDeploymentManagerConfig) extends LazyLogging {

  private val CommonConfigMountPath = "/config"
  private val LoggingConfigMountPath = "/logging-config"
  private val RuntimeConfigMountPath = "/runtime-config"

  def prepare(processVersion: ProcessVersion, typeSpecificData: TypeSpecificData, resourcesToMount: MountableResources, determinedReplicasCount: Int): Deployment = {
    val userConfigurationBasedDeployment = DeploymentUtils.parseDeploymentWithFallback(config.k8sDeploymentConfig, getClass.getResource(s"/defaultMinimalDeployment.conf"))
    applyDeploymentDefaults(userConfigurationBasedDeployment, processVersion, typeSpecificData, resourcesToMount, determinedReplicasCount, config.nussknackerInstanceName)
  }

  private def applyDeploymentDefaults(userConfigurationBasedDeployment: Deployment, processVersion: ProcessVersion, typeSpecificData: TypeSpecificData, resourcesToMount: MountableResources, determinedReplicasCount: Int, nussknackerInstanceName: Option[String]) = {
    val objectName = objectNameForScenario(processVersion, config.nussknackerInstanceName, None)
    val annotations = versionAnnotationForScenario(processVersion)
    val labels = labelsForScenario(processVersion, nussknackerInstanceName)

    //we use 'OptionOptics some' here and do not worry about withDefault because _.spec is provided in defaultMinimalDeployment
    val deploymentSpecLens = GenLens[Deployment](_.spec) composePrism some
    val templateSpecLens = deploymentSpecLens composeLens GenLens[Deployment.Spec](_.template.spec) composeIso withDefault(Pod.Spec())
    val deploymentLens =
      GenLens[Deployment](_.metadata.name).set(objectName) andThen
        GenLens[Deployment](_.metadata.labels).modify(_ ++ labels) andThen
        GenLens[Deployment](_.metadata.annotations).modify(_ ++ annotations) andThen
        //here we use id to avoid sanitization problems
        (deploymentSpecLens composeLens GenLens[Deployment.Spec](_.selector)).set(LabelSelector(IsEqualRequirement(scenarioIdLabel, processVersion.processId.value.toString))) andThen
        (deploymentSpecLens composeLens GenLens[Deployment.Spec](_.strategy)).modify(maybeStrategy => maybeStrategy.orElse(Some(deploymentStrategy(typeSpecificData)))) andThen
        (deploymentSpecLens composeLens GenLens[Deployment.Spec](_.replicas)).modify(modifyReplicasCount(determinedReplicasCount)) andThen
        (deploymentSpecLens composeLens GenLens[Deployment.Spec](_.template.metadata.name)).set(objectName) andThen
        (deploymentSpecLens composeLens GenLens[Deployment.Spec](_.template.metadata.labels)).modify(_ ++ labels) andThen
        (templateSpecLens composeLens GenLens[Pod.Spec](_.volumes)).modify(_ ++ List(
          Volume("common-conf", Volume.ConfigMapVolumeSource(resourcesToMount.commonConfigConfigMap)),
          Volume("logging-conf", Volume.ConfigMapVolumeSource(resourcesToMount.loggingConfigConfigMap)),
          Volume("runtime-conf", Volume.Secret(resourcesToMount.runtimeConfigSecret)),
        )) andThen
        (templateSpecLens composeLens GenLens[Pod.Spec](_.containers)).modify(containers => modifyContainers(containers))
    deploymentLens(userConfigurationBasedDeployment)
  }

  private def deploymentStrategy(typeSpecificData: TypeSpecificData): Strategy = {
    typeSpecificData match {
      case _: LiteStreamMetaData => Deployment.Strategy.Recreate
      case _: RequestResponseMetaData => Deployment.Strategy(rollingUpdate = Deployment.RollingUpdate(maxUnavailable = Right("25%"), maxSurge = Right("25%")))
      case other: TypeSpecificData => throw new IllegalStateException(s"Deploying $other unsupported on k8s")
    }
  }

  private def modifyReplicasCount(determinedReplicasCount: Int)(maybeReplicasFromRawConfig: Option[Int]) =
    maybeReplicasFromRawConfig match {
      case Some(replicasFromRawConfig) =>
        logger.warn(s"Found replicas specified in config: $replicasFromRawConfig that will be used instead of replicas determined based on scaling config: $determinedReplicasCount. It can cause not equal tasks assigment to replicas")
        Some(replicasFromRawConfig)
      case None =>
        Some(determinedReplicasCount)
    }

  private def withDefault[A](defaultValue: A): Iso[Option[A], A] =
    Iso[Option[A], A](_.getOrElse(defaultValue))(value => if (value == defaultValue) None else Some(value))

  private def modifyContainers(containers: List[Container]): List[Container] = {
    val image = s"${config.dockerImageName}:${config.dockerImageTag}"
    val runtimeContainer = Container(
      name = "runtime",
      image = image,
      env = List(
        EnvVar("SCENARIO_FILE", s"$CommonConfigMountPath/scenario.json"),
        EnvVar("CONFIG_FILE", s"/opt/nussknacker/conf/application.conf,$RuntimeConfigMountPath/runtimeConfig.conf"),
        EnvVar("DEPLOYMENT_CONFIG_FILE", s"$CommonConfigMountPath/deploymentConfig.conf"),
        EnvVar("LOGBACK_FILE", s"$LoggingConfigMountPath/logback.xml"),
        // We pass POD_NAME, because there is no option to pass only replica hash which is appended to pod name.
        // Hash will be extracted on entrypoint side.
        EnvVar("POD_NAME", FieldRef("metadata.name"))
      ),
      volumeMounts = List(
        Volume.Mount(name = "common-conf", mountPath = CommonConfigMountPath),
        Volume.Mount(name = "logging-conf", mountPath = LoggingConfigMountPath),
        Volume.Mount(name = "runtime-conf", mountPath = RuntimeConfigMountPath),
      ),
      // used standard AkkaManagement see HealthCheckServerRunner for details
      // TODO we should tune failureThreshold to some lower value
      readinessProbe = Some(Probe(new HTTPGetAction(Left(8080), path = "/ready"), periodSeconds = Some(1), failureThreshold = Some(60))),
      livenessProbe = Some(Probe(new HTTPGetAction(Left(8080), path = "/alive")))
    )

    def modifyRuntimeContainer(value: Container): Container = {
      val containerLens = GenLens[Container](_.env).modify(_ ++ runtimeContainer.env) andThen
        GenLens[Container](_.volumeMounts).modify(_ ++ runtimeContainer.volumeMounts) andThen
        GenLens[Container](_.readinessProbe).modify(_.orElse(runtimeContainer.readinessProbe)) andThen
        GenLens[Container](_.livenessProbe).modify(_.orElse(runtimeContainer.livenessProbe)) andThen
        GenLens[Container](_.image).modify { configuredImage =>
          if (configuredImage != runtimeContainer.image) logger.warn(s"Overriding $configuredImage image with ${runtimeContainer.image} image")
          runtimeContainer.image
        }
      containerLens(value)
    }

    val (runtimeContainers, nonRuntimeContainers) = containers.partition(_.name == "runtime")

    (runtimeContainers match {
      case Nil => List(runtimeContainer)
      case single :: Nil => List(modifyRuntimeContainer(single))
      case _ => throw new IllegalStateException("Deployment should have only one 'runtime' container")
    }) ++ nonRuntimeContainers
  }
}


text:
/************************************************************************************
 * Included Files
 ************************************************************************************/

#include <nuttx/config.h>

#include <stdint.h>
#include <stdbool.h>
#include <debug.h>

#include <nuttx/spi/spi.h>
#include <arch/board/board.h>

#include "up_arch.h"
#include "chip.h"
#include "stm32.h"
#include "viewtool_stm32f107.h"

#if defined(CONFIG_STM32_SPI1) || defined(CONFIG_STM32_SPI2) || defined(CONFIG_STM32_SPI3)

/************************************************************************************
 * Definitions
 ************************************************************************************/

/* Enables debug output from this file (needs CONFIG_DEBUG too) */

#undef SPI_DEBUG   /* Define to enable debug */
#undef SPI_VERBOSE /* Define to enable verbose debug */

#ifdef SPI_DEBUG
#  define spidbg  lldbg
#  ifdef SPI_VERBOSE
#    define spivdbg lldbg
#  else
#    define spivdbg(x...)
#  endif
#else
#  undef SPI_VERBOSE
#  define spidbg(x...)
#  define spivdbg(x...)
#endif

/************************************************************************************
 * Private Functions
 ************************************************************************************/

/************************************************************************************
 * Public Functions
 ************************************************************************************/

/************************************************************************************
 * Name: stm32_spiinitialize
 *
 * Description:
 *   Called to configure SPI chip select GPIO pins for the Viewtool stm32f103/107
 *   board.
 *
 ************************************************************************************/

void weak_function stm32_spiinitialize(void)
{
  /* NOTE: Clocking for SPIx was already provided in stm32_rcc.c.
   *       Configurations of SPI pins is performed in stm32_spi.c.
   *       Here, we only initialize chip select pins unique to the board
   *       architecture.
   */

#if defined(CONFIG_STM32_SPI2) && defined(CONFIG_INPUT_ADS7843E)
  /* Configure the XPT2046 SPI2 CS pin as an output */

  (void)stm32_configgpio(GPIO_LCDTP_CS);
#endif

#if defined(CONFIG_STM32_SPI3) && defined(CONFIG_MPL115A)
  /* Configure the MPL115A SPI3 CS pin as an output */

  (void)stm32_configgpio(GPIO_MPL115A_CS);
#endif
}

/****************************************************************************
 * Name:  stm32_spi1/2/3select and stm32_spi1/2/3status
 *
 * Description:
 *   The external functions, stm32_spi1/2/3select and stm32_spi1/2/3status must be
 *   provided by board-specific logic.  They are implementations of the select
 *   and status methods of the SPI interface defined by struct spi_ops_s (see
 *   include/nuttx/spi/spi.h). All other methods (including up_spiinitialize())
 *   are provided by common STM32 logic.  To use this common SPI logic on your
 *   board:
 *
 *   1. Provide logic in stm32_boardinitialize() to configure SPI chip select
 *      pins.
 *   2. Provide stm32_spi1/2/3select() and stm32_spi1/2/3status() functions in your
 *      board-specific logic.  These functions will perform chip selection and
 *      status operations using GPIOs in the way your board is configured.
 *   3. Add a calls to up_spiinitialize() in your low level application
 *      initialization logic
 *   4. The handle returned by up_spiinitialize() may then be used to bind the
 *      SPI driver to higher level logic (e.g., calling
 *      mmcsd_spislotinitialize(), for example, will bind the SPI driver to
 *      the SPI MMC/SD driver).
 *
 ****************************************************************************/

#ifdef CONFIG_STM32_SPI1
void stm32_spi1select(FAR struct spi_dev_s *dev, enum spi_dev_e devid, bool selected)
{
  spidbg("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert");
}

uint8_t stm32_spi1status(FAR struct spi_dev_s *dev, enum spi_dev_e devid)
{
  return 0;
}
#endif

#ifdef CONFIG_STM32_SPI2
void stm32_spi2select(FAR struct spi_dev_s *dev, enum spi_dev_e devid, bool selected)
{
  spidbg("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert");

#ifdef CONFIG_INPUT_ADS7843E
  /* Select/de-select the touchscreen */

  if (devid == SPIDEV_TOUCHSCREEN)
    {
      stm32_gpiowrite(GPIO_LCDTP_CS, !selected);
    }
#endif
}

uint8_t stm32_spi2status(FAR struct spi_dev_s *dev, enum spi_dev_e devid)
{
  return 0;
}
#endif

#ifdef CONFIG_STM32_SPI3
void stm32_spi3select(FAR struct spi_dev_s *dev, enum spi_dev_e devid, bool selected)
{
  spidbg("devid: %d CS: %s\n", (int)devid, selected ? "assert" : "de-assert");
}

uint8_t stm32_spi3status(FAR struct spi_dev_s *dev, enum spi_dev_e devid)
{
  return 0;
}
#endif

#endif /* CONFIG_STM32_SPI1 || CONFIG_STM32_SPI2 || CONFIG_STM32_SPI3*/


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>statsmodels.regression.quantile_regression.QuantRegResults — statsmodels v0.10.0 documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.regression.quantile_regression.QuantRegResults.HC0_se" href="statsmodels.regression.quantile_regression.QuantRegResults.HC0_se.html" />
    <link rel="prev" title="statsmodels.regression.linear_model.PredictionResults.conf_int" href="statsmodels.regression.linear_model.PredictionResults.conf_int.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

          next |

          previous |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Linear Regression |

statsmodels.regression.quantile_regression.QuantRegResults¶

class statsmodels.regression.quantile_regression.QuantRegResults(model, params, normalized_cov_params=None, scale=1.0, cov_type='nonrobust', cov_kwds=None, use_t=None, **kwargs)[source]¶

Results instance for the QuantReg model

Methods

<colgroup>
<col style="width: 10%" />
<col style="width: 90%" />
</colgroup>

HC0_se()

See statsmodels.RegressionResults

HC1_se()

See statsmodels.RegressionResults

HC2_se()

See statsmodels.RegressionResults

HC3_se()

See statsmodels.RegressionResults

aic()

Akaike's information criteria.

bic()

Bayes' information criteria.

bse()

The standard errors of the parameter estimates.

centered_tss()

The total (weighted) sum of squares centered about the mean.

compare_f_test(restricted)

use F test to test whether restricted model is correct

compare_lm_test(restricted[, demean, use_lr])

Use Lagrange Multiplier test to test whether restricted model is correct

compare_lr_test(restricted[, large_sample])

Likelihood ratio test to test whether restricted model is correct

condition_number()

Return condition number of exogenous matrix.

conf_int([alpha, cols])

Returns the confidence interval of the fitted parameters.

cov_HC0()

See statsmodels.RegressionResults

cov_HC1()

See statsmodels.RegressionResults

cov_HC2()

See statsmodels.RegressionResults

cov_HC3()

See statsmodels.RegressionResults

cov_params([r_matrix, column, scale, cov_p, …])

Returns the variance/covariance matrix.

eigenvals()

Return eigenvalues sorted in decreasing order.

ess()

Explained sum of squares.

f_pvalue()

p-value of the F-statistic

f_test(r_matrix[, cov_p, scale, invcov])

Compute the F-test for a joint linear hypothesis.

fittedvalues()

The predicted values for the original (unwhitened) design.

fvalue()

F-statistic of the fully specified model.

get_prediction([exog, transform, weights, …])

compute prediction results

get_robustcov_results([cov_type, use_t])

create new results instance with robust covariance as default

initialize(model, params, **kwd)

Initialize (possibly re-initialize) a Results instance.

llf()

Log-likelihood of model

load(fname)

load a pickle, (class method)

mse_model()

Mean squared error the model.

mse_resid()

Mean squared error of the residuals.

mse_total()

Total mean squared error.

nobs()

Number of observations n.

normalized_cov_params()

See specific model class docstring

predict([exog, transform])

Call self.model.predict with self.params as the first argument.

pvalues()

The two-tailed p values for the t-stats of the params.

remove_data()

remove data arrays, all nobs arrays from result and model

resid()

The residuals of the model.

resid_pearson()

Residuals, normalized to have unit variance.

rsquared()

R-squared of a model with an intercept.

rsquared_adj()

Adjusted R-squared.

save(fname[, remove_data])

save a pickle of this instance

scale()

A scale factor for the covariance matrix.

ssr()

Sum of squared (whitened) residuals.

summary([yname, xname, title, alpha])

Summarize the Regression Results

summary2([yname, xname, title, alpha, …])

Experimental summary function to summarize the regression results

t_test(r_matrix[, cov_p, scale, use_t])

Compute a t-test for a each linear hypothesis of the form Rb = q

t_test_pairwise(term_name[, method, alpha, …])

perform pairwise t_test with multiple testing corrected p-values

tvalues()

Return the t-statistic for a given parameter estimate.

uncentered_tss()

Uncentered sum of squares.

wald_test(r_matrix[, cov_p, scale, invcov, …])

Compute a Wald-test for a joint linear hypothesis.

wald_test_terms([skip_single, …])

Compute a sequence of Wald tests for terms over multiple columns

wresid()

The residuals of the transformed/whitened regressand and regressor(s)

<colgroup>
<col style="width: 57%" />
<col style="width: 43%" />
</colgroup>

mse

prsquared

Previous topic

statsmodels.regression.linear_model.PredictionResults.conf_int

Next topic

statsmodels.regression.quantile_regression.QuantRegResults.HC0_se

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" aria-labelledby="searchlabel" />
      <input type="submit" value="Go" />
    </form>

        © Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 2.1.2.


text:
using System.Net;
using System.Threading.Tasks;
using NUnit.Framework;
using Umbraco.Cms.Tests.Integration.TestServerTest;
using Umbraco.Cms.Web.BackOffice.Controllers;

namespace Umbraco.Cms.Tests.Integration.Umbraco.Web.BackOffice.Controllers;

[TestFixture]
public class BackOfficeAssetsControllerTests : UmbracoTestServerTestBase
{
    [Test]
    public async Task EnsureSuccessStatusCode()
    {
        // Arrange
        var url = PrepareApiControllerUrl<BackOfficeAssetsController>(x => x.GetSupportedLocales());

        // Act
        var response = await Client.GetAsync(url);

        // Assert
        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
    }
}


text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Example - example-ng-repeat-production</title>
  <link href="animations.css" rel="stylesheet" type="text/css">

  I have {{friends.length}} friends. They are:
  <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />

      [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.

      No results found...


text:
// Copyright 2000-2018 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.codeInspection.dataFlow;

import com.intellij.codeInspection.dataFlow.instructions.*;
import com.intellij.codeInspection.dataFlow.value.DfaConstValue;
import com.intellij.codeInspection.dataFlow.value.DfaValue;
import com.intellij.psi.*;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.util.PsiModificationTracker;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.JavaPsiConstructorUtil;
import com.intellij.util.ObjectUtils;
import com.siyeh.ig.psiutils.ExpressionUtils;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

import static com.intellij.codeInspection.dataFlow.DfaUtil.hasImplicitImpureSuperCall;

public class CommonDataflow {
  /**
   * Represents the result of dataflow applied to some code fragment (usually a method)
   */
  public static class DataflowResult {
    private final Map<PsiExpression, DfaFactMap> myFacts = new HashMap<>();
    private final Set<PsiExpression> myUnknowns = new HashSet<>();

    DataflowResult copy() {
      DataflowResult copy = new DataflowResult();
      copy.myFacts.putAll(myFacts);
      return copy;
    }

    void add(PsiExpression expression, DfaMemoryStateImpl memState, DfaValue value) {
      if (memState.isUnknownState(value)) {
        myUnknowns.add(expression);
      }
      DfaFactMap existing = myFacts.get(expression);
      if(existing != DfaFactMap.EMPTY) {
        DfaFactMap newMap = memState.getFactMap(value);
        if (!Boolean.FALSE.equals(newMap.get(DfaFactType.CAN_BE_NULL)) && memState.isNotNull(value)) {
          newMap = newMap.with(DfaFactType.CAN_BE_NULL, false);
        }
        myFacts.put(expression, existing == null ? newMap : existing.union(newMap));
      }
    }

    /**
     * Returns true if given expression was visited by dataflow. Note that dataflow usually tracks deparenthesized expressions only,
     * so you should deparenthesize it in advance if necessary.
     *
     * @param expression expression to check, not parenthesized
     * @return true if given expression was visited by dataflow.
     * If false is returned, it's possible that the expression exists in unreachable branch or this expression is not tracked due to
     * the dataflow implementation details.
     */
    public boolean expressionWasAnalyzed(PsiExpression expression) {
      assert !(expression instanceof PsiParenthesizedExpression);
      return myFacts.containsKey(expression) && !myUnknowns.contains(expression);
    }

    /**
     * Returns a fact of specific type which is known for given expression or null if fact is not known
     *
     * @param expression expression to get the fact
     * @param type a fact type
     * @param <T> resulting type
     * @return a fact value or null if fact of given type is not known for given expression
     */
    @Nullable
    public <T> T getExpressionFact(PsiExpression expression, DfaFactType<T> type) {
      DfaFactMap map = this.myFacts.get(expression);
      return map == null ? null : map.get(type);
    }

    /**
     * Returns the fact map which represents all the facts known for given expression
     *
     * @param expression an expression to check
     * @return the fact map which represents all the facts known for given expression; empty map if the expression was
     * analyzed, but no particular facts were inferred; null if the expression was not analyzed.
     */
    @Nullable
    public DfaFactMap getAllFacts(PsiExpression expression) {
      return this.myFacts.get(expression);
    }
  }

  @Contract("null -> null")
  @Nullable
  private static DataflowResult runDFA(@Nullable PsiElement block) {
    if (block == null) return null;
    DataFlowRunner runner = new DataFlowRunner(false, block);
    CommonDataflowVisitor visitor = new CommonDataflowVisitor(runner);
    RunnerResult result = runner.analyzeMethodRecursively(block, visitor);
    if (result != RunnerResult.OK) return null;
    if (!(block instanceof PsiClass)) return visitor.myResult;
    DataflowResult dfr = visitor.myResult.copy();
    List<DfaMemoryState> states = visitor.myEndOfInitializerStates;
    for (PsiMethod method : ((PsiClass)block).getConstructors()) {
      List<DfaMemoryState> initialStates;
      PsiCodeBlock body = method.getBody();
      if (body == null) continue;
      PsiMethodCallExpression call = JavaPsiConstructorUtil.findThisOrSuperCallInConstructor(method);
      if (JavaPsiConstructorUtil.isChainedConstructorCall(call) || (call == null && hasImplicitImpureSuperCall((PsiClass)block, method))) {
        initialStates = Collections.singletonList(runner.createMemoryState());
      } else {
        initialStates = StreamEx.of(states).map(DfaMemoryState::createCopy).toList();
      }
      if(runner.analyzeBlockRecursively(body, initialStates, visitor) == RunnerResult.OK) {
        dfr = visitor.myResult.copy();
      } else {
        visitor.myResult = dfr;
      }
    }
    return dfr;
  }

  /**
   * Returns the dataflow result for code fragment which contains given context
   * @param context a context to get the dataflow result
   * @return the dataflow result or null if dataflow cannot be launched for this context (e.g. we are inside too complex method)
   */
  @Nullable
  public static DataflowResult getDataflowResult(PsiExpression context) {
    PsiElement body = DfaUtil.getDataflowContext(context);
    if (body == null) return null;
    return CachedValuesManager.getCachedValue(body, () -> {
      DataflowResult result = runDFA(body);
      return CachedValueProvider.Result.create(result, PsiModificationTracker.MODIFICATION_COUNT);
    });
  }

  /**
   * Returns a fact of specific type which is known for given expression or null if fact is not known
   *
   * @param expression expression to get the fact
   * @param type a fact type
   * @param <T> resulting type
   * @return a fact value or null if fact of given type is not known for given expression
   */
  public static <T> T getExpressionFact(PsiExpression expression, DfaFactType<T> type) {
    DataflowResult result = getDataflowResult(expression);
    if (result == null) return null;
    return result.getExpressionFact(PsiUtil.skipParenthesizedExprDown(expression), type);
  }

  private static class CommonDataflowVisitor extends StandardInstructionVisitor {
    private DataflowResult myResult;
    private final DfaConstValue myFail;
    private final List<DfaMemoryState> myEndOfInitializerStates = new ArrayList<>();

    public CommonDataflowVisitor(DataFlowRunner runner) {
      myFail = runner.getFactory().getConstFactory().getContractFail();
      myResult = new DataflowResult();
    }

    @Override
    public DfaInstructionState[] visitEndOfInitializer(EndOfInitializerInstruction instruction,
                                                       DataFlowRunner runner,
                                                       DfaMemoryState state) {
      if (!instruction.isStatic()) {
        myEndOfInitializerStates.add(state.createCopy());
      }
      return super.visitEndOfInitializer(instruction, runner, state);
    }

    @Override
    public DfaInstructionState[] visitPush(PushInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
      DfaInstructionState[] states = super.visitPush(instruction, runner, memState);
      PsiExpression place = instruction.getPlace();
      if (place != null && !instruction.isReferenceWrite()) {
        for (DfaInstructionState state : states) {
          DfaMemoryState afterState = state.getMemoryState();
          myResult.add(place, (DfaMemoryStateImpl)afterState, instruction.getValue());
        }
      }
      return states;
    }

    @Override
    public DfaInstructionState[] visitArrayAccess(ArrayAccessInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
      DfaInstructionState[] states = super.visitArrayAccess(instruction, runner, memState);
      PsiArrayAccessExpression anchor = instruction.getExpression();
      for (DfaInstructionState state : states) {
        DfaMemoryState afterState = state.getMemoryState();
        myResult.add(anchor, (DfaMemoryStateImpl)afterState, afterState.peek());
      }
      return states;
    }

    @Override
    public DfaInstructionState[] visitBinop(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
      DfaInstructionState[] states = super.visitBinop(instruction, runner, memState);
      PsiElement anchor = instruction.getPsiAnchor();
      if (anchor instanceof PsiExpression) {
        for (DfaInstructionState state : states) {
          DfaMemoryState afterState = state.getMemoryState();
          myResult.add((PsiExpression)anchor, (DfaMemoryStateImpl)afterState, afterState.peek());
        }
      }
      return states;
    }

    @NotNull
    @Override
    protected DfaCallArguments popCall(MethodCallInstruction instruction,
                                       DataFlowRunner runner,
                                       DfaMemoryState memState,
                                       boolean contractOnly) {
      DfaCallArguments arguments = super.popCall(instruction, runner, memState, contractOnly);
      PsiElement context = instruction.getContext();
      if (instruction.getMethodType() == MethodCallInstruction.MethodType.REGULAR_METHOD_CALL &&
          context instanceof PsiMethodCallExpression) {
        PsiExpression qualifier =
          PsiUtil.skipParenthesizedExprDown(((PsiMethodCallExpression)context).getMethodExpression().getQualifierExpression());
        if (qualifier != null) {
          myResult.add(qualifier, (DfaMemoryStateImpl)memState, arguments.myQualifier);
        }
      }
      return arguments;
    }

    @Override
    public DfaInstructionState[] visitMethodCall(MethodCallInstruction instruction,
                                                 DataFlowRunner runner,
                                                 DfaMemoryState memState) {
      DfaInstructionState[] states = super.visitMethodCall(instruction, runner, memState);
      PsiExpression context = ObjectUtils.tryCast(instruction.getContext(), PsiExpression.class);
      if (context != null && ExpressionUtils.getCallForQualifier(context) == null) {
        for (DfaInstructionState state : states) {
          DfaValue value = state.getMemoryState().peek();
          if (value != myFail) {
            myResult.add(context, (DfaMemoryStateImpl)state.getMemoryState(), value);
          }
        }
      }
      return states;
    }
  }
}


text:
package com.jareddlc.turquoisebicuspid;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class SettingsService extends Service {
    // debug data
    private static final String LOG_TAG = "TurquoiseBicuspid:SettingsService";

    private static boolean smsEnabled = true;
    private static boolean phoneEnabled = true;
    private CallListener callListener;
    private SmsListener smsListener;
    private TelephonyManager telephony;
    private IntentFilter smsFilter;

    private String preference_sms_type;
    private String preference_sms_time;
    private String preference_sms_number;
    private String preference_sms_color;
    private String preference_phone_type;
    private String preference_phone_time;
    private String preference_phone_number;
    private String preference_phone_color;
    private String preference_repeat;

    private Handler mHandler;
    private static Bluetooth bluetooth;

    public static void setSms(boolean value) {
        Log.d(LOG_TAG, "SMS: "+value);
        smsEnabled = value;
    }

    public static void setPhone(boolean value) {
        Log.d(LOG_TAG, "Phone: "+value);
        phoneEnabled = value;
    }

    public void setPreferences(SavedPreferences sPrefs) {
        preference_sms_type = sPrefs.saved_preference_list_sms_type_value;
        preference_sms_time = sPrefs.saved_preference_list_sms_time_value;
        preference_sms_number = sPrefs.saved_preference_list_sms_number_value;
        preference_sms_color = sPrefs.saved_preference_color_sms;
        preference_phone_type = sPrefs.saved_preference_list_phone_type_value;
        preference_phone_time = sPrefs.saved_preference_list_phone_time_value;
        preference_phone_number = sPrefs.saved_preference_list_phone_number_value;
        preference_phone_color = sPrefs.saved_preference_color_phone;
        preference_repeat = sPrefs.saved_preference_list_repeat_value;
    }

    @SuppressLint("HandlerLeak")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
        Log.d(LOG_TAG, "Service running");

        // restore saved preferences
        final SavedPreferences sPrefs = new SavedPreferences(this);
        preference_sms_type = sPrefs.saved_preference_list_sms_type_value;
        preference_sms_time = sPrefs.saved_preference_list_sms_time_value;
        preference_sms_number = sPrefs.saved_preference_list_sms_number_value;
        preference_sms_color = sPrefs.saved_preference_color_sms;
        preference_phone_type = sPrefs.saved_preference_list_phone_type_value;
        preference_phone_time = sPrefs.saved_preference_list_phone_time_value;
        preference_phone_number = sPrefs.saved_preference_list_phone_number_value;
        preference_phone_color = sPrefs.saved_preference_color_phone;
        preference_repeat = sPrefs.saved_preference_list_repeat_value;

        // register broadcast events
         LocalBroadcastManager.getInstance(this).registerReceiver(smsReceiver, new IntentFilter("sms"));
         LocalBroadcastManager.getInstance(this).registerReceiver(phoneReceiver, new IntentFilter("phone"));
         LocalBroadcastManager.getInstance(this).registerReceiver(prefReceiver, new IntentFilter("setPreferences"));

        // setup message handler
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                String bluetoothMsg = msg.getData().getString("bluetooth");
                if(bluetoothMsg.equals("isEnabled")) {
                    CharSequence text = "Bluetooth Enabled";
                    Toast.makeText(SettingsService.this, text, Toast.LENGTH_SHORT).show();
                }
                if(bluetoothMsg.equals("isConnected")) {
                    Log.d(LOG_TAG, "Bluetooth Connected");
                    CharSequence text = "Bluetooth Connected";
                    Toast.makeText(SettingsService.this, text, Toast.LENGTH_SHORT).show();
                }
                if(bluetoothMsg.equals("isConnectedFailed")) {
                    Log.d(LOG_TAG, "Bluetooth Connected Failed");
                    CharSequence text = "Bluetooth Connected failed";
                    Toast.makeText(SettingsService.this, text, Toast.LENGTH_SHORT).show();
                }
            }
        };

        // initialize Bluetooth
        bluetooth = new Bluetooth(mHandler);

        if(bluetooth.isEnabled) {
            bluetooth.getPaired();
            bluetooth.setDevice(sPrefs.saved_preference_list_paired_value);
            bluetooth.connectDevice();
        }

        // register listeners
        if(smsEnabled) {
            smsListener = new SmsListener();
            smsFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
            this.registerReceiver(smsListener, smsFilter);
            Log.d(LOG_TAG, "sms listening");
        }

        if(phoneEnabled) {
            callListener = new CallListener(getApplicationContext());
            telephony = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
            telephony.listen(callListener, PhoneStateListener.LISTEN_CALL_STATE);
            Log.d(LOG_TAG, "phone listening");
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
        Log.d(LOG_TAG, "Service stopped");
        bluetooth.disconnectDevice();

        // unregister listeners
        if(smsEnabled) {
            this.unregisterReceiver(smsListener);
        }

        if(phoneEnabled) {
            telephony.listen(callListener, PhoneStateListener.LISTEN_NONE);
            callListener.destroy();
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "onBind");
        return null;
    }

    private BroadcastReceiver smsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
            String sender = intent.getStringExtra("sender");
            Log.d(LOG_TAG, "Recieved SMS message: "+sender+" - "+message);
            bluetooth.send(preference_sms_type, preference_sms_number, preference_sms_time, preference_repeat, preference_sms_color);
        }
    };

    private BroadcastReceiver phoneReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String sender = intent.getStringExtra("sender");
            Log.d(LOG_TAG, "Recieved PHONE: "+sender);
            bluetooth.send(preference_phone_type, preference_phone_number, preference_phone_time, preference_repeat, preference_phone_color);
        }
    };

    private BroadcastReceiver prefReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(LOG_TAG, "Recieved PREF: ");
            SavedPreferences sPrefs = new SavedPreferences(context);
            setPreferences(sPrefs);
        }
    };
}


text:
#ifndef __SYSTEM_QUEUE_H__
#define __SYSTEM_QUEUE_H__
namespace Sys { namespace Collections {

	/// <summary>
	/// QueueTemplate
	/// </summary>
	template<class T, int NextOffset>
	class QueueTemplate
	{
	public:
		QueueTemplate();
		void Add(T *element);
		T *Get();

	private:
		T *_first;
		T *_last;
	};

#define QUEUE_NEXT_PTR(element)	(*((T**)(((byte*)element) + nextOffset)))

	/// <summary>
	/// QueueTemplate
	/// </summary>
	template<class T, int NextOffset>
	QueueTemplate<T, NextOffset>::QueueTemplate() { _first = _last = nullptr; }

	/// <summary>
	/// Add
	/// </summary>
	template<class T, int NextOffset>
	void QueueTemplate<T, NextOffset>::Add(T *element)
	{
		QUEUE_NEXT_PTR(element) = nullptr;
		if (_last)
			QUEUE_NEXT_PTR(last) = element;
		else
			_first = element;
		_last = element;
	}

	/// <summary>
	/// Get
	/// </summary>
	template<class T, int NextOffset>
	T *QueueTemplate<T, NextOffset>::Get()
	{
		T *element = _first;
		if (element)
		{
			_first = QUEUE_NEXT_PTR(_first);
			if (_last == element)
				_last = nullptr;
			QUEUE_NEXT_PTR(element) = nullptr;
		}
		return element;
	}

	/// <summary>
	/// A node of a Queue
	/// </summary>
	template<typename T>
	class QueueNode
	{
	public:
		QueueNode() { _next = nullptr; }
		T *GetNext() const { return _next; }
		void SetNext(T *next) { this->_next = next; }

	private:
		T *_next;
	};

	/// <summary>
	/// A Queue, idQueue, is a template Container class implementing the Queue abstract data type.
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	class Queue
	{
	public:
		Queue();
		void Add(T *element);
		type *RemoveFirst();
		type *Peek() const;
		bool IsEmpty();

	private:
		T *_first;
		T *_last;
	};

	/// <summary>
	/// Queue
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	Queue<T, NodePtr>::Queue() { _first = _last = nullptr; }

	/// <summary>
	/// Add
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	void Queue<T, NodePtr>::Add(T *element)
	{
		(element->*NodePtr).SetNext(nullptr);
		if (_last)
			(_last->*NodePtr).SetNext(element);
		else
			_first = element;
		_last = element;
	}

	/// <summary>
	/// RemoveFirst
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	T *Queue<T, NodePtr>::RemoveFirst()
	{
		T *element = _first;
		if (element)
		{
			_first = (_first->*NodePtr).GetNext();
			if (_last == element)
				_last = nullptr;
			(element->*NodePtr).SetNext(nullptr);
		}
		return element;
	}

	/// <summary>
	/// Peek
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	T *Queue<T, NodePtr>::Peek() const { return _first; }

	/// <summary>
	/// IsEmpty
	/// </summary>
	template<typename T, QueueNode<T> T::*NodePtr>
	bool Queue<T, NodePtr>::IsEmpty() { return (_first == nullptr); }

	///// <summary>
	///// Test
	///// </summary>
	//template<typename T, QueueNode<T> T::*NodePtr>
	//void Queue<T, NodePtr>::Test()
	//{
	//	class MyType
	//	{
	//	public:
	//		QueueNode<MyType> queueNode;
	//	};
	//	Queue<MyType, &MyType::queueNode> myQueue;
	//	MyType *element = new (TAG_IDLIB) MyType;
	//	myQueue.Add(element);
	//	element = myQueue.RemoveFirst();
	//	delete element;
	//}

}}
#endif /* __SYSTEM_QUEUE_H__ */


text:
package com.baoyongan.java.eg.logback.chapter3;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.util.StatusPrinter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 修改logback 的默认配置JoranConfigurator ,来完成日志配置
 * Created by bqct_bya on 2017/3/31.
 */
public class MyApp3 {
    final static Logger logger = LoggerFactory.getLogger(MyApp3.class);

    public static void main(String[] args) {
        // assume SLF4J is bound to logback in the current environment
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

        try {
            JoranConfigurator configurator = new JoranConfigurator();
            configurator.setContext(context);
            // Call context.reset() to clear any previous configuration, e.g. default
            // configuration. For multi-step configuration, omit calling context.reset().
            context.reset();
            configurator.doConfigure("D:\\Intellij_project\\java-examples\\java-eg-logback\\src\\main\\resources\\logback0.xml");
        } catch (Exception je) {
            // StatusPrinter will handle this
        }
        StatusPrinter.printInCaseOfErrorsOrWarnings(context);
        logger.info("Entering application.");

        Foo foo = new Foo();
        foo.doit();
        logger.info("Exiting application.");
    }
}


text:
#include "moveDeclarations.h"

namespace P4 {

const IR::Node* MoveDeclarations::postorder(IR::P4Action* action) {
    if (findContext<IR::P4Control>() == nullptr) {
        // Else let the parent control get these
        auto body = new IR::IndexedVector<IR::StatOrDecl>();
        auto m = getMoves();
        body->insert(body->end(), m->begin(), m->end());
        body->append(action->body->components);
        action->body =
            new IR::BlockStatement(action->body->srcInfo, action->body->annotations, *body);
        pop();
    }
    return action;
}

const IR::Node* MoveDeclarations::postorder(IR::P4Control* control) {
    LOG1("Visiting " << control << " toMove " << toMove.size());
    auto decls = new IR::IndexedVector<IR::Declaration>();
    for (auto decl : *getMoves()) {
        LOG1("Moved " << decl);
        decls->push_back(decl);
    }
    decls->append(control->controlLocals);
    control->controlLocals = *decls;
    pop();
    return control;
}

const IR::Node* MoveDeclarations::postorder(IR::P4Parser* parser) {
    auto newStateful = new IR::IndexedVector<IR::Declaration>();
    newStateful->append(*getMoves());
    newStateful->append(parser->parserLocals);
    parser->parserLocals = *newStateful;
    pop();
    return parser;
}

const IR::Node* MoveDeclarations::postorder(IR::Function* function) {
    auto body = new IR::IndexedVector<IR::StatOrDecl>();
    auto m = getMoves();
    body->insert(body->end(), m->begin(), m->end());
    body->append(function->body->components);
    function->body =
        new IR::BlockStatement(function->body->srcInfo, function->body->annotations, *body);
    pop();
    return function;
}

const IR::Node* MoveDeclarations::postorder(IR::Declaration_Variable* decl) {
    auto parent = getContext()->node;
    // We must keep the initializer here
    if (decl->initializer != nullptr && !parent->is<IR::IndexedVector<IR::Declaration>>() &&
        !parent->is<IR::P4Parser>() && !parent->is<IR::P4Control>()) {
        // Don't split initializers from declarations that are at the "toplevel".
        // We cannot have assignment statements there.
        LOG1("Moving and splitting " << decl);
        auto move = new IR::Declaration_Variable(decl->srcInfo, decl->name, decl->annotations,
                                                 decl->type, nullptr);
        addMove(move);
        auto varRef = new IR::PathExpression(decl->name);
        auto keep = new IR::AssignmentStatement(decl->srcInfo, varRef, decl->initializer);
        return keep;
    } else {
        LOG1("Moving " << decl);
        addMove(decl);
        return nullptr;
    }
}

const IR::Node* MoveDeclarations::postorder(IR::Declaration_Constant* decl) {
    if (findContext<IR::P4Control>() == nullptr && findContext<IR::P4Action>() == nullptr &&
        findContext<IR::P4Parser>() == nullptr)
        // This is a global declaration
        return decl;
    addMove(decl);
    return nullptr;
}

////////////////////////////////////////////////////////////////////

const IR::Node* MoveInitializers::preorder(IR::P4Parser* parser) {
    // Determine if we have anything to do in this parser.
    // Check if we have top-level declarations with intializers.
    auto someInitializers = false;
    for (auto d : parser->parserLocals) {
        if (auto dv = d->to<IR::Declaration_Variable>()) {
            if (dv->initializer != nullptr) {
                someInitializers = true;
                break;
            }
        }
    }
    if (someInitializers) {
        newStartName = refMap->newName(IR::ParserState::start);
        oldStart = parser->states.getDeclaration(IR::ParserState::start)->to<IR::ParserState>();
        CHECK_NULL(oldStart);
    }
    return parser;
}

const IR::Node* MoveInitializers::postorder(IR::P4Parser* parser) {
    if (oldStart == nullptr) return parser;
    auto newStart = new IR::ParserState(IR::ID(IR::ParserState::start), *toMove,
                                        new IR::PathExpression(newStartName));
    toMove = new IR::IndexedVector<IR::StatOrDecl>();
    parser->states.insert(parser->states.begin(), newStart);
    return parser;
}

const IR::Node* MoveInitializers::postorder(IR::Declaration_Variable* decl) {
    if (getContext() == nullptr) return decl;
    auto parent = getContext()->node;
    if (!parent->is<IR::P4Control>() && !parent->is<IR::P4Parser>())
        // We are not in the local toplevel declarations
        return decl;
    if (decl->initializer == nullptr) return decl;

    auto varRef = new IR::PathExpression(decl->name);
    auto assign = new IR::AssignmentStatement(decl->srcInfo, varRef, decl->initializer);
    toMove->push_back(assign);
    decl->initializer = nullptr;
    return decl;
}

const IR::Node* MoveInitializers::postorder(IR::ParserState* state) {
    if (oldStart == nullptr) return state;
    if (state->name == IR::ParserState::start) state->name = newStartName;
    return state;
}

const IR::Node* MoveInitializers::postorder(IR::P4Control* control) {
    if (toMove->empty()) return control;
    toMove->append(control->body->components);
    auto newBody = new IR::BlockStatement(control->body->annotations, *toMove);
    control->body = newBody;
    toMove = new IR::IndexedVector<IR::StatOrDecl>();
    return control;
}

const IR::Node* MoveInitializers::postorder(IR::Path* path) {
    if (oldStart == nullptr || path->name != IR::ParserState::start) return path;
    auto decl = refMap->getDeclaration(getOriginal()->to<IR::Path>());
    if (!decl->is<IR::ParserState>()) return path;
    return new IR::Path(newStartName);
}

}  // namespace P4


text:
class AdminAssistant
  class Search
    attr_reader :params

    def initialize(admin_assistant, params)
      @admin_assistant, @params = admin_assistant, params
      @params ||= {}
      @attributes = HashWithIndifferentAccess.new
      columns.each do |c|
        c.verify_for_search
        compare_to_range = compare_to_range?(c.name) if c.respond_to?(:name)
        attributes = c.attributes_for_search_object(@params, compare_to_range)
        attributes.each do |key, value|
          @attributes[key] = value
        end
      end
    end

    def [](name)
      @params[name]
    end

    def add_to_query(ar_query)
      unless @params.empty?
        ar_query.add_condition do |cond|
          if match_any_conditions?
            cond.boolean_join = :or
          end
          columns.each do |column|
            column.add_to_query_condition cond, self
          end
        end
      end
    end

    def blank?(column_name)
      @params["#{column_name}(blank)"] == '1'
    end

    def columns
      column_names = settings.column_names
      if column_names.empty?
        [DefaultSearchColumn.new(
          @admin_assistant.model_class,
          :fields_to_match => @admin_assistant.default_search_matches_on
        )]
      else
        column_names.map { |column_name|
          @admin_assistant.column(column_name.to_s)
        }
      end
    end

    def column_views(action_view)
      columns.map { |c|
        c.search_view action_view, @admin_assistant, :search => self
      }
    end

    def comparator(column_name)
      c = @params["#{column_name}(comparator)"]
      c if %w(< <= = >= >).include?(c)
    end

    def compare_to_range?(column_name)
      settings[column_name].compare_to_range
    end

    def id
      @attributes[:id] if @attributes.has_key?(:id)
    end

    def match_all_conditions?
      !match_any_conditions?
    end

    def match_any_conditions?
      @params["(all_or_any)"] == 'any'
    end

    def method_missing(meth, *args)
      if @attributes.has_key?(meth)
        @attributes[meth]
      else
        super
      end
    end

    def model_class
      @admin_assistant.model_class
    end

    def settings
      @admin_assistant.search_settings
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Reflection;

namespace SafeOrbit.Memory.SafeContainerServices.Instance.Validation
{
    internal class SingletonShouldNotImplementIDisposable : IInstanceProviderRule
    {
        public IEnumerable<string> Errors { get; private set; }
        public RuleType Type { get; } = RuleType.Warning;

        public bool IsSatisfiedBy(IInstanceProvider instance)
        {
            if (instance.LifeTime == LifeTime.Transient) return true;
            var type = instance.ImplementationType;
            if (type == null) throw new ArgumentException($"Type ({type.FullName}) could not be loaded");
            var isDisposable = typeof(IDisposable).GetTypeInfo().IsAssignableFrom(type);
            if (!isDisposable) return true;
            Errors = new[]
            {
                $"{type.AssemblyQualifiedName} implements {nameof(IDisposable)} but registered as {nameof(LifeTime.Singleton)}"
            };
            return false;
        }
    }
}


text:
package apiserver

import (
	"net/http"

	"k8s.io/kubernetes/pkg/probe"
	httpprober "k8s.io/kubernetes/pkg/probe/http"
	utilnet "k8s.io/kubernetes/pkg/util/net"
	"time"
)

const (
	probeTimeOut = 20 * time.Second
)

// TODO: this basic interface is duplicated in N places.  consolidate?
type httpGet interface {
	Get(url string) (*http.Response, error)
}

type ValidatorFn func([]byte) error

type Server struct {
	Addr        string
	Port        int
	Path        string
	EnableHTTPS bool
	Validate    ValidatorFn
}

type ServerStatus struct {
	Component  string       `json:"component,omitempty"`
	Health     string       `json:"health,omitempty"`
	HealthCode probe.Result `json:"healthCode,omitempty"`
	Msg        string       `json:"msg,omitempty"`
	Err        string       `json:"err,omitempty"`
}

func (server *Server) DoServerCheck(prober httpprober.HTTPProber) (probe.Result, string, error) {
	scheme := "http"
	if server.EnableHTTPS {
		scheme = "https"
	}
	url := utilnet.FormatURL(scheme, server.Addr, server.Port, server.Path)

	result, data, err := prober.Probe(url, nil, probeTimeOut)

	if err != nil {
		return probe.Unknown, "", err
	}
	if result == probe.Failure {
		return probe.Failure, string(data), err
	}
	if server.Validate != nil {
		if err := server.Validate([]byte(data)); err != nil {
			return probe.Failure, string(data), err
		}
	}
	return result, string(data), nil
}


text:
import os

from swagger_tester import swagger_test

import connexion
from multiprocessing import Process

class ConnexionProcess(Process):
    def run(self):
        self.conn = connexion.App(
            'tests',
            debug=True,
            specification_dir=os.path.dirname(__file__)
        )
        self.conn.add_api('swagger.yaml')
        self.conn.app.run(port=8080)

    def start(self):
        Process.start(self)

        import time
        time.sleep(3)

    def terminate(self):
        Process.terminate(self)
        Process.join(self)

swagger_yaml_path = os.path.join(os.path.dirname(__file__), 'swagger.yaml')
authorize_error = {
    'post': {
        '/v2/pet/{petId}': [200],
        '/v2/pet': [200]
    },
    'put': {
        '/v2/user/{username}': [200],
        '/v2/pet': [200]
    },
    'delete': {
        '/v2/pet/{petId}': [200],
        '/v2/store/order/{orderId}': [200],
        '/v2/user/{username}': [200]
    }
}
swagger_io_url = 'http://localhost:8080/v2'

def test_swagger_test_use_example():
    swagger_test(swagger_yaml_path, use_example=True)

def test_swagger_test_dont_use_example():
    swagger_test(swagger_yaml_path, use_example=False)

def test_swagger_test_extra_headers():
    swagger_test(swagger_yaml_path, extra_headers={'X-Header': 'Value'})

def test_swagger_test_specify_app_url_use_example():
    conn = ConnexionProcess()
    conn.start()
    swagger_test(app_url=swagger_io_url,
                 authorize_error=authorize_error,
                 use_example=True)
    conn.terminate()

def test_issue_51_fixed():
    conn = ConnexionProcess()
    conn.start()
    swagger_test(app_url='http://v2@localhost:8080/v2',
                 authorize_error=authorize_error)
    conn.terminate()

def test_swagger_test_specify_app_url_dont_use_example():
    conn = ConnexionProcess()
    conn.start()
    swagger_test(app_url=swagger_io_url,
                 authorize_error=authorize_error,
                 use_example=False)
    conn.terminate()


text:
import React from 'react'
import { render } from 'react-testing-library'
import { items, groups } from '../../../__fixtures__/itemsAndGroups'
import {
  props as defaultProps
} from '../../../__fixtures__/stateAndProps'
import 'react-testing-library/cleanup-after-each'
import Timeline from 'lib/Timeline'
import 'jest-dom/extend-expect'

/**
 * Testing The Default Functionality
 */
describe('Renders default headers correctly', () => {
  it('Given Timeline When not using TimelineHeaders then it should render 2 DateHeaders and a left sidebar header by default ', () => {
    const { getAllByTestId, getByTestId } = renderDefaultTimeline();
    expect(getAllByTestId('dateHeader')).toHaveLength(2);
    expect(getByTestId('headerContainer').children).toHaveLength(2);
    expect(getByTestId('sidebarHeader')).toBeInTheDocument();
  });
  it('Given TimelineHeader When pass a rightSidebarWidthWidth Then it should render two sidebar headers', () => {
    let rightSidebarWidth = 150;
    const { getAllByTestId } = renderDefaultTimeline({ rightSidebarWidth });
    const sidebarHeaders = getAllByTestId('sidebarHeader');
    expect(sidebarHeaders).toHaveLength(2);
    expect(sidebarHeaders[0]).toBeInTheDocument();
    expect(sidebarHeaders[1]).toBeInTheDocument();
    const { width } = getComputedStyle(sidebarHeaders[1]);
    expect(width).toBe('150px');
  });
});

export function renderDefaultTimeline(props = {}) {
  const timelineProps = {
    ...defaultProps,
    items,
    groups,
    ...props
  }
  return render(<Timeline {...timelineProps} />)
}


text:
<?php

namespace Assely\Adapter;

use Illuminate\Support\Collection;
use Illuminate\Contracts\Config\Repository;
use Assely\Contracts\Singularity\Model\ModelInterface;

class AdapterPlugger
{
    /**
     * Collection of connected adapters.
     *
     * @var \Illuminate\Support\Collection
     */
    protected $collection;

    /**
     * Application config instance.
     *
     * @var \Illuminate\Contracts\Config\Repository
     */
    protected $config;

    /**
     * Adapter object.
     *
     * @var string
     */
    protected $adapter;

    /**
     * Adapter model.
     *
     * @var \Assely\Contracts\Singularity\Model\ModelInterface
     */
    protected $model;

    /**
     * Construct adapters plugger.
     *
     * @param \Illuminate\Support\Collection $collection
     * @param \Illuminate\Contracts\Config\Repository $config
     */
    public function __construct(
        Collection $collection,
        Repository $config
    ) {
        $this->collection = $collection;
        $this->config = $config;
    }

    /**
     * Plugin adaptees.
     *
     * @return void
     */
    public function plugIn($adaptee)
    {
        if (is_array($adaptee)) {
            foreach ($adaptee as $item) {
                $this->plugIn($item);
            }

            return $this;
        }

        $this->collection->push($this->connectAdapter($adaptee));

        return $this;
    }

    /**
     * Connect adapter, model and adaptee.
     *
     * @param string $adaptee
     *
     * @return \Assely\Contracts\Adapter\AdapterInterface
     */
    public function connectAdapter($adaptee)
    {
        $adapter = new $this->adapter($this->config);

        return $adapter
            ->setAdaptee($adaptee)
            ->setModel($this->model);
    }

    /**
     * Gets connected adapters.
     *
     * @return array
     */
    public function getConnected()
    {
        return $this->collection;
    }

    /**
     * Sets the Adapter model.
     *
     * @param \Assely\Contracts\Singularity\Model\ModelInterface $model the model
     *
     * @return self
     */
    public function setModel(ModelInterface $model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Sets the Adapter object.
     *
     * @param string $adapter the adapter
     *
     * @return self
     */
    public function setAdapter($adapter)
    {
        $this->adapter = $adapter;

        return $this;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.gradle.tooling.model.java Class Hierarchy (Gradle API 2.13)</title>
<meta name="date" content="2016-04-25">
<link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.gradle.tooling.model.java

Package Hierarchies:

All Packages

Interface Hierarchy

org.gradle.tooling.model.java.InstalledJdk

org.gradle.tooling.model.java.JavaRuntime

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
title: Sina Ghandian
author: sina_ghandian
layout: author-bio
jobtitle: Research Data Analyst
bio:
type: member
excerpt: "Sina graduated from UC Berkeley with a B.S. in Bioengineering and a concentration in data science. As an undergraduate, his research laid in the field of clinic"
header:
  teaser: /assets/images/people/bio-ghandian.jpg
papers:
---


text:
package com.intellij.lang.jsgraphql.ide.validation.fixes;

import com.intellij.codeInspection.IntentionAndQuickFixAction;
import com.intellij.lang.jsgraphql.GraphQLBundle;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SmartPointerManager;
import com.intellij.psi.SmartPsiElementPointer;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class GraphQLNavigateToRelatedDefinitionFix extends IntentionAndQuickFixAction {
    private final @NotNull SmartPsiElementPointer<PsiElement> myElement;
    private final @Nullable String myName;

    public GraphQLNavigateToRelatedDefinitionFix(@NotNull PsiElement element, @Nullable String name) {
        myElement = SmartPointerManager.getInstance(element.getProject()).createSmartPsiElementPointer(element);
        myName = name;
    }

    @Nls(capitalization = Nls.Capitalization.Sentence)
    @NotNull
    @Override
    public String getName() {
        return StringUtil.isEmpty(myName) ?
            getFamilyName() : GraphQLBundle.message("graphql.inspection.go.to.related.definition.name", myName);
    }

    @Nls(capitalization = Nls.Capitalization.Sentence)
    @NotNull
    @Override
    public String getFamilyName() {
        return GraphQLBundle.message("graphql.inspection.go.to.related.definition.family.name");
    }

    @Override
    public void applyFix(@NotNull Project project, PsiFile file, @Nullable Editor editor) {
        PsiElement element = myElement.getElement();
        if (element instanceof Navigatable) ((Navigatable) element).navigate(true);
    }
}


text:
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;

namespace droid.Runtime.Shaders.Experimental.Skybox_Shaders.Editor {
  public class RgbmCubedSkyboxInspector : MaterialEditor {
    public override void OnInspectorGUI() {
      base.OnInspectorGUI();

      if (this.isVisible) {
        var material = this.target as Material;

        var use_linear = false;
        foreach (var keyword in material.shaderKeywords) {
          if (keyword == "USE_LINEAR") {
            use_linear = true;
            break;
          }
        }

        EditorGUI.BeginChangeCheck();

        use_linear = EditorGUILayout.Toggle("Linear Space Lighting", use_linear);

        if (EditorGUI.EndChangeCheck()) {
          if (use_linear) {
            material.EnableKeyword("USE_LINEAR");
            material.DisableKeyword("USE_GAMMA");
          } else {
            material.DisableKeyword("USE_LINEAR");
            material.EnableKeyword("USE_GAMMA");
          }

          EditorUtility.SetDirty(this.target);
        }
      }
    }
  }
}
#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>com.centurylink.cloud.sdk.server.services.dsl.domain.statistics.billing.filter (sdk 1.2.2 API)</title>
<meta name="date" content="2016-01-06">
<link rel="stylesheet" type="text/css" href="../../../../../../../../../../../stylesheet.css" title="Style">

com.centurylink.cloud.sdk.server.services.dsl.domain.statistics.billing.filter

Interfaces

BillingStatsFilter

Classes

BillingStatsDataCenterFilter

BillingStatsGroupFilter

BillingStatsServerFilter


text:
//============================================================================
// Name        : BlackberryAudioGW.cpp
// Description : Blackberry audio gateway
//============================================================================
#if defined(__QNXNTO__)

#include "BlackberryAudioGW.h"
#include "../../Logger.h"
#include <gulliver.h>
#include <pthread.h>

#include <string.h>
#include <stdio.h>

#define AUDIO_BUFFER_SIZE 1024

namespace BatteryTech {

static BlackberryAudioGW *gw;

static void* gwThreadLoop(void *param) {
	while (gw->run) {
		if (!gw->paused) {
			gw->fillBuffer();
		} else {
			// sleep 100ms while waiting to start up again
			usleep(100000);
		}
	}
	return NULL;
}

BlackberryAudioGW::BlackberryAudioGW(AudioManager *audioManager) {
	this->audioManager = audioManager;
	// we should only have one instance of an audio gateway
	gw = this;
	audioBuf = new unsigned char[AUDIO_BUFFER_SIZE];
	paused = false;
	thread = 0;
}

BlackberryAudioGW::~BlackberryAudioGW() {
	gw = NULL;
	delete[] audioBuf;
	audioBuf = NULL;
}

void BlackberryAudioGW::fillBuffer() {
	audioManager->fillBuffer(audioBuf, AUDIO_BUFFER_SIZE);
	int written = snd_pcm_plugin_write(pcm_handle, audioBuf, AUDIO_BUFFER_SIZE);
	if (written < 0) {
		logmsg("Playback error");
		run = false;
	} else if (written < AUDIO_BUFFER_SIZE) {
		snd_pcm_channel_status_t status;
		memset(&status, 0, sizeof(status));
		status.channel = SND_PCM_CHANNEL_PLAYBACK;
		if (snd_pcm_plugin_status(pcm_handle, &status) < 0) {
			logmsg("Playback channel status error (underrun)");
			run = false;
		}
		if (status.status == SND_PCM_STATUS_READY || status.status == SND_PCM_STATUS_UNDERRUN) {
			if (snd_pcm_plugin_prepare(pcm_handle, SND_PCM_CHANNEL_PLAYBACK) < 0) {
				logmsg("Playback channel prepare error (underrun)");
				run = false;
			}
		}
	}
}

void BlackberryAudioGW::init() {
	logmsg("Initializing Blackberry Audio");
	int rtn;
	int card = -1;
	int dev = 0;
	int sample_rate;
	int sample_channels;
	int sample_bits;
	snd_pcm_channel_info_t pi;
	snd_mixer_group_t group;
	snd_pcm_channel_params_t pp;
	snd_pcm_channel_setup_t setup;
	if ((rtn = snd_pcm_open_preferred(&pcm_handle, &card, &dev, SND_PCM_OPEN_PLAYBACK)) < 0) {
		logmsg("Error opening PCM device");
		return;
	}
	sample_rate = ENDIAN_LE32(44100);
	sample_channels = ENDIAN_LE16(2);
	sample_bits = ENDIAN_LE16(16);
	//audioManager->fillBuffer();
	memset(&pi, 0, sizeof(pi));
	pi.channel = SND_PCM_CHANNEL_PLAYBACK;
	if ((rtn = snd_pcm_plugin_info(pcm_handle, &pi)) < 0) {
		logmsg("snd_pcm_plugin_info failed");
		return;
	}

	memset(&pp, 0, sizeof(pp));
	pp.mode = SND_PCM_MODE_BLOCK;
	pp.channel = SND_PCM_CHANNEL_PLAYBACK;
	pp.start_mode = SND_PCM_START_FULL;
	pp.stop_mode = SND_PCM_STOP_STOP;
	pp.buf.block.frag_size = pi.max_fragment_size;
	pp.buf.block.frags_max = 1; // What should this be?
	pp.buf.block.frags_min = 1;

	pp.format.interleave = 1;
	pp.format.rate = sample_rate;
	pp.format.voices = sample_channels;
	pp.format.format = SND_PCM_SFMT_S16_LE;

	strcpy(pp.sw_mixer_subchn_name, "Wave playback channel");
	if ((rtn = snd_pcm_plugin_params(pcm_handle, &pp)) < 0) {
		logmsg("snd_pcm_plugin_params failed");
		return;
	}
	if ((rtn = snd_pcm_plugin_prepare(pcm_handle, SND_PCM_CHANNEL_PLAYBACK)) < 0) {
		logmsg("snd_pcm_plugin_prepare failed");
		return;
	}

	memset(&setup, 0, sizeof(setup));
	memset(&group, 0, sizeof(group));
	setup.channel = SND_PCM_CHANNEL_PLAYBACK;
	setup.mixer_gid = &group.gid;
	if ((rtn = snd_pcm_plugin_setup(pcm_handle, &setup)) < 0) {
		logmsg("snd_pcm_plugin_setup failed");
		return;
	}
	if (group.gid.name[0] == 0) {
		logmsg("Mixer Pcm Group Not Set");
		return;
	}
	if ((rtn = snd_mixer_open(&mixer_handle, card, setup.mixer_device)) < 0) {
		logmsg("snd_mixer_open failed");
		return;
	}
	logmsg("BB PCM Channel Ready");
	run = true;
	int ret = pthread_create(&thread, NULL, gwThreadLoop, (void*) NULL);
	if (ret) {
		char buf[255];
		sprintf(buf, "Error creating audio thread - %d", ret);
		logmsg(buf);
	}
}

void BlackberryAudioGW::release() {
	logmsg("Releasing Blackberry Audio");
	run = false;
	void *status;
	pthread_join(thread, &status);
	thread = NULL;
	snd_mixer_close(mixer_handle);
	snd_pcm_close(pcm_handle);
}

} /* namespace BatteryTech */
#endif


text:
import os, sys, re

# Find all "foo.exe" files on the PATH.
def find_all_on_path(filename, extras = None):
    entries = os.environ["PATH"].split(os.pathsep)
    ret = []
    for p in entries:
        fname = os.path.abspath(os.path.join(p, filename))
        if os.path.isfile(fname) and fname not in ret:
            ret.append(fname)
    if extras:
        for p in extras:
            fname = os.path.abspath(os.path.join(p, filename))
            if os.path.isfile(fname) and fname not in ret:
                ret.append(fname)
    return ret

# Find a suitable Perl installation for OpenSSL.
# cygwin perl does *not* work.  ActivePerl does.
# Being a Perl dummy, the simplest way I can check is if the "Win32" package
# is available.
def find_working_perl(perls):
    for perl in perls:
        fh = os.popen(perl + ' -e "use Win32;"')
        fh.read()
        rc = fh.close()
        if rc:
            continue
        return perl
    print "Can not find a suitable PERL:"
    if perls:
        print " the following perl interpreters were found:"
        for p in perls:
            print " ", p
        print " None of these versions appear suitable for building OpenSSL"
    else:
        print " NO perl interpreters were found on this machine at all!"
    print " Please install ActivePerl and ensure it appears on your path"
    print "The Python SSL module was not built"
    return None

# Locate the best SSL directory given a few roots to look into.
def find_best_ssl_dir(sources):
    candidates = []
    for s in sources:
        try:
            # note: do not abspath s; the build will fail if any
            # higher up directory name has spaces in it.
            fnames = os.listdir(s)
        except os.error:
            fnames = []
        for fname in fnames:
            fqn = os.path.join(s, fname)
            if os.path.isdir(fqn) and fname.startswith("openssl-"):
                candidates.append(fqn)
    # Now we have all the candidates, locate the best.
    best_parts = []
    best_name = None
    for c in candidates:
        parts = re.split("[.-]", os.path.basename(c))[1:]
        # eg - openssl-0.9.7-beta1 - ignore all "beta" or any other qualifiers
        if len(parts) >= 4:
            continue
        if parts > best_parts:
            best_parts = parts
            best_name = c
    if best_name is not None:
        print "Found an SSL directory at '%s'" % (best_name,)
    else:
        print "Could not find an SSL directory in '%s'" % (sources,)
    sys.stdout.flush()
    return best_name

def run_configure(configure, do_script):
    os.system("perl Configure "+configure)
    os.system(do_script)

def main():
    build_all = "-a" in sys.argv
    if sys.argv[1] == "Release":
        arch = "x86"
        debug = False
        configure = "VC-WIN32"
        do_script = "ms\\do_masm"
        makefile = "ms\\nt.mak"
    elif sys.argv[1] == "Debug":
        arch = "x86"
        debug = True
        configure = "VC-WIN32"
        do_script = "ms\\do_masm"
        makefile="ms\\d32.mak"
    elif sys.argv[1] == "ReleaseItanium":
        arch = "ia64"
        debug = False
        configure = "VC-WIN64I"
        do_script = "ms\\do_win64i"
        makefile = "ms\\nt.mak"
        os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM"
    elif sys.argv[1] == "ReleaseAMD64":
        arch="amd64"
        debug=False
        configure = "VC-WIN64A"
        do_script = "ms\\do_win64a"
        makefile = "ms\\nt.mak"
        os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON"
    make_flags = ""
    if build_all:
        make_flags = "-a"
    # perl should be on the path, but we also look in "\perl" and "c:\\perl"
    # as "well known" locations
    perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"])
    perl = find_working_perl(perls)
    if perl is None:
        sys.exit(1)

    print "Found a working perl at '%s'" % (perl,)
    sys.stdout.flush()
    # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live.
    ssl_dir = find_best_ssl_dir(("..\\..",))
    if ssl_dir is None:
        sys.exit(1)

    old_cd = os.getcwd()
    try:
        os.chdir(ssl_dir)
        # If the ssl makefiles do not exist, we invoke Perl to generate them.
        # Due to a bug in this script, the makefile sometimes ended up empty
        # Force a regeneration if it is.
        if not os.path.isfile(makefile) or os.path.getsize(makefile)==0:
            print "Creating the makefiles..."
            sys.stdout.flush()
            # Put our working Perl at the front of our path
            os.environ["PATH"] = os.path.dirname(perl) + \
                                          os.pathsep + \
                                          os.environ["PATH"]
            run_configure(configure, do_script)
            if arch=="x86" and debug:
                # the do_masm script in openssl doesn't generate a debug
                # build makefile so we generate it here:
                os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile)

        # Now run make.
        makeCommand = "nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile)
        print "Executing ssl makefiles:", makeCommand
        sys.stdout.flush()
        rc = os.system(makeCommand)
        if rc:
            print "Executing "+makefile+" failed"
            print rc
            sys.exit(rc)
    finally:
        os.chdir(old_cd)
    # And finally, we can build the _ssl module itself for Python.
    defs = "SSL_DIR=\"%s\"" % (ssl_dir,)
    if debug:
        defs = defs + " " + "DEBUG=1"
    if arch in ('amd64', 'ia64'):
        defs = defs + " EXTRA_CFLAGS=/GS-"
    makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags
    print "Executing:", makeCommand
    sys.stdout.flush()
    rc = os.system(makeCommand)
    sys.exit(rc)

if __name__=='__main__':
    main()


text:
package unversioned

import (
	"net/url"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/unversioned"
)

// DiscoveryInterface holds the methods that discover server-supported API groups,
// versions and resources.
type DiscoveryInterface interface {
	ServerGroupsInterface
	ServerResourcesInterface
}

// ServerGroupsInterface has methods for obtaining supported groups on the API server
type ServerGroupsInterface interface {
	// ServerGroups returns the supported groups, with information like supported versions and the
	// preferred version.
	ServerGroups() (*unversioned.APIGroupList, error)
}

// ServerResourcesInterface has methods for obtaining supported resources on the API server
type ServerResourcesInterface interface {
	// ServerResourcesForGroupVersion returns the supported resources for a group and version.
	ServerResourcesForGroupVersion(groupVersion string) (*unversioned.APIResourceList, error)
	// ServerResources returns the supported resources for all groups and versions.
	ServerResources() (map[string]*unversioned.APIResourceList, error)
}

// DiscoveryClient implements the functions that dicovery server-supported API groups,
// versions and resources.
type DiscoveryClient struct {
	*RESTClient
}

// Convert unversioned.APIVersions to unversioned.APIGroup. APIVersions is used by legacy v1, so
// group would be "".
func apiVersionsToAPIGroup(apiVersions *unversioned.APIVersions) (apiGroup unversioned.APIGroup) {
	groupVersions := []unversioned.GroupVersionForDiscovery{}
	for _, version := range apiVersions.Versions {
		groupVersion := unversioned.GroupVersionForDiscovery{
			GroupVersion: version,
			Version:      version,
		}
		groupVersions = append(groupVersions, groupVersion)
	}
	apiGroup.Versions = groupVersions
	// There should be only one groupVersion returned at /api
	apiGroup.PreferredVersion = groupVersions[0]
	return
}

// ServerGroups returns the supported groups, with information like supported versions and the
// preferred version.
func (d *DiscoveryClient) ServerGroups() (apiGroupList *unversioned.APIGroupList, err error) {
	// Get the groupVersions exposed at /api
	v := &unversioned.APIVersions{}
	err = d.Get().AbsPath("/api").Do().Into(v)
	apiGroup := unversioned.APIGroup{}
	if err == nil {
		apiGroup = apiVersionsToAPIGroup(v)
	}
	if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
		return nil, err
	}

	// Get the groupVersions exposed at /apis
	apiGroupList = &unversioned.APIGroupList{}
	err = d.Get().AbsPath("/apis").Do().Into(apiGroupList)
	if err != nil && !errors.IsNotFound(err) && !errors.IsForbidden(err) {
		return nil, err
	}
	// to be compatible with a v1.0 server, if it's a 403 or 404, ignore and return whatever we got from /api
	if err != nil && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
		apiGroupList = &unversioned.APIGroupList{}
	}

	// append the group retrieved from /api to the list
	apiGroupList.Groups = append(apiGroupList.Groups, apiGroup)
	return apiGroupList, nil
}

// ServerResourcesForGroupVersion returns the supported resources for a group and version.
func (d *DiscoveryClient) ServerResourcesForGroupVersion(groupVersion string) (resources *unversioned.APIResourceList, err error) {
	url := url.URL{}
	if groupVersion == "v1" {
		url.Path = "/api/" + groupVersion
	} else {
		url.Path = "/apis/" + groupVersion
	}
	resources = &unversioned.APIResourceList{}
	err = d.Get().AbsPath(url.String()).Do().Into(resources)
	if err != nil {
		// ignore 403 or 404 error to be compatible with an v1.0 server.
		if groupVersion == "v1" && (errors.IsNotFound(err) || errors.IsForbidden(err)) {
			return resources, nil
		} else {
			return nil, err
		}
	}
	return resources, nil
}

// ServerResources returns the supported resources for all groups and versions.
func (d *DiscoveryClient) ServerResources() (map[string]*unversioned.APIResourceList, error) {
	apiGroups, err := d.ServerGroups()
	if err != nil {
		return nil, err
	}
	groupVersions := ExtractGroupVersions(apiGroups)
	result := map[string]*unversioned.APIResourceList{}
	for _, groupVersion := range groupVersions {
		resources, err := d.ServerResourcesForGroupVersion(groupVersion)
		if err != nil {
			return nil, err
		}
		result[groupVersion] = resources
	}
	return result, nil
}

func setDiscoveryDefaults(config *Config) error {
	config.Prefix = ""
	config.Version = ""
	// Discovery client deals with unversioned objects, so we use api.Codec.
	config.Codec = api.Codec
	return nil
}

// NewDiscoveryClient creates a new DiscoveryClient for the given config. This client
// can be used to discover supported resources in the API server.
func NewDiscoveryClient(c *Config) (*DiscoveryClient, error) {
	config := *c
	if err := setDiscoveryDefaults(&config); err != nil {
		return nil, err
	}
	client, err := UnversionedRESTClientFor(&config)
	return &DiscoveryClient{client}, err
}