text
stringlengths 2
1.04M
| meta
dict |
---|---|
/* Author: Benjamin Scholz */
#pragma once
#include <fcl/config.h>
#define FCL_VERSION_CHECK(major, minor, patch) ((major << 16) | (minor << 8) | (patch))
#define MOVEIT_FCL_VERSION FCL_VERSION_CHECK(FCL_MAJOR_VERSION, FCL_MINOR_VERSION, FCL_PATCH_VERSION)
#if (MOVEIT_FCL_VERSION < FCL_VERSION_CHECK(0, 6, 0))
namespace fcl
{
class CollisionGeometry;
using CollisionGeometryd = fcl::CollisionGeometry;
class CollisionObject;
using CollisionObjectd = fcl::CollisionObject;
class BroadPhaseCollisionManager;
using BroadPhaseCollisionManagerd = fcl::BroadPhaseCollisionManager;
class Transform3f;
using Transform3d = fcl::Transform3f;
class Contact;
using Contactd = fcl::Contact;
class CostSource;
using CostSourced = fcl::CostSource;
class CollisionRequest;
using CollisionRequestd = fcl::CollisionRequest;
class CollisionResult;
using CollisionResultd = fcl::CollisionResult;
class DistanceRequest;
using DistanceRequestd = fcl::DistanceRequest;
class DistanceResult;
using DistanceResultd = fcl::DistanceResult;
class Plane;
using Planed = fcl::Plane;
class Sphere;
using Sphered = fcl::Sphere;
class Box;
using Boxd = fcl::Box;
class Cylinder;
using Cylinderd = fcl::Cylinder;
class Cone;
using Coned = fcl::Cone;
namespace details
{
struct sse_meta_f4;
template <typename T>
struct Vec3Data;
} // namespace details
template <typename T>
class Vec3fX;
#if FCL_HAVE_SSE
using Vector3d = Vec3fX<details::sse_meta_f4>;
#else
using Vector3d = Vec3fX<details::Vec3Data<double> >;
#endif
class OcTree;
using OcTreed = fcl::OcTree;
class OBBRSS;
using OBBRSSd = fcl::OBBRSS;
class DynamicAABBTreeCollisionManager;
using DynamicAABBTreeCollisionManagerd = fcl::DynamicAABBTreeCollisionManager;
} // namespace fcl
#endif
| {
"content_hash": "95f6905c6f68dbeec76c5672683f225b",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 101,
"avg_line_length": 25.746268656716417,
"alnum_prop": 0.7802898550724637,
"repo_name": "ros-planning/moveit",
"id": "6d5c774a87e0b65299810a938a4112a35dcec278",
"size": "3522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "moveit_core/collision_detection_fcl/include/moveit/collision_detection_fcl/fcl_compat.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2268"
},
{
"name": "C++",
"bytes": "7614097"
},
{
"name": "CMake",
"bytes": "157245"
},
{
"name": "Dockerfile",
"bytes": "5483"
},
{
"name": "GDB",
"bytes": "376"
},
{
"name": "HTML",
"bytes": "1171"
},
{
"name": "Makefile",
"bytes": "252"
},
{
"name": "NASL",
"bytes": "2404"
},
{
"name": "Python",
"bytes": "276327"
},
{
"name": "Shell",
"bytes": "15782"
},
{
"name": "TeX",
"bytes": "7222"
}
],
"symlink_target": ""
} |
package joptsimple;
import static java.util.Collections.*;
import org.junit.Before;
import org.junit.Test;
import static joptsimple.ExceptionMatchers.*;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:[email protected]">Paul Holser</a>
*/
public class WExtensionNoArgumentTest extends AbstractOptionParserFixture {
@Before
public final void initializeParser() {
parser.accepts( "silent" );
parser.recognizeAlternativeLongOptions( true );
}
@Test
public void turnOffWExtension() {
parser.recognizeAlternativeLongOptions( false );
thrown.expect( UnrecognizedOptionException.class );
thrown.expect( withOption( "W" ) );
parser.parse( "-W", "silent" );
}
@Test
public void wExtensionWithLongOptionWithoutAnArgument() {
OptionSet options = parser.parse( "-W", "silent" );
assertOptionNotDetected( options, "W" );
assertOptionDetected( options, "silent" );
assertEquals( emptyList(), options.valuesOf( "silent" ) );
assertEquals( emptyList(), options.nonOptionArguments() );
}
}
| {
"content_hash": "f436ea33430c54ba539d19ff0534d768",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 75,
"avg_line_length": 26.952380952380953,
"alnum_prop": 0.6749116607773852,
"repo_name": "pholser/jopt-simple",
"id": "31d18ee7d6e5463949c8145478203745046640ea",
"size": "2240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/joptsimple/WExtensionNoArgumentTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "804"
},
{
"name": "Java",
"bytes": "642662"
},
{
"name": "JavaScript",
"bytes": "56900"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="html/html; charset=utf-8" />
<title>EC2SpotPlacementUnmarshaller Class Reference</title>
<meta id="xcode-display" name="xcode-display" content="render"/>
<meta name="viewport" content="width=550" />
<link rel="stylesheet" type="text/css" href="../css/styles.css" media="all" />
<link rel="stylesheet" type="text/css" media="print" href="../css/stylesPrint.css" />
<meta name="generator" content="appledoc 2.0.5 (build 789)" />
</head>
<body>
<header id="top_header">
<div id="library" class="hideInXcode">
<h1><a id="libraryTitle" href="../index.html">AWS SDK for iOS v1.4.3 </a></h1>
<a id="developerHome" href="../index.html">Amazon Web Services, Inc.</a>
</div>
<div id="title" role="banner">
<h1 class="hideInXcode">EC2SpotPlacementUnmarshaller Class Reference</h1>
</div>
<ul id="headerButtons" role="toolbar">
<li id="toc_button">
<button aria-label="Show Table of Contents" role="checkbox" class="open" id="table_of_contents"><span class="disclosure"></span>Table of Contents</button>
</li>
<li id="jumpto_button" role="navigation">
<select id="jumpTo">
<option value="top">Jump To…</option>
<option value="overview">Overview</option>
</select>
</li>
</ul>
</header>
<nav id="tocContainer" class="isShowingTOC">
<ul id="toc" role="tree">
<li role="treeitem"><span class="nodisclosure"></span><span class="sectionName"><a href="#overview">Overview</a></span></li>
</ul>
</nav>
<article>
<div id="contents" class="isShowingTOC" role="main">
<a title="EC2SpotPlacementUnmarshaller Class Reference" name="top"></a>
<div class="main-navigation navigation-top">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="header">
<div class="section-header">
<h1 class="title title-header">EC2SpotPlacementUnmarshaller Class Reference</h1>
</div>
</div>
<div id="container">
<div class="section section-specification"><table cellspacing="0"><tbody>
<tr>
<td class="specification-title">Inherits from</td>
<td class="specification-value">EC2ResponseUnmarshaller : AmazonServiceResponseUnmarshaller : <a href="../Classes/AmazonUnmarshallerXMLParserDelegate.html">AmazonUnmarshallerXMLParserDelegate</a> : NSObject</td>
</tr><tr>
<td class="specification-title">Declared in</td>
<td class="specification-value">EC2SpotPlacementUnmarshaller.h</td>
</tr>
</tbody></table></div>
<div class="section section-overview">
<a title="Overview" name="overview"></a>
<h2 class="subtitle subtitle-overview">Overview</h2>
<p>Spot Placement Unmarshaller</p>
</div>
</div>
<div class="main-navigation navigation-bottom">
<ul>
<li><a href="../index.html">Index</a></li>
<li><a href="../hierarchy.html">Hierarchy</a></li>
</ul>
</div>
<div id="footer"><script src="/urchin.js" type="text/javascript"></script><script type="text/javascript">urchinTracker();</script>
<hr />
<div class="footer-copyright">
<p><span class="copyright">© 2012 Amazon Web Services, Inc.. All rights reserved. (Last updated: 2012-10-05)</span><br />
<span class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.0.5 (build 789)</a>.</span></p>
</div>
</div>
</div>
</article>
<script type="text/javascript">
function jumpToChange()
{
window.location.hash = this.options[this.selectedIndex].value;
}
function toggleTOC()
{
var contents = document.getElementById('contents');
var tocContainer = document.getElementById('tocContainer');
if (this.getAttribute('class') == 'open')
{
this.setAttribute('class', '');
contents.setAttribute('class', '');
tocContainer.setAttribute('class', '');
window.name = "hideTOC";
}
else
{
this.setAttribute('class', 'open');
contents.setAttribute('class', 'isShowingTOC');
tocContainer.setAttribute('class', 'isShowingTOC');
window.name = "";
}
return false;
}
function toggleTOCEntryChildren(e)
{
e.stopPropagation();
var currentClass = this.getAttribute('class');
if (currentClass == 'children') {
this.setAttribute('class', 'children open');
}
else if (currentClass == 'children open') {
this.setAttribute('class', 'children');
}
return false;
}
function tocEntryClick(e)
{
e.stopPropagation();
return true;
}
function init()
{
var selectElement = document.getElementById('jumpTo');
selectElement.addEventListener('change', jumpToChange, false);
var tocButton = document.getElementById('table_of_contents');
tocButton.addEventListener('click', toggleTOC, false);
var taskTreeItem = document.getElementById('task_treeitem');
if (taskTreeItem.getElementsByTagName('li').length > 0)
{
taskTreeItem.setAttribute('class', 'children');
taskTreeItem.firstChild.setAttribute('class', 'disclosure');
}
var tocList = document.getElementById('toc');
var tocEntries = tocList.getElementsByTagName('li');
for (var i = 0; i < tocEntries.length; i++) {
tocEntries[i].addEventListener('click', toggleTOCEntryChildren, false);
}
var tocLinks = tocList.getElementsByTagName('a');
for (var i = 0; i < tocLinks.length; i++) {
tocLinks[i].addEventListener('click', tocEntryClick, false);
}
if (window.name == "hideTOC") {
toggleTOC.call(tocButton);
}
}
window.onload = init;
// If showing in Xcode, hide the TOC and Header
if (navigator.userAgent.match(/xcode/i)) {
document.getElementById("contents").className = "hideInXcode"
document.getElementById("tocContainer").className = "hideInXcode"
document.getElementById("top_header").className = "hideInXcode"
}
</script>
</body>
</html>
| {
"content_hash": "2a7a6ec2a4309bee32ad495a59200a5a",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 212,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.6284337349397591,
"repo_name": "abovelabs/aws-ios-sdk",
"id": "2a79b7d30689300222835eed88cfbb2bffc4f72b",
"size": "6225",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Documentation/html/Classes/EC2SpotPlacementUnmarshaller.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
<route id="genemu_upload" pattern="/genemu_upload">
<default key="_controller">GenemuFormBundle:Upload:upload</default>
</route>
</routes> | {
"content_hash": "fb5f4601fd5fc3332f9822cab0ae7593",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 109,
"avg_line_length": 38.63636363636363,
"alnum_prop": 0.6823529411764706,
"repo_name": "lrt/lrt",
"id": "1cffe2deff81244635e8580f13ecc2534c3f35d0",
"size": "425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/genemu/form-bundle/Genemu/Bundle/FormBundle/Resources/config/routing/upload.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "143710"
},
{
"name": "PHP",
"bytes": "256054"
},
{
"name": "Perl",
"bytes": "1091"
},
{
"name": "Shell",
"bytes": "2275"
}
],
"symlink_target": ""
} |
+++
title = "Getting started with Deep Generative Models - Part I"
description = "Understanding the math behind the recent wave of ML research"
date = 2019-01-31
categories = [
"machine learning",
"blog"
]
tags = [
"theory",
"deep learning"
]
[distill]
[[distill.authors]]
author = "Abhay Gupta"
authorURL = "http://gupta-abhay.github.io"
[[distill.authors.affiliations]]
name = "The Robotics Institute, CMU"
url = "https://ri.cmu.edu"
+++
In recent years, there has been a resurgence of interest in deep generative models. Emerging approaches such as [Generative Adversarial Networks](https://arxiv.org/abs/1406.2661) (GANs), [Variational Autoencoders](https://arxiv.org/abs/1312.6114) (VAEs), auto-regressive networks (e.g. [pixelRNNs](https://arxiv.org/abs/1601.06759), [RNN language models](www.fit.vutbr.cz/research/groups/speech/publi/2010/mikolov_interspeech2010_IS100722.pdf)), and many of their variants and extensions have led to impressive results in a myriad of applications. Researchers are making great progress in generating realistic high-resolution images, manipulating and changing text, learning interpretable data representations, automatically augmenting data for training of other models, etc.
## A general formulation
Consider a set of data points {{<math>}} \{x_1, x_2, ..., x_n\} {{</math>}} whose true distribution {{<math>}}p(x){{</math>}} we want to model. In the example below, the blue region shows the part of the image space that, with a high probability contains real images, and black dots indicate our data points. Now, our model also describes a distribution {{<math>}}\hat{p}(x){{</math>}} that is defined by taking points from a unit Gaussian distribution and mapping them through a neural network (our generative model). Our network is a function with parameters {{<math>}}\theta{{</math>}}, and tweaking these parameters will tweak the generated distribution of images. Our goal then is to find parameters {{<math>}}\theta{{</math>}} that produce a distribution that closely matches the true data distribution. Therefore, you can imagine the green distribution starting out randomly and then the training process iteratively refines the parameters to better match the blue distribution.
{{<figure class="figure" src="/img/gen-models-diag-2.png" title="Example of a Deep Generative Model">}}
## Approaches to Deep Generative Models
Most generative models have this basic setup but differ in details. Here are three popular examples of generative model approaches to give a sense of their variation:
1. [Variational Autoencoders](https://arxiv.org/abs/1312.6114) (VAEs) allow us to formalize the problem in the framework of probabilistic graphical models where we are maximizing a lower bound on the log likelihood of the data.
2. [Generative Adversarial Networks](https://arxiv.org/abs/1406.2661) (GANs), pose the training process as a [minimax](https://en.wikipedia.org/wiki/Minimax) game between two separate networks: a generator network and a second discriminative network that tries to classify samples as either coming from the true distribution {{<math>}}p(x){{</math>}} or the model distribution {{<math>}}\hat{p}(x){{</math>}}. This essentially models the unsupervised problem to a supervised one.
3. Flow-based generative models are essentially constructed by a sequence of invertible transformations. Unlike the two models above, these model explicitly learn the data distribution {{<math>}}p(x){{</math>}} and therefore the loss function is simply the negative log-likelihood.
{{<figure class="figure" src="/img/three-generative-models.png" title="Comparison of Three Types of Deep Generative Models">}}
All of the above approaches have their own set of pros and cons. For example, GANs generate high-quality and sharp images, but their training process is very difficult. VAEs allow for efficient Bayesian inference using sophisticated probabilistic graphical models but generate blurry images. Flow-based models have a simple and stable training process and currently give the best log-likelihoods. However, they are very inefficient during sampling and do not easily provide low-dimensional representations for images.
## Some Mathematical Background
The concepts presented here form the basis for the upcoming discussions. Primarily, we discuss how to compare probability distributions and an introduction to some fundamental concepts in Linear Algebra and the [Change of Variable Theorem](http://mathworld.wolfram.com/ChangeofVariablesTheorem.html).
### Kullback-Leibler Divergence
[Kullback-Leibler (KL) divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) measures how one probability distribution {{<math>}}p{{</math>}} diverges from a second probability distribution {{<math>}}q{{</math>}}.
{{<math block="true">}}
D_{KL}(p \| q) = \int_x p(x) \log \frac{p(x)}{q(x)} dx
{{</math>}}
{{<math>}}D_{KL}(p \| q){{</math>}} achieves its minimum value of zero when {{<math>}}p(x) == q(x){{</math>}} everywhere. One of the fundamental problems with using KL divergence is that it is asymmetric. When {{<math>}}p(x){{</math>}} is close to zero, but {{<math>}}q(x){{</math>}} is significantly non-zero, the effect of {{<math>}}q{{</math>}} is disregarded. It can cause buggy results when our intention might be to measure the similarity between the two distributions.
### Jensen-Shannon Divergence
[Jensen-Shannon Divergence](https://en.wikipedia.org/wiki/Jensen%E2%80%93Shannon_divergence) is another measure of similarity between two probability distributions, bounded by [0,1]. JS Divergence is symmetric and more smooth.
{{<math block="true">}}
D_{JS}(p \| q) = \frac{1}{2} D_{KL}(p \| \frac{p+q}{2}) + \frac{1}{2} D_{KL}(q \| \frac{p+q}{2})
{{</math>}}
{{<figure class="figure" src="/img/KL-JS-divergence.png" title="KL and JS Divergence for two probability distributions">}}
### Jacobian Matrix
Given a function which maps an {{<math>}}n{{</math>}}-dimensional input vector {{<math>}}\bf{x}{{</math>}} to a {{<math>}}m{{</math>}}-dimensional output vector, {{<math>}}\bf{f}: \mathbb{R}^n \rightarrow \mathbb{R}^m{{</math>}}, the matrix of all first-order partial derivatives of this function is called the [Jacobian matrix](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant), {{<math>}}\bf{J}{{</math>}}, where one entry on the {{<math>}}i{{</math>}}-th row and the {{<math>}}j{{</math>}}-th column is {{<math>}}J_{ij} = \frac{df_i}{dx_j}{{</math>}}. Thus, the entire Jacobian matrix can be written as
{{<math block="true">}}
\mathbf{J}=\left[ \begin{array}{ccc}{\frac{\partial f_{1}}{\partial x_{1}}} & {\cdots} & {\frac{\partial f_{1}}{\partial x_{n}}} \\ {\vdots} & {\ddots} & {\vdots} \\ {\frac{\partial f_{m}}{\partial x_{1}}} & {\cdots} & {\frac{\partial f_{m}}{\partial x_{n}}}\end{array}\right]
{{</math>}}
### Change of Variable Theorem
Let’s review the change of variable theorem specifically in the context of probability density estimation, starting with a single variable case.
Given a random variable {{<math>}}z{{</math>}} and its known probability density function {{<math>}}z \sim \pi(z){{</math>}}, we would like to construct a new random variable using a 1-1 mapping function {{<math>}}x=f(z){{</math>}}. The function {{<math>}}f{{</math>}} is invertible, so {{<math>}}z = f^{-1}(x){{</math>}}. Now the question is ``how to infer the unknown probability density function of the new variable``, {{<math>}}p(x){{</math>}}?
{{<math block="true">}}
\int p(x) d x=\int \pi(z) d z=1
{{</math>}}
{{<math block="true">}}
p(x)=\pi(z)\left|\frac{d z}{d x}\right|=\pi\left(f^{-1}(x)\right)\left|\frac{d f^{-1}}{d x}\right|=\pi\left(f^{-1}(x)\right)\left|\left(f^{-1}\right)^{\prime}(x)\right|
{{</math>}}
By definition, the integral {{<math>}}\int \pi(z)dz{{</math>}} is the sum of an infinite number of rectangles of infinitesimal width {{<math>}}\Delta z{{</math>}}. The height of such a rectangle at position {{<math>}}z{{</math>}} is the value of the density function {{<math>}}\pi(z){{</math>}}. When we substitute the variable, {{<math>}}z = f^{-1}(x){{</math>}} yeilds {{<math>}}\frac{\Delta z}{\Delta x} = (f^{-1}(x))'{{</math>}} and {{<math>}}\Delta z = (f^{-1}(x))'\Delta x{{</math>}}. Here {{<math>}}\vert(f^{-1}(x))'\vert{{</math>}} indicates the ratio between the area of the rectangles defined in two different coordinate of variables {{<math>}}z{{</math>}} and {{<math>}}x{{</math>}} respectively.
___
In the next set of posts, we will cover the actual mathematical intuitions behind each of the different types of models. See you then!
___
**References**
1. Goodfellow, Ian, et al. "[Generative Adversarial Nets](https://arxiv.org/abs/1406.2661)" NIPS, 2014.
2. Diederik P. Kingma, Max Welling. "[Auto-encoding variational bayes](https://arxiv.org/abs/1312.6114)" ICLR 2014.
3. Oord, Aaron, et al. "[Pixel Recurrent Neural Networks](https://arxiv.org/abs/1601.06759)". ICML 2016.
4. [Quora post](https://www.quora.com/Why-isnt-the-Jensen-Shannon-divergence-used-more-often-than-the-Kullback-Leibler-since-JS-is-symmetric-thus-possibly-a-better-indicator-of-distance) on JS (vs) KL Divergence
5. Danilo Jimenez Rezende, and Shakir Mohamed. "[Variational Inference with Normalizing Flows](https://arxiv.org/abs/1505.05770)". ICML 2015. | {
"content_hash": "58e04146bb71f679513fdb8740598847",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 985,
"avg_line_length": 94.16161616161617,
"alnum_prop": 0.7161553314739326,
"repo_name": "gupta-abhay/blog",
"id": "ae8290943a5a8633797521bb2ae86e4a2026a1bb",
"size": "9324",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/generative-models.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "131"
},
{
"name": "Shell",
"bytes": "419"
},
{
"name": "TeX",
"bytes": "1571"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>metacoq-template: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.1 / metacoq-template - 1.0~alpha2+8.11</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
metacoq-template
<small>
1.0~alpha2+8.11
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-10-17 18:19:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-17 18:19:02 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.06.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.06.1 Official 4.06.1 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://metacoq.github.io/metacoq"
dev-repo: "git+https://github.com/MetaCoq/metacoq.git#coq-8.11"
bug-reports: "https://github.com/MetaCoq/metacoq/issues"
authors: ["Abhishek Anand <[email protected]>"
"Simon Boulier <[email protected]>"
"Cyril Cohen <[email protected]>"
"Yannick Forster <[email protected]>"
"Fabian Kunze <[email protected]>"
"Gregory Malecha <[email protected]>"
"Matthieu Sozeau <[email protected]>"
"Nicolas Tabareau <[email protected]>"
"Théo Winterhalter <[email protected]>"
]
license: "MIT"
build: [
["sh" "./configure.sh"]
[make "-j%{jobs}%" "template-coq"]
]
install: [
[make "-C" "template-coq" "install"]
]
depends: [
"ocaml" {>= "4.07.1" & < "4.10"}
"coq" {>= "8.11" & < "8.12~"}
"coq-equations" {>= "1.2.1"}
]
synopsis: "A quoting and unquoting library for Coq in Coq"
description: """
MetaCoq is a meta-programming framework for Coq.
Template Coq is a quoting library for Coq. It takes Coq terms and
constructs a representation of their syntax tree as a Coq inductive data
type. The representation is based on the kernel's term representation.
In addition to a complete reification and denotation of CIC terms,
Template Coq includes:
- Reification of the environment structures, for constant and inductive declarations.
- Denotation of terms and global declarations
- A monad for manipulating global declarations, calling the type
checker, and inserting them in the global environment, in the style of
MetaCoq/MTac.
"""
url {
src: "https://github.com/MetaCoq/metacoq/archive/v1.0-alpha2-8.11.tar.gz"
checksum: "sha256=8f1d2b42ad97d7c8660a57aabe53ddcc7b1645ced43386a1d2bef428b20d6b42"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-metacoq-template.1.0~alpha2+8.11 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1).
The following dependencies couldn't be met:
- coq-metacoq-template -> ocaml >= 4.07.1
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-metacoq-template.1.0~alpha2+8.11</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "cb3440b49f688b9dbb649a104a505521",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 159,
"avg_line_length": 43.03225806451613,
"alnum_prop": 0.564967516241879,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "393749158970604257bea9e3bd694bfe0fe2c116",
"size": "8030",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.06.1-2.0.5/released/8.8.1/metacoq-template/1.0~alpha2+8.11.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
const http = require('http');
const darkutil = require('./util');
function proxy(self, msg, commandReq, commandResp) {
var opts = {
hostname: msg.data.req.remote.host,
port: msg.data.req.remote.port,
path: msg.data.req.uri,
method: msg.data.req.method,
headers: {}
}
for(var name in msg.data.req.headers) {
var value = msg.data.req.headers[name];
if(name == 'content-length') {
value = darkutil.b64len(msg.data.req.body).toString();
}
opts.headers[name] = value;
}
var req = http.request(opts, (resp) => {
msg.data.resp = {
created: new Date().getTime(),
code: resp.statusCode,
reason: resp.statusMessage,
headers: resp.headers
};
resp.setEncoding('base64');
darkutil.loadBody(resp, commandResp, (body) => {
msg.data.resp.body = body;
darkutil.sendJson(commandResp, msg.data);
self.emit('proxyResponse', self, msg);
});
});
req.on('error', (err) => {
darkutil.sendError(commandResp, err);
});
if(msg.data.req.body) {
req.write(msg.data.req.body, 'base64');
}
req.end();
}
function sendResp(self, msg, commandReq, commandResp) {
if(msg.resp.headersSent || msg.resp.finished) {
darkutil.sendNotFound(commandResp);
return;
}
msg.resp.statusCode = msg.data.resp.code;
msg.resp.statusMessage = msg.data.resp.reason;
for(var name in msg.data.resp.headers) {
var value = msg.data.resp.headers[name];
if (name == 'content-length') {
value = darkutil.b64len(msg.data.resp.body).toString();
}
msg.resp.setHeader(name, value);
}
msg.resp.end(msg.data.resp.body, 'base64', () => {
self.msgs.remove(msg.data.id);
darkutil.sendJson(commandResp, 'OK');
self.emit('serverResponse', self, msg);
});
}
exports.proxy = proxy;
exports.sendResp = sendResp;
| {
"content_hash": "5d3cb222c7745fbcd5d330a780ee00e8",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 67,
"avg_line_length": 31.609375,
"alnum_prop": 0.5724172021749876,
"repo_name": "murer/darkproxy",
"id": "fef616aa01ecab46660861694647019d7f5165ea",
"size": "2023",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/server/proxy.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "428"
},
{
"name": "HTML",
"bytes": "8897"
},
{
"name": "JavaScript",
"bytes": "163922"
},
{
"name": "Shell",
"bytes": "50"
}
],
"symlink_target": ""
} |
require 'test_helper'
class DownloadTest < ActionDispatch::IntegrationTest
context "The download controller" do
should "display its index page correctly" do
get "/abdesign/download"
assert_select "div#root", "I'm root"
end
end
end
| {
"content_hash": "93f4a2f06429465de37ca81c0299348a",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 52,
"avg_line_length": 25.6,
"alnum_prop": 0.7109375,
"repo_name": "arbesfeld/gem_abdesign",
"id": "0b41ac066dcb7f71aa395c7c0ae0f65314ad65be",
"size": "256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/download_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1092"
},
{
"name": "JavaScript",
"bytes": "1198"
},
{
"name": "Ruby",
"bytes": "14561"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
app:showDividers="middle|end"
app:divider="@drawable/about_buttons_divider">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/primary"
android:orientation="vertical"
android:gravity="center"
android:padding="30dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/box"/>
<ImageView
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:src="@drawable/logo"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:text="@string/app_name"
android:textColor="@android:color/white"
android:textSize="16sp"/>
</LinearLayout>
<Button
android:id="@+id/btn_faq"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/about_btn_faq"
android:background="@android:color/transparent"/>
<Button
android:id="@+id/btn_feedback"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/about_btn_feedback"
android:background="@android:color/transparent"/>
<Button
android:id="@+id/btn_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/about_btn_contact"
android:background="@android:color/transparent"/>
<Button
android:id="@+id/btn_license"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/about_btn_license"
android:background="@android:color/transparent"/>
</androidx.appcompat.widget.LinearLayoutCompat> | {
"content_hash": "025b4e75fbdf376a4bd1d11edb422ea3",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 62,
"avg_line_length": 32.67605633802817,
"alnum_prop": 0.6724137931034483,
"repo_name": "contentful/gallery-app-android",
"id": "bbcce88be0528736aff1cec261023fc1e55a0457",
"size": "2320",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_about.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "52486"
}
],
"symlink_target": ""
} |
- npm
## Instructions
- `npm install`
## Building the app
- For debug mode run: `gulp build:debug`
- Source files located /dist/debug/
- For release mode run: `gulp build:release`
- Source files located /dist/release/
## Running the app on a local machine
- `gulp`
- `gulp watch`
## Task Description
Included in the zip there is a file called menu.json. Use it to complete the following points.
- Create a blank web page and load this JSON with JavaScript
- Use the loaded JSON to create a tree menu taking into consideration this JSON structure description:
- Id: id of the element
- Leaf: If true, this is an end-node
- Description: Text displayed in the menu
- Link: Not applicable
- Content Explained later
- CssClass: CSS class of the menu element
- Menu: If available contains the submenu nodes
- Include the following attributes in each menu element: id, cssClass. Also the description has to be displayed as the menu text.
- When you click on a menu it should display any nested sub navigation, displaying the content on the page.
### Requirements
- Use Object Oriented JavaScript for the implementation; do not use a framework for this task, it should be plain Javascript.
- Make the code the most adaptable possible. | {
"content_hash": "961c67a029fb7ec31d8579cb664bc6d3",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 129,
"avg_line_length": 36.285714285714285,
"alnum_prop": 0.7385826771653543,
"repo_name": "fontainej/wh-task3",
"id": "ef4ab735b873ef3845437f874a32f8ee3c2e8cdd",
"size": "1318",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "460"
},
{
"name": "JavaScript",
"bytes": "8183"
}
],
"symlink_target": ""
} |
package org.assertj.core.api;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
/**
* Tests for <code>{@link org.assertj.core.api.Assertions#assertThat(Class)}</code>.
*
* @author William Delanoue
*/
public class Assertions_assertThat_with_Class_Test {
@Test
public void should_create_Assert() {
Class<Assertions_assertThat_with_Class_Test> clazz = Assertions_assertThat_with_Class_Test.class;
AbstractClassAssert<?> assertions = Assertions.assertThat(clazz);
assertThat(assertions).isNotNull();
}
@Test
public void should_pass_actual() {
Class<Assertions_assertThat_with_Class_Test> clazz = Assertions_assertThat_with_Class_Test.class;
AbstractClassAssert<?> assertions = Assertions.assertThat(clazz);
assertThat(assertions.actual).isSameAs(clazz);
}
}
| {
"content_hash": "a716118f325da0d8b147a38b8eb36a68",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 101,
"avg_line_length": 29.714285714285715,
"alnum_prop": 0.7427884615384616,
"repo_name": "dorzey/assertj-core",
"id": "986ebc4c4260735b1857ebedc6eeb09d0da42d23",
"size": "1439",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/assertj/core/api/Assertions_assertThat_with_Class_Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8364137"
},
{
"name": "Shell",
"bytes": "40820"
}
],
"symlink_target": ""
} |
<?php
namespace BricksPlatformComposerExtras\Processor;
use BricksPlatformComposerExtras\Handler;
use Composer\IO\IOInterface;
use Composer\Script\Event;
/**
* Class Generic
*
* Loosely based in https://github.com/Incenteev/ParameterHandler/blob/master/Processor.php
*
* @package BricksPlatformComposerExtras
*/
class Copy implements ProcessorInterface
{
protected $io;
protected $config;
public function __construct(IOInterface $io)
{
$this->setIO($io);
}
public function process(array $config, Event $event)
{
$this->setConfig($config);
$config = $this->getConfig();
$realFile = $config['file'];
if (isset($config['sudo'])) {
$sudo = $config['sudo'];
} else {
$sudo = false;
}
if (isset($config['mode'])) {
$mode=$config['mode'];
} else {
$mode=null;
}
$exists = file_exists($realFile);
$sourceFile = $this->getSourceFile($realFile,$config);
if ($exists) {
if ($this->getIO()->askConfirmation(sprintf('Destination file %s already exists - copy from %s ([y]/n)? ',$realFile, $sourceFile),true)) {
if ($sudo) {
$this->getIO()->write(sprintf('<comment>Copying with sudo %s -> %s</comment>', $sourceFile, $realFile));
$command="sudo sh -c 'cp -f ".$sourceFile." ".$realFile."'";
$this->getIO()->write($command);
shell_exec($command);
if ($mode) {
$command="sudo sh -c 'chmod ".$mode." ".$realFile."'";
shell_exec($command);
}
} else {
$this->getIO()->write(sprintf('<comment>Copying %s -> %s</comment>', $sourceFile, $realFile));
copy($sourceFile, $realFile);
if ($mode) {
$command="sh -c 'chmod ".$mode." ".$realFile."'";
shell_exec($command);
}
}
}
} else {
if ($sudo) {
$this->getIO()->write(sprintf('<comment>Copying with sudo %s -> %s</comment>', $sourceFile, $realFile));
$command="sudo sh -c 'cp -f ".$sourceFile." ".$realFile."'";
$this->getIO()->write($command);
shell_exec($command);
if ($mode) {
$command="sudo sh -c 'chmod ".$mode." ".$realFile."'";
shell_exec($command);
}
} else {
$this->getIO()->write(sprintf('<comment>Copying %s -> %s</comment>', $sourceFile, $realFile));
copy($sourceFile, $realFile);
if ($mode) {
$command="sh -c 'chmod ".$mode." ".$realFile."'";
shell_exec($command);
}
}
}
return true;
}
/**
* @return IOInterface
*/
public function getIO()
{
return $this->io;
}
/**
* @param IOInterface $io
*/
public function setIO(IOInterface $io)
{
$this->io = $io;
}
/**
* @return mixed
*/
public function getConfig()
{
return $this->config;
}
/**
* @param mixed $config
*/
public function setConfig($config)
{
if (empty($config['file'])) {
throw new \InvalidArgumentException('The extra.bricks-platform.config.file setting is required.');
}
$this->config = $config;
}
protected function getSourceFile($realFile,$config) {
if (isset($config['source-file'])) {
return $config['source-file'];
}
if (isset($config['color-only']) && $config['color-only']) {
$source= Handler\AbstractHandler::getColor();
} else {
$source = Handler\AbstractHandler::getTarget();
}
if (isset($config['use-hostname'])) {
$hostname=gethostname();
$source=$source.'_'.$hostname;
}
$realFileSegments = explode('/',$realFile);
$filename = array_pop($realFileSegments);
$filenameSegments = explode('.',$filename);
if (count($filenameSegments)==1) {
// regular files without suffix
return $filenameSegments[0].'.'.$source;
} else if (count($filenameSegments) == 2 && $filenameSegments[0]=='') {
// dot-files without suffix
return '.'.$filenameSegments[1].'.'.$source;
}
// regular files with suffix
$suffix = array_pop($filenameSegments);
return implode('.',$filenameSegments).'.'.$source.'.'.$suffix;
}
}
| {
"content_hash": "71d5aaff83908c7fd0fb92ed82430421",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 147,
"avg_line_length": 26.72222222222222,
"alnum_prop": 0.5426195426195426,
"repo_name": "20steps/bricks-platform-composer-extras",
"id": "11b516bf72ccdfc1988b1f297a94730681a0100e",
"size": "4329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Processor/Copy.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "62990"
}
],
"symlink_target": ""
} |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
#config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
| {
"content_hash": "99d5be1ee8778162facf14f514d25eff",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 85,
"avg_line_length": 39.093023255813954,
"alnum_prop": 0.7584770969660916,
"repo_name": "girque/rubyProject",
"id": "d3cdfb701584eadf849e15d3a661c83a201db5a7",
"size": "1681",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/environments/development.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2749"
},
{
"name": "CoffeeScript",
"bytes": "1055"
},
{
"name": "HTML",
"bytes": "25683"
},
{
"name": "JavaScript",
"bytes": "661"
},
{
"name": "Ruby",
"bytes": "71081"
}
],
"symlink_target": ""
} |
@interface DNOSingleText : NSObject
@property (nonatomic, copy ) NSString *text;
@property (nonatomic, strong) UIColor *textColor;
@property (nonatomic, assign) CGFloat animationRange;
@property (nonatomic, assign) BOOL enumerated;
+ (instancetype)singleTextWithAnimationRange:(CGFloat)animationRange;
- (CGFloat)locationWithFirstEnumerate;
- (CGFloat)locationWithNormalAnimation;
- (void)normalReset;
- (CGFloat)locationWithWaveAnimationCompletion:(void(^)())completion;
- (void)waveReset;
@end
| {
"content_hash": "d7787af436c3a85a16582f34f1199e66",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 69,
"avg_line_length": 28.27777777777778,
"alnum_prop": 0.7819253438113949,
"repo_name": "imagons/DNOLabelAnimation",
"id": "84d288711d4c2289be03385a748fdb0765895e3b",
"size": "684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DNOLabelAnimation/DNOSingleText.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "18737"
},
{
"name": "Ruby",
"bytes": "6320"
}
],
"symlink_target": ""
} |
Set-StrictMode -version 2.0
$ErrorActionPreference="Stop"
# Import Arcade functions
. (Join-Path $PSScriptRoot "common\tools.ps1")
$VSSetupDir = Join-Path $ArtifactsDir "VSSetup\$configuration"
$PackagesDir = Join-Path $ArtifactsDir "packages\$configuration"
$PublishDataUrl = "https://raw.githubusercontent.com/dotnet/roslyn/master/eng/config/PublishData.json"
$binaryLog = if (Test-Path variable:binaryLog) { $binaryLog } else { $false }
$nodeReuse = if (Test-Path variable:nodeReuse) { $nodeReuse } else { $false }
$bootstrapDir = if (Test-Path variable:bootstrapDir) { $bootstrapDir } else { "" }
$bootstrapConfiguration = if (Test-Path variable:bootstrapConfiguration) { $bootstrapConfiguration } else { "Release" }
$properties = if (Test-Path variable:properties) { $properties } else { @() }
function GetProjectOutputBinary([string]$fileName, [string]$projectName = "", [string]$configuration = $script:configuration, [string]$tfm = "net472", [string]$rid = "", [bool]$published = $false) {
$projectName = if ($projectName -ne "") { $projectName } else { [System.IO.Path]::GetFileNameWithoutExtension($fileName) }
$publishDir = if ($published) { "publish\" } else { "" }
$ridDir = if ($rid -ne "") { "$rid\" } else { "" }
return Join-Path $ArtifactsDir "bin\$projectName\$configuration\$tfm\$ridDir$publishDir$fileName"
}
function GetPublishData() {
if (Test-Path variable:global:_PublishData) {
return $global:_PublishData
}
Write-Host "Downloading $PublishDataUrl"
$content = (Invoke-WebRequest -Uri $PublishDataUrl -UseBasicParsing).Content
return $global:_PublishData = ConvertFrom-Json $content
}
function GetBranchPublishData([string]$branchName) {
$data = GetPublishData
if (Get-Member -InputObject $data.branches -Name $branchName) {
return $data.branches.$branchName
} else {
return $null
}
}
function GetReleasePublishData([string]$releaseName) {
$data = GetPublishData
if (Get-Member -InputObject $data.releases -Name $releaseName) {
return $data.releases.$releaseName
} else {
return $null
}
}
# Handy function for executing a command in powershell and throwing if it
# fails.
#
# Use this when the full command is known at script authoring time and
# doesn't require any dynamic argument build up. Example:
#
# Exec-Block { & $msbuild Test.proj }
#
# Original sample came from: http://jameskovacs.com/2010/02/25/the-exec-problem/
function Exec-Block([scriptblock]$cmd) {
& $cmd
# Need to check both of these cases for errors as they represent different items
# - $?: did the powershell script block throw an error
# - $lastexitcode: did a windows command executed by the script block end in error
if ((-not $?) -or ($lastexitcode -ne 0)) {
throw "Command failed to execute: $cmd"
}
}
function Exec-CommandCore([string]$command, [string]$commandArgs, [switch]$useConsole = $true) {
if ($useConsole) {
$exitCode = Exec-Process $command $commandArgs
if ($exitCode -ne 0) {
throw "Command failed to execute with exit code $($exitCode): $command $commandArgs"
}
return
}
$startInfo = New-Object System.Diagnostics.ProcessStartInfo
$startInfo.FileName = $command
$startInfo.Arguments = $commandArgs
$startInfo.UseShellExecute = $false
$startInfo.WorkingDirectory = Get-Location
$startInfo.RedirectStandardOutput = $true
$startInfo.CreateNoWindow = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $startInfo
$process.Start() | Out-Null
$finished = $false
try {
# The OutputDataReceived event doesn't fire as events are sent by the
# process in powershell. Possibly due to subtlties of how Powershell
# manages the thread pool that I'm not aware of. Using blocking
# reading here as an alternative which is fine since this blocks
# on completion already.
$out = $process.StandardOutput
while (-not $out.EndOfStream) {
$line = $out.ReadLine()
Write-Output $line
}
while (-not $process.WaitForExit(100)) {
# Non-blocking loop done to allow ctr-c interrupts
}
$finished = $true
if ($process.ExitCode -ne 0) {
throw "Command failed to execute with exit code $($process.ExitCode): $command $commandArgs"
}
}
finally {
# If we didn't finish then an error occurred or the user hit ctrl-c. Either
# way kill the process
if (-not $finished) {
$process.Kill()
}
}
}
# Handy function for executing a windows command which needs to go through
# windows command line parsing.
#
# Use this when the command arguments are stored in a variable. Particularly
# when the variable needs reparsing by the windows command line. Example:
#
# $args = "/p:ManualBuild=true Test.proj"
# Exec-Command $msbuild $args
#
function Exec-Command([string]$command, [string]$commandArgs) {
Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$false
}
# Functions exactly like Exec-Command but lets the process re-use the current
# console. This means items like colored output will function correctly.
#
# In general this command should be used in place of
# Exec-Command $msbuild $args | Out-Host
#
function Exec-Console([string]$command, [string]$commandArgs) {
Exec-CommandCore -command $command -commandArgs $commandargs -useConsole:$true
}
# Handy function for executing a powershell script in a clean environment with
# arguments. Prefer this over & sourcing a script as it will both use a clean
# environment and do proper error checking
function Exec-Script([string]$script, [string]$scriptArgs = "") {
Exec-Command "powershell" "-noprofile -executionPolicy RemoteSigned -file `"$script`" $scriptArgs"
}
# Ensure the proper .NET Core SDK is available. Returns the location to the dotnet.exe.
function Ensure-DotnetSdk() {
return Join-Path (InitializeDotNetCli -install:$true) "dotnet.exe"
}
function Get-VersionCore([string]$name, [string]$versionFile) {
$name = $name.Replace(".", "")
$name = $name.Replace("-", "")
$nodeName = "$($name)Version"
$x = [xml](Get-Content -raw $versionFile)
$node = $x.SelectSingleNode("//Project/PropertyGroup/$nodeName")
if ($node -ne $null) {
return $node.InnerText
}
throw "Cannot find package $name in $versionFile"
}
# Return the version of the NuGet package as used in this repo
function Get-PackageVersion([string]$name) {
return Get-VersionCore $name (Join-Path $EngRoot "Versions.props")
}
# Locate the directory where our NuGet packages will be deployed. Needs to be kept in sync
# with the logic in Version.props
function Get-PackagesDir() {
$d = $null
if ($env:NUGET_PACKAGES -ne $null) {
$d = $env:NUGET_PACKAGES
}
else {
$d = Join-Path $env:UserProfile ".nuget\packages\"
}
Create-Directory $d
return $d
}
# Locate the directory of a specific NuGet package which is restored via our main
# toolset values.
function Get-PackageDir([string]$name, [string]$version = "") {
if ($version -eq "") {
$version = Get-PackageVersion $name
}
$p = Get-PackagesDir
$p = Join-Path $p $name.ToLowerInvariant()
$p = Join-Path $p $version
return $p
}
function Run-MSBuild([string]$projectFilePath, [string]$buildArgs = "", [string]$logFileName = "", [switch]$parallel = $true, [switch]$summary = $true, [switch]$warnAsError = $true, [string]$configuration = $script:configuration) {
# Because we override the C#/VB toolset to build against our LKG package, it is important
# that we do not reuse MSBuild nodes from other jobs/builds on the machine. Otherwise,
# we'll run into issues such as https://github.com/dotnet/roslyn/issues/6211.
# MSBuildAdditionalCommandLineArgs=
$args = "/p:TreatWarningsAsErrors=true /nologo /nodeReuse:false /p:Configuration=$configuration ";
if ($warnAsError) {
$args += " /warnaserror"
}
if ($summary) {
$args += " /consoleloggerparameters:Verbosity=minimal;summary"
} else {
$args += " /consoleloggerparameters:Verbosity=minimal"
}
if ($parallel) {
$args += " /m"
}
if ($skipAnalyzers) {
$args += " /p:UseRoslynAnalyzers=false"
}
if ($binaryLog) {
if ($logFileName -eq "") {
$logFileName = [IO.Path]::GetFileNameWithoutExtension($projectFilePath)
}
$logFileName = [IO.Path]::ChangeExtension($logFileName, ".binlog")
$logFilePath = Join-Path $LogDir $logFileName
$args += " /bl:$logFilePath"
}
if ($officialBuildId) {
$args += " /p:OfficialBuildId=" + $officialBuildId
}
if ($ci) {
$args += " /p:ContinuousIntegrationBuild=true"
}
if ($bootstrapDir -ne "") {
$args += " /p:BootstrapBuildPath=$bootstrapDir"
}
$args += " $buildArgs"
$args += " $projectFilePath"
$args += " $properties"
$buildTool = InitializeBuildTool
Exec-Console $buildTool.Path "$($buildTool.Command) $args"
}
# Create a bootstrap build of the compiler. Returns the directory where the bootstrap build
# is located.
#
# Important to not set $script:bootstrapDir here yet as we're actually in the process of
# building the bootstrap.
function Make-BootstrapBuild([switch]$force32 = $false) {
Write-Host "Building bootstrap compiler"
$dir = Join-Path $ArtifactsDir "Bootstrap"
Remove-Item -re $dir -ErrorAction SilentlyContinue
Create-Directory $dir
$packageName = "Microsoft.Net.Compilers.Toolset"
$projectPath = "src\NuGet\$packageName\$packageName.Package.csproj"
$force32Flag = if ($force32) { " /p:BOOTSTRAP32=true" } else { "" }
Run-MSBuild $projectPath "/restore /t:Pack /p:RoslynEnforceCodeStyle=false /p:UseRoslynAnalyzers=false /p:DotNetUseShippingVersions=true /p:InitialDefineConstants=BOOTSTRAP /p:PackageOutputPath=`"$dir`" /p:EnableNgenOptimization=false /p:PublishWindowsPdb=false $force32Flag" -logFileName "Bootstrap" -configuration $bootstrapConfiguration
$packageFile = Get-ChildItem -Path $dir -Filter "$packageName.*.nupkg"
Unzip "$dir\$packageFile" $dir
Write-Host "Cleaning Bootstrap compiler artifacts"
Run-MSBuild $projectPath "/t:Clean" -logFileName "BootstrapClean"
return $dir
}
Add-Type -AssemblyName 'System.Drawing'
Add-Type -AssemblyName 'System.Windows.Forms'
function Capture-Screenshot($path) {
$width = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width
$height = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height
$bitmap = New-Object System.Drawing.Bitmap $width, $height
try {
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
try {
$graphics.CopyFromScreen( `
[System.Windows.Forms.Screen]::PrimaryScreen.Bounds.X, `
[System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Y, `
0, `
0, `
$bitmap.Size, `
[System.Drawing.CopyPixelOperation]::SourceCopy)
} finally {
$graphics.Dispose()
}
$bitmap.Save($path, [System.Drawing.Imaging.ImageFormat]::Png)
} finally {
$bitmap.Dispose()
}
}
| {
"content_hash": "49d3c3c8f6f8ed8020ec5b84fb20123f",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 341,
"avg_line_length": 34.65714285714286,
"alnum_prop": 0.7024823669506275,
"repo_name": "agocke/roslyn",
"id": "763c6a0e0cff961af84a8d117bf35b544328bc3a",
"size": "11001",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "eng/build-utils.ps1",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "126326705"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "8276"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "237208"
},
{
"name": "Shell",
"bytes": "94927"
},
{
"name": "Visual Basic .NET",
"bytes": "70527543"
}
],
"symlink_target": ""
} |
package org.hisp.dhis.schema.descriptors;
import org.hisp.dhis.color.Color;
import org.hisp.dhis.schema.Schema;
import org.hisp.dhis.schema.SchemaDescriptor;
/**
* @author Lars Helge Overland
*/
public class ColorSchemaDescriptor implements SchemaDescriptor
{
public static final String SINGULAR = "color";
public static final String PLURAL = "colors";
public static final String API_ENDPOINT = "/" + PLURAL;
@Override
public Schema getSchema()
{
return new Schema( Color.class, SINGULAR, PLURAL );
}
}
| {
"content_hash": "6f49f9d8960a02b9e83ff64bf1b53180",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 62,
"avg_line_length": 21.92,
"alnum_prop": 0.7116788321167883,
"repo_name": "msf-oca-his/dhis-core",
"id": "d953c93c78fc346b16d60768e0712010411b8b8f",
"size": "2104",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dhis-2/dhis-services/dhis-service-schema/src/main/java/org/hisp/dhis/schema/descriptors/ColorSchemaDescriptor.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "195574"
},
{
"name": "HTML",
"bytes": "68728"
},
{
"name": "Java",
"bytes": "18310173"
},
{
"name": "JavaScript",
"bytes": "1002108"
},
{
"name": "PLpgSQL",
"bytes": "690824"
},
{
"name": "Ruby",
"bytes": "1011"
},
{
"name": "Shell",
"bytes": "394"
},
{
"name": "XSLT",
"bytes": "8281"
}
],
"symlink_target": ""
} |
Domain Adaptation with Randomized Expectation Maximization
--------------------------
This is the implementation of the AdREM method for domain adaptation, plus accompanying code to test it on a variety of datasets.
The method itself is implemented in `src/adrem/predict_adrem.m`.
Example:
addpath src/adrem
addpath src/evaluation
data = load_dataset('amazon');
% Predict labels of 'dvd' target domain using 'books' as source
% Preprocess data: divide by standard deviation over both domains
[x_src, x_tgt] = preprocess(data.x{1}, data.y{1}, data.x{2}, 'joint-std');
y = predict_adrem(x_src, data.y{1}, x_tgt);
mean(y == data.y{2})
The method requires that the MATLAB/octave bindings for liblinear are installed. These can be downloaded from https://www.csie.ntu.edu.tw/~cjlin/liblinear/
As a starting point for the experiments, look at `src/evaluation/run_methods.m`.
If you use this code, please cite
Biased Bagging for Unsupervised Domain Adaptation
Twan van Laarhoven, Elena Marchiori
2017
Additional information can be found at http://twanvl.nl/research/domain-adaptation-2017/
The datasets used in the experiments can also be downloaded there.
Comparison methods
----
The comparison methods can be downloaded from:
* GFK: http://www-scf.usc.edu/~boqinggo/domainadaptation.html
* FLDA: https://github.com/wmkouw/da-fl
* Domain adaptation toolbox: https://github.com/viggin/domain-adaptation-toolbox
* Coral: included in the source code
* Subspace Alignment: included in the source code
License
----
The AdREM method and evaluation code is provided under the MIT license (see file LICENSE).
The comparison methods may be subject to other licenses.
| {
"content_hash": "927212870e6c2c82fd63508672498c85",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 155,
"avg_line_length": 39.674418604651166,
"alnum_prop": 0.7444314185228605,
"repo_name": "twanvl/abib",
"id": "1c5feae8ed25b2cca20ed043d99935bfa8a4576a",
"size": "1706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "M",
"bytes": "6261"
},
{
"name": "Matlab",
"bytes": "57519"
},
{
"name": "Python",
"bytes": "16954"
}
],
"symlink_target": ""
} |
<!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 (version 1.7.0-google-v5) on Thu Dec 19 17:42:41 EST 2013 -->
<title>PublisherQueryLanguageServiceLocator</title>
<meta name="date" content="2013-12-19">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PublisherQueryLanguageServiceLocator";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceSoapBindingStub.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html" target="_top">Frames</a></li>
<li><a href="PublisherQueryLanguageServiceLocator.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><a href="#nested_classes_inherited_from_class_org.apache.axis.client.Service">Nested</a> | </li>
<li><a href="#fields_inherited_from_class_org.apache.axis.client.Service">Field</a> | </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">com.google.api.ads.dfp.v201308</div>
<h2 title="Class PublisherQueryLanguageServiceLocator" class="title">Class PublisherQueryLanguageServiceLocator</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.apache.axis.client.Service</li>
<li>
<ul class="inheritance">
<li>com.google.api.ads.dfp.v201308.PublisherQueryLanguageServiceLocator</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageService</a>, java.io.Serializable, javax.naming.Referenceable, javax.xml.rpc.Service</dd>
</dl>
<hr>
<br>
<pre>public class <span class="strong">PublisherQueryLanguageServiceLocator</span>
extends org.apache.axis.client.Service
implements <a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageService</a></pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../../serialized-form.html#com.google.api.ads.dfp.v201308.PublisherQueryLanguageServiceLocator">Serialized Form</a></dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="nested_classes_inherited_from_class_org.apache.axis.client.Service">
<!-- -->
</a>
<h3>Nested classes/interfaces inherited from class org.apache.axis.client.Service</h3>
<code>org.apache.axis.client.Service.HandlerRegistryImpl</code></li>
</ul>
</li>
</ul>
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field_summary">
<!-- -->
</a>
<h3>Field Summary</h3>
<ul class="blockList">
<li class="blockList"><a name="fields_inherited_from_class_org.apache.axis.client.Service">
<!-- -->
</a>
<h3>Fields inherited from class org.apache.axis.client.Service</h3>
<code>_call</code></li>
</ul>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" 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><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#PublisherQueryLanguageServiceLocator()">PublisherQueryLanguageServiceLocator</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#PublisherQueryLanguageServiceLocator(org.apache.axis.EngineConfiguration)">PublisherQueryLanguageServiceLocator</a></strong>(org.apache.axis.EngineConfiguration config)</code> </td>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#PublisherQueryLanguageServiceLocator(java.lang.String, javax.xml.namespace.QName)">PublisherQueryLanguageServiceLocator</a></strong>(java.lang.String wsdlLoc,
javax.xml.namespace.QName sName)</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="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.rmi.Remote</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPort(java.lang.Class)">getPort</a></strong>(java.lang.Class serviceEndpointInterface)</code>
<div class="block">For the given interface, get the stub implementation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.rmi.Remote</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPort(javax.xml.namespace.QName, java.lang.Class)">getPort</a></strong>(javax.xml.namespace.QName portName,
java.lang.Class serviceEndpointInterface)</code>
<div class="block">For the given interface, get the stub implementation.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.util.Iterator</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPorts()">getPorts</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageServiceInterface</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPublisherQueryLanguageServiceInterfacePort()">getPublisherQueryLanguageServiceInterfacePort</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageServiceInterface</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPublisherQueryLanguageServiceInterfacePort(java.net.URL)">getPublisherQueryLanguageServiceInterfacePort</a></strong>(java.net.URL portAddress)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPublisherQueryLanguageServiceInterfacePortAddress()">getPublisherQueryLanguageServiceInterfacePortAddress</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getPublisherQueryLanguageServiceInterfacePortWSDDServiceName()">getPublisherQueryLanguageServiceInterfacePortWSDDServiceName</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>javax.xml.namespace.QName</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#getServiceName()">getServiceName</a></strong>()</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#setEndpointAddress(javax.xml.namespace.QName, java.lang.String)">setEndpointAddress</a></strong>(javax.xml.namespace.QName portName,
java.lang.String address)</code>
<div class="block">Set the endpoint address for the specified port name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#setEndpointAddress(java.lang.String, java.lang.String)">setEndpointAddress</a></strong>(java.lang.String portName,
java.lang.String address)</code>
<div class="block">Set the endpoint address for the specified port name.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#setPublisherQueryLanguageServiceInterfacePortEndpointAddress(java.lang.String)">setPublisherQueryLanguageServiceInterfacePortEndpointAddress</a></strong>(java.lang.String address)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html#setPublisherQueryLanguageServiceInterfacePortWSDDServiceName(java.lang.String)">setPublisherQueryLanguageServiceInterfacePortWSDDServiceName</a></strong>(java.lang.String name)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_org.apache.axis.client.Service">
<!-- -->
</a>
<h3>Methods inherited from class org.apache.axis.client.Service</h3>
<code>createCall, createCall, createCall, createCall, getAxisClient, getCacheWSDL, getCall, getCalls, getEngine, getEngineConfiguration, getHandlerRegistry, getMaintainSession, getPort, getReference, getTypeMappingRegistry, getWSDLDocumentLocation, getWSDLParser, getWSDLService, setCacheWSDL, setEngine, setEngineConfiguration, setMaintainSession, setTypeMappingRegistry, setTypeMappingVersion</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>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_javax.xml.rpc.Service">
<!-- -->
</a>
<h3>Methods inherited from interface javax.xml.rpc.Service</h3>
<code>createCall, createCall, createCall, createCall, getCalls, getHandlerRegistry, getTypeMappingRegistry, getWSDLDocumentLocation</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="PublisherQueryLanguageServiceLocator()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PublisherQueryLanguageServiceLocator</h4>
<pre>public PublisherQueryLanguageServiceLocator()</pre>
</li>
</ul>
<a name="PublisherQueryLanguageServiceLocator(org.apache.axis.EngineConfiguration)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>PublisherQueryLanguageServiceLocator</h4>
<pre>public PublisherQueryLanguageServiceLocator(org.apache.axis.EngineConfiguration config)</pre>
</li>
</ul>
<a name="PublisherQueryLanguageServiceLocator(java.lang.String, javax.xml.namespace.QName)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PublisherQueryLanguageServiceLocator</h4>
<pre>public PublisherQueryLanguageServiceLocator(java.lang.String wsdlLoc,
javax.xml.namespace.QName sName)
throws javax.xml.rpc.ServiceException</pre>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getPublisherQueryLanguageServiceInterfacePortAddress()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPublisherQueryLanguageServiceInterfacePortAddress</h4>
<pre>public java.lang.String getPublisherQueryLanguageServiceInterfacePortAddress()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html#getPublisherQueryLanguageServiceInterfacePortAddress()">getPublisherQueryLanguageServiceInterfacePortAddress</a></code> in interface <code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageService</a></code></dd>
</dl>
</li>
</ul>
<a name="getPublisherQueryLanguageServiceInterfacePortWSDDServiceName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPublisherQueryLanguageServiceInterfacePortWSDDServiceName</h4>
<pre>public java.lang.String getPublisherQueryLanguageServiceInterfacePortWSDDServiceName()</pre>
</li>
</ul>
<a name="setPublisherQueryLanguageServiceInterfacePortWSDDServiceName(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPublisherQueryLanguageServiceInterfacePortWSDDServiceName</h4>
<pre>public void setPublisherQueryLanguageServiceInterfacePortWSDDServiceName(java.lang.String name)</pre>
</li>
</ul>
<a name="getPublisherQueryLanguageServiceInterfacePort()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPublisherQueryLanguageServiceInterfacePort</h4>
<pre>public <a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageServiceInterface</a> getPublisherQueryLanguageServiceInterfacePort()
throws javax.xml.rpc.ServiceException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html#getPublisherQueryLanguageServiceInterfacePort()">getPublisherQueryLanguageServiceInterfacePort</a></code> in interface <code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageService</a></code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
<a name="getPublisherQueryLanguageServiceInterfacePort(java.net.URL)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPublisherQueryLanguageServiceInterfacePort</h4>
<pre>public <a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageServiceInterface</a> getPublisherQueryLanguageServiceInterfacePort(java.net.URL portAddress)
throws javax.xml.rpc.ServiceException</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html#getPublisherQueryLanguageServiceInterfacePort(java.net.URL)">getPublisherQueryLanguageServiceInterfacePort</a></code> in interface <code><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageService.html" title="interface in com.google.api.ads.dfp.v201308">PublisherQueryLanguageService</a></code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
<a name="setPublisherQueryLanguageServiceInterfacePortEndpointAddress(java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setPublisherQueryLanguageServiceInterfacePortEndpointAddress</h4>
<pre>public void setPublisherQueryLanguageServiceInterfacePortEndpointAddress(java.lang.String address)</pre>
</li>
</ul>
<a name="getPort(java.lang.Class)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPort</h4>
<pre>public java.rmi.Remote getPort(java.lang.Class serviceEndpointInterface)
throws javax.xml.rpc.ServiceException</pre>
<div class="block">For the given interface, get the stub implementation.
If this service has no port for the given interface,
then ServiceException is thrown.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getPort</code> in interface <code>javax.xml.rpc.Service</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>getPort</code> in class <code>org.apache.axis.client.Service</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
<a name="getPort(javax.xml.namespace.QName, java.lang.Class)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPort</h4>
<pre>public java.rmi.Remote getPort(javax.xml.namespace.QName portName,
java.lang.Class serviceEndpointInterface)
throws javax.xml.rpc.ServiceException</pre>
<div class="block">For the given interface, get the stub implementation.
If this service has no port for the given interface,
then ServiceException is thrown.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getPort</code> in interface <code>javax.xml.rpc.Service</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>getPort</code> in class <code>org.apache.axis.client.Service</code></dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
<a name="getServiceName()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getServiceName</h4>
<pre>public javax.xml.namespace.QName getServiceName()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getServiceName</code> in interface <code>javax.xml.rpc.Service</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>getServiceName</code> in class <code>org.apache.axis.client.Service</code></dd>
</dl>
</li>
</ul>
<a name="getPorts()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getPorts</h4>
<pre>public java.util.Iterator getPorts()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code>getPorts</code> in interface <code>javax.xml.rpc.Service</code></dd>
<dt><strong>Overrides:</strong></dt>
<dd><code>getPorts</code> in class <code>org.apache.axis.client.Service</code></dd>
</dl>
</li>
</ul>
<a name="setEndpointAddress(java.lang.String, java.lang.String)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setEndpointAddress</h4>
<pre>public void setEndpointAddress(java.lang.String portName,
java.lang.String address)
throws javax.xml.rpc.ServiceException</pre>
<div class="block">Set the endpoint address for the specified port name.</div>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</code></dd></dl>
</li>
</ul>
<a name="setEndpointAddress(javax.xml.namespace.QName, java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setEndpointAddress</h4>
<pre>public void setEndpointAddress(javax.xml.namespace.QName portName,
java.lang.String address)
throws javax.xml.rpc.ServiceException</pre>
<div class="block">Set the endpoint address for the specified port name.</div>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>javax.xml.rpc.ServiceException</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><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceInterface.html" title="interface in com.google.api.ads.dfp.v201308"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../../com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceSoapBindingStub.html" title="class in com.google.api.ads.dfp.v201308"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html" target="_top">Frames</a></li>
<li><a href="PublisherQueryLanguageServiceLocator.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><a href="#nested_classes_inherited_from_class_org.apache.axis.client.Service">Nested</a> | </li>
<li><a href="#fields_inherited_from_class_org.apache.axis.client.Service">Field</a> | </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>
| {
"content_hash": "65752ce72caa036b8293f926a938a7cf",
"timestamp": "",
"source": "github",
"line_count": 553,
"max_line_length": 443,
"avg_line_length": 47.11934900542496,
"alnum_prop": 0.6946693786698392,
"repo_name": "google-code-export/google-api-dfp-java",
"id": "edbb4b45638df44c6324c401d03d7a58ade7db8e",
"size": "26057",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/com/google/api/ads/dfp/v201308/PublisherQueryLanguageServiceLocator.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "39950935"
}
],
"symlink_target": ""
} |
/* $NetBSD: linux_syscallargs.h,v 1.35 1998/12/15 19:31:30 itohy Exp $ */
/*-
* Copyright (c) 1998 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Eric Haszlakiewicz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#ifndef _LINUX_SYSCALLARGS_H
#define _LINUX_SYSCALLARGS_H
#if defined(i386)
#include <compat/linux/arch/i386/linux_syscallargs.h>
#elif defined(__m68k__)
#include <compat/linux/arch/m68k/linux_syscallargs.h>
#elif defined(__alpha__)
#include <compat/linux/arch/alpha/linux_syscallargs.h>
#else
#error Undefined linux_syscallargs.h machine type.
#endif
#endif /* !_LINUX_SYSCALLARGS_H */
| {
"content_hash": "b43f160a3e56b23ddd94559c45766d45",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 78,
"avg_line_length": 46,
"alnum_prop": 0.7612876254180602,
"repo_name": "MarginC/kame",
"id": "c7be5b5cfdb9e4c573b5008bf9bd7c81ee396eeb",
"size": "2392",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "netbsd/sys/compat/linux/linux_syscallargs.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Arc",
"bytes": "7491"
},
{
"name": "Assembly",
"bytes": "14375563"
},
{
"name": "Awk",
"bytes": "313712"
},
{
"name": "Batchfile",
"bytes": "6819"
},
{
"name": "C",
"bytes": "356715789"
},
{
"name": "C++",
"bytes": "4231647"
},
{
"name": "DIGITAL Command Language",
"bytes": "11155"
},
{
"name": "Emacs Lisp",
"bytes": "790"
},
{
"name": "Forth",
"bytes": "253695"
},
{
"name": "GAP",
"bytes": "9964"
},
{
"name": "Groff",
"bytes": "2220485"
},
{
"name": "Lex",
"bytes": "168376"
},
{
"name": "Logos",
"bytes": "570213"
},
{
"name": "Makefile",
"bytes": "1778847"
},
{
"name": "Mathematica",
"bytes": "16549"
},
{
"name": "Objective-C",
"bytes": "529629"
},
{
"name": "PHP",
"bytes": "11283"
},
{
"name": "Perl",
"bytes": "151251"
},
{
"name": "Perl6",
"bytes": "2572"
},
{
"name": "Ruby",
"bytes": "7283"
},
{
"name": "Scheme",
"bytes": "76872"
},
{
"name": "Shell",
"bytes": "583253"
},
{
"name": "Stata",
"bytes": "408"
},
{
"name": "Yacc",
"bytes": "606054"
}
],
"symlink_target": ""
} |
<?php
namespace Drupal\comment\Form;
use Drupal\comment\CommentManagerInterface;
use Drupal\Core\Entity\EntityDeleteForm;
use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a confirmation form for deleting a comment type entity.
*/
class CommentTypeDeleteForm extends EntityDeleteForm {
/**
* The comment manager service.
*
* @var \Drupal\comment\CommentManagerInterface
*/
protected $commentManager;
/**
* The entity manager service.
*
* @var \Drupal\Core\Entity\EntityManager
*/
protected $entityManager;
/**
* A logger instance.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* The entity being used by this form.
*
* @var \Drupal\comment\CommentTypeInterface
*/
protected $entity;
/**
* Constructs a query factory object.
*
* @param \Drupal\comment\CommentManagerInterface $comment_manager
* The comment manager service.
* @param \Drupal\Core\Entity\EntityManager $entity_manager
* The entity manager service.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(CommentManagerInterface $comment_manager, EntityManager $entity_manager, LoggerInterface $logger) {
$this->commentManager = $comment_manager;
$this->entityManager = $entity_manager;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('comment.manager'),
$container->get('entity.manager'),
$container->get('logger.factory')->get('comment')
);
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$comments = $this->entityTypeManager->getStorage('comment')->getQuery()
->condition('comment_type', $this->entity->id())
->execute();
$entity_type = $this->entity->getTargetEntityTypeId();
$caption = '';
foreach (array_keys($this->commentManager->getFields($entity_type)) as $field_name) {
/** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
if (($field_storage = FieldStorageConfig::loadByName($entity_type, $field_name)) && $field_storage->getSetting('comment_type') == $this->entity->id() && !$field_storage->isDeleted()) {
$caption .= '<p>' . $this->t('%label is used by the %field field on your site. You can not remove this comment type until you have removed the field.', [
'%label' => $this->entity->label(),
'%field' => $field_storage->label(),
]) . '</p>';
}
}
if (!empty($comments)) {
$caption .= '<p>' . $this->formatPlural(count($comments), '%label is used by 1 comment on your site. You can not remove this comment type until you have removed all of the %label comments.', '%label is used by @count comments on your site. You may not remove %label until you have removed all of the %label comments.', ['%label' => $this->entity->label()]) . '</p>';
}
if ($caption) {
$form['description'] = ['#markup' => $caption];
return $form;
}
else {
return parent::buildForm($form, $form_state);
}
}
}
| {
"content_hash": "1a1ee397ded4e3a8266b61d19bf9079e",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 372,
"avg_line_length": 32.39423076923077,
"alnum_prop": 0.6586524191154646,
"repo_name": "kgatjens/d8_vm_vagrant",
"id": "30181c1d9b820596cbaedcc70a3b5b1ad5644556",
"size": "3369",
"binary": false,
"copies": "219",
"ref": "refs/heads/master",
"path": "project/core/modules/comment/src/Form/CommentTypeDeleteForm.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "9038"
},
{
"name": "CSS",
"bytes": "962176"
},
{
"name": "HTML",
"bytes": "1769288"
},
{
"name": "JavaScript",
"bytes": "1302117"
},
{
"name": "PHP",
"bytes": "40520904"
},
{
"name": "PLpgSQL",
"bytes": "2020"
},
{
"name": "PowerShell",
"bytes": "471"
},
{
"name": "Ruby",
"bytes": "6985"
},
{
"name": "Shell",
"bytes": "85027"
}
],
"symlink_target": ""
} |
<?php
namespace Tests\Api;
use \App\Models\Country;
use \App\Models\Address;
class AddressesTest extends BaseTestCase
{
private $table_name = 'addresses';
public function setUp() {
parent::setUp();
$this->base_url = '/api/addresses';
// Instanciate some countries
$this->country_1 = factory(Country::class)->make(['id' => 1, 'name' => 'France', 'alpha3' => 'FRA']);
$this->country_2 = factory(Country::class)->make(['id' => 2, 'name' => 'Germany', 'alpha3' => 'DEU']);
// Create some addresses
$this->address_1 = factory(Address::class)->create(['country_id' => $this->country_1]);
$this->address_2 = factory(Address::class)->create(['country_id' => $this->country_1]);
$this->address_3 = factory(Address::class)->create(['country_id' => $this->country_2]);
$this->address_4 = factory(Address::class)->create(['country_id' => $this->country_2]);
}
public static function getResponseStructure() : Array {
return [
'name',
'address1',
'address2',
'city',
'zip',
'region',
'country_id',
'country' => \Tests\Api\CountriesTest::getResponseStructure(),
'created_at',
'updated_at'
];
}
/**
* Return for each token type the expected response code
*
* @return Array
* [0] The API token for each scenario
* [1] The expected response for listing the metals
* [2] The expected response for creating a new metal
* [3] The expected response for view a metal
* [4] The expected response for delete a metal
* [5] The expected response for update a metal
*/
public function providerResponseCodeForUserTypeOnValidActionList() {
return [
// L C V D U
[$this->api_token_admin_user, 200, 201, 200, 200, 200],
[$this->api_token_employee_user, 200, 201, 200, 200, 200],
[$this->api_token_deactivated_user, 401, 401, 401, 401, 401],
[$this->api_token_invalid, 401, 401, 401, 401, 401],
];
}
/**
* Make sure all the required fields are passed and the foreign keys honored
*
* @return Array
* [0] An invalid Address parameters
* [1] ...
* ...
*/
public function providerMissingInvalidArguments() {
return [
[['name' => null, 'country_id' => 1]],
[['address1' => null, 'country_id' => 1]],
[['city' => null, 'country_id' => 1]],
[['zip' => null, 'country_id' => 1]],
[['region' => null, 'country_id' => 1]],
[['country_id' => null]],
[['country_id' => 3000]],
];
}
/**
*
*
* Listing tests
*
*
*/
/**
* @dataProvider providerResponseCodeForUserTypeOnValidActionList
* @group Addresses
*/
public function testGetCorrectResponseCodeForListing(
$token,
$expected_listing_code,
$expected_creating_code,
$expected_view_code,
$expected_delete_code,
$expected_update_code
) {
$response = $this->prepareRequest($token)->get($this->getBaseUrl());
$response->assertStatus($expected_listing_code);
}
/**
* @dataProvider dataProviderActiveUsersToken
* @group Addresses
*/
public function testCanAccessListWithToken($valid_token) {
// Get the list of generated names and sort them
$sorted_names = [
$this->address_1->name,
$this->address_2->name,
$this->address_3->name,
$this->address_4->name,
];
array_multisort($sorted_names, SORT_NATURAL);
$response = $this->prepareRequest($valid_token)->get($this->getBaseUrl());
$response
->assertJsonStructure(
$this->json_paginate_resource_structure
)
->assertJson([
'data' => [
['name' => $sorted_names[0]],
['name' => $sorted_names[1]],
['name' => $sorted_names[2]],
['name' => $sorted_names[3]],
]
])
->assertJsonStructure([
'data' => [
$this->getResponseStructure(),
$this->getResponseStructure(),
$this->getResponseStructure(),
$this->getResponseStructure(),
]
]);
}
/**
*
*
* Creation tests
*
*
*/
/**
* @dataProvider providerResponseCodeForUserTypeOnValidActionList
* @group Addresses
*/
public function testGetCorrectResponseCodeForCreating(
$token,
$expected_listing_code,
$expected_creating_code,
$expected_view_code,
$expected_delete_code,
$expected_update_code
) {
$address_new = factory(Address::class)->create(['country_id' => $this->country_1]);
$response = $this->prepareRequest($token)->post(
$this->getBaseUrl(),
$address_new->toArray()
);
$response->assertStatus($expected_creating_code);
}
/**
* @group Addresses
*/
public function testCanCreateWhenAuthorized() {
$address = factory(Address::class)->make(['country_id' => $this->country_1]);
$address_data = $address->toArray();
unset($address_data['id']);
$response = $this->prepareRequest($this->api_token_admin_user)->post(
$this->getBaseUrl(),
$address_data
);
$response
->assertJson(['address' => $address_data])
->assertJsonStructure(['address' => $this->getResponseStructure()]);
$this->assertDatabaseHas($this->table_name, $address_data);
}
/**
* @dataProvider providerMissingInvalidArguments
* @group Addresses
*/
public function testCanNotCreateWhenAuthorizedWithMissingArguments(Array $address_data) {
$address = factory(Address::class)->make($address_data);
$response = $this->prepareRequest($this->api_token_admin_user)->post($this->getBaseUrl(), $address->toArray());
$response
->assertStatus(422)
->assertJsonStructure($this->json_validation_error_structure);
}
/**
*
*
* View tests
*
*
*/
/**
* @dataProvider providerResponseCodeForUserTypeOnValidActionList
* @group Addresses
*/
public function testGetCorrectResponseCodeForViewing(
$token,
$expected_listing_code,
$expected_creating_code,
$expected_view_code,
$expected_delete_code,
$expected_update_code
) {
$response = $this->prepareRequest($token)->get($this->getBaseUrl($this->address_1->id));
$response->assertStatus($expected_view_code);
}
/**
* @group Addresses
*/
public function testCanViewDetailsWhenAllowed() {
$response = $this->prepareRequest()->get($this->getBaseUrl($this->address_1->id));
$response
->assertJsonStructure(['address' => $this->getResponseStructure()])
->assertJson(
['address' =>
[
'name' => $this->address_1->name,
'address1' => $this->address_1->address1,
'address2' => $this->address_1->address2,
'city' => $this->address_1->city,
'zip' => $this->address_1->zip,
'region' => $this->address_1->region,
'country' => [
'name' => $this->country_1->name,
'alpha3' => $this->country_1->alpha3,
]
]
]
);
}
/**
* @group Addresses
*/
public function testCanRetrieveNullMetalDetailsWhenPassingNonExistingId() {
$response = $this->prepareRequest()->get($this->getBaseUrl(3000));
$response
->assertStatus(404)
->assertJsonStructure($this->json_error_structure);
}
/**
*
*
* Update tests
*
*
*/
/**
* @dataProvider providerResponseCodeForUserTypeOnValidActionList
* @group Addresses
*/
public function testGetCorrectResponseCodeForUpdating(
$token,
$expected_listing_code,
$expected_creating_code,
$expected_view_code,
$expected_delete_code,
$expected_update_code
) {
$address = $this->address_1;
$response = $this->prepareRequest($token)->put($this->getBaseUrl($address->id), $address->toArray());
$response->assertStatus($expected_update_code);
}
/**
* @group Addresses
*/
public function testCanUpdateExisting() {
$address = $this->address_1;
$address_new = factory(Address::class)->make(['country_id' => $this->country_2]);
$response = $this->prepareRequest()->put($this->getBaseUrl($address->id), $address_new->toArray());
$response
->assertJsonStructure(['address' => $this->getResponseStructure()])
->assertJson(
['address' =>
[
'id' => $address->id,
'name' => $address_new->name,
'address1' => $address_new->address1,
'address2' => $address_new->address2,
'city' => $address_new->city,
'zip' => $address_new->zip,
'region' => $address_new->region,
'country' => [
'name' => $this->country_2->name,
'alpha3' => $this->country_2->alpha3,
]
]
]
);
$this->assertDatabaseHas($this->table_name, ['id' => $address->id, 'name' => $address_new->name]);
}
/**
* @group Addresses
*/
public function testCanNotUpdateNonExistingAddress() {
$address = $this->address_1;
$non_existing_address_id = 3000;
$response = $this->prepareRequest()->put($this->getBaseUrl($non_existing_address_id), $address->toArray());
$response
->assertStatus(404)
->assertJsonStructure($this->json_error_structure);
}
/**
* @dataProvider providerMissingInvalidArguments
* @group Addresses
*/
public function testCanNotUpdateWhenAuthorizedWithMissingArguments(Array $address_data) {
$address = factory(Address::class)->make($address_data);
$response = $this->prepareRequest($this->api_token_admin_user)->put($this->getBaseUrl(1), $address->toArray());
$response
->assertStatus(422)
->assertJsonStructure($this->json_validation_error_structure);
}
/**
*
*
* Delete tests
*
*
*/
/**
* @dataProvider providerResponseCodeForUserTypeOnValidActionList
* @group Addresses
*/
public function testGetCorrectResponseCodeForDeleting(
$token,
$expected_listing_code,
$expected_creating_code,
$expected_view_code,
$expected_delete_code,
$expected_update_code
) {
$address = $this->address_1;
$response = $this->prepareRequest($token)->delete($this->getBaseUrl($address->id));
$response->assertStatus($expected_delete_code);
}
/**
* @group Addresses
*/
public function testCanDeleteExistingById() {
$address = $this->address_1;
$this->assertDatabaseHas($this->table_name, ['id' => $address->id]);
$response = $this->prepareRequest()->delete($this->getBaseUrl($address->id));
$this->assertDatabaseMissing($this->table_name, ['id' => $address->id]);
$response->assertStatus(200);
}
/**
* @group Addresses
*/
public function testCanDeleteNotExistingMetalById() {
$address_id = 3000;
$this->assertDatabaseMissing($this->table_name, ['id' => $address_id]);
$response = $this->prepareRequest()->delete($this->getBaseUrl($address_id));
$this->assertDatabaseMissing($this->table_name, ['id' => $address_id]);
$response->assertStatus(200);
}
}
| {
"content_hash": "2bedcc0b5da0eed0c1db08161aa2f170",
"timestamp": "",
"source": "github",
"line_count": 396,
"max_line_length": 119,
"avg_line_length": 31.911616161616163,
"alnum_prop": 0.5256785629500672,
"repo_name": "AlexandreBERGIA/LivrOr_V4",
"id": "8bed71b2df1e9d83aad441976991cb97cd60bbd8",
"size": "12637",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Livror_Api/tests/Api/AddressesTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "135678"
},
{
"name": "PHP",
"bytes": "809806"
},
{
"name": "TypeScript",
"bytes": "69732"
},
{
"name": "Vue",
"bytes": "63298"
}
],
"symlink_target": ""
} |
namespace Microsoft.Azure.Management.Monitor.Management.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Monitor;
using Microsoft.Azure.Management.Monitor.Management;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents a collection of diagnostic setting category resources.
/// </summary>
public partial class DiagnosticSettingsCategoryResourceCollection
{
/// <summary>
/// Initializes a new instance of the
/// DiagnosticSettingsCategoryResourceCollection class.
/// </summary>
public DiagnosticSettingsCategoryResourceCollection()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// DiagnosticSettingsCategoryResourceCollection class.
/// </summary>
/// <param name="value">The collection of diagnostic settings category
/// resources.</param>
public DiagnosticSettingsCategoryResourceCollection(IList<DiagnosticSettingsCategoryResource> value = default(IList<DiagnosticSettingsCategoryResource>))
{
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the collection of diagnostic settings category
/// resources.
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<DiagnosticSettingsCategoryResource> Value { get; set; }
}
}
| {
"content_hash": "ef34fca1af835f949ecc4ae2c13161f4",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 161,
"avg_line_length": 34.254901960784316,
"alnum_prop": 0.6514024041213509,
"repo_name": "nathannfan/azure-sdk-for-net",
"id": "3e373ec4948d66ebc8086b738c74a644a761b7a6",
"size": "2059",
"binary": false,
"copies": "6",
"ref": "refs/heads/psSdkJson6",
"path": "src/SDKs/Monitor/Management.Monitor/Generated/Management/Monitor/Models/DiagnosticSettingsCategoryResourceCollection.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118"
},
{
"name": "Batchfile",
"bytes": "37691"
},
{
"name": "C#",
"bytes": "60453879"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "JavaScript",
"bytes": "7875"
},
{
"name": "PowerShell",
"bytes": "21530"
},
{
"name": "Shell",
"bytes": "5829"
},
{
"name": "XSLT",
"bytes": "6114"
}
],
"symlink_target": ""
} |
JGProgressHUD
=============
Simple, powerful and modern progress HUD for iOS.<br>
<p align="center">
<img src="Presentation.png">
</p>
Overview
==========
<b>The ultimate progress HUD for iOS has arrived: JGProgressHUD!</b><br>
• Super simple to implement.<br>
• Feature-rich.<br>
• Easy extensibility and customization (custom animations, indicator views and more).<br>
• Up to date and modern, example: Blurred HUD (iOS 8), parallax effect (iOS 7).<br>
• Backward compatibility to iOS 5.<br>
• Well documented and maintained.<br>
• Detects and repositions when keyboards appear/disappear.<br>
• Voice Over/`UIAccessibility` support.<br>
• And most importantly, it looks good!<br>
<br>
The <a href="Examples">Examples</a> project contains all kinds of different uses of JGProgressHUD. Check out the code and see what JGProgressHUD can do!
<br>
<br>
[](https://github.com/JonasGessner/JGProgressHUD/releases)
[](https://github.com/JonasGessner/JGProgressHUD/blob/master/LICENSE.txt)
[](https://cocoapods.org/pods/JGProgressHUD)
[](https://github.com/Carthage/Carthage)
##Customization:
###Styles:
JGProgressHUD can be displayed in 3 styles:<br>
• <b>Extra Light</b><br>
• <b>Light</b><br>
• <b>Dark</b><br>
###Indicator Views:
By default a HUD will display an indeterminate progress indicator. You can not show an indicator view at all by setting the `indicatorView` property to nil. These indicator views are available:<br>
• <b>Indeterminate progress indicator</b><br>
• <b>Pie progress indicator</b><br>
• <b>Ring progress indicator</b><br>
• <b>Success indicator</b><br>
• <b>Error indicator</b><br>
• <b>Image indicator</b><br>
By subclassing `JGProgressHUDIndicatorView` you can create a custom indicator view!<br>
###Animations:
By default a HUD will use a fade animation. Several parameters can be altered such as animation duration or animation curve. A HUD can be displayed without animation and different animations can be used. By default there are the following animations built in:<br>
• <b>Fade</b><br>
• <b>Zoom and Fade</b><br><br>
By subclassing `JGProgressHUDAnimation` you can create a custom animation!
<br><br>
To dim the content behind the HUD set your dim color as `backgroundColor` of your `JGProgressHUD` instance.
Requirements
=================
• Base SDK of iOS 8 or higher.<br>
• Deployment target of iOS 5.0 or higher.<br>
• ARC.
• JGProgressHUD can also be used by projects written in Swift. See <a href="https://github.com/JonasGessner/JGProgressHUD#installation">Installation</a> for details.
Documentation
================
Detailed documentation can be found on <a href="http://cocoadocs.org/docsets/JGProgressHUD">CocoaDocs</a>.<br><br>
Each method is well documented, making it easy to quickly get a great overview of JGProgressHUD. To start, see <a href="JGProgressHUD/JGProgressHUD/JGProgressHUD.h">JGProgressHUD.h</a>.
Examples
=================
#####Showing indeterminate progress:
```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.textLabel.text = @"Loading";
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```
This displays a dark HUD with a spinner and the title "Loading", it is presented with a fade animation and is dismissed after 3 seconds with a fade animation.
<br>
#####Showing an error message:
```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.textLabel.text = @"Error";
HUD.indicatorView = [[JGProgressHUDErrorIndicatorView alloc] init]; //JGProgressHUDSuccessIndicatorView is also available
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```
#####Showing a custom image:
```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.indicatorView = [[JGProgressHUDImageIndicatorView alloc] initWithImage:[UIImage imageNamed:@"my_image.png"]];
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```
#####Showing determinate progress:
```objc
JGProgressHUD *HUD = [JGProgressHUD progressHUDWithStyle:JGProgressHUDStyleDark];
HUD.indicatorView = [[JGProgressHUDPieIndicatorView alloc] initWithHUDStyle:HUD.style]; //Or JGProgressHUDRingIndicatorView
[HUD showInView:self.view];
[HUD dismissAfterDelay:3.0];
```
<br>
<b>Important:</b> You should always show HUDs in a UIViewController's view.
<br><br>
See the <a href="Examples">Examples</a> project for more example implementations.
Installation
================
<b>CocoaPods:</b><br>
Add this to your `Podfile`:
```
pod 'JGProgressHUD'
```
<br>
OR:
<br><br>
<b>Carthage:</b><br>
Add this to your `Cartfile`:
```
github "JonasGessner/JGProgressHUD" >= 1.3.1
```
<br>
OR:
<br><br>
<b>Framework (iOS >= 8.0 only):</b><br>
1. Drag the `JGProgressHUD.xcodeproj` file into your Xcode project.<br>
2. Add `JGProgressHUD.framework` to "Embedded Binaries" in the "General" tab of your project's target.<br>
3. Add the `-ObjC` flag to "Other Linker Flags" in the "Build Settings" tab of your project's target.<br><br>
See the <a href="Examples">Examples</a> project for an example implementation of JGProgressHUD as framework.
<br><br>
After you have included JGProgressHUD as framework simply import `JGProgressHUD.h` like this:
```objc
#import <JGProgressHUD/JGProgressHUD.h>
```
Swift projects:
```swift
import JGProgressHUD
```
<br><br>
OR:
<br><br>
<b>Static Library:</b><br>
1. Drag the `JGProgressHUD.xcodeproj` file into your Xcode project.<br>
2. Add `JGProgressHUD` and `JGProgressHUD Resources` to "Target Dependencies" in the "Build Phases" tab of your project's target.<br>
3. Add `libJGProgressHUD.a` to "Link Binary With Libraries".<br>
4. From the `JGProgressHUD.xcodeproj`'s "Products" Directory drag the `JGProgressHUD Resources.bundle` into the "Copy Bundle Resources" section.<br>
5. Add the `-ObjC` flag to "Other Linker Flags" in the "Build Settings" tab of your project's target.<br><br>
See the <a href="Examples">Examples</a> project for an example implementation of JGProgressHUD as static library.
<br><br>
After you have included JGProgressHUD as static library simply import `JGProgressHUD.h` like this:
```objc
#import "JGProgressHUD.h"
```
Swift projects need to import JGProgressHUD in the Objective-C bridging header.
<br><br>
####RubyMotion
An example of JGProgressHUD in a RubyMotion project can be found [here](https://github.com/IconoclastLabs/rm-jgprogresshud-example).
Screenshots
============
<p align="center">
<img src="Examples/Screenshots/1.png" width="24%">
<img src="Examples/Screenshots/3.png" width="24%">
<img src="Examples/Screenshots/6.png" width="24%">
<img src="Examples/Screenshots/5.png" width="24%">
</p>
License
==========
MIT License.<br>
© 2014-2015, Jonas Gessner.
Credits
==========
Created and maintained by Jonas Gessner, © 2014-2015.<br>
| {
"content_hash": "f0185ea805fe833c82652ddc940d1411",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 263,
"avg_line_length": 40.39204545454545,
"alnum_prop": 0.7425798283865522,
"repo_name": "yesidi/MVCBase",
"id": "045bcfc5c07292f237c3e5a2cd80ee89cd7a4e4b",
"size": "7159",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "MVCBase/Pods/JGProgressHUD/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "643592"
},
{
"name": "Ruby",
"bytes": "130"
},
{
"name": "Shell",
"bytes": "8351"
},
{
"name": "Swift",
"bytes": "25152"
}
],
"symlink_target": ""
} |
module.exports = {
policy: require('./auth'),
schema: {}
};
| {
"content_hash": "7d09a78a397dad5f68c46cccbeb26415",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 28,
"avg_line_length": 16,
"alnum_prop": 0.5625,
"repo_name": "srcnix/express-gateway",
"id": "76e05fc92f35f56d19cd6a9c31ecf4270a7f8d9f",
"size": "64",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/policies/basic-auth/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "806"
},
{
"name": "JavaScript",
"bytes": "615258"
}
],
"symlink_target": ""
} |
license: >
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
---
# globalization.getDateNames
返回一個陣列的幾個月的名稱或一周內,根據用戶端的使用者首選項和日曆天。
navigator.globalization.getDateNames(successCallback, errorCallback, options);
## 說明
返回的陣列的名稱為 `successCallback` 與 `properties` 物件作為參數。 該物件包含 `value` 屬性與 `Array` 的 `String` 的值。 從任一開始一年或一周內,根據所選的選項的第一天中的第一個月的陣列功能名稱。
如果有錯誤取得名字,然後 `errorCallback` 執行與 `GlobalizationError` 物件作為參數。 錯誤的期望的代碼`GlobalizationError.UNKNOWN\_ERROR`.
`options`參數是可選的且其預設值:
{類型: '寬'、 專案: '月'}
值 `options.type` 可以是 `narrow` 或`wide`.
值 `options.item` 可以是 `months` 或`days`.
## 支援的平臺
* Android 系統
* 黑莓手機 WebWorks (OS 5.0 和更高)
* iOS
* Windows Phone 8
## 快速的示例
當瀏覽器設置為 `en\_US` 的地區設定,本示例顯示一系列的十二個彈出對話方塊,每個月,與類似的文本一個 `month: January` :
navigator.globalization.getDateNames(
function (names) {
for (var i = 0; i < names.value.length; i++) {
alert('month: ' + names.value[i] + '\n');
}
},
function () { alert('Error getting names\n'); },
{ type: 'wide', item: 'months' }
);
## 完整的示例
<!DOCTYPE HTML>
<html>
<head>
<title>getDateNames Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function checkDateNames() {
navigator.globalization.getDateNames(
function (names) {
for (var i=0; i<names.value.length; i++) {
alert('month: ' + names.value[i] + '\n');
}
},
function () {alert('Error getting names\n');},
{type:'wide', item:'months'}
);
}
</script>
</head>
<body>
<button onclick="checkDateNames()">Click for date names</button>
</body>
</html> | {
"content_hash": "94312d81a41d9fdf0364a48053942c8a",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 129,
"avg_line_length": 29.2,
"alnum_prop": 0.625951293759513,
"repo_name": "drbeermann/cordova-docs",
"id": "2d8bd48c9bc453e2c026cfa1c40628116a5622c0",
"size": "3102",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "docs/zh/3.1.0/cordova/globalization/globalization.getDateNames.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5116"
},
{
"name": "CSS",
"bytes": "11129"
},
{
"name": "HTML",
"bytes": "113105"
},
{
"name": "JavaScript",
"bytes": "69082"
}
],
"symlink_target": ""
} |
package hudson;
import hudson.model.TaskListener;
import jenkins.model.Jenkins;
import static hudson.util.jna.GNUCLibrary.LIBC;
import hudson.util.IOException2;
import hudson.util.QuotedStringTokenizer;
import hudson.util.VariableResolver;
import hudson.Proc.LocalProc;
import hudson.os.PosixAPI;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.taskdefs.Chmod;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.io.IOUtils;
import org.jruby.ext.posix.FileStat;
import org.jruby.ext.posix.POSIX;
import org.kohsuke.stapler.Stapler;
import org.jvnet.animal_sniffer.IgnoreJRERequirement;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.SimpleTimeZone;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.charset.Charset;
import com.sun.jna.Native;
import com.sun.jna.Memory;
import com.sun.jna.NativeLong;
/**
* Various utility methods that don't have more proper home.
*
* @author Kohsuke Kawaguchi
*/
public class Util {
// Constant number of milliseconds in various time units.
private static final long ONE_SECOND_MS = 1000;
private static final long ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
private static final long ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
private static final long ONE_DAY_MS = 24 * ONE_HOUR_MS;
private static final long ONE_MONTH_MS = 30 * ONE_DAY_MS;
private static final long ONE_YEAR_MS = 365 * ONE_DAY_MS;
/**
* Creates a filtered sublist.
* @since 1.176
*/
public static <T> List<T> filter( Iterable<?> base, Class<T> type ) {
List<T> r = new ArrayList<T>();
for (Object i : base) {
if(type.isInstance(i))
r.add(type.cast(i));
}
return r;
}
/**
* Creates a filtered sublist.
*/
public static <T> List<T> filter( List<?> base, Class<T> type ) {
return filter((Iterable)base,type);
}
/**
* Pattern for capturing variables. Either $xyz or ${xyz}, while ignoring "$$"
*/
private static final Pattern VARIABLE = Pattern.compile("\\$([A-Za-z0-9_]+|\\{[A-Za-z0-9_]+\\}|\\$)");
/**
* Replaces the occurrence of '$key' by <tt>properties.get('key')</tt>.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*
*/
public static String replaceMacro(String s, Map<String,String> properties) {
return replaceMacro(s,new VariableResolver.ByMap<String>(properties));
}
/**
* Replaces the occurrence of '$key' by <tt>resolver.get('key')</tt>.
*
* <p>
* Unlike shell, undefined variables are left as-is (this behavior is the same as Ant.)
*/
public static String replaceMacro(String s, VariableResolver<String> resolver) {
if (s == null) {
return null;
}
int idx=0;
while(true) {
Matcher m = VARIABLE.matcher(s);
if(!m.find(idx)) return s;
String key = m.group().substring(1);
// escape the dollar sign or get the key to resolve
String value;
if(key.charAt(0)=='$') {
value = "$";
} else {
if(key.charAt(0)=='{') key = key.substring(1,key.length()-1);
value = resolver.resolve(key);
}
if(value==null)
idx = m.end(); // skip this
else {
s = s.substring(0,m.start())+value+s.substring(m.end());
idx = m.start() + value.length();
}
}
}
/**
* Loads the contents of a file into a string.
*/
public static String loadFile(File logfile) throws IOException {
return loadFile(logfile, Charset.defaultCharset());
}
public static String loadFile(File logfile,Charset charset) throws IOException {
if(!logfile.exists())
return "";
StringBuilder str = new StringBuilder((int)logfile.length());
BufferedReader r = new BufferedReader(new InputStreamReader(new FileInputStream(logfile),charset));
try {
char[] buf = new char[1024];
int len;
while((len=r.read(buf,0,buf.length))>0)
str.append(buf,0,len);
} finally {
r.close();
}
return str.toString();
}
/**
* Deletes the contents of the given directory (but not the directory itself)
* recursively.
*
* @throws IOException
* if the operation fails.
*/
public static void deleteContentsRecursive(File file) throws IOException {
File[] files = file.listFiles();
if(files==null)
return; // the directory didn't exist in the first place
for (File child : files)
deleteRecursive(child);
}
/**
* Deletes this file (and does not take no for an answer).
* @param f a file to delete
* @throws IOException if it exists but could not be successfully deleted
*/
public static void deleteFile(File f) throws IOException {
if (!f.delete()) {
if(!f.exists())
// we are trying to delete a file that no longer exists, so this is not an error
return;
// perhaps this file is read-only?
makeWritable(f);
/*
on Unix both the file and the directory that contains it has to be writable
for a file deletion to be successful. (Confirmed on Solaris 9)
$ ls -la
total 6
dr-xr-sr-x 2 hudson hudson 512 Apr 18 14:41 .
dr-xr-sr-x 3 hudson hudson 512 Apr 17 19:36 ..
-r--r--r-- 1 hudson hudson 469 Apr 17 19:36 manager.xml
-rw-r--r-- 1 hudson hudson 0 Apr 18 14:41 x
$ rm x
rm: x not removed: Permission denied
*/
makeWritable(f.getParentFile());
if(!f.delete() && f.exists()) {
// trouble-shooting.
// see http://www.nabble.com/Sometimes-can%27t-delete-files-from-hudson.scm.SubversionSCM%24CheckOutTask.invoke%28%29-tt17333292.html
// I suspect other processes putting files in this directory
File[] files = f.listFiles();
if(files!=null && files.length>0)
throw new IOException("Unable to delete " + f.getPath()+" - files in dir: "+Arrays.asList(files));
throw new IOException("Unable to delete " + f.getPath());
}
}
}
/**
* Makes the given file writable by any means possible.
*/
@IgnoreJRERequirement
private static void makeWritable(File f) {
// try chmod. this becomes no-op if this is not Unix.
try {
Chmod chmod = new Chmod();
chmod.setProject(new Project());
chmod.setFile(f);
chmod.setPerm("u+w");
chmod.execute();
} catch (BuildException e) {
LOGGER.log(Level.INFO,"Failed to chmod "+f,e);
}
// also try JDK6-way of doing it.
try {
f.setWritable(true);
} catch (NoSuchMethodError e) {
// not JDK6
}
try {// try libc chmod
POSIX posix = PosixAPI.get();
String path = f.getAbsolutePath();
FileStat stat = posix.stat(path);
posix.chmod(path, stat.mode()|0200); // u+w
} catch (Throwable t) {
LOGGER.log(Level.FINE,"Failed to chmod(2) "+f,t);
}
}
public static void deleteRecursive(File dir) throws IOException {
if(!isSymlink(dir))
deleteContentsRecursive(dir);
try {
deleteFile(dir);
} catch (IOException e) {
// if some of the child directories are big, it might take long enough to delete that
// it allows others to create new files, causing problemsl ike JENKINS-10113
// so give it one more attempt before we give up.
if(!isSymlink(dir))
deleteContentsRecursive(dir);
deleteFile(dir);
}
}
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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.
*/
/**
* Checks if the given file represents a symlink.
*/
//Taken from http://svn.apache.org/viewvc/maven/shared/trunk/file-management/src/main/java/org/apache/maven/shared/model/fileset/util/FileSetManager.java?view=markup
public static boolean isSymlink(File file) throws IOException {
String name = file.getName();
if (name.equals(".") || name.equals(".."))
return false;
File fileInCanonicalParent;
File parentDir = file.getParentFile();
if ( parentDir == null ) {
fileInCanonicalParent = file;
} else {
fileInCanonicalParent = new File( parentDir.getCanonicalPath(), name );
}
return !fileInCanonicalParent.getCanonicalFile().equals( fileInCanonicalParent.getAbsoluteFile() );
}
/**
* Creates a new temporary directory.
*/
public static File createTempDir() throws IOException {
File tmp = File.createTempFile("hudson", "tmp");
if(!tmp.delete())
throw new IOException("Failed to delete "+tmp);
if(!tmp.mkdirs())
throw new IOException("Failed to create a new directory "+tmp);
return tmp;
}
private static final Pattern errorCodeParser = Pattern.compile(".*CreateProcess.*error=([0-9]+).*");
/**
* On Windows, error messages for IOException aren't very helpful.
* This method generates additional user-friendly error message to the listener
*/
public static void displayIOException( IOException e, TaskListener listener ) {
String msg = getWin32ErrorMessage(e);
if(msg!=null)
listener.getLogger().println(msg);
}
public static String getWin32ErrorMessage(IOException e) {
return getWin32ErrorMessage((Throwable)e);
}
/**
* Extracts the Win32 error message from {@link Throwable} if possible.
*
* @return
* null if there seems to be no error code or if the platform is not Win32.
*/
public static String getWin32ErrorMessage(Throwable e) {
String msg = e.getMessage();
if(msg!=null) {
Matcher m = errorCodeParser.matcher(msg);
if(m.matches()) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error"+m.group(1));
} catch (Exception _) {
// silently recover from resource related failures
}
}
}
if(e.getCause()!=null)
return getWin32ErrorMessage(e.getCause());
return null; // no message
}
/**
* Gets a human readable message for the given Win32 error code.
*
* @return
* null if no such message is available.
*/
public static String getWin32ErrorMessage(int n) {
try {
ResourceBundle rb = ResourceBundle.getBundle("/hudson/win32errors");
return rb.getString("error"+n);
} catch (MissingResourceException e) {
LOGGER.log(Level.WARNING,"Failed to find resource bundle",e);
return null;
}
}
/**
* Guesses the current host name.
*/
public static String getHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "localhost";
}
}
public static void copyStream(InputStream in,OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
}
public static void copyStream(Reader in, Writer out) throws IOException {
char[] buf = new char[8192];
int len;
while((len=in.read(buf))>0)
out.write(buf,0,len);
}
public static void copyStreamAndClose(InputStream in,OutputStream out) throws IOException {
try {
copyStream(in,out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
public static void copyStreamAndClose(Reader in,Writer out) throws IOException {
try {
copyStream(in,out);
} finally {
IOUtils.closeQuietly(in);
IOUtils.closeQuietly(out);
}
}
/**
* Tokenizes the text separated by delimiters.
*
* <p>
* In 1.210, this method was changed to handle quotes like Unix shell does.
* Before that, this method just used {@link StringTokenizer}.
*
* @since 1.145
* @see QuotedStringTokenizer
*/
public static String[] tokenize(String s,String delimiter) {
return QuotedStringTokenizer.tokenize(s,delimiter);
}
public static String[] tokenize(String s) {
return tokenize(s," \t\n\r\f");
}
/**
* Converts the map format of the environment variables to the K=V format in the array.
*/
public static String[] mapToEnv(Map<String,String> m) {
String[] r = new String[m.size()];
int idx=0;
for (final Map.Entry<String,String> e : m.entrySet()) {
r[idx++] = e.getKey() + '=' + e.getValue();
}
return r;
}
public static int min(int x, int... values) {
for (int i : values) {
if(i<x)
x=i;
}
return x;
}
public static String nullify(String v) {
if(v!=null && v.length()==0) v=null;
return v;
}
public static String removeTrailingSlash(String s) {
if(s.endsWith("/")) return s.substring(0,s.length()-1);
else return s;
}
/**
* Computes MD5 digest of the given input stream.
*
* @param source
* The stream will be closed by this method at the end of this method.
* @return
* 32-char wide string
*/
public static String getDigestOf(InputStream source) throws IOException {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
DigestInputStream in =new DigestInputStream(source,md5);
try {
while(in.read(buffer)>0)
; // simply discard the input
} finally {
in.close();
}
return toHexString(md5.digest());
} catch (NoSuchAlgorithmException e) {
throw new IOException2("MD5 not installed",e); // impossible
}
}
public static String getDigestOf(String text) {
try {
return getDigestOf(new ByteArrayInputStream(text.getBytes("UTF-8")));
} catch (IOException e) {
throw new Error(e);
}
}
/**
* Converts a string into 128-bit AES key.
* @since 1.308
*/
public static SecretKey toAes128Key(String s) {
try {
// turn secretKey into 256 bit hash
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(s.getBytes("UTF-8"));
// Due to the stupid US export restriction JDK only ships 128bit version.
return new SecretKeySpec(digest.digest(),0,128/8, "AES");
} catch (NoSuchAlgorithmException e) {
throw new Error(e);
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
public static String toHexString(byte[] data, int start, int len) {
StringBuilder buf = new StringBuilder();
for( int i=0; i<len; i++ ) {
int b = data[start+i]&0xFF;
if(b<16) buf.append('0');
buf.append(Integer.toHexString(b));
}
return buf.toString();
}
public static String toHexString(byte[] bytes) {
return toHexString(bytes,0,bytes.length);
}
public static byte[] fromHexString(String data) {
byte[] r = new byte[data.length() / 2];
for (int i = 0; i < data.length(); i += 2)
r[i / 2] = (byte) Integer.parseInt(data.substring(i, i + 2), 16);
return r;
}
/**
* Returns a human readable text of the time duration, for example "3 minutes 40 seconds".
* This version should be used for representing a duration of some activity (like build)
*
* @param duration
* number of milliseconds.
*/
public static String getTimeSpanString(long duration) {
// Break the duration up in to units.
long years = duration / ONE_YEAR_MS;
duration %= ONE_YEAR_MS;
long months = duration / ONE_MONTH_MS;
duration %= ONE_MONTH_MS;
long days = duration / ONE_DAY_MS;
duration %= ONE_DAY_MS;
long hours = duration / ONE_HOUR_MS;
duration %= ONE_HOUR_MS;
long minutes = duration / ONE_MINUTE_MS;
duration %= ONE_MINUTE_MS;
long seconds = duration / ONE_SECOND_MS;
duration %= ONE_SECOND_MS;
long millisecs = duration;
if (years > 0)
return makeTimeSpanString(years, Messages.Util_year(years), months, Messages.Util_month(months));
else if (months > 0)
return makeTimeSpanString(months, Messages.Util_month(months), days, Messages.Util_day(days));
else if (days > 0)
return makeTimeSpanString(days, Messages.Util_day(days), hours, Messages.Util_hour(hours));
else if (hours > 0)
return makeTimeSpanString(hours, Messages.Util_hour(hours), minutes, Messages.Util_minute(minutes));
else if (minutes > 0)
return makeTimeSpanString(minutes, Messages.Util_minute(minutes), seconds, Messages.Util_second(seconds));
else if (seconds >= 10)
return Messages.Util_second(seconds);
else if (seconds >= 1)
return Messages.Util_second(seconds+(float)(millisecs/100)/10); // render "1.2 sec"
else if(millisecs>=100)
return Messages.Util_second((float)(millisecs/10)/100); // render "0.12 sec".
else
return Messages.Util_millisecond(millisecs);
}
/**
* Create a string representation of a time duration. If the quantity of
* the most significant unit is big (>=10), then we use only that most
* significant unit in the string representation. If the quantity of the
* most significant unit is small (a single-digit value), then we also
* use a secondary, smaller unit for increased precision.
* So 13 minutes and 43 seconds returns just "13 minutes", but 3 minutes
* and 43 seconds is "3 minutes 43 seconds".
*/
private static String makeTimeSpanString(long bigUnit,
String bigLabel,
long smallUnit,
String smallLabel) {
String text = bigLabel;
if (bigUnit < 10)
text += ' ' + smallLabel;
return text;
}
/**
* Get a human readable string representing strings like "xxx days ago",
* which should be used to point to the occurrence of an event in the past.
*/
public static String getPastTimeString(long duration) {
return Messages.Util_pastTime(getTimeSpanString(duration));
}
/**
* Combines number and unit, with a plural suffix if needed.
*
* @deprecated
* Use individual localization methods instead.
* See {@link Messages#Util_year(Object)} for an example.
* Deprecated since 2009-06-24, remove method after 2009-12-24.
*/
public static String combine(long n, String suffix) {
String s = Long.toString(n)+' '+suffix;
if(n!=1)
// Just adding an 's' won't work in most natural languages, even English has exception to the rule (e.g. copy/copies).
s += "s";
return s;
}
/**
* Create a sub-list by only picking up instances of the specified type.
*/
public static <T> List<T> createSubList( Collection<?> source, Class<T> type ) {
List<T> r = new ArrayList<T>();
for (Object item : source) {
if(type.isInstance(item))
r.add(type.cast(item));
}
return r;
}
/**
* Escapes non-ASCII characters in URL.
*
* <p>
* Note that this methods only escapes non-ASCII but leaves other URL-unsafe characters,
* such as '#'.
* {@link #rawEncode(String)} should generally be used instead, though be careful to pass only
* a single path component to that method (it will encode /, but this method does not).
*/
public static String encode(String s) {
try {
boolean escaped = false;
StringBuilder out = new StringBuilder(s.length());
ByteArrayOutputStream buf = new ByteArrayOutputStream();
OutputStreamWriter w = new OutputStreamWriter(buf,"UTF-8");
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i);
if (c<128 && c!=' ') {
out.append((char) c);
} else {
// 1 char -> UTF8
w.write(c);
w.flush();
for (byte b : buf.toByteArray()) {
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
buf.reset();
escaped = true;
}
}
return escaped ? out.toString() : s;
} catch (IOException e) {
throw new Error(e); // impossible
}
}
private static final boolean[] uriMap = new boolean[123];
static {
String raw =
"! $ &'()*+,-. 0123456789 = @ABCDEFGHIJKLMNOPQRSTUVWXYZ _ abcdefghijklmnopqrstuvwxyz";
// "# % / :;< >? [\]^ ` {|}~
// ^--so these are encoded
int i;
// Encode control chars and space
for (i = 0; i < 33; i++) uriMap[i] = true;
for (int j = 0; j < raw.length(); i++, j++)
uriMap[i] = (raw.charAt(j) == ' ');
// If we add encodeQuery() just add a 2nd map to encode &+=
// queryMap[38] = queryMap[43] = queryMap[61] = true;
}
/**
* Encode a single path component for use in an HTTP URL.
* Escapes all non-ASCII, general unsafe (space and "#%<>[\]^`{|}~)
* and HTTP special characters (/;:?) as specified in RFC1738.
* (so alphanumeric and !@$&*()-_=+',. are not encoded)
* Note that slash(/) is encoded, so the given string should be a
* single path component used in constructing a URL.
* Method name inspired by PHP's rawurlencode.
*/
public static String rawEncode(String s) {
boolean escaped = false;
StringBuilder out = null;
CharsetEncoder enc = null;
CharBuffer buf = null;
char c;
for (int i = 0, m = s.length(); i < m; i++) {
c = s.charAt(i);
if (c > 122 || uriMap[c]) {
if (!escaped) {
out = new StringBuilder(i + (m - i) * 3);
out.append(s.substring(0, i));
enc = Charset.forName("UTF-8").newEncoder();
buf = CharBuffer.allocate(1);
escaped = true;
}
// 1 char -> UTF8
buf.put(0,c);
buf.rewind();
try {
ByteBuffer bytes = enc.encode(buf);
while (bytes.hasRemaining()) {
byte b = bytes.get();
out.append('%');
out.append(toDigit((b >> 4) & 0xF));
out.append(toDigit(b & 0xF));
}
} catch (CharacterCodingException ex) { }
} else if (escaped) {
out.append(c);
}
}
return escaped ? out.toString() : s;
}
private static char toDigit(int n) {
return (char)(n < 10 ? '0' + n : 'A' + n - 10);
}
/**
* Surrounds by a single-quote.
*/
public static String singleQuote(String s) {
return '\''+s+'\'';
}
/**
* Escapes HTML unsafe characters like <, & to the respective character entities.
*/
public static String escape(String text) {
if (text==null) return null;
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='\n')
buf.append("<br>");
else
if(ch=='<')
buf.append("<");
else
if(ch=='&')
buf.append("&");
else
if(ch=='"')
buf.append(""");
else
if(ch=='\'')
buf.append("'");
else
if(ch==' ') {
// All spaces in a block of consecutive spaces are converted to
// non-breaking space ( ) except for the last one. This allows
// significant whitespace to be retained without prohibiting wrapping.
char nextCh = i+1 < text.length() ? text.charAt(i+1) : 0;
buf.append(nextCh==' ' ? " " : " ");
}
else
buf.append(ch);
}
return buf.toString();
}
public static String xmlEscape(String text) {
StringBuilder buf = new StringBuilder(text.length()+64);
for( int i=0; i<text.length(); i++ ) {
char ch = text.charAt(i);
if(ch=='<')
buf.append("<");
else
if(ch=='&')
buf.append("&");
else
buf.append(ch);
}
return buf.toString();
}
/**
* Creates an empty file.
*/
public static void touch(File file) throws IOException {
new FileOutputStream(file).close();
}
/**
* Copies a single file by using Ant.
*/
public static void copyFile(File src, File dst) throws BuildException {
Copy cp = new Copy();
cp.setProject(new org.apache.tools.ant.Project());
cp.setTofile(dst);
cp.setFile(src);
cp.setOverwrite(true);
cp.execute();
}
/**
* Convert null to "".
*/
public static String fixNull(String s) {
if(s==null) return "";
else return s;
}
/**
* Convert empty string to null.
*/
public static String fixEmpty(String s) {
if(s==null || s.length()==0) return null;
return s;
}
/**
* Convert empty string to null, and trim whitespace.
*
* @since 1.154
*/
public static String fixEmptyAndTrim(String s) {
if(s==null) return null;
return fixEmpty(s.trim());
}
public static <T> List<T> fixNull(List<T> l) {
return l!=null ? l : Collections.<T>emptyList();
}
public static <T> Set<T> fixNull(Set<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
public static <T> Collection<T> fixNull(Collection<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
public static <T> Iterable<T> fixNull(Iterable<T> l) {
return l!=null ? l : Collections.<T>emptySet();
}
/**
* Cuts all the leading path portion and get just the file name.
*/
public static String getFileName(String filePath) {
int idx = filePath.lastIndexOf('\\');
if(idx>=0)
return getFileName(filePath.substring(idx+1));
idx = filePath.lastIndexOf('/');
if(idx>=0)
return getFileName(filePath.substring(idx+1));
return filePath;
}
/**
* Concatenate multiple strings by inserting a separator.
*/
public static String join(Collection<?> strings, String separator) {
StringBuilder buf = new StringBuilder();
boolean first=true;
for (Object s : strings) {
if(first) first=false;
else buf.append(separator);
buf.append(s);
}
return buf.toString();
}
/**
* Combines all the given collections into a single list.
*/
public static <T> List<T> join(Collection<? extends T>... items) {
int size = 0;
for (Collection<? extends T> item : items)
size += item.size();
List<T> r = new ArrayList<T>(size);
for (Collection<? extends T> item : items)
r.addAll(item);
return r;
}
/**
* Creates Ant {@link FileSet} with the base dir and include pattern.
*
* <p>
* The difference with this and using {@link FileSet#setIncludes(String)}
* is that this method doesn't treat whitespace as a pattern separator,
* which makes it impossible to use space in the file path.
*
* @param includes
* String like "foo/bar/*.xml" Multiple patterns can be separated
* by ',', and whitespace can surround ',' (so that you can write
* "abc, def" and "abc,def" to mean the same thing.
* @param excludes
* Exclusion pattern. Follows the same format as the 'includes' parameter.
* Can be null.
* @since 1.172
*/
public static FileSet createFileSet(File baseDir, String includes, String excludes) {
FileSet fs = new FileSet();
fs.setDir(baseDir);
fs.setProject(new Project());
StringTokenizer tokens;
tokens = new StringTokenizer(includes,",");
while(tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
fs.createInclude().setName(token);
}
if(excludes!=null) {
tokens = new StringTokenizer(excludes,",");
while(tokens.hasMoreTokens()) {
String token = tokens.nextToken().trim();
fs.createExclude().setName(token);
}
}
return fs;
}
public static FileSet createFileSet(File baseDir, String includes) {
return createFileSet(baseDir,includes,null);
}
/**
* Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
* <p>
* If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
*
* @param baseDir
* Base directory to resolve the 'symlinkPath' parameter.
* @param targetPath
* The file that the symlink should point to.
* @param symlinkPath
* Where to create a symlink in.
*/
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener) throws InterruptedException {
if(Functions.isWindows() || NO_SYMLINK) return;
try {
String errmsg = "";
// if a file or a directory exists here, delete it first.
// try simple delete first (whether exists() or not, as it may be symlink pointing
// to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
File symlinkFile = new File(baseDir, symlinkPath);
if (!symlinkFile.delete() && symlinkFile.exists())
// ignore a failure.
new LocalProc(new String[]{"rm","-rf", symlinkPath},new String[0],listener.getLogger(), baseDir).join();
int r;
if (!SYMLINK_ESCAPEHATCH) {
try {
r = LIBC.symlink(targetPath,symlinkFile.getAbsolutePath());
if (r!=0) {
r = Native.getLastError();
errmsg = LIBC.strerror(r);
}
} catch (LinkageError e) {
// if JNA is unavailable, fall back.
// we still prefer to try JNA first as PosixAPI supports even smaller platforms.
r = PosixAPI.get().symlink(targetPath,symlinkFile.getAbsolutePath());
}
} else // escape hatch, until we know that the above works well.
r = new LocalProc(new String[]{
"ln","-s", targetPath, symlinkPath},
new String[0],listener.getLogger(), baseDir).join();
if(r!=0)
listener.getLogger().println(String.format("ln -s %s %s failed: %d %s",targetPath, symlinkFile, r, errmsg));
} catch (IOException e) {
PrintStream log = listener.getLogger();
log.printf("ln %s %s failed%n",targetPath, new File(baseDir, symlinkPath));
Util.displayIOException(e,listener);
e.printStackTrace( log );
}
}
/**
* Resolves symlink, if the given file is a symlink. Otherwise return null.
* <p>
* If the resolution fails, report an error.
*
* @param listener
* If we rely on an external command to resolve symlink, this is it.
* (TODO: try readlink(1) available on some platforms)
*/
public static String resolveSymlink(File link, TaskListener listener) throws InterruptedException, IOException {
if(Functions.isWindows()) return null;
String filename = link.getAbsolutePath();
try {
for (int sz=512; sz < 65536; sz*=2) {
Memory m = new Memory(sz);
int r = LIBC.readlink(filename,m,new NativeLong(sz));
if (r<0) {
int err = Native.getLastError();
if (err==22/*EINVAL --- but is this really portable?*/)
return null; // this means it's not a symlink
throw new IOException("Failed to readlink "+link+" error="+ err+" "+ LIBC.strerror(err));
}
if (r==sz)
continue; // buffer too small
byte[] buf = new byte[r];
m.read(0,buf,0,r);
return new String(buf);
}
// something is wrong. It can't be this long!
throw new IOException("Symlink too long: "+link);
} catch (LinkageError e) {
// if JNA is unavailable, fall back.
// we still prefer to try JNA first as PosixAPI supports even smaller platforms.
return PosixAPI.get().readlink(filename);
}
}
/**
* Encodes the URL by RFC 2396.
*
* I thought there's another spec that refers to UTF-8 as the encoding,
* but don't remember it right now.
*
* @since 1.204
* @deprecated since 2008-05-13. This method is broken (see ISSUE#1666). It should probably
* be removed but I'm not sure if it is considered part of the public API
* that needs to be maintained for backwards compatibility.
* Use {@link #encode(String)} instead.
*/
@Deprecated
public static String encodeRFC2396(String url) {
try {
return new URI(null,url,null).toASCIIString();
} catch (URISyntaxException e) {
LOGGER.warning("Failed to encode "+url); // could this ever happen?
return url;
}
}
/**
* Wraps with the error icon and the CSS class to render error message.
* @since 1.173
*/
public static String wrapToErrorSpan(String s) {
s = "<span class=error><img src='"+
Stapler.getCurrentRequest().getContextPath()+ Jenkins.RESOURCE_PATH+
"/images/none.gif' height=16 width=1>"+s+"</span>";
return s;
}
/**
* Returns the parsed string if parsed successful; otherwise returns the default number.
* If the string is null, empty or a ParseException is thrown then the defaultNumber
* is returned.
* @param numberStr string to parse
* @param defaultNumber number to return if the string can not be parsed
* @return returns the parsed string; otherwise the default number
*/
public static Number tryParseNumber(String numberStr, Number defaultNumber) {
if ((numberStr == null) || (numberStr.length() == 0)) {
return defaultNumber;
}
try {
return NumberFormat.getNumberInstance().parse(numberStr);
} catch (ParseException e) {
return defaultNumber;
}
}
/**
* Checks if the public method defined on the base type with the given arguments
* are overridden in the given derived type.
*/
public static boolean isOverridden(Class base, Class derived, String methodName, Class... types) {
// the rewriteHudsonWar method isn't overridden.
try {
return !base.getMethod(methodName, types).equals(
derived.getMethod(methodName,types));
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
/**
* Returns a file name by changing its extension.
*
* @param ext
* For example, ".zip"
*/
public static File changeExtension(File dst, String ext) {
String p = dst.getPath();
int pos = p.lastIndexOf('.');
if (pos<0) return new File(p+ext);
else return new File(p.substring(0,pos)+ext);
}
/**
* Null-safe String intern method.
*/
public static String intern(String s) {
return s==null ? s : s.intern();
}
/**
* Loads a key/value pair string as {@link Properties}
* @since 1.392
*/
@IgnoreJRERequirement
public static Properties loadProperties(String properties) throws IOException {
Properties p = new Properties();
try {
p.load(new StringReader(properties));
} catch (NoSuchMethodError e) {
// load(Reader) method is only available on JDK6.
// this fall back version doesn't work correctly with non-ASCII characters,
// but there's no other easy ways out it seems.
p.load(new ByteArrayInputStream(properties.getBytes()));
}
return p;
}
public static final FastDateFormat XS_DATETIME_FORMATTER = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'",new SimpleTimeZone(0,"GMT"));
// Note: RFC822 dates must not be localized!
public static final FastDateFormat RFC822_DATETIME_FORMATTER
= FastDateFormat.getInstance("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
private static final Logger LOGGER = Logger.getLogger(Util.class.getName());
/**
* On Unix environment that cannot run "ln", set this to true.
*/
public static boolean NO_SYMLINK = Boolean.getBoolean(Util.class.getName()+".noSymLink");
public static boolean SYMLINK_ESCAPEHATCH = Boolean.getBoolean(Util.class.getName()+".symlinkEscapeHatch");
}
| {
"content_hash": "32247a84336fd0336cb5b5484d0a8096",
"timestamp": "",
"source": "github",
"line_count": 1185,
"max_line_length": 169,
"avg_line_length": 35.01350210970464,
"alnum_prop": 0.5694969993492565,
"repo_name": "mrobinet/jenkins",
"id": "c1f54fb8446c5faf953c037a71653ac8b8c52efe",
"size": "42664",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/src/main/java/hudson/Util.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2091"
},
{
"name": "Groovy",
"bytes": "73801"
},
{
"name": "Java",
"bytes": "5958800"
},
{
"name": "JavaScript",
"bytes": "115678"
},
{
"name": "Perl",
"bytes": "13335"
},
{
"name": "Python",
"bytes": "2169"
},
{
"name": "Ruby",
"bytes": "4152"
},
{
"name": "Shell",
"bytes": "61019"
}
],
"symlink_target": ""
} |
@import "devoxx_android.css";
@font-face {
font-family: 'Roboto Condensed Bold', sans-serif;
src: url('RobotoCondensed-Bold.ttf');
}
@font-face {
font-family: 'Roboto Condensed', sans-serif;
src: url('RobotoCondensed-Regular.ttf');
}
.root {
-fx-font-family: 'Roboto Condensed';
}
.app-bar > .title-box > .label,
.search-app-bar.app-bar > .title-box > .search-text-field,
.vote-pane > .title-box > .title,
.dialog > .container > .dialog-title,
.dialog .dialog-badge-title.label {
-fx-font-family: 'Roboto Condensed Bold';
} | {
"content_hash": "851d1a819fbccad7efefbfaff20d2e3e",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 58,
"avg_line_length": 23,
"alnum_prop": 0.6612318840579711,
"repo_name": "devoxx/MyDevoxxGluon",
"id": "8a08ab3060ca2d93b2a954afd9cd3297e194a137",
"size": "2125",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "DevoxxClientMobile/src/main/resources/com/devoxx/devoxx_android_sans.css",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "74240"
},
{
"name": "Java",
"bytes": "842823"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Vaccinium hirtellum Ait.
### Remarks
null | {
"content_hash": "c86b80310479c9f61c8724f1375593de",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 11.23076923076923,
"alnum_prop": 0.726027397260274,
"repo_name": "mdoering/backbone",
"id": "3d51a6bf6f07ca6c3e66d3408b27139fb42227cc",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Ericaceae/Gaylussacia/Gaylussacia dumosa/Gaylussacia dumosa hirtella/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!-- saved from url=(0014)about:internet --><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<!-- Standard Head Part -->
<head>
<title>NUnit - Nunit-console</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<meta http-equiv="Content-Language" content="en-US">
<link rel="stylesheet" type="text/css" href="nunit.css">
<link rel="shortcut icon" href="favicon.ico">
</head>
<!-- End Standard Head Part -->
<body>
<!-- Standard Header for NUnit.org -->
<div id="header">
<a id="logo" href="http://www.nunit.org"><img src="img/logo.gif" alt="NUnit.org" title="NUnit.org"></a>
<div id="nav">
<a href="http://www.nunit.org">NUnit</a>
<a class="active" href="index.html">Documentation</a>
</div>
</div>
<!-- End of Header -->
<div id="content">
<h2>NUnit-Console</h2>
<p>The nunit-console.exe program is a text-based runner and can be used when you
want to run all your tests and don’t need a red/yellow/green indication of
success or failure.</p>
<p>It is useful for automation of tests and integration into other systems. It
automatically saves its results in XML format, allowing you to produce reports
or otherwise process the results. The following is a screenshot of the console
program.</p>
<div class="screenshot-left">
<img src="img/console-mock.jpg"></div>
<p>
<p>In this example, nunit-console has just run the tests in the mock-assembly.dll
that is part of the NUnit distribution. This assembly contains a number of tests, some
of which are either ignored or marked explicit. The summary line shows the
result of the test run. Click <a href="files/TestResult.xml">here</a>
to see the XML produced for this test run.</p>
<p>The .NET 2.0 version of the nunit-console program is built using /platform:anycpu,
which causes it to be jit-compiled to 32-bit code on a 32-bit system and 64-bit code
on a 64 bit system. This causes an exception when NUnit is used to test a 32-bit
application on a 64-bit system. To avoid this problem, use the nunit-console-x86
program, which is built using /platform:x86, when testing 32-bit code on a
64-bit system.
</div>
<!-- Submenu -->
<div id="subnav">
<ul>
<li><a href="index.html">NUnit 2.5.10</a></li>
<ul>
<li><a href="getStarted.html">Getting Started</a></li>
<li><a href="assertions.html">Assertions</a></li>
<li><a href="constraintModel.html">Constraints</a></li>
<li><a href="attributes.html">Attributes</a></li>
<li><a href="runningTests.html">Running Tests</a></li>
<ul>
<li id="current"><a href="nunit-console.html">Console Runner</a></li>
<ul>
<li><a href="consoleCommandLine.html">Command-Line</a></li>
</ul>
<li><a href="nunit-gui.html">Gui Runner</a></li>
<li><a href="pnunit.html">PNUnit Runner</a></li>
<li><a href="nunit-agent.html">NUnit Agent</a></li>
<li><a href="runtimeSelection.html">Runtime Selection</a></li>
<li><a href="assemblyIsolation.html">Assembly Isolation</a></li>
<li><a href="configFiles.html">Configuration Files</a></li>
<li><a href="multiAssembly.html">Multiple Assemblies</a></li>
<li><a href="vsSupport.html">Visual Studio Support</a></li>
</ul>
<li><a href="extensibility.html">Extensibility</a></li>
<li><a href="releaseNotes.html">Release Notes</a></li>
<li><a href="samples.html">Samples</a></li>
<li><a href="license.html">License</a></li>
</ul>
</ul>
</div>
<!-- End of Submenu -->
<!-- Standard Footer for NUnit.org -->
<div id="footer">
Copyright © 2010 Charlie Poole. All Rights Reserved.
</div>
<!-- End of Footer -->
</body>
</html>
| {
"content_hash": "934f209442104b714b522570090458e5",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 105,
"avg_line_length": 37.8,
"alnum_prop": 0.6942355889724311,
"repo_name": "kring/grisu.net",
"id": "54fcbff14750dc531ec9ab77027a0596828b206e",
"size": "3591",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "ThirdParty/NUnit-2.5.10.11092/doc/nunit-console.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "71954"
}
],
"symlink_target": ""
} |
<?php
use yii\apidoc\helpers\ApiMarkdown;
use yii\apidoc\models\ClassDoc;
use yii\apidoc\models\TraitDoc;
use yii\helpers\ArrayHelper;
/* @var $type ClassDoc|TraitDoc */
/* @var $protected boolean */
/* @var $this yii\web\View */
/* @var $renderer \yii\apidoc\templates\html\ApiRenderer */
$renderer = $this->context;
if ($protected && count($type->getProtectedProperties()) == 0 || !$protected && count($type->getPublicProperties()) == 0) {
return;
} ?>
<div class="summary doc-property">
<h2><?= $protected ? '受保护的属性' : '公共属性' ?></h2>
<p><a href="#" class="toggle">隐藏继承属性</a></p>
<table class="summary-table table table-striped table-bordered table-hover">
<colgroup>
<col class="col-property" />
<col class="col-type" />
<col class="col-description" />
<col class="col-defined" />
</colgroup>
<tr>
<th>属性</th><th>类型</th><th>描述</th><th>定义在</th>
</tr>
<?php
$properties = $type->properties;
ArrayHelper::multisort($properties, 'name');
foreach ($properties as $property): ?>
<?php if ($protected && $property->visibility == 'protected' || !$protected && $property->visibility != 'protected'): ?>
<tr<?= $property->definedBy != $type->name ? ' class="inherited"' : '' ?> id="<?= $property->name ?>">
<td><?= $renderer->createSubjectLink($property) ?></td>
<td><?= $renderer->createTypeLink($property->types) ?></td>
<td><?= ApiMarkdown::process($property->shortDescription, $property->definedBy, true) ?></td>
<td><?= $renderer->createTypeLink($property->definedBy) ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</table>
</div>
| {
"content_hash": "20ce7c689796a044120d7f03533224d9",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 124,
"avg_line_length": 33.541666666666664,
"alnum_prop": 0.6273291925465838,
"repo_name": "fengyh/yii2",
"id": "8277894b1a0a614c64a964f819f7b27d5caaac03",
"size": "1660",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "extensions/apidoc/templates/html/views/propertySummary.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "28"
},
{
"name": "Batchfile",
"bytes": "1603"
},
{
"name": "CSS",
"bytes": "13811"
},
{
"name": "JavaScript",
"bytes": "72858"
},
{
"name": "Makefile",
"bytes": "146"
},
{
"name": "PHP",
"bytes": "5525142"
},
{
"name": "PLSQL",
"bytes": "13778"
},
{
"name": "Ruby",
"bytes": "207"
},
{
"name": "Shell",
"bytes": "2896"
},
{
"name": "TeX",
"bytes": "4802"
}
],
"symlink_target": ""
} |
<?php
/*
Plugin Name: Markdown Category
Plugin URI: https://github.com/toparrow/MarkdownCategory
Description: Markdown is applied only to the specified category.
Author: toparrow
Version: 1.0
Author URI: https://github.com/toparrow
*/
class MarkdownCategory
{
private $url = '';
private $path = '';
private $parseDown = null;
public function __construct()
{
$this->url = plugins_url('', __FILE__);
$this->path = plugin_dir_path(__FILE__);
require_once $this->path . 'lib/parsedown/Parsedown.php';
$this->parsedown = new Parsedown();
add_action('admin_menu', array($this, 'admin_menu'));
add_action('wp_head', array($this, 'wp_head'));
add_filter('the_content', array($this, 'the_content'), 0);
}
public function wp_head()
{
$skin = get_option('skin');
if (!$skin) {
$skin = 'default';
}
echo '<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js?skin=' . $skin . '"></script>';
echo '<script src="' . $this->url . '/lib/marked.min.js"></script>' . "\n";
}
public function admin_menu()
{
add_submenu_page('plugins.php', 'Markdown Category Setting', 'Markdown Category Setting', 8, __FILE__, array($this, 'add_submenu_page'));
}
public function add_submenu_page()
{
include $this->path . 'markdown-category.setting.php';
}
public function the_content($content)
{
$class = get_post_class();
$categoryList = get_option('category_list');
if ($categoryList) {
$categoryList = explode(',', $categoryList);
foreach ($categoryList as $category) {
$category = trim($category);
if ($category && in_array($category, $class)) {
$content = $this->parsedown->text($content);
$content = str_replace('<pre>', '<pre class="prettyprint">', $content);
break;
}
}
}
return $content;
}
}
$markdownCategory = new MarkdownCategory(); | {
"content_hash": "647ca6962076eb51a621ca94fcbd4493",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 146,
"avg_line_length": 32.04347826086956,
"alnum_prop": 0.5395748530076888,
"repo_name": "toparrow/MarkdownCategory",
"id": "27dc522312dc0897e6e6c292aa01021fe0410317",
"size": "2211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "markdown-category.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "37491"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="Erre\TransitoMultasBundle\Entity\Ciudad" table="Ciudad">
<id name="idciudad" type="integer" column="idCiudad">
<generator strategy="IDENTITY"/>
</id>
<field name="ciudad" type="string" column="Ciudad" length="45" nullable="false"/>
<many-to-one field="iddepartamento" target-entity="Departamento">
<join-columns>
<join-column name="idDepartamento" referenced-column-name="idDepartamento"/>
</join-columns>
</many-to-one>
</entity>
</doctrine-mapping>
| {
"content_hash": "38e80c3aec1c3b051409579645c57387",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 276,
"avg_line_length": 59.357142857142854,
"alnum_prop": 0.7135980746089049,
"repo_name": "z3774/transitoMultas",
"id": "e817caf7752c3e50104dcaf5e6801b2fa9492990",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Erre/TransitoMultasBundle/Resources/config/doctrine/Ciudad.orm.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2647"
},
{
"name": "CSS",
"bytes": "2204"
},
{
"name": "HTML",
"bytes": "8217"
},
{
"name": "PHP",
"bytes": "80519"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Cdn;
using Cdn.Tests.Helpers;
using Xunit;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
namespace Cdn.Tests.ScenarioTests
{
public class OperationsTests
{
[Fact]
public void ListOperationsTest()
{
var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK };
using (MockContext context = MockContext.Start(this.GetType().FullName))
{
// Create client
var cdnMgmtClient = CdnTestUtilities.GetCdnManagementClient(context, handler1);
// Get operations
var operations = cdnMgmtClient.Operations.List();
// Verify operations are returned
Assert.NotNull(operations);
Assert.NotEmpty(operations);
}
}
}
}
| {
"content_hash": "40d29c21248cd81a150762709ebfbe2a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 100,
"avg_line_length": 33.833333333333336,
"alnum_prop": 0.6576354679802956,
"repo_name": "shahabhijeet/azure-sdk-for-net",
"id": "24e47c52cbf95a531e2d3006509ba3149bf2e9d1",
"size": "1220",
"binary": false,
"copies": "3",
"ref": "refs/heads/psSdkJson6",
"path": "src/SDKs/Cdn/Cdn.Tests/ScenarioTests/OperationsTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "15346"
},
{
"name": "C#",
"bytes": "131793423"
},
{
"name": "HTML",
"bytes": "191432"
},
{
"name": "JavaScript",
"bytes": "7875"
},
{
"name": "PowerShell",
"bytes": "108166"
},
{
"name": "Shell",
"bytes": "32482"
}
],
"symlink_target": ""
} |
package org.pentaho.hadoop.hbase.factory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.pentaho.hbase.factory.HBaseAdmin;
class HBase9xAdmin implements HBaseAdmin {
private final org.apache.hadoop.hbase.client.HBaseAdmin admin;
HBase9xAdmin( Configuration conf ) throws IOException {
admin = new org.apache.hadoop.hbase.client.HBaseAdmin(conf);
}
@Override
public boolean tableExists( String tableName ) throws IOException {
return admin.tableExists( tableName );
}
@Override
public HTableDescriptor[] listTables() throws IOException {
return admin.listTables();
}
@Override
public boolean isTableDisabled( String tableName ) throws IOException {
return admin.isTableDisabled( tableName );
}
@Override
public boolean isTableEnabled( String tableName ) throws IOException {
return admin.isTableEnabled( tableName );
}
@Override
public boolean isTableAvailable( String tableName ) throws IOException {
return admin.isTableAvailable( tableName );
}
@Override
public HTableDescriptor getTableDescriptor( byte[] tableName ) throws IOException {
return admin.getTableDescriptor( tableName );
}
@Override
public void enableTable( String tableName ) throws IOException {
admin.enableTable( tableName );
}
@Override
public void disableTable( String tableName ) throws IOException {
admin.disableTable( tableName );
}
@Override
public void deleteTable( String tableName ) throws IOException {
admin.deleteTable( tableName );
}
@Override
public void createTable( HTableDescriptor tableDesc ) throws IOException {
admin.createTable( tableDesc );
}
@Override
public void close() throws IOException {
Method closeMethod = null;
try {
closeMethod = admin.getClass().getMethod( "close", new Class<?> [0] );
} catch ( NoSuchMethodException e ) {
} catch ( SecurityException e ) {
throw new IOException( "can't find 'close' method", e );
}
if ( closeMethod != null ) {
try {
closeMethod.invoke( admin, new Object[0] );
} catch ( IllegalAccessException e ) {
throw new IOException( "can't close admin", e );
} catch ( IllegalArgumentException e ) {
throw new IOException( "can't close admin", e );
} catch ( InvocationTargetException e ) {
throw new IOException( "can't close admin", e );
}
}
}
}
| {
"content_hash": "35f78d7b5afda5f666c0c0b0924387a0",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 85,
"avg_line_length": 29.428571428571427,
"alnum_prop": 0.6833457804331591,
"repo_name": "stepanovdg/pentaho-hadoop-shims",
"id": "eda3c829456acecd10c3a125ff2f13439a6aa694",
"size": "3572",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "common/src-hbase-pre1.0/org/pentaho/hadoop/hbase/factory/HBase9xAdmin.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "6975"
},
{
"name": "Java",
"bytes": "1610634"
},
{
"name": "PigLatin",
"bytes": "4387"
}
],
"symlink_target": ""
} |
package com.google.ads.googleads.v10.services;
import com.google.ads.googleads.v10.services.CustomerFeedServiceGrpc.CustomerFeedServiceImplBase;
import com.google.api.core.BetaApi;
import com.google.protobuf.AbstractMessage;
import io.grpc.stub.StreamObserver;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import javax.annotation.Generated;
@BetaApi
@Generated("by gapic-generator-java")
public class MockCustomerFeedServiceImpl extends CustomerFeedServiceImplBase {
private List<AbstractMessage> requests;
private Queue<Object> responses;
public MockCustomerFeedServiceImpl() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
public List<AbstractMessage> getRequests() {
return requests;
}
public void addResponse(AbstractMessage response) {
responses.add(response);
}
public void setResponses(List<AbstractMessage> responses) {
this.responses = new LinkedList<Object>(responses);
}
public void addException(Exception exception) {
responses.add(exception);
}
public void reset() {
requests = new ArrayList<>();
responses = new LinkedList<>();
}
@Override
public void mutateCustomerFeeds(
MutateCustomerFeedsRequest request,
StreamObserver<MutateCustomerFeedsResponse> responseObserver) {
Object response = responses.poll();
if (response instanceof MutateCustomerFeedsResponse) {
requests.add(request);
responseObserver.onNext(((MutateCustomerFeedsResponse) response));
responseObserver.onCompleted();
} else if (response instanceof Exception) {
responseObserver.onError(((Exception) response));
} else {
responseObserver.onError(
new IllegalArgumentException(
String.format(
"Unrecognized response type %s for method MutateCustomerFeeds, expected %s or %s",
response == null ? "null" : response.getClass().getName(),
MutateCustomerFeedsResponse.class.getName(),
Exception.class.getName())));
}
}
}
| {
"content_hash": "35cc080ab054546b810152d86899c096",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 100,
"avg_line_length": 31.014705882352942,
"alnum_prop": 0.7164532954006638,
"repo_name": "googleads/google-ads-java",
"id": "3b6fc9da18b77802ac6d930ef7df3a2eb83f2d7d",
"size": "2704",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "google-ads-stubs-v10/src/test/java/com/google/ads/googleads/v10/services/MockCustomerFeedServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28701198"
}
],
"symlink_target": ""
} |
SET(CMAKE_DEPENDS_LANGUAGES
"CXX"
)
# The set of files for implicit dependencies of each language:
SET(CMAKE_DEPENDS_CHECK_CXX
"/home/cmeon/SimplexLP/eigen/test/swap.cpp" "/home/cmeon/SimplexLP/lib/test/CMakeFiles/swap_1.dir/swap.cpp.o"
)
SET(CMAKE_CXX_COMPILER_ID "GNU")
# Targets to which this target links.
SET(CMAKE_TARGET_LINKED_INFO_FILES
)
# The include file search paths:
SET(CMAKE_C_TARGET_INCLUDE_PATH
"test"
"/home/cmeon/SimplexLP/eigen/test"
"/home/cmeon/SimplexLP/eigen"
"."
)
SET(CMAKE_CXX_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_Fortran_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
SET(CMAKE_ASM_TARGET_INCLUDE_PATH ${CMAKE_C_TARGET_INCLUDE_PATH})
| {
"content_hash": "a2504b27ea65bda997d9ba83e4b47692",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 111,
"avg_line_length": 31.043478260869566,
"alnum_prop": 0.7408963585434174,
"repo_name": "cmeon/Simplex",
"id": "88f8e3ba70c5faf69aa7fa3e1b5f0316dbaf2ee2",
"size": "781",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/test/CMakeFiles/swap_1.dir/DependInfo.cmake",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2192597"
},
{
"name": "C++",
"bytes": "3497542"
},
{
"name": "CSS",
"bytes": "5151"
},
{
"name": "FORTRAN",
"bytes": "1462981"
},
{
"name": "JavaScript",
"bytes": "7839"
},
{
"name": "Objective-C",
"bytes": "2089"
},
{
"name": "Python",
"bytes": "8750"
},
{
"name": "Shell",
"bytes": "15472"
},
{
"name": "Tcl",
"bytes": "2329"
}
],
"symlink_target": ""
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _asyncMap;
var _isArrayLike = require('lodash/isArrayLike');
var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
var _getIterator = require('./getIterator');
var _getIterator2 = _interopRequireDefault(_getIterator);
var _noop = require('lodash/noop');
var _noop2 = _interopRequireDefault(_noop);
var _once = require('lodash/once');
var _once2 = _interopRequireDefault(_once);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncMap(eachfn, arr, iteratee, callback) {
callback = (0, _once2.default)(callback || _noop2.default);
arr = arr || [];
var results = (0, _isArrayLike2.default)(arr) || (0, _getIterator2.default)(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iteratee(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
module.exports = exports['default']; | {
"content_hash": "e26fd4ba2776e21700804648b9624a08",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 95,
"avg_line_length": 28,
"alnum_prop": 0.6428571428571429,
"repo_name": "fedejoaquin/IAW",
"id": "f8cff4f1d53b56af0a204041a0ffa055e74fb08f",
"size": "1092",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "serverNode/node_modules/async/internal/map.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "353"
},
{
"name": "CSS",
"bytes": "19208"
},
{
"name": "HTML",
"bytes": "8261677"
},
{
"name": "JavaScript",
"bytes": "510249"
},
{
"name": "PHP",
"bytes": "8959975"
}
],
"symlink_target": ""
} |
package com.intel.analytics.bigdl.dllib.nn.ops
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.utils.T
import com.intel.analytics.bigdl.dllib.utils.serializer.ModuleSerializationTest
import org.scalatest.{FlatSpec, Matchers}
import scala.util.Random
class FloorSpec extends FlatSpec with Matchers {
"Floor Float operation" should "works correctly" in {
val input =
Tensor[Float](T(1.5f, 2.1f, 2.9f))
val expectOutput = Tensor[Float](T(1f, 2f, 2f))
val output = Floor[Double]().forward(input)
output should be(expectOutput)
}
"Floor Double operation" should "works correctly" in {
val input =
Tensor[Double](T(1.5, 2.1, 2.9))
val expectOutput = Tensor[Double](T(1, 2, 2))
val output = Floor[Double]().forward(input)
output should be(expectOutput)
}
"Floor Int operation" should "works correctly" in {
val input =
Tensor[Int](T(1, 2, 2))
val expectOutput = Tensor[Int](T(1, 2, 2))
val output = Floor[Int]().forward(input)
output should be(expectOutput)
}
}
class FloorSerialTest extends ModuleSerializationTest {
override def test(): Unit = {
val floor = Floor[Float]().setName("floor")
val input = Tensor[Float](5).apply1(_ => Random.nextFloat())
runSerializationTest(floor, input, floor.
asInstanceOf[ModuleToOperation[Float]].module.getClass)
}
}
| {
"content_hash": "1e74f738ba4c93367f27665f7dd18baa",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 79,
"avg_line_length": 28.14,
"alnum_prop": 0.6929637526652452,
"repo_name": "yangw1234/BigDL",
"id": "d2ce600d55e46f1d4c0b7714be4d677c705cd3ce",
"size": "2008",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/nn/ops/FloorSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5342"
},
{
"name": "Dockerfile",
"bytes": "138760"
},
{
"name": "Java",
"bytes": "1321348"
},
{
"name": "Jupyter Notebook",
"bytes": "54063856"
},
{
"name": "Lua",
"bytes": "1904"
},
{
"name": "Makefile",
"bytes": "19253"
},
{
"name": "PowerShell",
"bytes": "1137"
},
{
"name": "PureBasic",
"bytes": "593"
},
{
"name": "Python",
"bytes": "8762180"
},
{
"name": "RobotFramework",
"bytes": "16117"
},
{
"name": "Scala",
"bytes": "13216038"
},
{
"name": "Shell",
"bytes": "844916"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a47aa298517d171ed03219c6e9d67e16",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "859a14e0c713144c91d480fccfbde9f4a27f7ae0",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lentibulariaceae/Utricularia/Utricularia cutleri/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace Nathalie\Exam16;
/**
* Class Session
*
* @package Nathalie\Exam16
*/
class Session
{
const LOGIN_STATE_FAILURE = 0;
const LOGIN_STATE_AUTHENTICATED = 1;
const LOGIN_STATE_GUEST = 2;
private $hash;
private $session_key = 'secret_key';
/**
* Session constructor.
*/
public function __construct()
{
session_start();
$this->hash = file_get_contents(__DIR__ . '/../.password');
}
/**
* @return int
*/
public function getLoginState()
{
$loginState = self::LOGIN_STATE_GUEST;
if (isset($_SESSION[$this->session_key]) && $_SESSION[$this->session_key] == $this->hash)
{
$loginState = self::LOGIN_STATE_AUTHENTICATED;
}
return $loginState;
}
/**
* @param $password
*
* @return int
*/
public function login($password)
{
$loginState = password_verify($password, $this->hash) ? self::LOGIN_STATE_AUTHENTICATED : self::LOGIN_STATE_FAILURE;
if ($loginState == self::LOGIN_STATE_AUTHENTICATED)
{
$_SESSION[$this->session_key] = $this->hash;
if (isset($_SESSION['redirect']))
{
$redirect = $_SESSION['redirect'];
unset($_SESSION['redirect']);
header('Location: ' . $redirect);
}
}
return $loginState;
}
/**
* @return int
*/
public function logout()
{
$_SESSION[$this->session_key] = null;
session_write_close();
return self::LOGIN_STATE_GUEST;
}
/**
* @return bool
*/
public function isValid()
{
return $this->getLoginState() == self::LOGIN_STATE_AUTHENTICATED;
}
/**
*/
public function assertValidSession()
{
if (!$this->isValid())
{
$_SESSION['redirect'] = $_SERVER['REQUEST_URI'];
header('Location: login.php');
}
}
}
| {
"content_hash": "b3fa2dbe416d30e873d76b435e92aef4",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 124,
"avg_line_length": 21.020833333333332,
"alnum_prop": 0.5084241823587711,
"repo_name": "NathalieBraczek/exam16_restaurant",
"id": "c3d5f1d553bee5d85864428391861968e67f6d15",
"size": "2245",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/classes/Session.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4635"
},
{
"name": "PHP",
"bytes": "53282"
},
{
"name": "Visual Basic",
"bytes": "8910"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from __future__ import unicode_literals
from pre_commit_hooks.check_case_conflict import find_conflicting_filenames
from pre_commit_hooks.check_case_conflict import main
from pre_commit_hooks.util import cmd_output
from testing.util import cwd
from testing.util import write_file
def test_nothing_added(temp_git_dir):
with cwd(temp_git_dir):
assert find_conflicting_filenames(['f.py']) == 0
def test_adding_something(temp_git_dir):
with cwd(temp_git_dir):
write_file('f.py', "print('hello world')")
cmd_output('git', 'add', 'f.py')
assert find_conflicting_filenames(['f.py']) == 0
def test_adding_something_with_conflict(temp_git_dir):
with cwd(temp_git_dir):
write_file('f.py', "print('hello world')")
cmd_output('git', 'add', 'f.py')
write_file('F.py', "print('hello world')")
cmd_output('git', 'add', 'F.py')
assert find_conflicting_filenames(['f.py', 'F.py']) == 1
def test_added_file_not_in_pre_commits_list(temp_git_dir):
with cwd(temp_git_dir):
write_file('f.py', "print('hello world')")
cmd_output('git', 'add', 'f.py')
assert find_conflicting_filenames(['g.py']) == 0
def test_file_conflicts_with_committed_file(temp_git_dir):
with cwd(temp_git_dir):
write_file('f.py', "print('hello world')")
cmd_output('git', 'add', 'f.py')
cmd_output('git', 'commit', '--no-verify', '-m', 'Add f.py')
write_file('F.py', "print('hello world')")
cmd_output('git', 'add', 'F.py')
assert find_conflicting_filenames(['F.py']) == 1
def test_integration(temp_git_dir):
with cwd(temp_git_dir):
assert main(argv=[]) == 0
write_file('f.py', "print('hello world')")
cmd_output('git', 'add', 'f.py')
assert main(argv=['f.py']) == 0
write_file('F.py', "print('hello world')")
cmd_output('git', 'add', 'F.py')
assert main(argv=['F.py']) == 1
| {
"content_hash": "7e695e98d0a7f7dbddbc339a2f7de7c1",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 75,
"avg_line_length": 30.439393939393938,
"alnum_prop": 0.600298656047785,
"repo_name": "bgschiller/pre-commit-hooks",
"id": "2a32918a7374840047427b951cc3be8a5c6bdf77",
"size": "2009",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tests/check_case_conflict_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "402"
},
{
"name": "Python",
"bytes": "95546"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>HornetQ JMS AeroGear Example</title>
<link rel="stylesheet" type="text/css" href="../common/common.css" />
<link rel="stylesheet" type="text/css" href="../common/prettify.css" />
<script type="text/javascript" src="../common/prettify.js"></script>
</head>
<body onload="prettyPrint()">
<h1>JMS AeroGear Example</h1>
<p>This example shows how you can send a message to a mobile device by leveraging <a href="http://aerogear.org/push/">AeroGears push</a> technology which
provides support for different push notification technologies like Google Cloud Messaging, Apple's APNs or
Mozilla's SimplePush.</p>
<p>For this example you will need an AeroGear Application running somewhere, a good way to do this is to deploy the
Push Application on <href a="">openshift</href>, you can follow the AeroGear Push 0.X Quickstart.</p>
<p>Once you have created your AeroGear Push Application you can create a mobile application. Simply log into the application
on the web and create a new mobile application by clicking the 'create' button. Once created you will see an application id
and a master secret, you will need the later to run the example.</p>
<p>lastly you will need to create a variant. For this example we will be using Android so you will need to create a google project,
this <a href="http://aerogear.org/docs/guides/aerogear-push-android/google-setup/">article</a> explains how to do this.
Once created click on your app then click 'add' to add a variant. choose 'google cloud messaging', enter your google
API key and the project number from your google project and click create</p>
<p>Now before we run the example we need a mobile application to receive it. Writing a mobile app is beyond the scope
of this example but for testing purposes we have supplied an Android app you can use, simply install on your android phone.
It can be found <a href="http://downloads.jboss.org/hornetq/HornetQAeroGear.apk">here</a>. For a more in depth mobile
app example visit the AeroGear site.</p>
<p>Once you have installed the mobile app you will need to configure the following:</p>
<p>AeroGear Unified Push URL : This is the URL where your aerogear server is running, something like http://myapp-mydomain.rhcloud.com
AeroGear Variant ID : This is the ID of the variant you created in AeroGear
AeroGear Variant Secret : This is the secret for your variant
GCM Sender ID : this is the Google project Number you created on Google
Variant : you can use this to target messages if needed.
</p>
<p>Once you set all these correctly you should get a message saying your mobile app is registered, if you log into
your AeroGear app you should see it registered with the variant.</p>
<p>Now to run the example simply run the following command
'mvn -Dendpoint=my aerogear url -Dapplicationid=my application id -Dmastersecret=my master secret -Djsse.enableSNIExtension=false clean verify'.
If you arent using java 7 you can omit the 'jsse.enableSNIExtension=false'</p>
<p>You should see something like this in your HornetQServer</p>
<ol>
<pre class="prettyprint">
<code>
Dec 04, 2013 3:25:39 PM org.jboss.aerogear.unifiedpush.SenderClient submitPayload
INFO: HTTP Response code from UnifiedPush Server: 302
Dec 04, 2013 3:25:39 PM org.jboss.aerogear.unifiedpush.SenderClient submitPayload
INFO: Performing redirect to 'https://myapp-mydomain.rhcloud.com/rest/sender/'
Dec 04, 2013 3:25:40 PM org.jboss.aerogear.unifiedpush.SenderClient submitPayload
INFO: HTTP Response code from UnifiedPush Server: 200
</code>
</pre>
</ol>
<p>And on your mobile app you should see a message from HornetQ</p>
<p>Now lets look a bit more closely at the configuration in hornetq-configuration.xml</p>
<ol>
<pre class="prettyprint">
<code>
<queues>
<queue name="jms.queue.aerogearQueue">
<address>jms.queue.aerogearQueue</address>
</queue>
</queues>
<connector-services>
<connector-service name="aerogear-connector">
<factory-class>org.hornetq.integration.aerogear.AeroGearConnectorServiceFactory</factory-class>
<param key="endpoint" value="${endpoint}"/>
<param key="queue" value="jms.queue.aerogearQueue"/>
<param key="application-id" value="${applicationid}"/>
<param key="master-secret" value="${mastersecret}"/>
</connector-service>
</connector-services>
</code>
</pre>
</ol>
<p>Firstly you will see that we have to create a core queue so it is available when the connector is started, the following are mandatory parameters:</p>
<ol>
<li>endpoint - The endpoint or URL of you AeroGear application</li>
<li>queue - The name of the queue to consume from</li>
<li>application-id - The application id of your mobile application in AeroGear</li>
<li>master-secret - the secret of your mobile application in AeroGear</li>
</ol>
<p>as well as those there are also the following optional parameters</p>
<ol>
<li>ttl - The time to live for the message once AeroGear receives it</li>
<li>badge - The badge the mobile app should use for the notification</li>
<li>sound - The sound the mobile app should use for the notification</li>
<li>filter - A message filter(selector) to use on the connector</li>
<li>retry-interval - If an error occurs on send, how long before we try again</li>
<li>retry-attempts - How many times we should try to reconnect after an error</li>
<li>variants - A comma separated list of variants that should get the message</li>
<li>aliases - A list of aliases that should get the message</li>
<li>device-types - A list of device types that should get the message</li>
</ol>
<p>More in depth explanations of these can be found in the AeroGear docs.</p>
<p>Now lets look at a snippet of code we used to send the message for our JMS client</p>
<pre class="prettyprint">
<code>
Queue queue = (Queue)initialContext.lookup("/queue/aerogearQueue");
// Step 3. Perform a lookup on the Connection Factory
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
// Step 4.Create a JMS Connection
connection = cf.createConnection();
// Step 5. Create a JMS Session
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Step 6. Create a JMS Message Producer
MessageProducer producer = session.createProducer(queue);
// Step 7. Create a Text Message
Message message = session.createMessage();
message.setStringProperty("AEROGEAR_ALERT", "Hello this is a notification from HornetQ");
producer.send(message);
</code>
</pre>
<p> The most important thing here is string propert we have set on the message, i.e. 'AEROGEAR_ALERT'. This is the
actual alert that is sent via AeroGear</p>
<p>As well as the alert itself you can override any of the above optional parameters in the same fashionby using the
following propert names: AEROGEAR_SOUND,AEROGEAR_BADGE,AEROGEAR_TTL,AEROGEAR_VARIANTS,AEROGEAR_ALIASES and AEROGEAR_DEVICE_TYPES</p>
</body>
</html> | {
"content_hash": "66504a9d58e95bba7a964e4705e162af",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 158,
"avg_line_length": 55.14074074074074,
"alnum_prop": 0.7062063406770553,
"repo_name": "Dauth/cs3219-JMS",
"id": "66112a0aef3d98963ab3f8bd14eb7717cf0aec71",
"size": "7444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hornetq-2.4.0.Final/examples/jms/aerogear/readme.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5161"
},
{
"name": "CSS",
"bytes": "141931"
},
{
"name": "HTML",
"bytes": "11041932"
},
{
"name": "Java",
"bytes": "791170"
},
{
"name": "JavaScript",
"bytes": "1436"
},
{
"name": "Python",
"bytes": "2051"
},
{
"name": "Ruby",
"bytes": "1821"
},
{
"name": "Shell",
"bytes": "3130"
}
],
"symlink_target": ""
} |
package grpc_logrus_test
import (
"context"
"io"
"io/ioutil"
"runtime"
"strings"
"testing"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/logging/logrus"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"google.golang.org/grpc"
)
var (
nullLogger = &logrus.Logger{
Out: ioutil.Discard,
Formatter: new(logrus.TextFormatter),
Hooks: make(logrus.LevelHooks),
Level: logrus.PanicLevel,
}
)
func TestLogrusPayloadSuite(t *testing.T) {
if strings.HasPrefix(runtime.Version(), "go1.7") {
t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7")
return
}
alwaysLoggingDeciderServer := func(ctx context.Context, fullMethodName string, servingObject interface{}) bool { return true }
alwaysLoggingDeciderClient := func(ctx context.Context, fullMethodName string) bool { return true }
b := newLogrusBaseSuite(t)
b.InterceptorTestSuite.ClientOpts = []grpc.DialOption{
grpc.WithUnaryInterceptor(grpc_logrus.PayloadUnaryClientInterceptor(logrus.NewEntry(b.logger), alwaysLoggingDeciderClient)),
grpc.WithStreamInterceptor(grpc_logrus.PayloadStreamClientInterceptor(logrus.NewEntry(b.logger), alwaysLoggingDeciderClient)),
}
b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.StreamServerInterceptor(logrus.NewEntry(nullLogger)),
grpc_logrus.PayloadStreamServerInterceptor(logrus.NewEntry(b.logger), alwaysLoggingDeciderServer)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_logrus.UnaryServerInterceptor(logrus.NewEntry(nullLogger)),
grpc_logrus.PayloadUnaryServerInterceptor(logrus.NewEntry(b.logger), alwaysLoggingDeciderServer)),
}
suite.Run(t, &logrusPayloadSuite{b})
}
type logrusPayloadSuite struct {
*logrusBaseSuite
}
func (s *logrusPayloadSuite) getServerAndClientMessages(expectedServer int, expectedClient int) (serverMsgs []map[string]interface{}, clientMsgs []map[string]interface{}) {
msgs := s.getOutputJSONs()
for _, m := range msgs {
if m["span.kind"] == "server" {
serverMsgs = append(serverMsgs, m)
} else if m["span.kind"] == "client" {
clientMsgs = append(clientMsgs, m)
}
}
require.Len(s.T(), serverMsgs, expectedServer, "must match expected number of server log messages")
require.Len(s.T(), clientMsgs, expectedClient, "must match expected number of client log messages")
return serverMsgs, clientMsgs
}
func (s *logrusPayloadSuite) TestPing_LogsBothRequestAndResponse() {
_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "there must be not be an on a successful call")
serverMsgs, clientMsgs := s.getServerAndClientMessages(2, 2)
for _, m := range append(serverMsgs, clientMsgs...) {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
assert.Equal(s.T(), m["grpc.method"], "Ping", "all lines must contain the correct method name")
assert.Equal(s.T(), m["level"], "info", "all lines must contain method name")
}
serverReq, serverResp := serverMsgs[0], serverMsgs[1]
clientReq, clientResp := clientMsgs[0], clientMsgs[1]
assert.Contains(s.T(), clientReq, "grpc.request.content", "request payload must be logged in a structured way")
assert.Contains(s.T(), serverReq, "grpc.request.content", "request payload must be logged in a structured way")
assert.Contains(s.T(), clientResp, "grpc.response.content", "response payload must be logged in a structured way")
assert.Contains(s.T(), serverResp, "grpc.response.content", "response payload must be logged in a structured way")
}
func (s *logrusPayloadSuite) TestPingError_LogsOnlyRequestsOnError() {
_, err := s.Client.PingError(s.SimpleCtx(), &pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(4)})
require.Error(s.T(), err, "there must be not be an error on a successful call")
serverMsgs, clientMsgs := s.getServerAndClientMessages(1, 1)
for _, m := range append(serverMsgs, clientMsgs...) {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
assert.Equal(s.T(), m["grpc.method"], "PingError", "all lines must contain the correct method name")
assert.Equal(s.T(), m["level"], "info", "all lines must be logged at info level")
}
assert.Contains(s.T(), clientMsgs[0], "grpc.request.content", "request payload must be logged by the client")
assert.Contains(s.T(), serverMsgs[0], "grpc.request.content", "request payload must be logged by the server")
}
func (s *logrusPayloadSuite) TestPingStream_LogsAllRequestsAndResponses() {
messagesExpected := 20
stream, err := s.Client.PingStream(s.SimpleCtx())
require.NoError(s.T(), err, "no error on stream creation")
for i := 0; i < messagesExpected; i++ {
require.NoError(s.T(), stream.Send(goodPing), "sending must succeed")
}
require.NoError(s.T(), stream.CloseSend(), "no error on close of stream")
for {
pong := &pb_testproto.PingResponse{}
err := stream.RecvMsg(pong)
if err == io.EOF {
break
}
require.NoError(s.T(), err, "no error on receive")
}
serverMsgs, clientMsgs := s.getServerAndClientMessages(2*messagesExpected, 2*messagesExpected)
for _, m := range append(serverMsgs, clientMsgs...) {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain the correct service name")
assert.Equal(s.T(), m["grpc.method"], "PingStream", "all lines must contain the correct method name")
assert.Equal(s.T(), m["level"], "info", "all lines must be at info log level")
content := m["grpc.request.content"] != nil || m["grpc.response.content"] != nil
assert.True(s.T(), content, "all messages must contain a payload")
}
}
| {
"content_hash": "8f743057b711f5138089a875ef5cf5aa",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 172,
"avg_line_length": 45.888888888888886,
"alnum_prop": 0.7415657788539144,
"repo_name": "mwitkow/go-grpc-middleware",
"id": "342a1e5fb0370f5a61b2730b58723e3c20db479b",
"size": "6195",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "logging/logrus/payload_interceptors_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "154289"
},
{
"name": "Makefile",
"bytes": "298"
},
{
"name": "Protocol Buffer",
"bytes": "1283"
},
{
"name": "Shell",
"bytes": "1717"
}
],
"symlink_target": ""
} |
<header class="container-fluid">
<div class="row">
<div class="col-12">
<a class="logo" routerLink="/">
<img src="/assets/images/ressources/sebastienbarbier_logo.svg" alt="This image contains: sebastien's logo which is simply his first and last name together with a stylish font" />
</a>
</div>
</div>
</header>
| {
"content_hash": "6b3dcb1fa49188bf78c4a0eb9777a0f3",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 186,
"avg_line_length": 38.22222222222222,
"alnum_prop": 0.6482558139534884,
"repo_name": "sebastienbarbier/sebastienbarbier.com",
"id": "095dda674f8a4dccef892f5dc2ad01167a77ef0f",
"size": "344",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/app/shared/header/header.component.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "28071"
},
{
"name": "JavaScript",
"bytes": "4704"
},
{
"name": "SCSS",
"bytes": "74508"
},
{
"name": "Shell",
"bytes": "3092"
},
{
"name": "TypeScript",
"bytes": "41210"
}
],
"symlink_target": ""
} |
<?php
class Mage_Adminhtml_Model_System_Config_Source_Currency
{
protected $_options;
public function toOptionArray($isMultiselect)
{
if (!$this->_options) {
$this->_options = Mage::app()->getLocale()->getOptionCurrencies();
}
$options = $this->_options;
return $options;
}
}
| {
"content_hash": "f5adf5d1762abaadb93a7889f32a9fb1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 78,
"avg_line_length": 20,
"alnum_prop": 0.5823529411764706,
"repo_name": "tagalpha/library",
"id": "903845a85de9495be0f132cf1f66594c01ffc6d0",
"size": "1296",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/code/core/Mage/Adminhtml/Model/System/Config/Source/Currency.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "20063"
},
{
"name": "ApacheConf",
"bytes": "8117"
},
{
"name": "Batchfile",
"bytes": "1036"
},
{
"name": "CSS",
"bytes": "1805855"
},
{
"name": "HTML",
"bytes": "5531269"
},
{
"name": "JavaScript",
"bytes": "1295882"
},
{
"name": "PHP",
"bytes": "45317581"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "288"
},
{
"name": "Shell",
"bytes": "19717"
},
{
"name": "XSLT",
"bytes": "2066"
}
],
"symlink_target": ""
} |
package kafka.security;
import java.io.IOException;
import java.nio.channels.Channel;
/**
* An interface to secure channels. It is usually recommended to perform the
* initial SSL handshake with the separate handshake method, although the
* implementation may support embedded handshaking within the read and write
* methods. The shutdown process may also be started separately but should be
* called automatically by the close method of the implementation.
*
* @author Ilkka Priha
*/
public interface SecureChannel extends Channel
{
/**
* Returns true if this channel is finished with handshaking.
*
* @return true if finished, false otherwise.
*/
public boolean finished();
/**
* Returns the number of encrypted bytes not yet flushed.
*
* @return the number of encrypted bytes.
*/
public int encrypted();
/**
* Returns the number of decrypted bytes not yet read.
*
* @return the number of decrypted bytes.
*/
public int decrypted();
/**
* Starts or continues handshaking with the specified operations.
*
* @param ops the current ready operations set.
* @return the interest set to continue or 0 if finished.
* @throws IOException on I/O errors.
*/
public int handshake(int ops) throws IOException;
/**
* Starts the shutdown sequence but does not close the channel.
*
* @return true if finished, false otherwise.
* @throws IOException on I/O errors.
*/
public boolean shutdown() throws IOException;
/**
* Flushes remaining encrypted bytes if any.
*
* @throws IOException on I/O errors.
*/
public void flush() throws IOException;
}
| {
"content_hash": "d5a24f93b05f4cd39af6bf1eac01750b",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 77,
"avg_line_length": 27.603174603174605,
"alnum_prop": 0.6687751581368603,
"repo_name": "darrendao/kafka.play.time",
"id": "94b614d0e0d9644114d2466331ed3fd05bab148c",
"size": "2604",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "security/src/main/java/kafka/security/SecureChannel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "623688"
},
{
"name": "Python",
"bytes": "252881"
},
{
"name": "Scala",
"bytes": "1638661"
},
{
"name": "Shell",
"bytes": "101063"
}
],
"symlink_target": ""
} |
#ifndef __G_TLS_SERVER_CONNECTION_H__
#define __G_TLS_SERVER_CONNECTION_H__
#if !defined (__GIO_GIO_H_INSIDE__) && !defined (GIO_COMPILATION)
#error "Only <gio/gio.h> can be included directly."
#endif
#include <gio/gtlsconnection.h>
G_BEGIN_DECLS
#define G_TYPE_TLS_SERVER_CONNECTION (g_tls_server_connection_get_type ())
#define G_TLS_SERVER_CONNECTION(inst) (G_TYPE_CHECK_INSTANCE_CAST ((inst), G_TYPE_TLS_SERVER_CONNECTION, GTlsServerConnection))
#define G_IS_TLS_SERVER_CONNECTION(inst) (G_TYPE_CHECK_INSTANCE_TYPE ((inst), G_TYPE_TLS_SERVER_CONNECTION))
#define G_TLS_SERVER_CONNECTION_GET_INTERFACE(inst) (G_TYPE_INSTANCE_GET_INTERFACE ((inst), G_TYPE_TLS_SERVER_CONNECTION, GTlsServerConnectionInterface))
/**
* GTlsServerConnection:
*
* TLS server-side connection. This is the server-side implementation
* of a #GTlsConnection.
*
* Since: 2.28
*/
typedef struct _GTlsServerConnectionInterface GTlsServerConnectionInterface;
/**
* GTlsServerConnectionInterface:
* @g_iface: The parent interface.
*
* vtable for a #GTlsServerConnection implementation.
*
* Since: 2.26
*/
struct _GTlsServerConnectionInterface
{
GTypeInterface g_iface;
};
GLIB_AVAILABLE_IN_ALL
GType g_tls_server_connection_get_type (void) G_GNUC_CONST;
GLIB_AVAILABLE_IN_ALL
GIOStream * g_tls_server_connection_new (GIOStream *base_io_stream,
GTlsCertificate *certificate,
GError **error);
G_END_DECLS
#endif /* __G_TLS_SERVER_CONNECTION_H__ */
| {
"content_hash": "c0aaf5b959ac3c5e7c45b1422953daea",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 153,
"avg_line_length": 29.90566037735849,
"alnum_prop": 0.6794952681388012,
"repo_name": "zhch/como",
"id": "ad61e30fc933c9fc41508d4f5437355748cebbf0",
"size": "2346",
"binary": false,
"copies": "56",
"ref": "refs/heads/master",
"path": "lib/glib/glib-2.50.2/gio/gtlsserverconnection.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "20"
},
{
"name": "C",
"bytes": "22771445"
},
{
"name": "C++",
"bytes": "412587"
},
{
"name": "CSS",
"bytes": "26436"
},
{
"name": "DTrace",
"bytes": "3366"
},
{
"name": "GDB",
"bytes": "62"
},
{
"name": "HTML",
"bytes": "19508358"
},
{
"name": "M4",
"bytes": "168874"
},
{
"name": "Makefile",
"bytes": "2855062"
},
{
"name": "Perl",
"bytes": "50661"
},
{
"name": "Python",
"bytes": "300092"
},
{
"name": "Roff",
"bytes": "366736"
},
{
"name": "Shell",
"bytes": "785286"
}
],
"symlink_target": ""
} |
'''
Copyright (c) OS-Networks, http://os-networks.net
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the HWIOS Project 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 DEVELOPERS ``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 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.'''
import sys
import random
from twisted.spread.pb import PBServerFactory
from twisted.cred import portal
from twisted.application import internet
from zope.interface import implements, Interface
from twisted.spread.flavors import Referenceable, NoSuchMethod
from twisted.spread.pb import _JellyableAvatarMixin, IPerspective, IUsernameMD5Password
from twisted.python.components import registerAdapter
from twisted.cred import credentials, error
from twisted.cred.credentials import IAnonymous, ICredentials, IUsernamePassword
from twisted.cred.credentials import IUsernameHashedPassword, Anonymous
from twisted.internet import defer
from twisted.python import failure, log
from hwios.core.application import HWIOS
from dsm_server import DSMServer,DSMRealm,DSMCredChecker,DSMPortalRoot
class DsmService(object):
"""
Twisted PB Service for remote service management
"""
def __init__(self,service_config, hwios_config):
self.hwios_config = hwios_config
self.config = service_config
self.realm = DSMRealm()
self.realm.server = DSMServer(self)
django_checker = DSMCredChecker()
p = portal.Portal(self.realm)
p.registerChecker(django_checker)
pr = DSMPortalRoot(p)
if self.hwios_config.has_option('general','ssl'):
from twisted.internet import ssl
from hwios.core.connection import ServerContextFactory
self.__service = internet.SSLServer(self.config.getint('service','port'),PBServerFactory(pr),ServerContextFactory())
else:
if self.config.getboolean('service','ssl') == True:
from twisted.internet import ssl
from hwios.core.connection import ServerContextFactory
self.__service = internet.SSLServer(self.config.getint('service','port'),PBServerFactory(pr),ServerContextFactory())
else:
self.__service = internet.TCPServer(self.config.getint('service','port'),PBServerFactory(pr))
def get_service(self):
return self.__service
def register_server(self,pb_server):
HWIOS.pb_server = pb_server
def update_pb_pool(self,pb_clients):
HWIOS.pb_pool = pb_clients
def notify(self,data):
print data
#dispatch a pb call to the matching
def dispatch(self, url, params):
try:
method = HWIOS.ws_realm.dispatcher.route(url)
if method is None: raise MethodNotFound()
t = type(params)
if t is list:
#mix client and list params in
method[2]['params'] = params
res = getattr(method[0],method[1])(**method[2])
elif t is dict:
params.update(method[2])
res = getattr(method[0],method[1])(**params)
else: raise InvalidParams()
if isinstance(res, defer.Deferred):
res.addBoth(self.respAny)
return
except Exception, e:
res = e
def respResult(self, result):
print result
def respErr(self, err):
log.err(err)
#self.transport.write(HWIOS.tools.json_encode({'error':'error'}))
class JsonRPCErr(Exception):
def __call__(self):
ret = {'code': self.code, 'message': self.message}
if self.args:
ret['data'] = self.args[0]
return ret;
class ParseErr(JsonRPCErr):
code = -32700
message = "Parse error."
class InvalidReq(JsonRPCErr):
code = -32600
message = "Invalid Request."
class MethodNotFound(JsonRPCErr):
code = -32601
message = "Method not found."
class InvalidParams(JsonRPCErr):
code = -32602
message = "Invalid params."
class InternalError(JsonRPCErr):
code = -32603
message = "Internal error."
| {
"content_hash": "eb532926f8687bd6a89dbca053fc4bfd",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 132,
"avg_line_length": 39.74264705882353,
"alnum_prop": 0.6732654949121184,
"repo_name": "Knygar/hwios",
"id": "17162d28f70b9c1b9aa851f1f78ebbc0c5b8c3c1",
"size": "5405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services/dsm/service.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
require_relative "../../../spec_helper"
require "kontena/cli/services/services_helper"
module Kontena::Cli::Services
describe ServicesHelper do
subject{klass.new}
let(:klass) { Class.new { include ServicesHelper } }
let(:client) do
double
end
let(:token) do
'token'
end
before(:each) do
allow(subject).to receive(:client).with(token).and_return(client)
allow(subject).to receive(:current_grid).and_return('test-grid')
end
describe '#create_service' do
it 'creates POST grids/:grid/:name/services request to Kontena Server' do
expect(client).to receive(:post).with('grids/test-grid/services', {'name' => 'test-service'})
subject.create_service(token, 'test-grid', {'name' => 'test-service'})
end
end
describe '#update_service' do
it 'creates PUT services/:id request to Kontena Server' do
expect(client).to receive(:put).with('services/test-grid/1', {'name' => 'test-service'})
subject.update_service(token, '1', {'name' => 'test-service'})
end
end
describe '#get_service' do
it 'creates GET services/:id request to Kontena Server' do
expect(client).to receive(:get).with('services/test-grid/test-service')
subject.get_service(token, 'test-service')
end
end
describe '#deploy_service' do
it 'creates POST services/:id/deploy request to Kontena Server' do
allow(client).to receive(:get).with('services/test-grid/1').and_return({'state' => 'running'})
expect(client).to receive(:post).with('services/test-grid/1/deploy', {'strategy' => 'ha'})
subject.deploy_service(token, '1', {'strategy' => 'ha'})
end
it 'polls Kontena Server until service is running' do
allow(client).to receive(:post).with('services/test-grid/1/deploy', anything)
expect(client).to receive(:get).with('services/test-grid/1').twice.and_return({'state' => 'deploying'}, {'state' => 'running'})
subject.deploy_service(token, '1', {'strategy' => 'ha'})
end
end
describe '#parse_ports' do
it 'raises error if node_port is missing' do
expect{
subject.parse_ports(["80"])
}.to raise_error(ArgumentError)
end
it 'raises error if container_port is missing' do
expect{
subject.parse_ports(["80:"])
}.to raise_error(ArgumentError)
end
it 'returns hash of port options' do
valid_result = [{
container_port: '80',
node_port: '80',
protocol: 'tcp'
}]
port_options = subject.parse_ports(['80:80'])
expect(port_options).to eq(valid_result)
end
end
describe '#parse_links' do
it 'raises error if service name is missing' do
expect{
subject.parse_links([""])
}.to raise_error(ArgumentError)
end
it 'returns hash of link options' do
valid_result = [{
name: 'db',
alias: 'mysql',
}]
link_options = subject.parse_links(['db:mysql'])
expect(link_options).to eq(valid_result)
end
end
describe '#parse_service_id' do
it 'adds current_grid if service_id is missing prefix' do
expect(subject.parse_service_id('mysql')).to eq('test-grid/mysql')
end
it 'does not add current_grid if service id includes prefix' do
expect(subject.parse_service_id('second-grid/mysql')).to eq('second-grid/mysql')
end
end
end
end
| {
"content_hash": "37d0ec834a0cd2ed722120bee00356d7",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 135,
"avg_line_length": 32.21818181818182,
"alnum_prop": 0.6060948081264108,
"repo_name": "magiknono/kontena",
"id": "ebb08eef6ef44bfdc9cca6fac1b95893e8afac22",
"size": "3544",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "cli/spec/kontena/cli/services/services_helper_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2020"
},
{
"name": "Ruby",
"bytes": "349206"
},
{
"name": "Shell",
"bytes": "46881"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
// Logs controller
angular
.module('logs')
.controller('LogsController', LogsController);
LogsController.$inject = ['$scope', '$state', 'Authentication', 'logResolve'];
function LogsController ($scope, $state, Authentication, log) {
var vm = this;
vm.authentication = Authentication;
vm.log = log;
vm.error = null;
vm.form = {};
vm.remove = remove;
vm.save = save;
// Remove existing Log
function remove() {
if (confirm('Tem certeza de que deseja excluir?')) {
vm.log.$remove($state.go('logs.list'));
}
}
// Save Log
function save(isValid) {
console.log('entrou');
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.form.logForm');
return false;
}
// TODO: move create/update logic to service
if (vm.log._id) {
vm.log.$update(successCallback, errorCallback);
} else {
vm.log.$save(successCallback, errorCallback);
}
function successCallback(res) {
$state.go('logs.list', {
logId: res._id
});
}
function errorCallback(res) {
vm.error = res.data.message;
}
}
}
}());
| {
"content_hash": "aaf56634838bf4290092bd000d460d9e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 80,
"avg_line_length": 22.25,
"alnum_prop": 0.5634028892455859,
"repo_name": "joelbleichuvehl/fedora-server-config-0.5.0.beta",
"id": "0efd4da92239a6e9cf8af132a2af1daa7685aba8",
"size": "1246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/logs-system/client/controllers/logs.client.controller.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2293"
},
{
"name": "HTML",
"bytes": "130553"
},
{
"name": "JavaScript",
"bytes": "686968"
},
{
"name": "Shell",
"bytes": "736"
}
],
"symlink_target": ""
} |
IPC_STRUCT_TRAITS_BEGIN(page_load_metrics::PageLoadTiming)
IPC_STRUCT_TRAITS_MEMBER(navigation_start)
IPC_STRUCT_TRAITS_MEMBER(response_start)
IPC_STRUCT_TRAITS_MEMBER(dom_content_loaded_event_start)
IPC_STRUCT_TRAITS_MEMBER(load_event_start)
IPC_STRUCT_TRAITS_MEMBER(first_layout)
IPC_STRUCT_TRAITS_MEMBER(first_paint)
IPC_STRUCT_TRAITS_MEMBER(first_text_paint)
IPC_STRUCT_TRAITS_MEMBER(first_image_paint)
IPC_STRUCT_TRAITS_MEMBER(first_contentful_paint)
IPC_STRUCT_TRAITS_MEMBER(parse_start)
IPC_STRUCT_TRAITS_MEMBER(parse_stop)
IPC_STRUCT_TRAITS_MEMBER(parse_blocked_on_script_load_duration)
IPC_STRUCT_TRAITS_MEMBER(
parse_blocked_on_script_load_from_document_write_duration)
IPC_STRUCT_TRAITS_END()
IPC_STRUCT_TRAITS_BEGIN(page_load_metrics::PageLoadMetadata)
IPC_STRUCT_TRAITS_MEMBER(behavior_flags)
IPC_STRUCT_TRAITS_END()
// Sent from renderer to browser process when the PageLoadTiming for the
// associated frame changed.
IPC_MESSAGE_ROUTED2(PageLoadMetricsMsg_TimingUpdated,
page_load_metrics::PageLoadTiming,
page_load_metrics::PageLoadMetadata)
| {
"content_hash": "50b1fe65bf35bd4389e38586f0fc4d6d",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 72,
"avg_line_length": 43.61538461538461,
"alnum_prop": 0.7671957671957672,
"repo_name": "danakj/chromium",
"id": "1403667d59af2b399a7d8b11d73f163a6f3d686e",
"size": "1642",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/common/page_load_metrics/page_load_metrics_messages.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
/**
* UserApplePie v4 Forum Models Plugin
*
* UserApplePie - Forum Plugin
* @author David (DaVaR) Sargent <[email protected]>
* @version 2.1.2 for UAP v.4.3.0
*/
/** Forum model **/
namespace App\Plugins\Forum\Models;
use App\System\Models,
Libs\Url;
class Forum extends Models {
/**
* globalForumSetting
*
* get setting for requested setting.
*
* @param $action which setting to get
*
* @return string returns requested setting
*/
public function globalForumSetting($action){
$data = $this->db->select("
SELECT setting_value
FROM ".PREFIX."forum_settings
WHERE setting_title = :action
LIMIT 1
",
array(':action' => $action));
return $data[0]->setting_value;
}
/**
* forum_categories
*
* get list of all enabled forum categories.
*
* @return array returns all categories
*/
public function forum_categories(){
$data = $this->db->select("
SELECT
*
FROM
".PREFIX."forum_cat
WHERE
forum_name = 'forum'
GROUP BY
forum_title
ORDER BY
forum_order_title
ASC
");
return $data;
}
/**
* forum_titles
*
* get list of all enabled forum titles.
*
* @return array returns all titles
*/
public function forum_titles(){
$data = $this->db->select("
SELECT
a.*,
COUNT(DISTINCT t.forum_post_id) AS total_topics_display,
COUNT(DISTINCT r.id) AS total_topic_replys_display
FROM
".PREFIX."forum_cat AS a
LEFT OUTER JOIN
".PREFIX."forum_posts AS t
ON a.forum_id = t.forum_id
LEFT OUTER JOIN
".PREFIX."forum_post_replies AS r
ON a.forum_id = r.fpr_id
WHERE
a.forum_name = 'forum'
GROUP BY
a.forum_id
ORDER BY
a.forum_order_cat
ASC
");
return $data;
}
/**
* forum_recent_posts
*
* get list of all recent posts in forum ordered by date.
*
* @return array returns all recent forum posts
*/
public function forum_recent_posts($limit = "10"){
$data = $this->db->select("
SELECT
fp.forum_post_id as forum_post_id, fp.forum_id as forum_id,
fp.forum_user_id as forum_user_id, fp.forum_title as forum_title,
fp.forum_url as forum_url,
fp.forum_edit_date as forum_edit_date,
fp.forum_timestamp as forum_timestamp, fpr.id as id,
fpr.fpr_post_id as fpr_post_id, fpr.fpr_id as fpr_id,
fpr.fpr_user_id as fpr_user_id,
fpr.fpr_edit_date as fpr_edit_date,
fpr.fpr_timestamp as fpr_timestamp,
GREATEST(fp.forum_timestamp, COALESCE(fpr.fpr_timestamp, '00-00-00 00:00:00')) AS tstamp
FROM ".PREFIX."forum_posts fp
LEFT JOIN ".PREFIX."forum_post_replies fpr
ON fp.forum_post_id = fpr.fpr_post_id
WHERE fp.allow = 'TRUE'
AND ((fp.forum_publish = '1' AND fpr.forum_publish = '1') OR fp.forum_publish = '1' OR fpr.forum_publish = '1')
ORDER BY tstamp DESC
LIMIT $limit
");
return $data;
}
/**
* forum_cat
*
* get category data for current topic (Category)
*
* @param int $where_id = forum_id
*
* @return string returns forum category data (forum_cat)
*/
public function forum_cat($where_id){
$data = $this->db->select("
SELECT forum_cat
FROM ".PREFIX."forum_cat
WHERE forum_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_cat;
}
/**
* forum_cat_des
*
* get category data for current topic (Description)
*
* @param int $where_id = forum_id
*
* @return string returns forum category data (forum_des)
*/
public function forum_cat_des($where_id){
$data = $this->db->select("
SELECT forum_des
FROM ".PREFIX."forum_cat
WHERE forum_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_des;
}
/**
* forum_title
*
* get category data for current topic (Title)
*
* @param int $where_id = forum_id
*
* @return string returns forum category data (forum_title)
*/
public function forum_title($where_id){
$data = $this->db->select("
SELECT forum_title
FROM ".PREFIX."forum_cat
WHERE forum_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_title;
}
/**
* forum_topics
*
* get list of topics for given category
*
* @param int $where_id = forum_id
* @param string $limit data from Paginator class
*
* @return array returns forum topics list data
*/
public function forum_topics($where_id, $limit = null){
$data = $this->db->select("
SELECT
sub1.*,
fpr_post_id,
fpr_user_id AS LR_UserID,
fpr_timestamp AS LR_TimeStamp,
COUNT(fpr_post_id) AS total_topic_replys
FROM (
SELECT sub2.* FROM (
SELECT
fp.forum_post_id as forum_post_id, fp.forum_id as forum_id,
fp.forum_user_id as forum_user_id, fp.forum_title as forum_title,
fp.forum_url as forum_url,
fp.forum_edit_date as forum_edit_date,
fp.forum_timestamp as forum_timestamp,
fp.forum_status as forum_status, fpr.id as id,
fpr.fpr_post_id as fpr_post_id, fpr.fpr_id as fpr_id,
fpr.fpr_user_id as fpr_user_id,
fpr.fpr_edit_date as fpr_edit_date,
fpr.fpr_timestamp as fpr_timestamp,
GREATEST(fp.forum_timestamp, COALESCE(fpr.fpr_timestamp, '00-00-00 00:00:00')) AS tstamp
FROM ".PREFIX."forum_posts fp
LEFT JOIN ".PREFIX."forum_post_replies fpr
ON fp.forum_post_id = fpr.fpr_post_id
WHERE forum_id = :where_id
AND fp.allow = 'TRUE'
AND ((fp.forum_publish = '1' AND fpr.forum_publish = '1') OR fp.forum_publish = '1' OR fpr.forum_publish = '1')
) sub2
ORDER BY tstamp DESC
) sub1
GROUP BY forum_post_id
ORDER BY tstamp DESC
$limit
",
array(':where_id' => $where_id));
return $data;
}
/**
* forum_topic_cat_id
*
* get category ID that Topic is related to
*
* @param int $where_id = forum_post_id
*
* @return string returns forum category data (forum_id)
*/
public function forum_topic_cat_id($where_id){
$data = $this->db->select("
SELECT forum_id
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_id;
}
/**
* get Topic ID based on URL request
* @param string $forum_url
* @return int data
*/
public function get_topic_url_id($forum_url){
$data = $this->db->select("
SELECT forum_post_id
FROM ".PREFIX."forum_posts
WHERE forum_url = :forum_url
LIMIT 1
",
array(':forum_url' => $forum_url));
return $data[0]->forum_post_id;
}
/**
* get Topic ID based on URL request
* @param string $forum_url
* @param int $id
* @return int data
*/
public function get_topic_url($forum_url, $id){
$data = $this->db->select("
SELECT forum_post_id
FROM ".PREFIX."forum_posts
WHERE forum_url = :forum_url
AND NOT forum_post_id = :forum_post_id
LIMIT 1
",
array(':forum_url' => $forum_url, ':forum_post_id' => $id));
return $data[0]->forum_post_id;
}
/**
* topic_title
*
* get Topic Title for header
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_title)
*/
public function topic_title($where_id){
$data = $this->db->select("
SELECT forum_title
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_title;
}
/**
* topic_creator
*
* get Topic Creator userID
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_user_id)
*/
public function topic_creator($where_id){
$data = $this->db->select("
SELECT forum_user_id
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_user_id;
}
/**
* topic_date
*
* get Topic timestamp for age
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_timestamp)
*/
public function topic_date($where_id){
$data = $this->db->select("
SELECT forum_timestamp
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_timestamp;
}
/**
* topic_content
*
* get Topic Content data
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_content)
*/
public function topic_content($where_id){
$data = $this->db->select("
SELECT forum_content
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_content;
}
/**
* topic_edit_date
*
* get Topic Content last edit date for age
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_edit_date)
*/
public function topic_edit_date($where_id){
$data = $this->db->select("
SELECT forum_edit_date
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_edit_date;
}
/**
* topic_userID
*
* get Topic Content owner userID
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_user_id)
*/
public function topic_userID($where_id){
$data = $this->db->select("
SELECT forum_user_id
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_user_id;
}
/**
* topic_status
*
* get Topic Status (Locked = 2 or Open = 1)
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_status)
*/
public function topic_status($where_id){
$data = $this->db->select("
SELECT forum_status
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_status;
}
/**
* topic_allow
*
* get Topic Allowed Status (TRUE = show | FALSE = hide)
*
* @param int $where_id = forum_post_id
*
* @return string
*/
public function topic_allow($where_id){
$data = $this->db->select("
SELECT allow
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->allow;
}
/**
* topic_hidden_userID
*
* get Topic hidden userID
*
* @param int $where_id = forum_post_id
*
* @return int
*/
public function topic_hidden_userID($where_id){
$data = $this->db->select("
SELECT hide_userID
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->hide_userID;
}
/**
* topic_hidden_reason
*
* get Topic Hidden Reason
*
* @param int $where_id = forum_post_id
*
* @return string
*/
public function topic_hidden_reason($where_id){
$data = $this->db->select("
SELECT hide_reason
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->hide_reason;
}
/**
* topic_hidden_timestamp
*
* get Topic Hidden DateTime
*
* @param int $where_id = forum_post_id
*
* @return string
*/
public function topic_hidden_timestamp($where_id){
$data = $this->db->select("
SELECT hide_timestamp
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->hide_timestamp;
}
/**
* forum_topic_replys
*
* get list of topic replies for given topic
*
* @param int $where_id = fpr_post_id
* @param string $limit data from Paginator class
*
* @return array returns forum topic reply list data
*/
public function forum_topic_replys($where_id, $limit = null){
$data = $this->db->select("
SELECT
*
FROM
".PREFIX."forum_post_replies
WHERE
fpr_post_id = :where_id
AND
forum_publish = '1'
ORDER BY
id
ASC
$limit
",
array(':where_id' => $where_id));
return $data;
}
/**
* getTotalReplys
*
* get total count of topic replys for topic
*
* @param int $where_id = fpr_post_id
*
* @return int returns forum topic reply count
*/
public function getTotalReplys($where_id){
$data = $this->db->selectCount("
SELECT
*
FROM
".PREFIX."forum_post_replies
WHERE
fpr_post_id = :where_id
AND
forum_publish = '1'
ORDER BY
id
ASC
",
array(':where_id' => $where_id));
return $data;
}
/**
* sendTopic
*
* create new topic
*
* @param int $forum_user_id Current user's ID
* @param int $forum_id Current Category's ID
* @param string $forum_title New topic's title
* @param string $forum_content New topic's content
*
* @return booleen true/false
*/
public function sendTopic($forum_user_id, $forum_id, $forum_title, $forum_content, $forum_publish = "0"){
/** Generate URL based on title **/
$forum_url = URL::generateSafeSlug($forum_title);
/** Check to see if URL already exsist **/
if(SELF::get_topic_url_id($forum_url)){
$rand_string = mt_rand(1, 99);
$forum_url = $forum_url."-rn".$rand_string;
}
/** Add to Forum Posts **/
$query = $this->db->insert(PREFIX.'forum_posts', array('forum_id' => $forum_id, 'forum_user_id' => $forum_user_id, 'forum_title' => $forum_title, 'forum_url' => $forum_url, 'forum_content' => $forum_content, 'forum_publish' => $forum_publish));
$last_insert_id = $this->db->lastInsertId('forum_post_id');
$query_track = $this->db->insert(PREFIX.'forum_post_tracker', array('forum_post_id' => $last_insert_id));
$count = $query + $query_track;
// Check to make sure Topic was Created
if($count > 0){
// Run post count group checker
self::newMemberPostsChecker($forum_user_id);
return $last_insert_id;
}else{
return false;
}
}
/**
* sendNewImage
*
* add uploaded image to database
*
* @param in $user_id
* @param string $imageName
* @param string $imageLocation
* @param int $imageSize
* @param int $forumID
* @param int $forumTopicID
* @param int $forumTopicReplyID
*
* @return booleen true/false
*/
public function sendNewImage($user_id, $imageName, $imageLocation, $imageSize, $forumID, $forumTopicID, $forumTopicReplyID = null){
// Update forum images table
$query = $this->db->insert(PREFIX.'forum_images', array('user_id' => $user_id, 'imageName' => $imageName, 'imageLocation' => $imageLocation, 'imageSize' => $imageSize, 'forumID' => $forumID, 'forumTopicID' => $forumTopicID, 'forumTopicReplyID' => $forumTopicReplyID));
// Check to make sure row was inserted
if($query > 0){
return true;
}else{
return false;
}
}
/**
* getForumImagesTopic
*
* get topic images
*
* @param int $id
*
* @return string returns image url
*/
public function getForumImagesTopic($topic_id){
$data = $this->db->select("
SELECT imageName, imageLocation
FROM ".PREFIX."forum_images
WHERE forumTopicID = :topic_id
AND forumTopicReplyID IS NULL
",
array(':topic_id' => $topic_id));
return $data;
}
/**
* updateTopic
*
* edit/update topic
*
* @param int $id Current Topic's ID
* @param string $forum_title Topic's title
* @param string $forum_content Topic's content
*
* @return booleen true/false
*/
public function updateTopic($id, $forum_title, $forum_content){
/** Generate URL based on title **/
$forum_url = URL::generateSafeSlug($forum_title);
/** Check to see if URL already exsist **/
if(SELF::get_topic_url($forum_url, $id)){
$forum_url = $forum_url."-".$id;
}
/** Update the Forum Post **/
$query = $this->db->update(PREFIX.'forum_posts', array('forum_title' => $forum_title, 'forum_content' => $forum_content, 'forum_url' => $forum_url, 'forum_edit_date' => date('Y-m-d H:i:s')), array('forum_post_id' => $id));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}
/**
* topic_is_published
*
* check if Forum topic is published
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_publish)
*/
public function topic_is_published($where_id){
$data = $this->db->select("
SELECT forum_publish
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_publish;
}
/**
* updateSavedTopic
*
* edit/update saved topic
*
* @param int $id Current Topic's ID
* @param string $forum_title Topic's title
* @param string $forum_content Topic's content
*
* @return booleen true/false
*/
public function updateSavedTopic($id, $forum_title, $forum_content, $forum_publish = "0"){
/** Generate URL based on title **/
$forum_url = URL::generateSafeSlug($forum_title);
/** Check to see if URL already exsist **/
if(SELF::get_topic_url($forum_url, $id)){
$rand_string = mt_rand(1, 99);
$forum_url = $forum_url."-rn".$rand_string;
}
// Check to see if Topic is already published. If so then block edits.
$is_published = SELF::topic_is_published($id);
if($is_published == "0"){
// Update messages table
$query = $this->db->update(PREFIX.'forum_posts', array('forum_title' => $forum_title, 'forum_content' => $forum_content, 'forum_publish' => $forum_publish, 'forum_timestamp' => date('Y-m-d H:i:s')), array('forum_post_id' => $id));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}else{
return false;
}
}
/**
* getTotalOwner
*
* get topic owner's user ID
*
* @param int $where_id = forum_post_id
*
* @return string returns forum topic data (forum_user_id)
*/
public function getTopicOwner($where_id){
$data = $this->db->select("
SELECT forum_user_id
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_user_id;
}
/**
* sendTopicReply
*
* create new topic reply
*
* @param int $fpr_user_id Current user ID
* @param int $fpr_post_id Current Category ID
* @param int $fpr_id Current Topic ID
* @param string $forum_content New Reply's Content
*
* @return booleen/int ID or false
*/
public function sendTopicReply($fpr_user_id, $fpr_post_id, $fpr_id, $fpr_content, $subscribe, $forum_publish = "1", $afpr_post_id = ""){
// Check for email subscription status
if($subscribe == true){$subscribe = "true";}else{$subscribe = "false";}
if(!empty($afpr_post_id)){
// Update Reply
$query = $this->db->update(PREFIX.'forum_post_replies', array('fpr_content' => $fpr_content, 'fpr_timestamp' => date('Y-m-d H:i:s'), 'forum_publish' => '1'), array('id' => $afpr_post_id));
$last_insert_id = true;
}else{
// Insert Reply
$query = $this->db->insert(PREFIX.'forum_post_replies', array('fpr_post_id' => $fpr_post_id, 'fpr_user_id' => $fpr_user_id, 'fpr_id' => $fpr_id, 'fpr_content' => $fpr_content, 'subscribe_email' => $subscribe, 'forum_publish' => $forum_publish, 'fpr_timestamp' => date("Y-m-d H:i:s")));
$last_insert_id = $this->db->lastInsertId('id');
}
$query_track = $this->db->insert(PREFIX.'forum_post_tracker', array('forum_post_id' => $fpr_post_id, 'forum_reply_id' => $last_insert_id));
$count = $query + $query_track;
// Check to make sure Topic was Created
if($count > 0){
// Run post count group checker
self::newMemberPostsChecker($fpr_user_id);
return $last_insert_id;
}else{
return false;
}
}
/**
* lastTopicReplyID
*
* get last topic reply inserted ID
*
* @param int $where_id = fpr_post_id
*
* @return string returns forum topic reply data (id)
*/
public function lastTopicReplyID($where_id){
$data = $this->db->select("
SELECT id
FROM ".PREFIX."forum_post_replies
WHERE fpr_post_id = :where_id
ORDER BY id DESC
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->id;
}
/**
* updateTopicReply
*
* edit topic reply
*
* @param int $id Current Topic ID
* @param string $fpr_content New Reply's Content
*
* @return booleen true/false
*/
public function updateTopicReply($id, $fpr_content, $userID){
// Update messages table
$query = $this->db->update(PREFIX.'forum_post_replies', array('fpr_content' => $fpr_content, 'fpr_edit_date' => date('Y-m-d H:i:s')), array('id' => $id, 'fpr_user_id' => $userID));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}
/**
* updateTopicReplySavedReply
*
* edit topic reply
*
* @param int $id Current Topic ID
* @param string $fpr_content New Reply's Content
*
* @return booleen true/false
*/
public function updateSavedTopicReply($id, $fpr_content){
// Check to see if Topic is already published. If so then block edits.
$is_published = SELF::topic_reply_is_published($id);
if($is_published == "0"){
// Update forum post reply
$query = $this->db->update(PREFIX.'forum_post_replies', array('fpr_content' => $fpr_content, 'fpr_timestamp' => date('Y-m-d H:i:s')), array('id' => $id));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}else{
return false;
}
}
/**
* topic_reply_is_published
*
* check if forum reply is published
*
* @param int $where_id = id
*
* @return string returns forum reply data (forum_publish)
*/
public function topic_reply_is_published($where_id){
$data = $this->db->select("
SELECT forum_publish
FROM ".PREFIX."forum_post_replies
WHERE id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->forum_publish;
}
/**
* getReplyContent
*
* get content for selected forum topic reply
*
* @param int $where_id = id
*
* @return array returns forum topic reply
*/
public function getReplyContent($where_id){
$data = $this->db->select("
SELECT
fpr_content
FROM
".PREFIX."forum_post_replies
WHERE
id = :where_id
AND
forum_publish = '0'
",
array(':where_id' => $where_id));
return $data[0]->fpr_content;
}
/**
* getReplyOwner
*
* get topic reply owner user ID
*
* @param int $where_id = id
*
* @return string returns forum topic reply data (fpr_user_id)
*/
public function getReplyOwner($where_id){
$data = $this->db->select("
SELECT fpr_user_id
FROM ".PREFIX."forum_post_replies
WHERE id = :where_id
LIMIT 1
",
array(':where_id' => $where_id));
return $data[0]->fpr_user_id;
}
/**
* updateTopicLockStatus
*
* edit topic lock/unlock status
*
* @param int $id Current Topic ID
* @param int $setting (1)Open (2)Locked
*
* @return booleen true/false
*/
public function updateTopicLockStatus($id, $setting){
// Update messages table
$query = $this->db->update(PREFIX.'forum_posts', array('forum_status' => $setting), array('forum_post_id' => $id));
// Check to make sure Topic was Created
if($query){
return true;
}else{
return false;
}
}
/**
* updateTopicHideStatus
*
* edit topic hide/unhide status
*
* @param int $id Current Topic ID
* @param int $setting (FALSE)Show (TRUE)Hide
* @param int $user_id
* @param string $reason
*
* @return booleen true/false
*/
public function updateTopicHideStatus($id, $setting, $user_id = "0", $reason = ""){
// Update messages table
$current_datetime = date("Y-m-d H:i:s");
$query = $this->db->update(PREFIX.'forum_posts', array('allow' => $setting, 'hide_userID' => $user_id, 'hide_reason' => $reason, 'hide_timestamp' => $current_datetime), array('forum_post_id' => $id));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}
/**
* updateReplyHideStatus
*
* edit topic reply hide/unhide status
*
* @param int $id Current Topic Reply ID
* @param int $setting (FALSE)Show (TRUE)Hide
* @param int $user_id
* @param string $reason
*
* @return booleen true/false
*/
public function updateReplyHideStatus($id, $setting, $user_id = "0", $reason = ""){
// Update messages table
$current_datetime = date("Y-m-d H:i:s");
$query = $this->db->update(PREFIX.'forum_post_replies', array('allow' => $setting, 'hide_userID' => $user_id, 'hide_reason' => $reason, 'hide_timestamp' => $current_datetime), array('id' => $id));
// Check to make sure Topic was Created
if($query > 0){
return true;
}else{
return false;
}
}
/**
* checkUserPosted
*
* checks if current user has posted to topic
*
* @param int $post_id = current topic ID
* @param int $userID = current user ID
*
* @return boolean has user posted (true/false)
*/
public function checkUserPosted($post_id, $user_id){
$data = $this->db->selectCount("
SELECT * FROM (
(
SELECT fpr_post_id, fpr_user_id
FROM ".PREFIX."forum_post_replies
WHERE fpr_post_id = :post_id
AND fpr_user_id = :user_id
)
UNION ALL
(
SELECT forum_post_id, forum_user_id
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :post_id
AND forum_user_id = :user_id
)
) AS uniontable
",
array(':post_id' => $post_id, ':user_id' => $user_id));
if($data > 0){
return true;
}else {
return false;
}
}
/**
* checkTopicSubscribe
*
* checks if current user is subscribed to topic
*
* @param int $post_id = current topic ID
* @param int $userID = current user ID
*
* @return boolean is user subscribed (true/false)
*/
public function checkTopicSubscribe($post_id, $user_id){
$data = $this->db->selectCount("
SELECT * FROM (
(
SELECT fpr_post_id, fpr_user_id, subscribe_email
FROM ".PREFIX."forum_post_replies
WHERE fpr_post_id = :post_id
AND fpr_user_id = :user_id
AND subscribe_email = 'true'
)
UNION ALL
(
SELECT forum_post_id, forum_user_id, subscribe_email
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :post_id
AND forum_user_id = :user_id
AND subscribe_email = 'true'
)
) AS uniontable
",
array(':post_id' => $post_id, ':user_id' => $user_id));
if($data > 0){
return true;
}else {
return false;
}
}
/**
* updateTopicSubcrition
*
* edit user's topic subcrition status (true/false)
*
* @param int $id Current Topic ID
* @param int $user_id
* @param int $setting (1)Open (2)Locked
*
* @return booleen true/false
*/
public function updateTopicSubcrition($id, $user_id, $setting){
// Update messages table
$query_a = $this->db->update(PREFIX.'forum_posts', array('subscribe_email' => $setting), array('forum_post_id' => $id, 'forum_user_id' => $user_id));
$query_b = $this->db->update(PREFIX.'forum_post_replies', array('subscribe_email' => $setting), array('fpr_post_id' => $id, 'fpr_user_id' => $user_id));
$count = $query_a + $query_b;
// Check to make sure Topic was Created
if($count > 0){
return true;
}else{
return false;
}
}
/**
* getTopicSubscribeEmail
*
* get list of emails of all subscribed users to topic
* sends email to all the users subscribed
*
* @param int $post_id = current topic ID
* @param int $userID = current user ID
*
*/
public function sendTopicSubscribeEmails($post_id, $user_id, $topic_title, $topic_cat, $reply_content){
// Get userID's for all that are set to be notified except current user
$data = $this->db->select("
SELECT * FROM (
(
SELECT fpr_user_id AS F_UID
FROM ".PREFIX."forum_post_replies
WHERE fpr_post_id = :post_id
AND subscribe_email = 'true'
AND NOT fpr_user_id = :userID
GROUP BY fpr_user_id
ORDER BY fpr_timestamp DESC
)
UNION ALL
(
SELECT forum_user_id AS F_UID
FROM ".PREFIX."forum_posts
WHERE forum_post_id = :post_id
AND subscribe_email = 'true'
AND NOT forum_user_id = :userID
GROUP BY forum_user_id
ORDER BY forum_timestamp DESC
)
) AS uniontable
GROUP BY `F_UID`
ORDER BY `F_UID` ASC
",
array(':post_id' => $post_id, ':userID' => $user_id));
foreach($data as $row){
// Get to user data
$email_data = $this->db->select("
SELECT email, username
FROM ".PREFIX."users
WHERE userID = :where_id
LIMIT 1
",
array(':where_id' => $row->F_UID));
// Get from user data
$email_from_data = $this->db->select("
SELECT username
FROM ".PREFIX."users
WHERE userID = :where_id
LIMIT 1
",
array(':where_id' => $user_id));
//EMAIL MESSAGE USING PHPMAILER
$mail = new \Libs\PhpMailer\Mail();
$mail->setFrom(SITEEMAIL, EMAIL_FROM_NAME);
$mail->addAddress($email_data[0]->email);
$mail_subject = SITE_TITLE . " - Forum - ".$email_from_data[0]->username." replied to {$topic_title}";
$mail->subject($mail_subject);
$body = "Hello ".$email_data[0]->username."<br/><br/>";
$body .= SITE_TITLE . " - Forum Notification<br/>
<br/>
Category: $topic_cat<br/>
Topic: $topic_title<br/>
Reply by: ".$email_from_data[0]->username."<br/>
<br/>
Reply Content:<br/>
************************<br/>
$reply_content<br/>
************************<br/>";
$body .= "You may check the reply at: <b><a href=\"" . SITE_URL . "/Topic/$id\">" . SITE_TITLE . " Forum - $topic_title</a></b>";
$mail->body($body);
$mail->send();
}
}
/**
* forum_search
*
* get list of topics for given category
*
* @param int $search = Search String
* @param string $limit data from Paginator class
*
* @return array returns forum topics list data
*/
public function forum_search($search, $limit = null){
$data = $this->db->select("
(SELECT
forum_id,
forum_post_id,
forum_timestamp as tstamp,
forum_content as content,
forum_title as title,
forum_user_id,
forum_status,
forum_publish,
allow,
forum_url,
'main_post' AS post_type
FROM
`".PREFIX."forum_posts`
WHERE
(forum_content LIKE :search
OR
forum_title LIKE :search)
AND
allow = 'TRUE'
AND
forum_publish = '1')
UNION ALL
(SELECT
fpr.fpr_id,
fpr.fpr_post_id,
fpr.fpr_timestamp as tstamp,
fpr.fpr_content as content,
fp.forum_title as title,
fpr.fpr_user_id as forum_user_id,
fp.forum_status as forum_status,
fpr.forum_publish,
fpr.allow,
fp.forum_url as forum_url,
'reply_post' AS post_type
FROM
`".PREFIX."forum_post_replies` fpr
LEFT JOIN
`".PREFIX."forum_posts` fp
ON
fp.forum_post_id = fpr.fpr_post_id
WHERE
fpr_content LIKE :search
AND
fpr.allow = 'TRUE'
AND
fpr.forum_publish = '1')
ORDER BY tstamp DESC
$limit
",
array(':search' => '%'.$search.'%'));
return $data;
}
/**
* forum_tracker
*
* updates/adds forum user tracking informatinon
* tracking information used to track if a user has
* viewed a new topic or reply
*
* @param int $user_id = User's ID
* @param int $post_id = Forum Post ID
*
*/
public function forum_tracker($user_id = "", $post_id = "", $forum_id = ""){
/* Make sure there is a user id and post id */
if(!empty($user_id) && !empty($post_id) && !empty($forum_id)){
/* Check to see is user has a record for post_id */
$check_table = $this->db->selectCount("SELECT * FROM ".PREFIX."forum_tracker WHERE user_id=:user_id AND post_id=:post_id AND forum_id=:forum_id",array(":user_id"=>$user_id, ":post_id"=>$post_id, 'forum_id'=>$forum_id));
$current_date = date("Y-m-d H:i:s");
if($check_table > 0){
/* Data found for user - Update current date */
return $this->db->update(PREFIX.'forum_tracker', array('last_visit' => $current_date), array('user_id' => $user_id, 'post_id' => $post_id, 'forum_id' => $forum_id));
}else{
/* No Data for user - Create new entry */
return $this->db->insert(PREFIX.'forum_tracker', array('user_id' => $user_id, 'post_id' => $post_id, 'forum_id' => $forum_id, 'last_visit' => $current_date));
}
}
}
/**
* newMemberPostsChecker
*
* Check to see if user has posted enough times to
* change their group status from New Member to Member
*
* @param int user_id
* @param int posts_count
*/
public function newMemberPostsChecker($user_id = null){
if(SELF::globalForumSetting('forum_posts_group_change_enable') == 'true'){
$posts_count = \Libs\ForumStats::getTotalPosts($user_id);
if(isset($user_id) && isset($posts_count)){
// Check if user is in the New Member Group
$new_member_group = count($this->db->select("SELECT * FROM ".PREFIX."users_groups WHERE userID = :userID AND groupID = 1", array(':userID' => $user_id)));
if($new_member_group == 1){
$forum_posts_group_change = SELF::globalForumSetting('forum_posts_group_change');
if($posts_count >= $forum_posts_group_change){
return $this->db->update(PREFIX."users_groups", array('groupID' => '2'), array('userID' => $user_id));
}
}
}
}
}
/**
* user_forum_perms
*
* Check to which groups can do stuff on the forum
*
* @param id user_id
* @param string forum_group
*
* @return array group permissions
*/
public function group_forum_perms($user_id = null, $forum_group = null){
if(isset($user_id)){
/* Get user's groups */
$user_groups = $this->db->select("
SELECT
userID, groupID
FROM
".PREFIX."users_groups
WHERE
userID = :userID
",
array(':userID' => $user_id));
$match[] = null;
/* Check to see if user's groups match any of the forum groups */
foreach ($user_groups as $ug) {
$data = count($this->db->select("
SELECT *
FROM ".PREFIX."forum_groups
WHERE groupID = :groupID
AND forum_group = :forum_group
",
array(':groupID' => $ug->groupID, ':forum_group' => $forum_group)));
if($data > 0){
$match[] = true;
}
}
/* Check to see if user is part of group */
if (in_array(true, $match)) {
return true;
}else{
return false;
}
}else{
/* No user data */
return false;
}
}
/**
* getUnPublishedWork
*
* get category data for current topic (Title)
*
* @param int $where_id = forum_id
*
* @return string returns forum category data (forum_title)
*/
public function getUnPublishedWork($forum_user_id, $forum_id){
$data = $this->db->select("
SELECT forum_post_id
FROM ".PREFIX."forum_posts
WHERE forum_user_id = :forum_user_id
AND forum_id = :forum_id
AND forum_publish = '0'
ORDER BY forum_post_id DESC
LIMIT 1
",
array(':forum_user_id' => $forum_user_id, ':forum_id' => $forum_id));
return $data[0]->forum_post_id;
}
/**
* getUnPublishedWorkReply
*
* get un published topic reply for selected topic and user
*
* @param int $where_id = forum_id
*
* @return string
*/
public function getUnPublishedWorkReply($forum_user_id, $topic_id){
$data = $this->db->select("
SELECT id
FROM ".PREFIX."forum_post_replies
WHERE fpr_user_id = :forum_user_id
AND fpr_post_id = :fpr_post_id
AND forum_publish = '0'
ORDER BY id DESC
LIMIT 1
",
array(':forum_user_id' => $forum_user_id, ':fpr_post_id' => $topic_id));
return $data[0]->id;
}
}
| {
"content_hash": "c3f6690a6e399bd40ef6bb89cd67a97a",
"timestamp": "",
"source": "github",
"line_count": 1381,
"max_line_length": 293,
"avg_line_length": 29.60101375814627,
"alnum_prop": 0.5319112502752025,
"repo_name": "UserApplePie/UserApplePie-v3",
"id": "d8f65048fc3c25ac1752f95dde636955334d0037",
"size": "40879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Plugins/Forum/Models/Forum.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "6043"
},
{
"name": "CSS",
"bytes": "68732"
},
{
"name": "HTML",
"bytes": "13"
},
{
"name": "JavaScript",
"bytes": "11166"
},
{
"name": "PHP",
"bytes": "730821"
}
],
"symlink_target": ""
} |
<!-- HTML header for doxygen 1.8.18-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.9.4"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>OR-Tools: dense_doubly_linked_list.h File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="styleSheet.tmp.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="orLogo.png"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">OR-Tools
 <span id="projectnumber">9.4</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.9.4 -->
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
var searchBox = new SearchBox("searchBox", "search",'Search','.html');
/* @license-end */
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
/* @license-end */
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
/* @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT */
$(document).ready(function(){initNavTree('dense__doubly__linked__list_8h.html',''); initResizable(); });
/* @license-end */
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</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>
<div class="header">
<div class="summary">
<a href="#nested-classes">Classes</a> |
<a href="#namespaces">Namespaces</a> </div>
<div class="headertitle"><div class="title">dense_doubly_linked_list.h File Reference</div></div>
</div><!--header-->
<div class="contents">
<p><a href="dense__doubly__linked__list_8h_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a id="nested-classes" name="nested-classes"></a>
Classes</h2></td></tr>
<tr class="memitem:"><td class="memItemLeft" align="right" valign="top">class  </td><td class="memItemRight" valign="bottom"><a class="el" href="classoperations__research_1_1_dense_doubly_linked_list.html">DenseDoublyLinkedList</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a id="namespaces" name="namespaces"></a>
Namespaces</h2></td></tr>
<tr class="memitem:namespaceoperations__research"><td class="memItemLeft" align="right" valign="top">namespace  </td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceoperations__research.html">operations_research</a></td></tr>
<tr class="memdesc:namespaceoperations__research"><td class="mdescLeft"> </td><td class="mdescRight">Collection of objects used to extend the <a class="el" href="classoperations__research_1_1_constraint.html" title="A constraint is the main modeling object.">Constraint</a> <a class="el" href="classoperations__research_1_1_solver.html" title="Solver Class.">Solver</a> library. <br /></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- HTML footer for doxygen 1.8.18-->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_a7cc1eeded8f693d0da6c729bc88c45a.html">ortools</a></li><li class="navelem"><a class="el" href="dir_80dda7a75b0dfcf996988638a63eb03a.html">algorithms</a></li><li class="navelem"><a class="el" href="dense__doubly__linked__list_8h.html">dense_doubly_linked_list.h</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.9.4 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "d0823302d17718b427e3b2fbb6cbf83d",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 400,
"avg_line_length": 48.66393442622951,
"alnum_prop": 0.6868788950648476,
"repo_name": "or-tools/docs",
"id": "b4607e7b488cedebc01f577b3906c1748eb4ab4f",
"size": "5937",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/cpp/dense__doubly__linked__list_8h.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import numpy as np
import pytest
from scipy.sparse import issparse
from scipy.sparse import coo_matrix
from scipy.sparse import csc_matrix
from scipy.sparse import csr_matrix
from scipy.sparse import dok_matrix
from scipy.sparse import lil_matrix
from sklearn.utils.multiclass import type_of_target
from sklearn.utils._testing import assert_array_equal
from sklearn.utils._testing import ignore_warnings
from sklearn.utils import _to_object_array
from sklearn.preprocessing._label import LabelBinarizer
from sklearn.preprocessing._label import MultiLabelBinarizer
from sklearn.preprocessing._label import LabelEncoder
from sklearn.preprocessing._label import label_binarize
from sklearn.preprocessing._label import _inverse_binarize_thresholding
from sklearn.preprocessing._label import _inverse_binarize_multiclass
from sklearn import datasets
iris = datasets.load_iris()
def toarray(a):
if hasattr(a, "toarray"):
a = a.toarray()
return a
def test_label_binarizer():
# one-class case defaults to negative label
# For dense case:
inp = ["pos", "pos", "pos", "pos"]
lb = LabelBinarizer(sparse_output=False)
expected = np.array([[0, 0, 0, 0]]).T
got = lb.fit_transform(inp)
assert_array_equal(lb.classes_, ["pos"])
assert_array_equal(expected, got)
assert_array_equal(lb.inverse_transform(got), inp)
# For sparse case:
lb = LabelBinarizer(sparse_output=True)
got = lb.fit_transform(inp)
assert issparse(got)
assert_array_equal(lb.classes_, ["pos"])
assert_array_equal(expected, got.toarray())
assert_array_equal(lb.inverse_transform(got.toarray()), inp)
lb = LabelBinarizer(sparse_output=False)
# two-class case
inp = ["neg", "pos", "pos", "neg"]
expected = np.array([[0, 1, 1, 0]]).T
got = lb.fit_transform(inp)
assert_array_equal(lb.classes_, ["neg", "pos"])
assert_array_equal(expected, got)
to_invert = np.array([[1, 0],
[0, 1],
[0, 1],
[1, 0]])
assert_array_equal(lb.inverse_transform(to_invert), inp)
# multi-class case
inp = ["spam", "ham", "eggs", "ham", "0"]
expected = np.array([[0, 0, 0, 1],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[1, 0, 0, 0]])
got = lb.fit_transform(inp)
assert_array_equal(lb.classes_, ['0', 'eggs', 'ham', 'spam'])
assert_array_equal(expected, got)
assert_array_equal(lb.inverse_transform(got), inp)
def test_label_binarizer_unseen_labels():
lb = LabelBinarizer()
expected = np.array([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
got = lb.fit_transform(['b', 'd', 'e'])
assert_array_equal(expected, got)
expected = np.array([[0, 0, 0],
[1, 0, 0],
[0, 0, 0],
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]])
got = lb.transform(['a', 'b', 'c', 'd', 'e', 'f'])
assert_array_equal(expected, got)
def test_label_binarizer_set_label_encoding():
lb = LabelBinarizer(neg_label=-2, pos_label=0)
# two-class case with pos_label=0
inp = np.array([0, 1, 1, 0])
expected = np.array([[-2, 0, 0, -2]]).T
got = lb.fit_transform(inp)
assert_array_equal(expected, got)
assert_array_equal(lb.inverse_transform(got), inp)
lb = LabelBinarizer(neg_label=-2, pos_label=2)
# multi-class case
inp = np.array([3, 2, 1, 2, 0])
expected = np.array([[-2, -2, -2, +2],
[-2, -2, +2, -2],
[-2, +2, -2, -2],
[-2, -2, +2, -2],
[+2, -2, -2, -2]])
got = lb.fit_transform(inp)
assert_array_equal(expected, got)
assert_array_equal(lb.inverse_transform(got), inp)
@ignore_warnings
def test_label_binarizer_errors():
# Check that invalid arguments yield ValueError
one_class = np.array([0, 0, 0, 0])
lb = LabelBinarizer().fit(one_class)
multi_label = [(2, 3), (0,), (0, 2)]
with pytest.raises(ValueError):
lb.transform(multi_label)
lb = LabelBinarizer()
with pytest.raises(ValueError):
lb.transform([])
with pytest.raises(ValueError):
lb.inverse_transform([])
with pytest.raises(ValueError):
LabelBinarizer(neg_label=2, pos_label=1)
with pytest.raises(ValueError):
LabelBinarizer(neg_label=2, pos_label=2)
with pytest.raises(ValueError):
LabelBinarizer(neg_label=1, pos_label=2, sparse_output=True)
# Fail on y_type
with pytest.raises(ValueError):
_inverse_binarize_thresholding(y=csr_matrix([[1, 2], [2, 1]]),
output_type="foo", classes=[1, 2],
threshold=0)
# Sequence of seq type should raise ValueError
y_seq_of_seqs = [[], [1, 2], [3], [0, 1, 3], [2]]
with pytest.raises(ValueError):
LabelBinarizer().fit_transform(y_seq_of_seqs)
# Fail on the number of classes
with pytest.raises(ValueError):
_inverse_binarize_thresholding(y=csr_matrix([[1, 2], [2, 1]]),
output_type="foo",
classes=[1, 2, 3],
threshold=0)
# Fail on the dimension of 'binary'
with pytest.raises(ValueError):
_inverse_binarize_thresholding(y=np.array([[1, 2, 3], [2, 1, 3]]),
output_type="binary",
classes=[1, 2, 3],
threshold=0)
# Fail on multioutput data
with pytest.raises(ValueError):
LabelBinarizer().fit(np.array([[1, 3], [2, 1]]))
with pytest.raises(ValueError):
label_binarize(np.array([[1, 3], [2, 1]]), classes=[1, 2, 3])
@pytest.mark.parametrize(
"values, classes, unknown",
[(np.array([2, 1, 3, 1, 3], dtype='int64'),
np.array([1, 2, 3], dtype='int64'), np.array([4], dtype='int64')),
(np.array(['b', 'a', 'c', 'a', 'c'], dtype=object),
np.array(['a', 'b', 'c'], dtype=object),
np.array(['d'], dtype=object)),
(np.array(['b', 'a', 'c', 'a', 'c']),
np.array(['a', 'b', 'c']), np.array(['d']))],
ids=['int64', 'object', 'str'])
def test_label_encoder(values, classes, unknown):
# Test LabelEncoder's transform, fit_transform and
# inverse_transform methods
le = LabelEncoder()
le.fit(values)
assert_array_equal(le.classes_, classes)
assert_array_equal(le.transform(values), [1, 0, 2, 0, 2])
assert_array_equal(le.inverse_transform([1, 0, 2, 0, 2]), values)
le = LabelEncoder()
ret = le.fit_transform(values)
assert_array_equal(ret, [1, 0, 2, 0, 2])
with pytest.raises(ValueError, match="unseen labels"):
le.transform(unknown)
def test_label_encoder_negative_ints():
le = LabelEncoder()
le.fit([1, 1, 4, 5, -1, 0])
assert_array_equal(le.classes_, [-1, 0, 1, 4, 5])
assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]),
[1, 2, 3, 3, 4, 0, 0])
assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]),
[0, 1, 4, 4, 5, -1, -1])
with pytest.raises(ValueError):
le.transform([0, 6])
@pytest.mark.parametrize("dtype", ['str', 'object'])
def test_label_encoder_str_bad_shape(dtype):
le = LabelEncoder()
le.fit(np.array(["apple", "orange"], dtype=dtype))
msg = "should be a 1d array"
with pytest.raises(ValueError, match=msg):
le.transform("apple")
def test_label_encoder_errors():
# Check that invalid arguments yield ValueError
le = LabelEncoder()
with pytest.raises(ValueError):
le.transform([])
with pytest.raises(ValueError):
le.inverse_transform([])
# Fail on unseen labels
le = LabelEncoder()
le.fit([1, 2, 3, -1, 1])
msg = "contains previously unseen labels"
with pytest.raises(ValueError, match=msg):
le.inverse_transform([-2])
with pytest.raises(ValueError, match=msg):
le.inverse_transform([-2, -3, -4])
# Fail on inverse_transform("")
msg = r"should be a 1d array.+shape \(\)"
with pytest.raises(ValueError, match=msg):
le.inverse_transform("")
@pytest.mark.parametrize(
"values",
[np.array([2, 1, 3, 1, 3], dtype='int64'),
np.array(['b', 'a', 'c', 'a', 'c'], dtype=object),
np.array(['b', 'a', 'c', 'a', 'c'])],
ids=['int64', 'object', 'str'])
def test_label_encoder_empty_array(values):
le = LabelEncoder()
le.fit(values)
# test empty transform
transformed = le.transform([])
assert_array_equal(np.array([]), transformed)
# test empty inverse transform
inverse_transformed = le.inverse_transform([])
assert_array_equal(np.array([]), inverse_transformed)
def test_sparse_output_multilabel_binarizer():
# test input as iterable of iterables
inputs = [
lambda: [(2, 3), (1,), (1, 2)],
lambda: ({2, 3}, {1}, {1, 2}),
lambda: iter([iter((2, 3)), iter((1,)), {1, 2}]),
]
indicator_mat = np.array([[0, 1, 1],
[1, 0, 0],
[1, 1, 0]])
inverse = inputs[0]()
for sparse_output in [True, False]:
for inp in inputs:
# With fit_transform
mlb = MultiLabelBinarizer(sparse_output=sparse_output)
got = mlb.fit_transform(inp())
assert issparse(got) == sparse_output
if sparse_output:
# verify CSR assumption that indices and indptr have same dtype
assert got.indices.dtype == got.indptr.dtype
got = got.toarray()
assert_array_equal(indicator_mat, got)
assert_array_equal([1, 2, 3], mlb.classes_)
assert mlb.inverse_transform(got) == inverse
# With fit
mlb = MultiLabelBinarizer(sparse_output=sparse_output)
got = mlb.fit(inp()).transform(inp())
assert issparse(got) == sparse_output
if sparse_output:
# verify CSR assumption that indices and indptr have same dtype
assert got.indices.dtype == got.indptr.dtype
got = got.toarray()
assert_array_equal(indicator_mat, got)
assert_array_equal([1, 2, 3], mlb.classes_)
assert mlb.inverse_transform(got) == inverse
with pytest.raises(ValueError):
mlb.inverse_transform(csr_matrix(np.array([[0, 1, 1],
[2, 0, 0],
[1, 1, 0]])))
def test_multilabel_binarizer():
# test input as iterable of iterables
inputs = [
lambda: [(2, 3), (1,), (1, 2)],
lambda: ({2, 3}, {1}, {1, 2}),
lambda: iter([iter((2, 3)), iter((1,)), {1, 2}]),
]
indicator_mat = np.array([[0, 1, 1],
[1, 0, 0],
[1, 1, 0]])
inverse = inputs[0]()
for inp in inputs:
# With fit_transform
mlb = MultiLabelBinarizer()
got = mlb.fit_transform(inp())
assert_array_equal(indicator_mat, got)
assert_array_equal([1, 2, 3], mlb.classes_)
assert mlb.inverse_transform(got) == inverse
# With fit
mlb = MultiLabelBinarizer()
got = mlb.fit(inp()).transform(inp())
assert_array_equal(indicator_mat, got)
assert_array_equal([1, 2, 3], mlb.classes_)
assert mlb.inverse_transform(got) == inverse
def test_multilabel_binarizer_empty_sample():
mlb = MultiLabelBinarizer()
y = [[1, 2], [1], []]
Y = np.array([[1, 1],
[1, 0],
[0, 0]])
assert_array_equal(mlb.fit_transform(y), Y)
def test_multilabel_binarizer_unknown_class():
mlb = MultiLabelBinarizer()
y = [[1, 2]]
Y = np.array([[1, 0], [0, 1]])
warning_message = 'unknown class.* will be ignored'
with pytest.warns(UserWarning, match=warning_message):
matrix = mlb.fit(y).transform([[4, 1], [2, 0]])
Y = np.array([[1, 0, 0], [0, 1, 0]])
mlb = MultiLabelBinarizer(classes=[1, 2, 3])
with pytest.warns(UserWarning, match=warning_message):
matrix = mlb.fit(y).transform([[4, 1], [2, 0]])
assert_array_equal(matrix, Y)
def test_multilabel_binarizer_given_classes():
inp = [(2, 3), (1,), (1, 2)]
indicator_mat = np.array([[0, 1, 1],
[1, 0, 0],
[1, 0, 1]])
# fit_transform()
mlb = MultiLabelBinarizer(classes=[1, 3, 2])
assert_array_equal(mlb.fit_transform(inp), indicator_mat)
assert_array_equal(mlb.classes_, [1, 3, 2])
# fit().transform()
mlb = MultiLabelBinarizer(classes=[1, 3, 2])
assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat)
assert_array_equal(mlb.classes_, [1, 3, 2])
# ensure works with extra class
mlb = MultiLabelBinarizer(classes=[4, 1, 3, 2])
assert_array_equal(mlb.fit_transform(inp),
np.hstack(([[0], [0], [0]], indicator_mat)))
assert_array_equal(mlb.classes_, [4, 1, 3, 2])
# ensure fit is no-op as iterable is not consumed
inp = iter(inp)
mlb = MultiLabelBinarizer(classes=[1, 3, 2])
assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat)
# ensure a ValueError is thrown if given duplicate classes
err_msg = "The classes argument contains duplicate classes. Remove " \
"these duplicates before passing them to MultiLabelBinarizer."
mlb = MultiLabelBinarizer(classes=[1, 3, 2, 3])
with pytest.raises(ValueError, match=err_msg):
mlb.fit(inp)
def test_multilabel_binarizer_multiple_calls():
inp = [(2, 3), (1,), (1, 2)]
indicator_mat = np.array([[0, 1, 1],
[1, 0, 0],
[1, 0, 1]])
indicator_mat2 = np.array([[0, 1, 1],
[1, 0, 0],
[1, 1, 0]])
# first call
mlb = MultiLabelBinarizer(classes=[1, 3, 2])
assert_array_equal(mlb.fit_transform(inp), indicator_mat)
# second call change class
mlb.classes = [1, 2, 3]
assert_array_equal(mlb.fit_transform(inp), indicator_mat2)
def test_multilabel_binarizer_same_length_sequence():
# Ensure sequences of the same length are not interpreted as a 2-d array
inp = [[1], [0], [2]]
indicator_mat = np.array([[0, 1, 0],
[1, 0, 0],
[0, 0, 1]])
# fit_transform()
mlb = MultiLabelBinarizer()
assert_array_equal(mlb.fit_transform(inp), indicator_mat)
assert_array_equal(mlb.inverse_transform(indicator_mat), inp)
# fit().transform()
mlb = MultiLabelBinarizer()
assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat)
assert_array_equal(mlb.inverse_transform(indicator_mat), inp)
def test_multilabel_binarizer_non_integer_labels():
tuple_classes = _to_object_array([(1,), (2,), (3,)])
inputs = [
([('2', '3'), ('1',), ('1', '2')], ['1', '2', '3']),
([('b', 'c'), ('a',), ('a', 'b')], ['a', 'b', 'c']),
([((2,), (3,)), ((1,),), ((1,), (2,))], tuple_classes),
]
indicator_mat = np.array([[0, 1, 1],
[1, 0, 0],
[1, 1, 0]])
for inp, classes in inputs:
# fit_transform()
mlb = MultiLabelBinarizer()
inp = np.array(inp, dtype=object)
assert_array_equal(mlb.fit_transform(inp), indicator_mat)
assert_array_equal(mlb.classes_, classes)
indicator_mat_inv = np.array(mlb.inverse_transform(indicator_mat),
dtype=object)
assert_array_equal(indicator_mat_inv, inp)
# fit().transform()
mlb = MultiLabelBinarizer()
assert_array_equal(mlb.fit(inp).transform(inp), indicator_mat)
assert_array_equal(mlb.classes_, classes)
indicator_mat_inv = np.array(mlb.inverse_transform(indicator_mat),
dtype=object)
assert_array_equal(indicator_mat_inv, inp)
mlb = MultiLabelBinarizer()
with pytest.raises(TypeError):
mlb.fit_transform([({}), ({}, {'a': 'b'})])
def test_multilabel_binarizer_non_unique():
inp = [(1, 1, 1, 0)]
indicator_mat = np.array([[1, 1]])
mlb = MultiLabelBinarizer()
assert_array_equal(mlb.fit_transform(inp), indicator_mat)
def test_multilabel_binarizer_inverse_validation():
inp = [(1, 1, 1, 0)]
mlb = MultiLabelBinarizer()
mlb.fit_transform(inp)
# Not binary
with pytest.raises(ValueError):
mlb.inverse_transform(np.array([[1, 3]]))
# The following binary cases are fine, however
mlb.inverse_transform(np.array([[0, 0]]))
mlb.inverse_transform(np.array([[1, 1]]))
mlb.inverse_transform(np.array([[1, 0]]))
# Wrong shape
with pytest.raises(ValueError):
mlb.inverse_transform(np.array([[1]]))
with pytest.raises(ValueError):
mlb.inverse_transform(np.array([[1, 1, 1]]))
def test_label_binarize_with_class_order():
out = label_binarize([1, 6], classes=[1, 2, 4, 6])
expected = np.array([[1, 0, 0, 0], [0, 0, 0, 1]])
assert_array_equal(out, expected)
# Modified class order
out = label_binarize([1, 6], classes=[1, 6, 4, 2])
expected = np.array([[1, 0, 0, 0], [0, 1, 0, 0]])
assert_array_equal(out, expected)
out = label_binarize([0, 1, 2, 3], classes=[3, 2, 0, 1])
expected = np.array([[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[1, 0, 0, 0]])
assert_array_equal(out, expected)
def check_binarized_results(y, classes, pos_label, neg_label, expected):
for sparse_output in [True, False]:
if ((pos_label == 0 or neg_label != 0) and sparse_output):
with pytest.raises(ValueError):
label_binarize(y, classes=classes, neg_label=neg_label,
pos_label=pos_label,
sparse_output=sparse_output)
continue
# check label_binarize
binarized = label_binarize(y, classes=classes, neg_label=neg_label,
pos_label=pos_label,
sparse_output=sparse_output)
assert_array_equal(toarray(binarized), expected)
assert issparse(binarized) == sparse_output
# check inverse
y_type = type_of_target(y)
if y_type == "multiclass":
inversed = _inverse_binarize_multiclass(binarized, classes=classes)
else:
inversed = _inverse_binarize_thresholding(binarized,
output_type=y_type,
classes=classes,
threshold=((neg_label +
pos_label) /
2.))
assert_array_equal(toarray(inversed), toarray(y))
# Check label binarizer
lb = LabelBinarizer(neg_label=neg_label, pos_label=pos_label,
sparse_output=sparse_output)
binarized = lb.fit_transform(y)
assert_array_equal(toarray(binarized), expected)
assert issparse(binarized) == sparse_output
inverse_output = lb.inverse_transform(binarized)
assert_array_equal(toarray(inverse_output), toarray(y))
assert issparse(inverse_output) == issparse(y)
def test_label_binarize_binary():
y = [0, 1, 0]
classes = [0, 1]
pos_label = 2
neg_label = -1
expected = np.array([[2, -1], [-1, 2], [2, -1]])[:, 1].reshape((-1, 1))
check_binarized_results(y, classes, pos_label, neg_label, expected)
# Binary case where sparse_output = True will not result in a ValueError
y = [0, 1, 0]
classes = [0, 1]
pos_label = 3
neg_label = 0
expected = np.array([[3, 0], [0, 3], [3, 0]])[:, 1].reshape((-1, 1))
check_binarized_results(y, classes, pos_label, neg_label, expected)
def test_label_binarize_multiclass():
y = [0, 1, 2]
classes = [0, 1, 2]
pos_label = 2
neg_label = 0
expected = 2 * np.eye(3)
check_binarized_results(y, classes, pos_label, neg_label, expected)
with pytest.raises(ValueError):
label_binarize(y, classes=classes, neg_label=-1, pos_label=pos_label,
sparse_output=True)
def test_label_binarize_multilabel():
y_ind = np.array([[0, 1, 0], [1, 1, 1], [0, 0, 0]])
classes = [0, 1, 2]
pos_label = 2
neg_label = 0
expected = pos_label * y_ind
y_sparse = [sparse_matrix(y_ind)
for sparse_matrix in [coo_matrix, csc_matrix, csr_matrix,
dok_matrix, lil_matrix]]
for y in [y_ind] + y_sparse:
check_binarized_results(y, classes, pos_label, neg_label,
expected)
with pytest.raises(ValueError):
label_binarize(y, classes=classes, neg_label=-1, pos_label=pos_label,
sparse_output=True)
def test_invalid_input_label_binarize():
with pytest.raises(ValueError):
label_binarize([0, 2], classes=[0, 2], pos_label=0, neg_label=1)
with pytest.raises(ValueError, match="continuous target data is not "):
label_binarize([1.2, 2.7], classes=[0, 1])
with pytest.raises(ValueError, match="mismatch with the labels"):
label_binarize([[1, 3]], classes=[1, 2, 3])
def test_inverse_binarize_multiclass():
got = _inverse_binarize_multiclass(csr_matrix([[0, 1, 0],
[-1, 0, -1],
[0, 0, 0]]),
np.arange(3))
assert_array_equal(got, np.array([1, 1, 0]))
| {
"content_hash": "e44878918a9a12389cfcee987f9927c0",
"timestamp": "",
"source": "github",
"line_count": 618,
"max_line_length": 79,
"avg_line_length": 35.99514563106796,
"alnum_prop": 0.54488649134637,
"repo_name": "glemaitre/scikit-learn",
"id": "fd396ceb90712c3602cc12ca329035248d922810",
"size": "22245",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "sklearn/preprocessing/tests/test_label.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "2232"
},
{
"name": "C",
"bytes": "41025"
},
{
"name": "C++",
"bytes": "146835"
},
{
"name": "Makefile",
"bytes": "1711"
},
{
"name": "Python",
"bytes": "10011694"
},
{
"name": "Shell",
"bytes": "44168"
}
],
"symlink_target": ""
} |
set -xe
base=/tmp/release
gitbuilder_host=$1
codename=$2
git_ceph_url=$3
sha1=$4
flavor=$5
arch=$6
canonical_tags=$7
sudo apt-get update
sudo apt-get install -y git
export BUILDPACKAGES_CANONICAL_TAGS=$canonical_tags
source $(dirname $0)/common.sh
init_ceph $git_ceph_url $sha1
#codename=$(lsb_release -sc)
releasedir=$base/$(lsb_release -si)/WORKDIR
#
# git describe provides a version that is
# a) human readable
# b) is unique for each commit
# c) compares higher than any previous commit
# d) contains the short hash of the commit
#
vers=$(git describe --match "v*" | sed s/^v//)
#
# always set the debian version to 1 which is ok because the debian
# directory is included in the sources and the upstream version will
# change each time it is modified.
#
dvers="$vers-1"
: ${NPROC:=$(nproc)}
ceph_dir=$(pwd)
function build_package() {
rm -fr $releasedir
mkdir -p $releasedir
#
# remove all files not under git so they are not
# included in the distribution.
#
git clean -qdxff
fileext="gz"
# autotools only works in jewel and below
if [[ ! -e "make-dist" ]] ; then
#
# creating the distribution tarbal requires some configure
# options (otherwise parts of the source tree will be left out).
#
./autogen.sh
# Building with LTTNG on Ubuntu Precise is not possible.
# It fails the LTTNG-is-sane check (it misses headers)
# And the Debian rules files leave it out anyway
case $codename in
precise) lttng_opt="--without-lttng" ;;
*) lttng_opt="--with-lttng" ;;
esac
./configure $(flavor2configure $flavor) \
--with-rocksdb --with-ocf \
--with-nss --with-debug --enable-cephfs-java \
$lttng_opt --with-babeltrace
#
# use distdir= to set the name of the top level directory of the
# tarbal to match the desired version
#
make distdir=ceph-$vers dist
else
./make-dist
fileext="bz2"
fi
#
# rename the tarbal to match debian conventions and extract it
#
mv ceph-$vers.tar.$fileext $releasedir/ceph_$vers.orig.tar.$fileext
tar -C $releasedir -xf $releasedir/ceph_$vers.orig.tar.$fileext
#
# copy the debian directory over
#
cp -a debian $releasedir/ceph-$vers/debian
cd $releasedir
#
# uncomment to remove -dbg packages
# because they are large and take time to build
#
#perl -ni -e 'print if(!(/^Package: .*-dbg$/../^$/))' ceph-$vers/debian/control
#perl -pi -e 's/--dbg-package.*//' ceph-$vers/debian/rules
#
# update the changelog to match the desired version
#
cd ceph-$vers
local chvers=$(head -1 debian/changelog | perl -ne 's/.*\(//; s/\).*//; print')
if [ "$chvers" != "$dvers" ]; then
DEBEMAIL="[email protected]" dch -D $codename --force-distribution -b -v "$dvers" "new version"
fi
#
# create the packages (with ccache)
#
export CEPH_EXTRA_CONFIGURE_ARGS=$(flavor2configure $flavor)
j=$(maybe_parallel $NPROC $vers)
PATH=/usr/lib/ccache:$PATH dpkg-buildpackage $j -uc -us -sa
}
function build_repo() {
local gitbuilder_host=$1
sudo apt-get install -y reprepro
cd ${releasedir}/..
#
# Create a repository in a directory with a name structured
# as
#
base=ceph-deb-$codename-$arch-$flavor
sha1_dir=$codename/$base/sha1/$sha1
mkdir -p $sha1_dir/conf
cat > $sha1_dir/conf/distributions <<EOF
Codename: $codename
Suite: stable
Components: main
Architectures: i386 amd64 arm64 source
EOF
reprepro --basedir $sha1_dir include $codename WORKDIR/*.changes
echo $dvers > $sha1_dir/version
echo $sha1 > $sha1_dir/sha1
link_same $codename/$base/ref $ceph_dir $sha1
if test "$gitbuilder_host" ; then
cd $codename
sudo apt-get install -y rsync
RSYNC_RSH='ssh -o StrictHostKeyChecking=false' rsync -av $base/ $gitbuilder_host:/usr/share/nginx/html/$base/
fi
}
build_package
build_repo $gitbuilder_host
| {
"content_hash": "4b4c99615745cc4cb91b7d214d9f28bf",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 117,
"avg_line_length": 29.151079136690647,
"alnum_prop": 0.642152023692004,
"repo_name": "ktdreyer/teuthology",
"id": "fb7f4176d93d518d5bde3ae10e9d0c1fe2889ed7",
"size": "4789",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "teuthology/task/buildpackages/make-deb.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "307"
},
{
"name": "Jinja",
"bytes": "1096"
},
{
"name": "Lua",
"bytes": "2669"
},
{
"name": "Makefile",
"bytes": "4194"
},
{
"name": "Python",
"bytes": "1493007"
},
{
"name": "Shell",
"bytes": "61658"
}
],
"symlink_target": ""
} |
import os
import numpy as np
import sys
from collections import OrderedDict
import math
import torch
import torch.nn.functional as F
from torch import nn
from pytorch_lightning import LightningModule
from pytorch_lightning import seed_everything
from .doppelganger import DoppelGANger
from .network import RNNInitialStateType
from .loss import doppelganger_loss
from .util import gen_attribute_input_noise, gen_feature_input_noise,\
gen_feature_input_data_free, renormalize_per_sample
class DoppelGANger_pl(LightningModule):
def __init__(self,
data_feature_outputs,
data_attribute_outputs,
L_max,
num_real_attribute,
sample_len=10,
discriminator_num_layers=5,
discriminator_num_units=200,
attr_discriminator_num_layers=5,
attr_discriminator_num_units=200,
attribute_num_units=100,
attribute_num_layers=3,
feature_num_units=100,
feature_num_layers=1,
attribute_input_noise_dim=5,
addi_attribute_input_noise_dim=5,
d_gp_coe=10,
attr_d_gp_coe=10,
g_attr_d_coe=1,
d_lr=0.001,
attr_d_lr=0.001,
g_lr=0.001,
g_rounds=1,
d_rounds=1,
**kwargs):
super().__init__()
self.automatic_optimization = False
self.save_hyperparameters("discriminator_num_layers",
"discriminator_num_units",
"attr_discriminator_num_layers",
"attr_discriminator_num_units",
"attribute_num_units",
"attribute_num_layers",
"feature_num_units",
"feature_num_layers",
"attribute_input_noise_dim",
"addi_attribute_input_noise_dim",
"d_gp_coe",
"attr_d_gp_coe",
"g_attr_d_coe",
"d_lr",
"attr_d_lr",
"g_lr",
"g_rounds",
"d_rounds",
"L_max",
"sample_len",
"num_real_attribute")
self.g_rounds = g_rounds
self.d_rounds = d_rounds
self.sample_len = sample_len
self.L_max = L_max
self.data_feature_outputs = data_feature_outputs
self.data_attribute_outputs = data_attribute_outputs
self.length = self.L_max // self.sample_len
self.real_attribute_mask = ([True] * num_real_attribute +
[False] * (len(data_attribute_outputs)-num_real_attribute))
self.gen_flag_dims = []
dim = 0
from bigdl.nano.utils.log4Error import invalidInputError
for output in self.data_feature_outputs:
if output.is_gen_flag:
if output.dim != 2:
invalidInputError(False,
"gen flag output's dim should be 2")
self.gen_flag_dims = [dim, dim + 1]
break
dim += output.dim
if len(self.gen_flag_dims) == 0:
invalidInputError(False, "gen flag not found")
# model init
self.model =\
DoppelGANger(
data_feature_outputs=self.data_feature_outputs,
data_attribute_outputs=self.data_attribute_outputs,
real_attribute_mask=self.real_attribute_mask,
sample_len=self.sample_len,
L_max=self.L_max,
num_packing=1, # any num other than 1 will be supported later
discriminator_num_layers=self.hparams.discriminator_num_layers,
discriminator_num_units=self.hparams.discriminator_num_units,
attr_discriminator_num_layers=self.hparams.attr_discriminator_num_layers,
attr_discriminator_num_units=self.hparams.attr_discriminator_num_units,
attribute_num_units=self.hparams.attribute_num_units,
attribute_num_layers=self.hparams.attribute_num_layers,
feature_num_units=self.hparams.feature_num_units,
feature_num_layers=self.hparams.feature_num_layers,
attribute_input_noise_dim=self.hparams.attribute_input_noise_dim,
addi_attribute_input_noise_dim=self.hparams.addi_attribute_input_noise_dim,
initial_state=RNNInitialStateType.RANDOM) # currently we fix this value
def forward(self,
data_feature,
real_attribute_input_noise,
addi_attribute_input_noise,
feature_input_noise,
data_attribute):
return self.model([data_feature],
[real_attribute_input_noise],
[addi_attribute_input_noise],
[feature_input_noise],
[data_attribute])
def training_step(self, batch, batch_idx):
# data preparation
data_feature, data_attribute = batch
optimizer_d, optimizer_attr_d, optimizer_g = self.optimizers()
# generate noise input
real_attribute_input_noise = gen_attribute_input_noise(data_feature.shape[0])
addi_attribute_input_noise = gen_attribute_input_noise(data_feature.shape[0])
feature_input_noise = gen_feature_input_noise(data_feature.shape[0], self.length)
real_attribute_input_noise = torch.from_numpy(real_attribute_input_noise).float()
addi_attribute_input_noise = torch.from_numpy(addi_attribute_input_noise).float()
feature_input_noise = torch.from_numpy(feature_input_noise).float()
# g backward
# open the generator grad since we need to update the weights in g
for p in self.model.generator.parameters():
p.requires_grad = True
for i in range(self.g_rounds):
d_fake, attr_d_fake,\
d_real, attr_d_real = self(data_feature,
real_attribute_input_noise,
addi_attribute_input_noise,
feature_input_noise,
data_attribute)
g_loss, _, _ =\
doppelganger_loss(d_fake, attr_d_fake, d_real, attr_d_real)
optimizer_g.zero_grad()
self.manual_backward(g_loss)
optimizer_g.step()
# d backward
# close the generator grad since we only need to update the weights in d
for p in self.model.generator.parameters():
p.requires_grad = False
for i in range(self.d_rounds):
d_fake, attr_d_fake,\
d_real, attr_d_real = self(data_feature,
real_attribute_input_noise,
addi_attribute_input_noise,
feature_input_noise,
data_attribute)
_, d_loss, attr_d_loss =\
doppelganger_loss(d_fake, attr_d_fake, d_real, attr_d_real,
g_attr_d_coe=self.hparams.g_attr_d_coe,
gradient_penalty=True,
discriminator=self.model.discriminator,
attr_discriminator=self.model.attr_discriminator,
g_output_feature_train_tf=self.model.g_feature_train,
g_output_attribute_train_tf=self.model.g_attribute_train,
real_feature_pl=self.model.real_feature_pl,
real_attribute_pl=self.model.real_attribute_pl,
d_gp_coe=self.hparams.d_gp_coe,
attr_d_gp_coe=self.hparams.attr_d_gp_coe)
optimizer_d.zero_grad()
optimizer_attr_d.zero_grad()
self.manual_backward(d_loss)
self.manual_backward(attr_d_loss)
optimizer_d.step()
optimizer_attr_d.step()
# log tqdm
self.log("g_loss", g_loss.item(),
on_step=True, on_epoch=True, prog_bar=True, logger=True)
self.log("d_loss", d_loss.item(),
on_step=True, on_epoch=True, prog_bar=True, logger=True)
self.log("attr_d_loss", attr_d_loss.item(),
on_step=True, on_epoch=True, prog_bar=True, logger=True)
def configure_optimizers(self):
optimizer_d = torch.optim.Adam(self.model.discriminator.parameters(),
lr=self.hparams.d_lr, betas=(0.5, 0.999))
optimizer_attr_d = torch.optim.Adam(self.model.attr_discriminator.parameters(),
lr=self.hparams.attr_d_lr, betas=(0.5, 0.999))
optimizer_g = torch.optim.Adam(self.model.generator.parameters(),
lr=self.hparams.g_lr, betas=(0.5, 0.999))
return optimizer_d, optimizer_attr_d, optimizer_g
def sample_from(self,
real_attribute_input_noise,
addi_attribute_input_noise,
feature_input_noise,
feature_input_data,
batch_size=32):
features, attributes, gen_flags, lengths\
= self.model.sample_from(real_attribute_input_noise,
addi_attribute_input_noise,
feature_input_noise,
feature_input_data,
self.gen_flag_dims,
batch_size=batch_size)
return features, attributes, gen_flags, lengths
| {
"content_hash": "4610b8159ae00a41550f0e521445a8b9",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 95,
"avg_line_length": 47.77880184331797,
"alnum_prop": 0.5048225308641975,
"repo_name": "yangw1234/BigDL",
"id": "fbf96e5379a2b46ae7e90b2fd06452b73f5e53ca",
"size": "12708",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "python/chronos/src/bigdl/chronos/simulator/doppelganger/doppelganger_pl.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5342"
},
{
"name": "Dockerfile",
"bytes": "138760"
},
{
"name": "Java",
"bytes": "1321348"
},
{
"name": "Jupyter Notebook",
"bytes": "54063856"
},
{
"name": "Lua",
"bytes": "1904"
},
{
"name": "Makefile",
"bytes": "19253"
},
{
"name": "PowerShell",
"bytes": "1137"
},
{
"name": "PureBasic",
"bytes": "593"
},
{
"name": "Python",
"bytes": "8762180"
},
{
"name": "RobotFramework",
"bytes": "16117"
},
{
"name": "Scala",
"bytes": "13216038"
},
{
"name": "Shell",
"bytes": "844916"
}
],
"symlink_target": ""
} |
// Copyright (c) Jeremy W. Kuhne. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace WInterop.Console;
/// <summary>
/// Console output handle modes.
/// </summary>
/// <msdn><see cref="https://docs.microsoft.com/en-us/windows/console/getconsolemode"/></msdn>
[Flags]
public enum ConsoleOuputMode : uint
{
/// <summary>
/// [ENABLE_PROCESSED_OUTPUT]
/// </summary>
EnableProcessedOutput = 0x0001,
/// <summary>
/// [ENABLE_WRAP_AT_EOL_OUTPUT]
/// </summary>
EnalbeWrapAtEndOfLine = 0x0002,
/// <summary>
/// [ENABLE_VIRTUAL_TERMINAL_PROCESSING]
/// </summary>
EnableVirtualTerminalProcessing = 0x0004,
/// <summary>
/// [DISABLE_NEWLINE_AUTO_RETURN]
/// </summary>
DisableNewlineAutoReturn = 0x0008,
/// <summary>
/// [ENABLE_LVB_GRID_WORLDWIDE]
/// </summary>
EnableLvbGridWorldwide = 0x0010
} | {
"content_hash": "00923e12a6ce65ed6600e75440ad96f1",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 101,
"avg_line_length": 26.18918918918919,
"alnum_prop": 0.6429308565531475,
"repo_name": "JeremyKuhne/WInterop",
"id": "106419e0a40924cb7e49f9f4a928a98d95537756",
"size": "971",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/WInterop.Desktop/Console/ConsoleOuputMode.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2121"
},
{
"name": "C#",
"bytes": "2686796"
},
{
"name": "C++",
"bytes": "1778"
},
{
"name": "HTML",
"bytes": "92156"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="es">
<head>
<!-- Generated by javadoc (version 1.7.0_03) on Tue Jun 19 11:15:34 COT 2012 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>All Classes</title>
<meta name="date" content="2012-06-19">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="BESA/Local/Directory/AgLocalHandlerBESA.html" title="class in BESA.Local.Directory" target="classFrame">AgLocalHandlerBESA</a></li>
<li><a href="BESA/Local/LocalAdmBESA.html" title="class in BESA.Local" target="classFrame">LocalAdmBESA</a></li>
<li><a href="BESA/Local/Directory/LocalAdmHandlerBESA.html" title="class in BESA.Local.Directory" target="classFrame">LocalAdmHandlerBESA</a></li>
<li><a href="BESA/Local/Directory/LocalDirectoryBESA.html" title="class in BESA.Local.Directory" target="classFrame">LocalDirectoryBESA</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "0a06f16f63fae98edb9e1e1c3569a0ad",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 146,
"avg_line_length": 50.90909090909091,
"alnum_prop": 0.7071428571428572,
"repo_name": "Coregraph/Ayllu",
"id": "76aae8eeecb58a2b20ec0d0379eded10ea9c5d87",
"size": "1120",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "BESA/BESA-DOC/jdoc/LocalBESA/allclasses-frame.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "180550"
},
{
"name": "Erlang",
"bytes": "3957"
},
{
"name": "Groovy",
"bytes": "528"
},
{
"name": "Java",
"bytes": "2313027"
},
{
"name": "JavaScript",
"bytes": "60888"
},
{
"name": "Python",
"bytes": "66"
},
{
"name": "Scala",
"bytes": "3361"
},
{
"name": "Shell",
"bytes": "214934"
}
],
"symlink_target": ""
} |
import mechanize
class Navigator():
br = mechanize.Browser()
logged_in = False
def clearBrowser(self):
self.br = mechanize.Browser()
def login(self, username, password):
login_url = "https://auth.vt.edu/login?service=https://webapps.banner.vt.edu/banner-cas-prod/authorized/banner/SelfService"
br = self.br
br.open(login_url)
br.select_form(nr=0) # Select the 'Login' Form
br.set_handle_robots(False) # Ignore robots.txt file
br.form["username"] = username
br.form["password"] = password
resp = br.submit()
if ("Invalid username or password" in resp.read()):
return False
else:
self.logged_in = True
return True
def find(self, subj="", crse="", crn="", term="", year=""):
url = "https://banweb.banner.vt.edu/ssb/prod/HZSKVTSC.P_ProcRequest?"
# CAMPUS=0 is Blacksburg
# AR%25 is All Areas of Classes
url += "CAMPUS=" + str(0) + "&TERMYEAR=" + year + term
url += "&CORE_CODE=" + "AR%25" + "&SUBJ_CODE=" + subj
url += "&CRSE_NUMBER=" + crse + "&crn=" + crn + "&open_only=" + ""
url += "&PRINT_FRIEND=" + "Y" # + "&BTN_PRESSED=" + "FIND+class+sections"
browser = self.br.open(url)
contents = browser.read()
if ("NO SECTIONS FOUND FOR THIS INQUIRY." in contents):
return None
return contents
| {
"content_hash": "e61a923b3ec687a01aaa02cb9e832975",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 131,
"avg_line_length": 32.15555555555556,
"alnum_prop": 0.5618521078092605,
"repo_name": "ajn123/VT-Python-Class-Add",
"id": "09c36ec771923c4802c162a440f733b69ebeccd4",
"size": "1447",
"binary": false,
"copies": "1",
"ref": "refs/heads/testing",
"path": "Navigator.py",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
(function($) {
// Models§
window.User = Backbone.Model.extend({
});
window.Counter = Backbone.Model.extend({
});
// Collections
window.Users = Backbone.Collection.extend({
model: User,
url: '/users'
});
window.users = new Users();
window.Counters = Backbone.Collection.extend({
model: Counter,
url: '/counters'
});
window.counters = new Counters();
// Views
window.UserView = Backbone.View.extend({
tagName: 'tr',
className: 'user',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.template = _.template($('#user-template').html());
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
window.UserListView = UserView.extend({
tagName: 'section',
className: 'span14 userList',
initialize: function() {
_.bindAll(this, 'render');
this.template = _.template($('#user-list-template').html());
this.collection.bind('reset', this.render);
},
render: function() {
var $users,
collection = this.collection;
$(this.el).html(this.template({}));
$users = this.$('.users');
collection.each(function(user){
var view = new UserView({
model: user,
collection: collection
});
$users.append(view.render().el);
});
return this;
}
});
window.CounterView = Backbone.View.extend({
tagName: 'tr',
className: 'counter',
initialize: function() {
_.bindAll(this, 'render');
this.model.bind('change', this.render);
this.template = _.template($('#counter-template').html());
},
render: function() {
var renderedContent = this.template(this.model.toJSON());
$(this.el).html(renderedContent);
return this;
}
});
window.CounterListView = CounterView.extend({
tagName: 'section',
className: 'span14 counterList',
initialize: function() {
_.bindAll(this, 'render');
this.template = _.template($('#counter-list-template').html());
this.collection.bind('reset', this.render);
},
render: function() {
var $counters,
collection = this.collection;
$(this.el).html(this.template({}));
$counters = this.$('.counters');
collection.each(function(counter){
var view = new CounterView({
model: counter,
collection: collection
});
$counters.append(view.render().el);
});
return this;
}
});
// Router
window.BackboneWallE = Backbone.Router.extend({
routes: {
'' : 'home',
'users' : 'users',
'counters' : 'counters'
},
initialize: function(){
this.userListView = new UserListView({
collection: window.users
});
this.counterListView = new CounterListView({
collection: window.counters
});
},
home: function() {
$('h1').text('Dashboard');
var $container = $('#container');
$container.empty();
},
users: function() {
window.users.fetch();
$('h1').text('Users');
var $container = $('#container');
$container.empty();
$container.append(this.userListView.render().el);
},
counters: function() {
window.counters.fetch();
$('h1').text('Counters');
var $container = $('#container');
$container.empty();
$container.append(this.counterListView.render().el);
}
});
$(function() {
window.App = new BackboneWallE();
Backbone.history.start();
});
})(jQuery);
| {
"content_hash": "9dd616734479be9689239caf75f63768",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 69,
"avg_line_length": 23.006211180124225,
"alnum_prop": 0.5639848812095032,
"repo_name": "sborsje/wall-e",
"id": "0d9e22afe4bad9257744a939722e256af5732e27",
"size": "3705",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/javascripts/application.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "9118"
},
{
"name": "JavaScript",
"bytes": "5408"
}
],
"symlink_target": ""
} |
package gov.hhs.onc.dcdt.crypto.credentials;
import gov.hhs.onc.dcdt.crypto.CryptographyDescriptor;
import gov.hhs.onc.dcdt.crypto.certs.CertificateDescriptor;
import gov.hhs.onc.dcdt.crypto.certs.CertificateIntervalDescriptor;
import gov.hhs.onc.dcdt.crypto.keys.KeyDescriptor;
import javax.annotation.Nullable;
public interface CredentialDescriptor<T extends KeyDescriptor, U extends CertificateIntervalDescriptor, V extends CertificateDescriptor<U>> extends
CryptographyDescriptor {
public boolean hasCertificateDescriptor();
@Nullable
public V getCertificateDescriptor();
public void setCertificateDescriptor(@Nullable V certDesc);
public boolean hasKeyDescriptor();
@Nullable
public T getKeyDescriptor();
public void setKeyDescriptor(@Nullable T keyDesc);
}
| {
"content_hash": "919829cc31dc3303ae69f62f7aba98d4",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 147,
"avg_line_length": 33.583333333333336,
"alnum_prop": 0.8014888337468983,
"repo_name": "mkotelba/dcdt",
"id": "f0d56f53a3c1aca581496d82bc7e2b7cdf35ae47",
"size": "806",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "dcdt-core/src/main/java/gov/hhs/onc/dcdt/crypto/credentials/CredentialDescriptor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7846"
},
{
"name": "Groovy",
"bytes": "18146"
},
{
"name": "Java",
"bytes": "1541901"
},
{
"name": "JavaScript",
"bytes": "54163"
}
],
"symlink_target": ""
} |
This repository holds the work I did before for the Fleetwood Park Vex team. It also includes videos I found helpful to learn RobotC.
## RobotC or EasyC
RobotC is much better than EasyC. RobotC is more diffucult to learn because it teaches you programming not how to use a that specific program. Also, all the project are saved in one .c file format that can be opened in any text editor (notepad, vim, emacs, sublime text, etc.). EasyC uses this proprietary format and has multiple files for one project. All of the files in this repository are made in robotC.
"But I dont have enough time to 'actually learn programming'":
Dont program. Use jumpers instead. If you don't have enough time to learn programming then you'll probably not have enough time to program autonomous. Use jumpers and follow the vex manual to see where to plug in motors so that the preloaded program recognizes all your motors.
## Helpful Videos and Code
"I just wanna get basic user control working in RobotC"
https://www.youtube.com/watch?v=rWaiEHgQNic
"I just want to get the robot moving Forward and Back"
[Basic Template](https://github.com/anjandev/Fleetwood-Park-Vex/blob/master/Vex%20Sky-Rise%20(2015)/Drive_System_Programming_Template.c)
| {
"content_hash": "de509786bf97e5b7ca92723138e7356b",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 408,
"avg_line_length": 76.9375,
"alnum_prop": 0.7855402112103981,
"repo_name": "anjandev/Vex",
"id": "fe90a72138056b85c36e9a97e87ed0470de40ece",
"size": "1253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "11606"
}
],
"symlink_target": ""
} |
using EmbeddedSystems.ServiceLayer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EmbeddedSystems.Admin.Controllers
{
public class HandsetController : Controller
{
private readonly IHandsetService _handsetService;
public HandsetController(IHandsetService handsetService)
{
this._handsetService = handsetService;
}
public ActionResult Index()
{
var model = this._handsetService.GetAllHandsets();
return View(model);
}
public ActionResult HandsetSelect()
{
var handsets = this._handsetService.GetAllHandsets();
return this.PartialView(handsets);
}
public ActionResult ExpireRental(int handsetId)
{
var rental = this._handsetService.GetCurrentRentalForHandset(handsetId);
if (rental != null)
{
this._handsetService.ExpireRental(rental);
return RedirectToAction("Index", "Handset");
}
return RedirectToAction("Index", "Handset");
}
public ActionResult AddHandset(string handsetNumber)
{
this._handsetService.CreateHandset(handsetNumber);
return RedirectToAction("Index", "Handset");
}
}
} | {
"content_hash": "f1831f56f7d8e24a18ebe9f150c2f1bb",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 84,
"avg_line_length": 28.142857142857142,
"alnum_prop": 0.6163886874546773,
"repo_name": "james-dibble/Embedded-Systems-Assignment",
"id": "f6a28e0a6d97cf6166fd5dbdc47a613acfc71c3d",
"size": "1381",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EmbeddedSystems.Applications/EmbeddedSystems.Admin/Controllers/HandsetController.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "480"
},
{
"name": "C",
"bytes": "5203"
},
{
"name": "C#",
"bytes": "207641"
},
{
"name": "C++",
"bytes": "330101"
},
{
"name": "CSS",
"bytes": "1175"
},
{
"name": "IDL",
"bytes": "1618"
},
{
"name": "Python",
"bytes": "1803809"
}
],
"symlink_target": ""
} |
function IdealFig(num)
% IdealFig -- callback implementing functions of IdealDemo
global IDEALFIGNUM
global N rho qmf L
if 1 <= num & num <=10 ,
nihil = ~exist('IDEALFIGNUM');
if ~nihil,
empty = isempty(IDEALFIGNUM);
else
empty = 1;
end
if ~empty,
nil = IDEALFIGNUM == 0;
else
nil = 1;
end
if nil,
IdealInit
end
figname = FigNameString('idfig',num);
clc; home; help(figname);
eval(figname);
RegisterPlot(figname,'{R}');
drawnow;
IDEALFIGNUM = num;
elseif num==19, % change default settings
N = input('sample size for all figures, default 2048, must be power of 2?');
rho = input('signal-to-noise ratio, default 7?');
fam = input('family name of QMF, in quotes, default Symmlet?');
ind = input('index of QMF family, default 8?');
qmf = MakeONFilter(fam,ind);
L = input('index of coarsest resolution level, default 6');
IDEALFIGNUM = 0;
elseif num==20,
IdealInit
for num=1:10,
figname = FigNameString('idfig',num);
eval(figname);
RegisterPlot(figname,'{R}');
clc; home; help(figname);
drawnow;
IDEALFIGNUM = num;
end
else
disp('Bizarre argument in IdealFig')
disp(sprintf('num =%g',num))
end
%
% Part of Wavelab Version 850
% Built Tue Jan 3 13:20:41 EST 2006
% This is Copyrighted Material
% For Copying permissions see COPYING.m
% Comments? e-mail [email protected]
| {
"content_hash": "ce4bbf049c17914436d3c06209e9d3b6",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 80,
"avg_line_length": 27.603448275862068,
"alnum_prop": 0.5740162398500936,
"repo_name": "linhvannguyen/PhDworks",
"id": "1b350932407693ad0b690ab232f5774e20f6e6ed",
"size": "1601",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "codes/missingfuncs/Wavelab850/Papers/Ideal/IdealFig.m",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11203"
},
{
"name": "C",
"bytes": "1007620"
},
{
"name": "C++",
"bytes": "1012443"
},
{
"name": "CSS",
"bytes": "14933"
},
{
"name": "HTML",
"bytes": "1357543"
},
{
"name": "Java",
"bytes": "1833"
},
{
"name": "Jupyter Notebook",
"bytes": "415227"
},
{
"name": "M",
"bytes": "68479"
},
{
"name": "Makefile",
"bytes": "3007"
},
{
"name": "Matlab",
"bytes": "5625827"
},
{
"name": "Objective-C",
"bytes": "606"
},
{
"name": "Python",
"bytes": "32885"
},
{
"name": "Scheme",
"bytes": "6"
},
{
"name": "Shell",
"bytes": "124887"
},
{
"name": "TeX",
"bytes": "932814"
}
],
"symlink_target": ""
} |
/**
* Provides classes for evaluating predictors.
*/
package mltk.predictor.evaluation; | {
"content_hash": "be2e07a31dedb47840f61e4383f24ab6",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 46,
"avg_line_length": 23,
"alnum_prop": 0.7391304347826086,
"repo_name": "yinlou/mltk",
"id": "c7caf91d7115c37b7027e8abf854966732d31429",
"size": "92",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/mltk/predictor/evaluation/package-info.java",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "807619"
}
],
"symlink_target": ""
} |
namespace org {
namespace apache {
namespace lucene {
namespace analysis {
namespace util {
class MultiTermAwareComponent;
class AbstractAnalysisFactory;
}
namespace core {
class LowerCaseFilter;
}
class TokenStream;
}
}
}
}
namespace java {
namespace lang {
class Class;
class String;
}
namespace util {
class Map;
}
}
template<class T> class JArray;
namespace org {
namespace apache {
namespace lucene {
namespace analysis {
namespace core {
class LowerCaseFilterFactory : public ::org::apache::lucene::analysis::util::TokenFilterFactory {
public:
enum {
mid_init$_4c9e2b1c,
mid_create_40083866,
mid_getMultiTermComponent_0a3f1d72,
max_mid
};
static ::java::lang::Class *class$;
static jmethodID *mids$;
static bool live$;
static jclass initializeClass(bool);
explicit LowerCaseFilterFactory(jobject obj) : ::org::apache::lucene::analysis::util::TokenFilterFactory(obj) {
if (obj != NULL)
env->getClass(initializeClass);
}
LowerCaseFilterFactory(const LowerCaseFilterFactory& obj) : ::org::apache::lucene::analysis::util::TokenFilterFactory(obj) {}
LowerCaseFilterFactory(const ::java::util::Map &);
::org::apache::lucene::analysis::core::LowerCaseFilter create(const ::org::apache::lucene::analysis::TokenStream &) const;
::org::apache::lucene::analysis::util::AbstractAnalysisFactory getMultiTermComponent() const;
};
}
}
}
}
}
#include <Python.h>
namespace org {
namespace apache {
namespace lucene {
namespace analysis {
namespace core {
extern PyTypeObject PY_TYPE(LowerCaseFilterFactory);
class t_LowerCaseFilterFactory {
public:
PyObject_HEAD
LowerCaseFilterFactory object;
static PyObject *wrap_Object(const LowerCaseFilterFactory&);
static PyObject *wrap_jobject(const jobject&);
static void install(PyObject *module);
static void initialize(PyObject *module);
};
}
}
}
}
}
#endif
| {
"content_hash": "be9158a2907eedd21c4786b86fe28f92",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 137,
"avg_line_length": 26.60674157303371,
"alnum_prop": 0.5831925675675675,
"repo_name": "devs4v/devs4v-information-retrieval15",
"id": "66be7c3591fb9a97e9a5a4fcfe41c62b44dd1b01",
"size": "2564",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "project/lucene/pylucene-4.9.0-0/build/lucene/include/org/apache/lucene/analysis/core/LowerCaseFilterFactory.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "5652"
},
{
"name": "C++",
"bytes": "46179369"
},
{
"name": "CSS",
"bytes": "48509"
},
{
"name": "GAP",
"bytes": "10699"
},
{
"name": "Gnuplot",
"bytes": "2444"
},
{
"name": "Groff",
"bytes": "22"
},
{
"name": "HTML",
"bytes": "154190600"
},
{
"name": "Java",
"bytes": "28482713"
},
{
"name": "JavaScript",
"bytes": "125675"
},
{
"name": "Makefile",
"bytes": "14512"
},
{
"name": "Perl",
"bytes": "63759"
},
{
"name": "Python",
"bytes": "11523468"
},
{
"name": "Shell",
"bytes": "4083"
},
{
"name": "XSLT",
"bytes": "14748"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/jjasghar/hubot-dynstatus)
## A DynDNS checker for Hubots.
You can check all three (top, email, dns) http://www.dynstatus.com feeds from this script. You can check as many posts as you would like also.
See [`src/dynstatus.coffee`](src/dynstatus.coffee) for full documentation.
## Installation
Add **hubot-dynstatus** to your `package.json` file:
```json
"dependencies": {
"hubot": ">= 2.5.1",
"hubot-scripts": ">= 2.4.2",
"hubot-dynstatus": ">= 0.0.0"
}
```
Add **hubot-dynstatus** to your `external-scripts.json`:
```json
["hubot-dynstatus"]
```
Run `npm install hubot-dynstatus`
## Sample Interaction
```
user1>> hubot dyn email 1
hubot>> [RESOLVED] DynECT E-mail Sending Delays: http://www.dynstatus.com/dynect-email/6449/6449 @ Wed Mar 26 2014 16:01:43 GMT-0500 (CDT)
user1>> hubot dyn top 1
hubot>> [DynTLD, Standard & Remote Access Scheduled Maintenance: http://www.dynstatus.com/dyndns/6432/dyntld-standard-remote-access-scheduled-maintenance @ Tue Mar 25 2014 12:45:36 GMT-0500 (CDT)
user1>> hubot dyn dns 1
hubot>> [Resolved] DynECT DNS API and Portal Service Degradation: http://www.dynstatus.com/dynect-dns/6460/dynect-dns-api-and-portal-service-degradation @ Thu Mar 27 2014 15:08:03 GMT-0500 (CDT)
```
| {
"content_hash": "372c8c83ff2faafbde61cbed5065b00f",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 195,
"avg_line_length": 35.18421052631579,
"alnum_prop": 0.7202692595362753,
"repo_name": "hubot-scripts/hubot-dynstatus",
"id": "e3099a1b8cd705c48b3f54314979833e03d552fb",
"size": "1363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "2972"
},
{
"name": "Shell",
"bytes": "440"
}
],
"symlink_target": ""
} |
// Provides a C++11 implementation of a multi-producer, multi-consumer lock-free queue.
// An overview, including benchmark results, is provided here:
// http://moodycamel.com/blog/2014/a-fast-general-purpose-lock-free-queue-for-c++
// The full design is also described in excruciating detail at:
// http://moodycamel.com/blog/2014/detailed-design-of-a-lock-free-queue
// Simplified BSD license:
// Copyright (c) 2013-2016, Cameron Desrochers.
// 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.
//
// 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.
#pragma once
#if defined(__GNUC__)
// Disable -Wconversion warnings (spuriously triggered when Traits::size_t and
// Traits::index_t are set to < 32 bits, causing integer promotion, causing warnings
// upon assigning any computed values)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wconversion"
#ifdef MCDBGQ_USE_RELACY
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
#endif
#endif
#ifdef MCDBGQ_USE_RELACY
#include "relacy/relacy_std.hpp"
#include "relacy_shims.h"
// We only use malloc/free anyway, and the delete macro messes up `= delete` method declarations.
// We'll override the default trait malloc ourselves without a macro.
#undef new
#undef delete
#undef malloc
#undef free
#else
#include <atomic> // Requires C++11. Sorry VS2010.
#include <cassert>
#endif
#include <cstdint>
#include <cstdlib>
#include <type_traits>
#include <algorithm>
#include <utility>
#include <limits>
#include <climits> // for CHAR_BIT
#include <array>
#include <thread> // for __WINPTHREADS_VERSION if on MinGW-w64 w/ POSIX threading
// Platform-specific definitions of a numeric thread ID type and an invalid value
#if defined(MCDBGQ_USE_RELACY)
namespace moodycamel { namespace details {
typedef std::uint32_t thread_id_t;
static const thread_id_t invalid_thread_id = 0xFFFFFFFFU;
static const thread_id_t invalid_thread_id2 = 0xFFFFFFFEU;
static inline thread_id_t thread_id() { return rl::thread_index(); }
} }
#elif defined(_WIN32) || defined(__WINDOWS__) || defined(__WIN32__)
// No sense pulling in windows.h in a header, we'll manually declare the function
// we use and rely on backwards-compatibility for this not to break
extern "C" __declspec(dllimport) unsigned long __stdcall GetCurrentThreadId(void);
namespace moodycamel { namespace details {
static_assert(sizeof(unsigned long) == sizeof(std::uint32_t), "Expected size of unsigned long to be 32 bits on Windows");
typedef std::uint32_t thread_id_t;
static const thread_id_t invalid_thread_id = 0; // See http://blogs.msdn.com/b/oldnewthing/archive/2004/02/23/78395.aspx
static const thread_id_t invalid_thread_id2 = 0xFFFFFFFFU; // Not technically guaranteed to be invalid, but is never used in practice. Note that all Win32 thread IDs are presently multiples of 4.
static inline thread_id_t thread_id() { return static_cast<thread_id_t>(::GetCurrentThreadId()); }
} }
#else
// Use a nice trick from this answer: http://stackoverflow.com/a/8438730/21475
// In order to get a numeric thread ID in a platform-independent way, we use a thread-local
// static variable's address as a thread identifier :-)
#if defined(__GNUC__) || defined(__INTEL_COMPILER)
#define MOODYCAMEL_THREADLOCAL __thread
#elif defined(_MSC_VER)
#define MOODYCAMEL_THREADLOCAL __declspec(thread)
#else
// Assume C++11 compliant compiler
#define MOODYCAMEL_THREADLOCAL thread_local
#endif
namespace moodycamel { namespace details {
typedef std::uintptr_t thread_id_t;
static const thread_id_t invalid_thread_id = 0; // Address can't be nullptr
static const thread_id_t invalid_thread_id2 = 1; // Member accesses off a null pointer are also generally invalid. Plus it's not aligned.
static inline thread_id_t thread_id() { static MOODYCAMEL_THREADLOCAL int x; return reinterpret_cast<thread_id_t>(&x); }
} }
#endif
// Exceptions
#ifndef MOODYCAMEL_EXCEPTIONS_ENABLED
#if (defined(_MSC_VER) && defined(_CPPUNWIND)) || (defined(__GNUC__) && defined(__EXCEPTIONS)) || (!defined(_MSC_VER) && !defined(__GNUC__))
#define MOODYCAMEL_EXCEPTIONS_ENABLED
#define MOODYCAMEL_TRY try
#define MOODYCAMEL_CATCH(...) catch(__VA_ARGS__)
#define MOODYCAMEL_RETHROW throw
#define MOODYCAMEL_THROW(expr) throw (expr)
#else
#define MOODYCAMEL_TRY if (true)
#define MOODYCAMEL_CATCH(...) else if (false)
#define MOODYCAMEL_RETHROW
#define MOODYCAMEL_THROW(expr)
#endif
#endif
#ifndef MOODYCAMEL_NOEXCEPT
#if !defined(MOODYCAMEL_EXCEPTIONS_ENABLED)
#define MOODYCAMEL_NOEXCEPT
#define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) true
#define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) true
#elif defined(_MSC_VER) && defined(_NOEXCEPT) && _MSC_VER < 1800
// VS2012's std::is_nothrow_[move_]constructible is broken and returns true when it shouldn't :-(
// We have to assume *all* non-trivial constructors may throw on VS2012!
#define MOODYCAMEL_NOEXCEPT _NOEXCEPT
#define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) (std::is_rvalue_reference<valueType>::value && std::is_move_constructible<type>::value ? std::is_trivially_move_constructible<type>::value : std::is_trivially_copy_constructible<type>::value)
#define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) ((std::is_rvalue_reference<valueType>::value && std::is_move_assignable<type>::value ? std::is_trivially_move_assignable<type>::value || std::is_nothrow_move_assignable<type>::value : std::is_trivially_copy_assignable<type>::value || std::is_nothrow_copy_assignable<type>::value) && MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr))
#elif defined(_MSC_VER) && defined(_NOEXCEPT) && _MSC_VER < 1900
#define MOODYCAMEL_NOEXCEPT _NOEXCEPT
#define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) (std::is_rvalue_reference<valueType>::value && std::is_move_constructible<type>::value ? std::is_trivially_move_constructible<type>::value || std::is_nothrow_move_constructible<type>::value : std::is_trivially_copy_constructible<type>::value || std::is_nothrow_copy_constructible<type>::value)
#define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) ((std::is_rvalue_reference<valueType>::value && std::is_move_assignable<type>::value ? std::is_trivially_move_assignable<type>::value || std::is_nothrow_move_assignable<type>::value : std::is_trivially_copy_assignable<type>::value || std::is_nothrow_copy_assignable<type>::value) && MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr))
#else
#define MOODYCAMEL_NOEXCEPT noexcept
#define MOODYCAMEL_NOEXCEPT_CTOR(type, valueType, expr) noexcept(expr)
#define MOODYCAMEL_NOEXCEPT_ASSIGN(type, valueType, expr) noexcept(expr)
#endif
#endif
#ifndef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
#ifdef MCDBGQ_USE_RELACY
#define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
#else
//// VS2013 doesn't support `thread_local`, and MinGW-w64 w/ POSIX threading has a crippling bug: http://sourceforge.net/p/mingw-w64/bugs/445
//// g++ <=4.7 doesn't support thread_local either
//#if (!defined(_MSC_VER) || _MSC_VER >= 1900) && (!defined(__MINGW32__) && !defined(__MINGW64__) || !defined(__WINPTHREADS_VERSION)) && (!defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
//// Assume `thread_local` is fully supported in all other C++11 compilers/runtimes
//#define MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
//#endif
#endif
#endif
// VS2012 doesn't support deleted functions.
// In this case, we declare the function normally but don't define it. A link error will be generated if the function is called.
#ifndef MOODYCAMEL_DELETE_FUNCTION
#if defined(_MSC_VER) && _MSC_VER < 1800
#define MOODYCAMEL_DELETE_FUNCTION
#else
#define MOODYCAMEL_DELETE_FUNCTION = delete
#endif
#endif
// Compiler-specific likely/unlikely hints
namespace moodycamel { namespace details {
#if defined(__GNUC__)
inline bool likely(bool x) { return __builtin_expect((x), true); }
inline bool unlikely(bool x) { return __builtin_expect((x), false); }
#else
inline bool likely(bool x) { return x; }
inline bool unlikely(bool x) { return x; }
#endif
} }
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
#include "internal/concurrentqueue_internal_debug.h"
#endif
namespace moodycamel {
namespace details {
template<typename T>
struct const_numeric_max {
static_assert(std::is_integral<T>::value, "const_numeric_max can only be used with integers");
static const T value = std::numeric_limits<T>::is_signed
? (static_cast<T>(1) << (sizeof(T) * CHAR_BIT - 1)) - static_cast<T>(1)
: static_cast<T>(-1);
};
}
// Default traits for the ConcurrentQueue. To change some of the
// traits without re-implementing all of them, inherit from this
// struct and shadow the declarations you wish to be different;
// since the traits are used as a template type parameter, the
// shadowed declarations will be used where defined, and the defaults
// otherwise.
struct ConcurrentQueueDefaultTraits
{
// General-purpose size type. std::size_t is strongly recommended.
typedef std::size_t size_t;
// The type used for the enqueue and dequeue indices. Must be at least as
// large as size_t. Should be significantly larger than the number of elements
// you expect to hold at once, especially if you have a high turnover rate;
// for example, on 32-bit x86, if you expect to have over a hundred million
// elements or pump several million elements through your queue in a very
// short space of time, using a 32-bit type *may* trigger a race condition.
// A 64-bit int type is recommended in that case, and in practice will
// prevent a race condition no matter the usage of the queue. Note that
// whether the queue is lock-free with a 64-int type depends on the whether
// std::atomic<std::uint64_t> is lock-free, which is platform-specific.
typedef std::size_t index_t;
// Internally, all elements are enqueued and dequeued from multi-element
// blocks; this is the smallest controllable unit. If you expect few elements
// but many producers, a smaller block size should be favoured. For few producers
// and/or many elements, a larger block size is preferred. A sane default
// is provided. Must be a power of 2.
static const size_t BLOCK_SIZE = 32;
// For explicit producers (i.e. when using a producer token), the block is
// checked for being empty by iterating through a list of flags, one per element.
// For large block sizes, this is too inefficient, and switching to an atomic
// counter-based approach is faster. The switch is made for block sizes strictly
// larger than this threshold.
static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD = 32;
// How many full blocks can be expected for a single explicit producer? This should
// reflect that number's maximum for optimal performance. Must be a power of 2.
static const size_t EXPLICIT_INITIAL_INDEX_SIZE = 32;
// How many full blocks can be expected for a single implicit producer? This should
// reflect that number's maximum for optimal performance. Must be a power of 2.
static const size_t IMPLICIT_INITIAL_INDEX_SIZE = 32;
// The initial size of the hash table mapping thread IDs to implicit producers.
// Note that the hash is resized every time it becomes half full.
// Must be a power of two, and either 0 or at least 1. If 0, implicit production
// (using the enqueue methods without an explicit producer token) is disabled.
static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE = 32;
// Controls the number of items that an explicit consumer (i.e. one with a token)
// must consume before it causes all consumers to rotate and move on to the next
// internal queue.
static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE = 256;
// The maximum number of elements (inclusive) that can be enqueued to a sub-queue.
// Enqueue operations that would cause this limit to be surpassed will fail. Note
// that this limit is enforced at the block level (for performance reasons), i.e.
// it's rounded up to the nearest block size.
static const size_t MAX_SUBQUEUE_SIZE = details::const_numeric_max<size_t>::value;
#ifndef MCDBGQ_USE_RELACY
// Memory allocation can be customized if needed.
// malloc should return nullptr on failure, and handle alignment like std::malloc.
#if defined(malloc) || defined(free)
// Gah, this is 2016, stop defining macros that break standard code already!
// Work around malloc/free being special macros:
static inline void* WORKAROUND_malloc(size_t size) { return malloc(size); }
static inline void WORKAROUND_free(void* ptr) { return free(ptr); }
static inline void* (malloc)(size_t size) { return WORKAROUND_malloc(size); }
static inline void (free)(void* ptr) { return WORKAROUND_free(ptr); }
#else
static inline void* malloc(size_t size) { return std::malloc(size); }
static inline void free(void* ptr) { return std::free(ptr); }
#endif
#else
// Debug versions when running under the Relacy race detector (ignore
// these in user code)
static inline void* malloc(size_t size) { return rl::rl_malloc(size, $); }
static inline void free(void* ptr) { return rl::rl_free(ptr, $); }
#endif
};
// When producing or consuming many elements, the most efficient way is to:
// 1) Use one of the bulk-operation methods of the queue with a token
// 2) Failing that, use the bulk-operation methods without a token
// 3) Failing that, create a token and use that with the single-item methods
// 4) Failing that, use the single-parameter methods of the queue
// Having said that, don't create tokens willy-nilly -- ideally there should be
// a maximum of one token per thread (of each kind).
struct ProducerToken;
struct ConsumerToken;
template<typename T, typename Traits> class ConcurrentQueue;
template<typename T, typename Traits> class BlockingConcurrentQueue;
class ConcurrentQueueTests;
namespace details
{
struct ConcurrentQueueProducerTypelessBase
{
ConcurrentQueueProducerTypelessBase* next;
std::atomic<bool> inactive;
ProducerToken* token;
ConcurrentQueueProducerTypelessBase()
: inactive(false), token(nullptr)
{
}
};
template<bool use32> struct _hash_32_or_64 {
static inline std::uint32_t hash(std::uint32_t h)
{
// MurmurHash3 finalizer -- see https://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp
// Since the thread ID is already unique, all we really want to do is propagate that
// uniqueness evenly across all the bits, so that we can use a subset of the bits while
// reducing collisions significantly
h ^= h >> 16;
h *= 0x85ebca6b;
h ^= h >> 13;
h *= 0xc2b2ae35;
return h ^ (h >> 16);
}
};
template<> struct _hash_32_or_64<1> {
static inline std::uint64_t hash(std::uint64_t h)
{
h ^= h >> 33;
h *= 0xff51afd7ed558ccd;
h ^= h >> 33;
h *= 0xc4ceb9fe1a85ec53;
return h ^ (h >> 33);
}
};
template<std::size_t size> struct hash_32_or_64 : public _hash_32_or_64<(size > 4)> { };
static inline size_t hash_thread_id(thread_id_t id)
{
static_assert(sizeof(thread_id_t) <= 8, "Expected a platform where thread IDs are at most 64-bit values");
return static_cast<size_t>(hash_32_or_64<sizeof(thread_id_t)>::hash(id));
}
template<typename T>
static inline bool circular_less_than(T a, T b)
{
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4554)
#endif
static_assert(std::is_integral<T>::value && !std::numeric_limits<T>::is_signed, "circular_less_than is intended to be used only with unsigned integer types");
return static_cast<T>(a - b) > static_cast<T>(static_cast<T>(1) << static_cast<T>(sizeof(T) * CHAR_BIT - 1));
#ifdef _MSC_VER
#pragma warning(pop)
#endif
}
template<typename U>
static inline char* align_for(char* ptr)
{
const std::size_t alignment = std::alignment_of<U>::value;
return ptr + (alignment - (reinterpret_cast<std::uintptr_t>(ptr) % alignment)) % alignment;
}
template<typename T>
static inline T ceil_to_pow_2(T x)
{
static_assert(std::is_integral<T>::value && !std::numeric_limits<T>::is_signed, "ceil_to_pow_2 is intended to be used only with unsigned integer types");
// Adapted from http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
--x;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
for (std::size_t i = 1; i < sizeof(T); i <<= 1) {
x |= x >> (i << 3);
}
++x;
return x;
}
template<typename T>
static inline void swap_relaxed(std::atomic<T>& left, std::atomic<T>& right)
{
T temp = std::move(left.load(std::memory_order_relaxed));
left.store(std::move(right.load(std::memory_order_relaxed)), std::memory_order_relaxed);
right.store(std::move(temp), std::memory_order_relaxed);
}
template<typename T>
static inline T const& nomove(T const& x)
{
return x;
}
template<bool Enable>
struct nomove_if
{
template<typename T>
static inline T const& eval(T const& x)
{
return x;
}
};
template<>
struct nomove_if<false>
{
template<typename U>
static inline auto eval(U&& x)
-> decltype(std::forward<U>(x))
{
return std::forward<U>(x);
}
};
template<typename It>
static inline auto deref_noexcept(It& it) MOODYCAMEL_NOEXCEPT -> decltype(*it)
{
return *it;
}
#if defined(__clang__) || !defined(__GNUC__) || __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
template<typename T> struct is_trivially_destructible : std::is_trivially_destructible<T> { };
#else
template<typename T> struct is_trivially_destructible : std::has_trivial_destructor<T> { };
#endif
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
#ifdef MCDBGQ_USE_RELACY
typedef RelacyThreadExitListener ThreadExitListener;
typedef RelacyThreadExitNotifier ThreadExitNotifier;
#else
struct ThreadExitListener
{
typedef void (*callback_t)(void*);
callback_t callback;
void* userData;
ThreadExitListener* next; // reserved for use by the ThreadExitNotifier
};
class ThreadExitNotifier
{
public:
static void subscribe(ThreadExitListener* listener)
{
auto& tlsInst = instance();
listener->next = tlsInst.tail;
tlsInst.tail = listener;
}
static void unsubscribe(ThreadExitListener* listener)
{
auto& tlsInst = instance();
ThreadExitListener** prev = &tlsInst.tail;
for (auto ptr = tlsInst.tail; ptr != nullptr; ptr = ptr->next) {
if (ptr == listener) {
*prev = ptr->next;
break;
}
prev = &ptr->next;
}
}
private:
ThreadExitNotifier() : tail(nullptr) { }
ThreadExitNotifier(ThreadExitNotifier const&) MOODYCAMEL_DELETE_FUNCTION;
ThreadExitNotifier& operator=(ThreadExitNotifier const&) MOODYCAMEL_DELETE_FUNCTION;
~ThreadExitNotifier()
{
// This thread is about to exit, let everyone know!
assert(this == &instance() && "If this assert fails, you likely have a buggy compiler! Change the preprocessor conditions such that MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED is no longer defined.");
for (auto ptr = tail; ptr != nullptr; ptr = ptr->next) {
ptr->callback(ptr->userData);
}
}
// Thread-local
static inline ThreadExitNotifier& instance()
{
static thread_local ThreadExitNotifier notifier;
return notifier;
}
private:
ThreadExitListener* tail;
};
#endif
#endif
template<typename T> struct static_is_lock_free_num { enum { value = 0 }; };
template<> struct static_is_lock_free_num<signed char> { enum { value = ATOMIC_CHAR_LOCK_FREE }; };
template<> struct static_is_lock_free_num<short> { enum { value = ATOMIC_SHORT_LOCK_FREE }; };
template<> struct static_is_lock_free_num<int> { enum { value = ATOMIC_INT_LOCK_FREE }; };
template<> struct static_is_lock_free_num<long> { enum { value = ATOMIC_LONG_LOCK_FREE }; };
template<> struct static_is_lock_free_num<long long> { enum { value = ATOMIC_LLONG_LOCK_FREE }; };
template<typename T> struct static_is_lock_free : static_is_lock_free_num<typename std::make_signed<T>::type> { };
template<> struct static_is_lock_free<bool> { enum { value = ATOMIC_BOOL_LOCK_FREE }; };
template<typename U> struct static_is_lock_free<U*> { enum { value = ATOMIC_POINTER_LOCK_FREE }; };
}
struct ProducerToken
{
template<typename T, typename Traits>
explicit ProducerToken(ConcurrentQueue<T, Traits>& queue);
template<typename T, typename Traits>
explicit ProducerToken(BlockingConcurrentQueue<T, Traits>& queue);
explicit ProducerToken(ProducerToken&& other) MOODYCAMEL_NOEXCEPT
: producer(other.producer)
{
other.producer = nullptr;
if (producer != nullptr) {
producer->token = this;
}
}
inline ProducerToken& operator=(ProducerToken&& other) MOODYCAMEL_NOEXCEPT
{
swap(other);
return *this;
}
void swap(ProducerToken& other) MOODYCAMEL_NOEXCEPT
{
std::swap(producer, other.producer);
if (producer != nullptr) {
producer->token = this;
}
if (other.producer != nullptr) {
other.producer->token = &other;
}
}
// A token is always valid unless:
// 1) Memory allocation failed during construction
// 2) It was moved via the move constructor
// (Note: assignment does a swap, leaving both potentially valid)
// 3) The associated queue was destroyed
// Note that if valid() returns true, that only indicates
// that the token is valid for use with a specific queue,
// but not which one; that's up to the user to track.
inline bool valid() const { return producer != nullptr; }
~ProducerToken()
{
if (producer != nullptr) {
producer->token = nullptr;
producer->inactive.store(true, std::memory_order_release);
}
}
// Disable copying and assignment
ProducerToken(ProducerToken const&) MOODYCAMEL_DELETE_FUNCTION;
ProducerToken& operator=(ProducerToken const&) MOODYCAMEL_DELETE_FUNCTION;
private:
template<typename T, typename Traits> friend class ConcurrentQueue;
friend class ConcurrentQueueTests;
protected:
details::ConcurrentQueueProducerTypelessBase* producer;
};
struct ConsumerToken
{
template<typename T, typename Traits>
explicit ConsumerToken(ConcurrentQueue<T, Traits>& q);
template<typename T, typename Traits>
explicit ConsumerToken(BlockingConcurrentQueue<T, Traits>& q);
explicit ConsumerToken(ConsumerToken&& other) MOODYCAMEL_NOEXCEPT
: initialOffset(other.initialOffset), lastKnownGlobalOffset(other.lastKnownGlobalOffset), itemsConsumedFromCurrent(other.itemsConsumedFromCurrent), currentProducer(other.currentProducer), desiredProducer(other.desiredProducer)
{
}
inline ConsumerToken& operator=(ConsumerToken&& other) MOODYCAMEL_NOEXCEPT
{
swap(other);
return *this;
}
void swap(ConsumerToken& other) MOODYCAMEL_NOEXCEPT
{
std::swap(initialOffset, other.initialOffset);
std::swap(lastKnownGlobalOffset, other.lastKnownGlobalOffset);
std::swap(itemsConsumedFromCurrent, other.itemsConsumedFromCurrent);
std::swap(currentProducer, other.currentProducer);
std::swap(desiredProducer, other.desiredProducer);
}
// Disable copying and assignment
ConsumerToken(ConsumerToken const&) MOODYCAMEL_DELETE_FUNCTION;
ConsumerToken& operator=(ConsumerToken const&) MOODYCAMEL_DELETE_FUNCTION;
private:
template<typename T, typename Traits> friend class ConcurrentQueue;
friend class ConcurrentQueueTests;
private: // but shared with ConcurrentQueue
std::uint32_t initialOffset;
std::uint32_t lastKnownGlobalOffset;
std::uint32_t itemsConsumedFromCurrent;
details::ConcurrentQueueProducerTypelessBase* currentProducer;
details::ConcurrentQueueProducerTypelessBase* desiredProducer;
};
// Need to forward-declare this swap because it's in a namespace.
// See http://stackoverflow.com/questions/4492062/why-does-a-c-friend-class-need-a-forward-declaration-only-in-other-namespaces
template<typename T, typename Traits>
inline void swap(typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP& a, typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP& b) MOODYCAMEL_NOEXCEPT;
template<typename T, typename Traits = ConcurrentQueueDefaultTraits>
class ConcurrentQueue
{
public:
typedef ::moodycamel::ProducerToken producer_token_t;
typedef ::moodycamel::ConsumerToken consumer_token_t;
typedef typename Traits::index_t index_t;
typedef typename Traits::size_t size_t;
static const size_t BLOCK_SIZE = static_cast<size_t>(Traits::BLOCK_SIZE);
static const size_t EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD = static_cast<size_t>(Traits::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD);
static const size_t EXPLICIT_INITIAL_INDEX_SIZE = static_cast<size_t>(Traits::EXPLICIT_INITIAL_INDEX_SIZE);
static const size_t IMPLICIT_INITIAL_INDEX_SIZE = static_cast<size_t>(Traits::IMPLICIT_INITIAL_INDEX_SIZE);
static const size_t INITIAL_IMPLICIT_PRODUCER_HASH_SIZE = static_cast<size_t>(Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE);
static const std::uint32_t EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE = static_cast<std::uint32_t>(Traits::EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE);
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4307) // + integral constant overflow (that's what the ternary expression is for!)
#pragma warning(disable: 4309) // static_cast: Truncation of constant value
#endif
static const size_t MAX_SUBQUEUE_SIZE = (details::const_numeric_max<size_t>::value - static_cast<size_t>(Traits::MAX_SUBQUEUE_SIZE) < BLOCK_SIZE) ? details::const_numeric_max<size_t>::value : ((static_cast<size_t>(Traits::MAX_SUBQUEUE_SIZE) + (BLOCK_SIZE - 1)) / BLOCK_SIZE * BLOCK_SIZE);
#ifdef _MSC_VER
#pragma warning(pop)
#endif
static_assert(!std::numeric_limits<size_t>::is_signed && std::is_integral<size_t>::value, "Traits::size_t must be an unsigned integral type");
static_assert(!std::numeric_limits<index_t>::is_signed && std::is_integral<index_t>::value, "Traits::index_t must be an unsigned integral type");
static_assert(sizeof(index_t) >= sizeof(size_t), "Traits::index_t must be at least as wide as Traits::size_t");
static_assert((BLOCK_SIZE > 1) && !(BLOCK_SIZE & (BLOCK_SIZE - 1)), "Traits::BLOCK_SIZE must be a power of 2 (and at least 2)");
static_assert((EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD > 1) && !(EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD & (EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD - 1)), "Traits::EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD must be a power of 2 (and greater than 1)");
static_assert((EXPLICIT_INITIAL_INDEX_SIZE > 1) && !(EXPLICIT_INITIAL_INDEX_SIZE & (EXPLICIT_INITIAL_INDEX_SIZE - 1)), "Traits::EXPLICIT_INITIAL_INDEX_SIZE must be a power of 2 (and greater than 1)");
static_assert((IMPLICIT_INITIAL_INDEX_SIZE > 1) && !(IMPLICIT_INITIAL_INDEX_SIZE & (IMPLICIT_INITIAL_INDEX_SIZE - 1)), "Traits::IMPLICIT_INITIAL_INDEX_SIZE must be a power of 2 (and greater than 1)");
static_assert((INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) || !(INITIAL_IMPLICIT_PRODUCER_HASH_SIZE & (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE - 1)), "Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE must be a power of 2");
static_assert(INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0 || INITIAL_IMPLICIT_PRODUCER_HASH_SIZE >= 1, "Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE must be at least 1 (or 0 to disable implicit enqueueing)");
public:
// Creates a queue with at least `capacity` element slots; note that the
// actual number of elements that can be inserted without additional memory
// allocation depends on the number of producers and the block size (e.g. if
// the block size is equal to `capacity`, only a single block will be allocated
// up-front, which means only a single producer will be able to enqueue elements
// without an extra allocation -- blocks aren't shared between producers).
// This method is not thread safe -- it is up to the user to ensure that the
// queue is fully constructed before it starts being used by other threads (this
// includes making the memory effects of construction visible, possibly with a
// memory barrier).
explicit ConcurrentQueue(size_t capacity = 6 * BLOCK_SIZE)
: producerListTail(nullptr),
producerCount(0),
initialBlockPoolIndex(0),
nextExplicitConsumerId(0),
globalExplicitConsumerOffset(0)
{
implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
populate_initial_implicit_producer_hash();
populate_initial_block_list(capacity / BLOCK_SIZE + ((capacity & (BLOCK_SIZE - 1)) == 0 ? 0 : 1));
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
// Track all the producers using a fully-resolved typed list for
// each kind; this makes it possible to debug them starting from
// the root queue object (otherwise wacky casts are needed that
// don't compile in the debugger's expression evaluator).
explicitProducers.store(nullptr, std::memory_order_relaxed);
implicitProducers.store(nullptr, std::memory_order_relaxed);
#endif
}
// Computes the correct amount of pre-allocated blocks for you based
// on the minimum number of elements you want available at any given
// time, and the maximum concurrent number of each type of producer.
ConcurrentQueue(size_t minCapacity, size_t maxExplicitProducers, size_t maxImplicitProducers)
: producerListTail(nullptr),
producerCount(0),
initialBlockPoolIndex(0),
nextExplicitConsumerId(0),
globalExplicitConsumerOffset(0)
{
implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
populate_initial_implicit_producer_hash();
size_t blocks = ((((minCapacity + BLOCK_SIZE - 1) / BLOCK_SIZE) - 1) * (maxExplicitProducers + 1) + 2 * (maxExplicitProducers + maxImplicitProducers)) * BLOCK_SIZE;
populate_initial_block_list(blocks);
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
explicitProducers.store(nullptr, std::memory_order_relaxed);
implicitProducers.store(nullptr, std::memory_order_relaxed);
#endif
}
// Note: The queue should not be accessed concurrently while it's
// being deleted. It's up to the user to synchronize this.
// This method is not thread safe.
~ConcurrentQueue()
{
// Destroy producers
auto ptr = producerListTail.load(std::memory_order_relaxed);
while (ptr != nullptr) {
auto next = ptr->next_prod();
if (ptr->token != nullptr) {
ptr->token->producer = nullptr;
}
destroy(ptr);
ptr = next;
}
// Destroy implicit producer hash tables
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE != 0) {
auto hash = implicitProducerHash.load(std::memory_order_relaxed);
while (hash != nullptr) {
auto prev = hash->prev;
if (prev != nullptr) { // The last hash is part of this object and was not allocated dynamically
for (size_t i = 0; i != hash->capacity; ++i) {
hash->entries[i].~ImplicitProducerKVP();
}
hash->~ImplicitProducerHash();
(Traits::free)(hash);
}
hash = prev;
}
}
// Destroy global free list
auto block = freeList.head_unsafe();
while (block != nullptr) {
auto next = block->freeListNext.load(std::memory_order_relaxed);
if (block->dynamicallyAllocated) {
destroy(block);
}
block = next;
}
// Destroy initial free list
destroy_array(initialBlockPool, initialBlockPoolSize);
}
// Disable copying and copy assignment
ConcurrentQueue(ConcurrentQueue const&) MOODYCAMEL_DELETE_FUNCTION;
ConcurrentQueue& operator=(ConcurrentQueue const&) MOODYCAMEL_DELETE_FUNCTION;
// Moving is supported, but note that it is *not* a thread-safe operation.
// Nobody can use the queue while it's being moved, and the memory effects
// of that move must be propagated to other threads before they can use it.
// Note: When a queue is moved, its tokens are still valid but can only be
// used with the destination queue (i.e. semantically they are moved along
// with the queue itself).
ConcurrentQueue(ConcurrentQueue&& other) MOODYCAMEL_NOEXCEPT
: producerListTail(other.producerListTail.load(std::memory_order_relaxed)),
producerCount(other.producerCount.load(std::memory_order_relaxed)),
initialBlockPoolIndex(other.initialBlockPoolIndex.load(std::memory_order_relaxed)),
initialBlockPool(other.initialBlockPool),
initialBlockPoolSize(other.initialBlockPoolSize),
freeList(std::move(other.freeList)),
nextExplicitConsumerId(other.nextExplicitConsumerId.load(std::memory_order_relaxed)),
globalExplicitConsumerOffset(other.globalExplicitConsumerOffset.load(std::memory_order_relaxed))
{
// Move the other one into this, and leave the other one as an empty queue
implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
populate_initial_implicit_producer_hash();
swap_implicit_producer_hashes(other);
other.producerListTail.store(nullptr, std::memory_order_relaxed);
other.producerCount.store(0, std::memory_order_relaxed);
other.nextExplicitConsumerId.store(0, std::memory_order_relaxed);
other.globalExplicitConsumerOffset.store(0, std::memory_order_relaxed);
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
explicitProducers.store(other.explicitProducers.load(std::memory_order_relaxed), std::memory_order_relaxed);
other.explicitProducers.store(nullptr, std::memory_order_relaxed);
implicitProducers.store(other.implicitProducers.load(std::memory_order_relaxed), std::memory_order_relaxed);
other.implicitProducers.store(nullptr, std::memory_order_relaxed);
#endif
other.initialBlockPoolIndex.store(0, std::memory_order_relaxed);
other.initialBlockPoolSize = 0;
other.initialBlockPool = nullptr;
reown_producers();
}
inline ConcurrentQueue& operator=(ConcurrentQueue&& other) MOODYCAMEL_NOEXCEPT
{
return swap_internal(other);
}
// Swaps this queue's state with the other's. Not thread-safe.
// Swapping two queues does not invalidate their tokens, however
// the tokens that were created for one queue must be used with
// only the swapped queue (i.e. the tokens are tied to the
// queue's movable state, not the object itself).
inline void swap(ConcurrentQueue& other) MOODYCAMEL_NOEXCEPT
{
swap_internal(other);
}
private:
ConcurrentQueue& swap_internal(ConcurrentQueue& other)
{
if (this == &other) {
return *this;
}
details::swap_relaxed(producerListTail, other.producerListTail);
details::swap_relaxed(producerCount, other.producerCount);
details::swap_relaxed(initialBlockPoolIndex, other.initialBlockPoolIndex);
std::swap(initialBlockPool, other.initialBlockPool);
std::swap(initialBlockPoolSize, other.initialBlockPoolSize);
freeList.swap(other.freeList);
details::swap_relaxed(nextExplicitConsumerId, other.nextExplicitConsumerId);
details::swap_relaxed(globalExplicitConsumerOffset, other.globalExplicitConsumerOffset);
swap_implicit_producer_hashes(other);
reown_producers();
other.reown_producers();
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
details::swap_relaxed(explicitProducers, other.explicitProducers);
details::swap_relaxed(implicitProducers, other.implicitProducers);
#endif
return *this;
}
public:
// Enqueues a single item (by copying it).
// Allocates memory if required. Only fails if memory allocation fails (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
// or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(T const& item)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue<CanAlloc>(item);
}
// Enqueues a single item (by moving it, if possible).
// Allocates memory if required. Only fails if memory allocation fails (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0,
// or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(T&& item)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue<CanAlloc>(std::move(item));
}
// Enqueues a single item (by copying it) using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails (or
// Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(producer_token_t const& token, T const& item)
{
return inner_enqueue<CanAlloc>(token, item);
}
// Enqueues a single item (by moving it, if possible) using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails (or
// Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Thread-safe.
inline bool enqueue(producer_token_t const& token, T&& item)
{
return inner_enqueue<CanAlloc>(token, std::move(item));
}
// Enqueues several items.
// Allocates memory if required. Only fails if memory allocation fails (or
// implicit production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
// is 0, or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Note: Use std::make_move_iterator if the elements should be moved instead of copied.
// Thread-safe.
template<typename It>
bool enqueue_bulk(It itemFirst, size_t count)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue_bulk<CanAlloc>(std::forward<It>(itemFirst), count);
}
// Enqueues several items using an explicit producer token.
// Allocates memory if required. Only fails if memory allocation fails
// (or Traits::MAX_SUBQUEUE_SIZE has been defined and would be surpassed).
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
bool enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{
return inner_enqueue_bulk<CanAlloc>(token, std::forward<It>(itemFirst), count);
}
// Enqueues a single item (by copying it).
// Does not allocate memory. Fails if not enough room to enqueue (or implicit
// production is disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE
// is 0).
// Thread-safe.
inline bool try_enqueue(T const& item)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue<CannotAlloc>(item);
}
// Enqueues a single item (by moving it, if possible).
// Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Thread-safe.
inline bool try_enqueue(T&& item)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue<CannotAlloc>(std::move(item));
}
// Enqueues a single item (by copying it) using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Thread-safe.
inline bool try_enqueue(producer_token_t const& token, T const& item)
{
return inner_enqueue<CannotAlloc>(token, item);
}
// Enqueues a single item (by moving it, if possible) using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Thread-safe.
inline bool try_enqueue(producer_token_t const& token, T&& item)
{
return inner_enqueue<CannotAlloc>(token, std::move(item));
}
// Enqueues several items.
// Does not allocate memory (except for one-time implicit producer).
// Fails if not enough room to enqueue (or implicit production is
// disabled because Traits::INITIAL_IMPLICIT_PRODUCER_HASH_SIZE is 0).
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
bool try_enqueue_bulk(It itemFirst, size_t count)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return false;
return inner_enqueue_bulk<CannotAlloc>(std::forward<It>(itemFirst), count);
}
// Enqueues several items using an explicit producer token.
// Does not allocate memory. Fails if not enough room to enqueue.
// Note: Use std::make_move_iterator if the elements should be moved
// instead of copied.
// Thread-safe.
template<typename It>
bool try_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{
return inner_enqueue_bulk<CannotAlloc>(token, std::forward<It>(itemFirst), count);
}
// Attempts to dequeue from the queue.
// Returns false if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename U>
bool try_dequeue(U& item)
{
// Instead of simply trying each producer in turn (which could cause needless contention on the first
// producer), we score them heuristically.
size_t nonEmptyCount = 0;
ProducerBase* best = nullptr;
size_t bestSize = 0;
for (auto ptr = producerListTail.load(std::memory_order_acquire); nonEmptyCount < 3 && ptr != nullptr; ptr = ptr->next_prod()) {
auto size = ptr->size_approx();
if (size > 0) {
if (size > bestSize) {
bestSize = size;
best = ptr;
}
++nonEmptyCount;
}
}
// If there was at least one non-empty queue but it appears empty at the time
// we try to dequeue from it, we need to make sure every queue's been tried
if (nonEmptyCount > 0) {
if (details::likely(best->dequeue(item))) {
return true;
}
for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
if (ptr != best && ptr->dequeue(item)) {
return true;
}
}
}
return false;
}
// Attempts to dequeue from the queue.
// Returns false if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// This differs from the try_dequeue(item) method in that this one does
// not attempt to reduce contention by interleaving the order that producer
// streams are dequeued from. So, using this method can reduce overall throughput
// under contention, but will give more predictable results in single-threaded
// consumer scenarios. This is mostly only useful for internal unit tests.
// Never allocates. Thread-safe.
template<typename U>
bool try_dequeue_non_interleaved(U& item)
{
for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
if (ptr->dequeue(item)) {
return true;
}
}
return false;
}
// Attempts to dequeue from the queue using an explicit consumer token.
// Returns false if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename U>
bool try_dequeue(consumer_token_t& token, U& item)
{
// The idea is roughly as follows:
// Every 256 items from one producer, make everyone rotate (increase the global offset) -> this means the highest efficiency consumer dictates the rotation speed of everyone else, more or less
// If you see that the global offset has changed, you must reset your consumption counter and move to your designated place
// If there's no items where you're supposed to be, keep moving until you find a producer with some items
// If the global offset has not changed but you've run out of items to consume, move over from your current position until you find an producer with something in it
if (token.desiredProducer == nullptr || token.lastKnownGlobalOffset != globalExplicitConsumerOffset.load(std::memory_order_relaxed)) {
if (!update_current_producer_after_rotation(token)) {
return false;
}
}
// If there was at least one non-empty queue but it appears empty at the time
// we try to dequeue from it, we need to make sure every queue's been tried
if (static_cast<ProducerBase*>(token.currentProducer)->dequeue(item)) {
if (++token.itemsConsumedFromCurrent == EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE) {
globalExplicitConsumerOffset.fetch_add(1, std::memory_order_relaxed);
}
return true;
}
auto tail = producerListTail.load(std::memory_order_acquire);
auto ptr = static_cast<ProducerBase*>(token.currentProducer)->next_prod();
if (ptr == nullptr) {
ptr = tail;
}
while (ptr != static_cast<ProducerBase*>(token.currentProducer)) {
if (ptr->dequeue(item)) {
token.currentProducer = ptr;
token.itemsConsumedFromCurrent = 1;
return true;
}
ptr = ptr->next_prod();
if (ptr == nullptr) {
ptr = tail;
}
}
return false;
}
// Attempts to dequeue several elements from the queue.
// Returns the number of items actually dequeued.
// Returns 0 if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename It>
size_t try_dequeue_bulk(It itemFirst, size_t max)
{
size_t count = 0;
for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
count += ptr->dequeue_bulk(itemFirst, max - count);
if (count == max) {
break;
}
}
return count;
}
// Attempts to dequeue several elements from the queue using an explicit consumer token.
// Returns the number of items actually dequeued.
// Returns 0 if all producer streams appeared empty at the time they
// were checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename It>
size_t try_dequeue_bulk(consumer_token_t& token, It itemFirst, size_t max)
{
if (token.desiredProducer == nullptr || token.lastKnownGlobalOffset != globalExplicitConsumerOffset.load(std::memory_order_relaxed)) {
if (!update_current_producer_after_rotation(token)) {
return false;
}
}
size_t count = static_cast<ProducerBase*>(token.currentProducer)->dequeue_bulk(itemFirst, max);
if (count == max) {
if ((token.itemsConsumedFromCurrent += static_cast<std::uint32_t>(max)) >= EXPLICIT_CONSUMER_CONSUMPTION_QUOTA_BEFORE_ROTATE) {
globalExplicitConsumerOffset.fetch_add(1, std::memory_order_relaxed);
}
return max;
}
token.itemsConsumedFromCurrent += static_cast<std::uint32_t>(count);
max -= count;
auto tail = producerListTail.load(std::memory_order_acquire);
auto ptr = static_cast<ProducerBase*>(token.currentProducer)->next_prod();
if (ptr == nullptr) {
ptr = tail;
}
while (ptr != static_cast<ProducerBase*>(token.currentProducer)) {
auto dequeued = ptr->dequeue_bulk(itemFirst, max);
count += dequeued;
if (dequeued != 0) {
token.currentProducer = ptr;
token.itemsConsumedFromCurrent = static_cast<std::uint32_t>(dequeued);
}
if (dequeued == max) {
break;
}
max -= dequeued;
ptr = ptr->next_prod();
if (ptr == nullptr) {
ptr = tail;
}
}
return count;
}
// Attempts to dequeue from a specific producer's inner queue.
// If you happen to know which producer you want to dequeue from, this
// is significantly faster than using the general-case try_dequeue methods.
// Returns false if the producer's queue appeared empty at the time it
// was checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename U>
inline bool try_dequeue_from_producer(producer_token_t const& producer, U& item)
{
return static_cast<ExplicitProducer*>(producer.producer)->dequeue(item);
}
// Attempts to dequeue several elements from a specific producer's inner queue.
// Returns the number of items actually dequeued.
// If you happen to know which producer you want to dequeue from, this
// is significantly faster than using the general-case try_dequeue methods.
// Returns 0 if the producer's queue appeared empty at the time it
// was checked (so, the queue is likely but not guaranteed to be empty).
// Never allocates. Thread-safe.
template<typename It>
inline size_t try_dequeue_bulk_from_producer(producer_token_t const& producer, It itemFirst, size_t max)
{
return static_cast<ExplicitProducer*>(producer.producer)->dequeue_bulk(itemFirst, max);
}
// Returns an estimate of the total number of elements currently in the queue. This
// estimate is only accurate if the queue has completely stabilized before it is called
// (i.e. all enqueue and dequeue operations have completed and their memory effects are
// visible on the calling thread, and no further operations start while this method is
// being called).
// Thread-safe.
size_t size_approx() const
{
size_t size = 0;
for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
size += ptr->size_approx();
}
return size;
}
// Returns true if the underlying atomic variables used by
// the queue are lock-free (they should be on most platforms).
// Thread-safe.
static bool is_lock_free()
{
return
details::static_is_lock_free<bool>::value == 2 &&
details::static_is_lock_free<size_t>::value == 2 &&
details::static_is_lock_free<std::uint32_t>::value == 2 &&
details::static_is_lock_free<index_t>::value == 2 &&
details::static_is_lock_free<void*>::value == 2 &&
details::static_is_lock_free<details::thread_id_t>::value == 2;
}
private:
friend struct ProducerToken;
friend struct ConsumerToken;
friend struct ExplicitProducer;
friend class ConcurrentQueueTests;
enum AllocationMode { CanAlloc, CannotAlloc };
///////////////////////////////
// Queue methods
///////////////////////////////
template<AllocationMode canAlloc, typename U>
inline bool inner_enqueue(producer_token_t const& token, U&& element)
{
return static_cast<ExplicitProducer*>(token.producer)->ConcurrentQueue::ExplicitProducer::template enqueue<canAlloc>(std::forward<U>(element));
}
template<AllocationMode canAlloc, typename U>
inline bool inner_enqueue(U&& element)
{
auto producer = get_or_add_implicit_producer();
return producer == nullptr ? false : producer->ConcurrentQueue::ImplicitProducer::template enqueue<canAlloc>(std::forward<U>(element));
}
template<AllocationMode canAlloc, typename It>
inline bool inner_enqueue_bulk(producer_token_t const& token, It itemFirst, size_t count)
{
return static_cast<ExplicitProducer*>(token.producer)->ConcurrentQueue::ExplicitProducer::template enqueue_bulk<canAlloc>(std::forward<It>(itemFirst), count);
}
template<AllocationMode canAlloc, typename It>
inline bool inner_enqueue_bulk(It itemFirst, size_t count)
{
auto producer = get_or_add_implicit_producer();
return producer == nullptr ? false : producer->ConcurrentQueue::ImplicitProducer::template enqueue_bulk<canAlloc>(std::forward<It>(itemFirst), count);
}
inline bool update_current_producer_after_rotation(consumer_token_t& token)
{
// Ah, there's been a rotation, figure out where we should be!
auto tail = producerListTail.load(std::memory_order_acquire);
if (token.desiredProducer == nullptr && tail == nullptr) {
return false;
}
auto prodCount = producerCount.load(std::memory_order_relaxed);
auto globalOffset = globalExplicitConsumerOffset.load(std::memory_order_relaxed);
if (details::unlikely(token.desiredProducer == nullptr)) {
// Aha, first time we're dequeueing anything.
// Figure out our local position
// Note: offset is from start, not end, but we're traversing from end -- subtract from count first
std::uint32_t offset = prodCount - 1 - (token.initialOffset % prodCount);
token.desiredProducer = tail;
for (std::uint32_t i = 0; i != offset; ++i) {
token.desiredProducer = static_cast<ProducerBase*>(token.desiredProducer)->next_prod();
if (token.desiredProducer == nullptr) {
token.desiredProducer = tail;
}
}
}
std::uint32_t delta = globalOffset - token.lastKnownGlobalOffset;
if (delta >= prodCount) {
delta = delta % prodCount;
}
for (std::uint32_t i = 0; i != delta; ++i) {
token.desiredProducer = static_cast<ProducerBase*>(token.desiredProducer)->next_prod();
if (token.desiredProducer == nullptr) {
token.desiredProducer = tail;
}
}
token.lastKnownGlobalOffset = globalOffset;
token.currentProducer = token.desiredProducer;
token.itemsConsumedFromCurrent = 0;
return true;
}
///////////////////////////
// Free list
///////////////////////////
template <typename N>
struct FreeListNode
{
FreeListNode() : freeListRefs(0), freeListNext(nullptr) { }
std::atomic<std::uint32_t> freeListRefs;
std::atomic<N*> freeListNext;
};
// A simple CAS-based lock-free free list. Not the fastest thing in the world under heavy contention, but
// simple and correct (assuming nodes are never freed until after the free list is destroyed), and fairly
// speedy under low contention.
template<typename N> // N must inherit FreeListNode or have the same fields (and initialization of them)
struct FreeList
{
FreeList() : freeListHead(nullptr) { }
FreeList(FreeList&& other) : freeListHead(other.freeListHead.load(std::memory_order_relaxed)) { other.freeListHead.store(nullptr, std::memory_order_relaxed); }
void swap(FreeList& other) { details::swap_relaxed(freeListHead, other.freeListHead); }
FreeList(FreeList const&) MOODYCAMEL_DELETE_FUNCTION;
FreeList& operator=(FreeList const&) MOODYCAMEL_DELETE_FUNCTION;
inline void add(N* node)
{
#if MCDBGQ_NOLOCKFREE_FREELIST
debug::DebugLock lock(mutex);
#endif
// We know that the should-be-on-freelist bit is 0 at this point, so it's safe to
// set it using a fetch_add
if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST, std::memory_order_acq_rel) == 0) {
// Oh look! We were the last ones referencing this node, and we know
// we want to add it to the free list, so let's do it!
add_knowing_refcount_is_zero(node);
}
}
inline N* try_get()
{
#if MCDBGQ_NOLOCKFREE_FREELIST
debug::DebugLock lock(mutex);
#endif
auto head = freeListHead.load(std::memory_order_acquire);
while (head != nullptr) {
auto prevHead = head;
auto refs = head->freeListRefs.load(std::memory_order_relaxed);
if ((refs & REFS_MASK) == 0 || !head->freeListRefs.compare_exchange_strong(refs, refs + 1, std::memory_order_acquire, std::memory_order_relaxed)) {
head = freeListHead.load(std::memory_order_acquire);
continue;
}
// Good, reference count has been incremented (it wasn't at zero), which means we can read the
// next and not worry about it changing between now and the time we do the CAS
auto next = head->freeListNext.load(std::memory_order_relaxed);
if (freeListHead.compare_exchange_strong(head, next, std::memory_order_acquire, std::memory_order_relaxed)) {
// Yay, got the node. This means it was on the list, which means shouldBeOnFreeList must be false no
// matter the refcount (because nobody else knows it's been taken off yet, it can't have been put back on).
assert((head->freeListRefs.load(std::memory_order_relaxed) & SHOULD_BE_ON_FREELIST) == 0);
// Decrease refcount twice, once for our ref, and once for the list's ref
head->freeListRefs.fetch_add(-2, std::memory_order_release);
return head;
}
// OK, the head must have changed on us, but we still need to decrease the refcount we increased.
// Note that we don't need to release any memory effects, but we do need to ensure that the reference
// count decrement happens-after the CAS on the head.
refs = prevHead->freeListRefs.fetch_add(-1, std::memory_order_acq_rel);
if (refs == SHOULD_BE_ON_FREELIST + 1) {
add_knowing_refcount_is_zero(prevHead);
}
}
return nullptr;
}
// Useful for traversing the list when there's no contention (e.g. to destroy remaining nodes)
N* head_unsafe() const { return freeListHead.load(std::memory_order_relaxed); }
private:
inline void add_knowing_refcount_is_zero(N* node)
{
// Since the refcount is zero, and nobody can increase it once it's zero (except us, and we run
// only one copy of this method per node at a time, i.e. the single thread case), then we know
// we can safely change the next pointer of the node; however, once the refcount is back above
// zero, then other threads could increase it (happens under heavy contention, when the refcount
// goes to zero in between a load and a refcount increment of a node in try_get, then back up to
// something non-zero, then the refcount increment is done by the other thread) -- so, if the CAS
// to add the node to the actual list fails, decrease the refcount and leave the add operation to
// the next thread who puts the refcount back at zero (which could be us, hence the loop).
auto head = freeListHead.load(std::memory_order_relaxed);
while (true) {
node->freeListNext.store(head, std::memory_order_relaxed);
node->freeListRefs.store(1, std::memory_order_release);
if (!freeListHead.compare_exchange_strong(head, node, std::memory_order_release, std::memory_order_relaxed)) {
// Hmm, the add failed, but we can only try again when the refcount goes back to zero
if (node->freeListRefs.fetch_add(SHOULD_BE_ON_FREELIST - 1, std::memory_order_release) == 1) {
continue;
}
}
return;
}
}
private:
// Implemented like a stack, but where node order doesn't matter (nodes are inserted out of order under contention)
std::atomic<N*> freeListHead;
static const std::uint32_t REFS_MASK = 0x7FFFFFFF;
static const std::uint32_t SHOULD_BE_ON_FREELIST = 0x80000000;
#if MCDBGQ_NOLOCKFREE_FREELIST
debug::DebugMutex mutex;
#endif
};
///////////////////////////
// Block
///////////////////////////
enum InnerQueueContext { implicit_context = 0, explicit_context = 1 };
struct Block
{
Block()
: elementsCompletelyDequeued(0), freeListRefs(0), freeListNext(nullptr), shouldBeOnFreeList(false), dynamicallyAllocated(true)
{
#if MCDBGQ_TRACKMEM
owner = nullptr;
#endif
}
template<InnerQueueContext context>
inline bool is_empty() const
{
if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
// Check flags
for (size_t i = 0; i < BLOCK_SIZE; ++i) {
if (!emptyFlags[i].load(std::memory_order_relaxed)) {
return false;
}
}
// Aha, empty; make sure we have all other memory effects that happened before the empty flags were set
std::atomic_thread_fence(std::memory_order_acquire);
return true;
}
else {
// Check counter
if (elementsCompletelyDequeued.load(std::memory_order_relaxed) == BLOCK_SIZE) {
std::atomic_thread_fence(std::memory_order_acquire);
return true;
}
assert(elementsCompletelyDequeued.load(std::memory_order_relaxed) <= BLOCK_SIZE);
return false;
}
}
// Returns true if the block is now empty (does not apply in explicit context)
template<InnerQueueContext context>
inline bool set_empty(index_t i)
{
if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
// Set flag
assert(!emptyFlags[BLOCK_SIZE - 1 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1))].load(std::memory_order_relaxed));
emptyFlags[BLOCK_SIZE - 1 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1))].store(true, std::memory_order_release);
return false;
}
else {
// Increment counter
auto prevVal = elementsCompletelyDequeued.fetch_add(1, std::memory_order_release);
assert(prevVal < BLOCK_SIZE);
return prevVal == BLOCK_SIZE - 1;
}
}
// Sets multiple contiguous item statuses to 'empty' (assumes no wrapping and count > 0).
// Returns true if the block is now empty (does not apply in explicit context).
template<InnerQueueContext context>
inline bool set_many_empty(index_t i, size_t count)
{
if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
// Set flags
std::atomic_thread_fence(std::memory_order_release);
i = BLOCK_SIZE - 1 - static_cast<size_t>(i & static_cast<index_t>(BLOCK_SIZE - 1)) - count + 1;
for (size_t j = 0; j != count; ++j) {
assert(!emptyFlags[i + j].load(std::memory_order_relaxed));
emptyFlags[i + j].store(true, std::memory_order_relaxed);
}
return false;
}
else {
// Increment counter
auto prevVal = elementsCompletelyDequeued.fetch_add(count, std::memory_order_release);
assert(prevVal + count <= BLOCK_SIZE);
return prevVal + count == BLOCK_SIZE;
}
}
template<InnerQueueContext context>
inline void set_all_empty()
{
if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
// Set all flags
for (size_t i = 0; i != BLOCK_SIZE; ++i) {
emptyFlags[i].store(true, std::memory_order_relaxed);
}
}
else {
// Reset counter
elementsCompletelyDequeued.store(BLOCK_SIZE, std::memory_order_relaxed);
}
}
template<InnerQueueContext context>
inline void reset_empty()
{
if (context == explicit_context && BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD) {
// Reset flags
for (size_t i = 0; i != BLOCK_SIZE; ++i) {
emptyFlags[i].store(false, std::memory_order_relaxed);
}
}
else {
// Reset counter
elementsCompletelyDequeued.store(0, std::memory_order_relaxed);
}
}
inline T* operator[](index_t idx) MOODYCAMEL_NOEXCEPT { return reinterpret_cast<T*>(elements) + static_cast<size_t>(idx & static_cast<index_t>(BLOCK_SIZE - 1)); }
inline T const* operator[](index_t idx) const MOODYCAMEL_NOEXCEPT { return reinterpret_cast<T const*>(elements) + static_cast<size_t>(idx & static_cast<index_t>(BLOCK_SIZE - 1)); }
public:
Block* next;
std::atomic<size_t> elementsCompletelyDequeued;
std::atomic<bool> emptyFlags[BLOCK_SIZE <= EXPLICIT_BLOCK_EMPTY_COUNTER_THRESHOLD ? BLOCK_SIZE : 1];
private:
char elements[sizeof(T) * BLOCK_SIZE];
public:
std::atomic<std::uint32_t> freeListRefs;
std::atomic<Block*> freeListNext;
std::atomic<bool> shouldBeOnFreeList;
bool dynamicallyAllocated; // Perhaps a better name for this would be 'isNotPartOfInitialBlockPool'
#if MCDBGQ_TRACKMEM
void* owner;
#endif
};
#if MCDBGQ_TRACKMEM
public:
struct MemStats;
private:
#endif
///////////////////////////
// Producer base
///////////////////////////
struct ProducerBase : public details::ConcurrentQueueProducerTypelessBase
{
ProducerBase(ConcurrentQueue* parent, bool isExplicit) :
tailIndex(0),
headIndex(0),
dequeueOptimisticCount(0),
dequeueOvercommit(0),
tailBlock(nullptr),
isExplicit(isExplicit),
parent(parent)
{
}
virtual ~ProducerBase() { };
template<typename U>
inline bool dequeue(U& element)
{
if (isExplicit) {
return static_cast<ExplicitProducer*>(this)->dequeue(element);
}
else {
return static_cast<ImplicitProducer*>(this)->dequeue(element);
}
}
template<typename It>
inline size_t dequeue_bulk(It& itemFirst, size_t max)
{
if (isExplicit) {
return static_cast<ExplicitProducer*>(this)->dequeue_bulk(itemFirst, max);
}
else {
return static_cast<ImplicitProducer*>(this)->dequeue_bulk(itemFirst, max);
}
}
inline ProducerBase* next_prod() const { return static_cast<ProducerBase*>(next); }
inline size_t size_approx() const
{
auto tail = tailIndex.load(std::memory_order_relaxed);
auto head = headIndex.load(std::memory_order_relaxed);
return details::circular_less_than(head, tail) ? static_cast<size_t>(tail - head) : 0;
}
inline index_t getTail() const { return tailIndex.load(std::memory_order_relaxed); }
protected:
std::atomic<index_t> tailIndex; // Where to enqueue to next
std::atomic<index_t> headIndex; // Where to dequeue from next
std::atomic<index_t> dequeueOptimisticCount;
std::atomic<index_t> dequeueOvercommit;
Block* tailBlock;
public:
bool isExplicit;
ConcurrentQueue* parent;
protected:
#if MCDBGQ_TRACKMEM
friend struct MemStats;
#endif
};
///////////////////////////
// Explicit queue
///////////////////////////
struct ExplicitProducer : public ProducerBase
{
explicit ExplicitProducer(ConcurrentQueue* parent) :
ProducerBase(parent, true),
blockIndex(nullptr),
pr_blockIndexSlotsUsed(0),
pr_blockIndexSize(EXPLICIT_INITIAL_INDEX_SIZE >> 1),
pr_blockIndexFront(0),
pr_blockIndexEntries(nullptr),
pr_blockIndexRaw(nullptr)
{
size_t poolBasedIndexSize = details::ceil_to_pow_2(parent->initialBlockPoolSize) >> 1;
if (poolBasedIndexSize > pr_blockIndexSize) {
pr_blockIndexSize = poolBasedIndexSize;
}
new_block_index(0); // This creates an index with double the number of current entries, i.e. EXPLICIT_INITIAL_INDEX_SIZE
}
~ExplicitProducer()
{
// Destruct any elements not yet dequeued.
// Since we're in the destructor, we can assume all elements
// are either completely dequeued or completely not (no halfways).
if (this->tailBlock != nullptr) { // Note this means there must be a block index too
// First find the block that's partially dequeued, if any
Block* halfDequeuedBlock = nullptr;
if ((this->headIndex.load(std::memory_order_relaxed) & static_cast<index_t>(BLOCK_SIZE - 1)) != 0) {
// The head's not on a block boundary, meaning a block somewhere is partially dequeued
// (or the head block is the tail block and was fully dequeued, but the head/tail are still not on a boundary)
size_t i = (pr_blockIndexFront - pr_blockIndexSlotsUsed) & (pr_blockIndexSize - 1);
while (details::circular_less_than<index_t>(pr_blockIndexEntries[i].base + BLOCK_SIZE, this->headIndex.load(std::memory_order_relaxed))) {
i = (i + 1) & (pr_blockIndexSize - 1);
}
assert(details::circular_less_than<index_t>(pr_blockIndexEntries[i].base, this->headIndex.load(std::memory_order_relaxed)));
halfDequeuedBlock = pr_blockIndexEntries[i].block;
}
// Start at the head block (note the first line in the loop gives us the head from the tail on the first iteration)
auto block = this->tailBlock;
do {
block = block->next;
if (block->ConcurrentQueue::Block::template is_empty<explicit_context>()) {
continue;
}
size_t i = 0; // Offset into block
if (block == halfDequeuedBlock) {
i = static_cast<size_t>(this->headIndex.load(std::memory_order_relaxed) & static_cast<index_t>(BLOCK_SIZE - 1));
}
// Walk through all the items in the block; if this is the tail block, we need to stop when we reach the tail index
auto lastValidIndex = (this->tailIndex.load(std::memory_order_relaxed) & static_cast<index_t>(BLOCK_SIZE - 1)) == 0 ? BLOCK_SIZE : static_cast<size_t>(this->tailIndex.load(std::memory_order_relaxed) & static_cast<index_t>(BLOCK_SIZE - 1));
while (i != BLOCK_SIZE && (block != this->tailBlock || i != lastValidIndex)) {
(*block)[i++]->~T();
}
} while (block != this->tailBlock);
}
// Destroy all blocks that we own
if (this->tailBlock != nullptr) {
auto block = this->tailBlock;
do {
auto next = block->next;
if (block->dynamicallyAllocated) {
destroy(block);
}
block = next;
} while (block != this->tailBlock);
}
// Destroy the block indices
auto header = static_cast<BlockIndexHeader*>(pr_blockIndexRaw);
while (header != nullptr) {
auto prev = static_cast<BlockIndexHeader*>(header->prev);
header->~BlockIndexHeader();
(Traits::free)(header);
header = prev;
}
}
template<AllocationMode allocMode, typename U>
inline bool enqueue(U&& element)
{
index_t currentTailIndex = this->tailIndex.load(std::memory_order_relaxed);
index_t newTailIndex = 1 + currentTailIndex;
if ((currentTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
// We reached the end of a block, start a new one
auto startBlock = this->tailBlock;
auto originalBlockIndexSlotsUsed = pr_blockIndexSlotsUsed;
if (this->tailBlock != nullptr && this->tailBlock->next->ConcurrentQueue::Block::template is_empty<explicit_context>()) {
// We can re-use the block ahead of us, it's empty!
this->tailBlock = this->tailBlock->next;
this->tailBlock->ConcurrentQueue::Block::template reset_empty<explicit_context>();
// We'll put the block on the block index (guaranteed to be room since we're conceptually removing the
// last block from it first -- except instead of removing then adding, we can just overwrite).
// Note that there must be a valid block index here, since even if allocation failed in the ctor,
// it would have been re-attempted when adding the first block to the queue; since there is such
// a block, a block index must have been successfully allocated.
}
else {
// Whatever head value we see here is >= the last value we saw here (relatively),
// and <= its current value. Since we have the most recent tail, the head must be
// <= to it.
auto head = this->headIndex.load(std::memory_order_relaxed);
assert(!details::circular_less_than<index_t>(currentTailIndex, head));
if (!details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE)
|| (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value && (MAX_SUBQUEUE_SIZE == 0 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head))) {
// We can't enqueue in another block because there's not enough leeway -- the
// tail could surpass the head by the time the block fills up! (Or we'll exceed
// the size limit, if the second part of the condition was true.)
return false;
}
// We're going to need a new block; check that the block index has room
if (pr_blockIndexRaw == nullptr || pr_blockIndexSlotsUsed == pr_blockIndexSize) {
// Hmm, the circular block index is already full -- we'll need
// to allocate a new index. Note pr_blockIndexRaw can only be nullptr if
// the initial allocation failed in the constructor.
if (allocMode == CannotAlloc || !new_block_index(pr_blockIndexSlotsUsed)) {
return false;
}
}
// Insert a new block in the circular linked list
auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
if (newBlock == nullptr) {
return false;
}
#if MCDBGQ_TRACKMEM
newBlock->owner = this;
#endif
newBlock->ConcurrentQueue::Block::template reset_empty<explicit_context>();
if (this->tailBlock == nullptr) {
newBlock->next = newBlock;
}
else {
newBlock->next = this->tailBlock->next;
this->tailBlock->next = newBlock;
}
this->tailBlock = newBlock;
++pr_blockIndexSlotsUsed;
}
if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
// The constructor may throw. We want the element not to appear in the queue in
// that case (without corrupting the queue):
MOODYCAMEL_TRY {
new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
}
MOODYCAMEL_CATCH (...) {
// Revert change to the current block, but leave the new block available
// for next time
pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
this->tailBlock = startBlock == nullptr ? this->tailBlock : startBlock;
MOODYCAMEL_RETHROW;
}
}
else {
(void)startBlock;
(void)originalBlockIndexSlotsUsed;
}
// Add block to block index
auto& entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
entry.base = currentTailIndex;
entry.block = this->tailBlock;
blockIndex.load(std::memory_order_relaxed)->front.store(pr_blockIndexFront, std::memory_order_release);
pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
}
// Enqueue
new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
template<typename U>
bool dequeue(U& element)
{
auto tail = this->tailIndex.load(std::memory_order_relaxed);
auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
if (details::circular_less_than<index_t>(this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit, tail)) {
// Might be something to dequeue, let's give it a try
// Note that this if is purely for performance purposes in the common case when the queue is
// empty and the values are eventually consistent -- we may enter here spuriously.
// Note that whatever the values of overcommit and tail are, they are not going to change (unless we
// change them) and must be the same value at this point (inside the if) as when the if condition was
// evaluated.
// We insert an acquire fence here to synchronize-with the release upon incrementing dequeueOvercommit below.
// This ensures that whatever the value we got loaded into overcommit, the load of dequeueOptisticCount in
// the fetch_add below will result in a value at least as recent as that (and therefore at least as large).
// Note that I believe a compiler (signal) fence here would be sufficient due to the nature of fetch_add (all
// read-modify-write operations are guaranteed to work on the latest value in the modification order), but
// unfortunately that can't be shown to be correct using only the C++11 standard.
// See http://stackoverflow.com/questions/18223161/what-are-the-c11-memory-ordering-guarantees-in-this-corner-case
std::atomic_thread_fence(std::memory_order_acquire);
// Increment optimistic counter, then check if it went over the boundary
auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(1, std::memory_order_relaxed);
// Note that since dequeueOvercommit must be <= dequeueOptimisticCount (because dequeueOvercommit is only ever
// incremented after dequeueOptimisticCount -- this is enforced in the `else` block below), and since we now
// have a version of dequeueOptimisticCount that is at least as recent as overcommit (due to the release upon
// incrementing dequeueOvercommit and the acquire above that synchronizes with it), overcommit <= myDequeueCount.
assert(overcommit <= myDequeueCount);
// Note that we reload tail here in case it changed; it will be the same value as before or greater, since
// this load is sequenced after (happens after) the earlier load above. This is supported by read-read
// coherency (as defined in the standard), explained here: http://en.cppreference.com/w/cpp/atomic/memory_order
tail = this->tailIndex.load(std::memory_order_acquire);
if (details::likely(details::circular_less_than<index_t>(myDequeueCount - overcommit, tail))) {
// Guaranteed to be at least one element to dequeue!
// Get the index. Note that since there's guaranteed to be at least one element, this
// will never exceed tail. We need to do an acquire-release fence here since it's possible
// that whatever condition got us to this point was for an earlier enqueued element (that
// we already see the memory effects for), but that by the time we increment somebody else
// has incremented it, and we need to see the memory effects for *that* element, which is
// in such a case is necessarily visible on the thread that incremented it in the first
// place with the more current condition (they must have acquired a tail that is at least
// as recent).
auto index = this->headIndex.fetch_add(1, std::memory_order_acq_rel);
// Determine which block the element is in
auto localBlockIndex = blockIndex.load(std::memory_order_acquire);
auto localBlockIndexHead = localBlockIndex->front.load(std::memory_order_acquire);
// We need to be careful here about subtracting and dividing because of index wrap-around.
// When an index wraps, we need to preserve the sign of the offset when dividing it by the
// block size (in order to get a correct signed block count offset in all cases):
auto headBase = localBlockIndex->entries[localBlockIndexHead].base;
auto blockBaseIndex = index & ~static_cast<index_t>(BLOCK_SIZE - 1);
auto offset = static_cast<size_t>(static_cast<typename std::make_signed<index_t>::type>(blockBaseIndex - headBase) / BLOCK_SIZE);
auto block = localBlockIndex->entries[(localBlockIndexHead + offset) & (localBlockIndex->size - 1)].block;
// Dequeue
auto& el = *((*block)[index]);
if (!MOODYCAMEL_NOEXCEPT_ASSIGN(T, T&&, element = std::move(el))) {
// Make sure the element is still fully dequeued and destroyed even if the assignment
// throws
struct Guard {
Block* block;
index_t index;
~Guard()
{
(*block)[index]->~T();
block->ConcurrentQueue::Block::template set_empty<explicit_context>(index);
}
} guard = { block, index };
element = std::move(el);
}
else {
element = std::move(el);
el.~T();
block->ConcurrentQueue::Block::template set_empty<explicit_context>(index);
}
return true;
}
else {
// Wasn't anything to dequeue after all; make the effective dequeue count eventually consistent
this->dequeueOvercommit.fetch_add(1, std::memory_order_release); // Release so that the fetch_add on dequeueOptimisticCount is guaranteed to happen before this write
}
}
return false;
}
template<AllocationMode allocMode, typename It>
bool enqueue_bulk(It itemFirst, size_t count)
{
// First, we need to make sure we have enough room to enqueue all of the elements;
// this means pre-allocating blocks and putting them in the block index (but only if
// all the allocations succeeded).
index_t startTailIndex = this->tailIndex.load(std::memory_order_relaxed);
auto startBlock = this->tailBlock;
auto originalBlockIndexFront = pr_blockIndexFront;
auto originalBlockIndexSlotsUsed = pr_blockIndexSlotsUsed;
Block* firstAllocatedBlock = nullptr;
// Figure out how many blocks we'll need to allocate, and do so
size_t blockBaseDiff = ((startTailIndex + count - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1)) - ((startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1));
index_t currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
if (blockBaseDiff > 0) {
// Allocate as many blocks as possible from ahead
while (blockBaseDiff > 0 && this->tailBlock != nullptr && this->tailBlock->next != firstAllocatedBlock && this->tailBlock->next->ConcurrentQueue::Block::template is_empty<explicit_context>()) {
blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
this->tailBlock = this->tailBlock->next;
firstAllocatedBlock = firstAllocatedBlock == nullptr ? this->tailBlock : firstAllocatedBlock;
auto& entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
entry.base = currentTailIndex;
entry.block = this->tailBlock;
pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
}
// Now allocate as many blocks as necessary from the block pool
while (blockBaseDiff > 0) {
blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
auto head = this->headIndex.load(std::memory_order_relaxed);
assert(!details::circular_less_than<index_t>(currentTailIndex, head));
bool full = !details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE) || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value && (MAX_SUBQUEUE_SIZE == 0 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head));
if (pr_blockIndexRaw == nullptr || pr_blockIndexSlotsUsed == pr_blockIndexSize || full) {
if (allocMode == CannotAlloc || full || !new_block_index(originalBlockIndexSlotsUsed)) {
// Failed to allocate, undo changes (but keep injected blocks)
pr_blockIndexFront = originalBlockIndexFront;
pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
return false;
}
// pr_blockIndexFront is updated inside new_block_index, so we need to
// update our fallback value too (since we keep the new index even if we
// later fail)
originalBlockIndexFront = originalBlockIndexSlotsUsed;
}
// Insert a new block in the circular linked list
auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
if (newBlock == nullptr) {
pr_blockIndexFront = originalBlockIndexFront;
pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
return false;
}
#if MCDBGQ_TRACKMEM
newBlock->owner = this;
#endif
newBlock->ConcurrentQueue::Block::template set_all_empty<explicit_context>();
if (this->tailBlock == nullptr) {
newBlock->next = newBlock;
}
else {
newBlock->next = this->tailBlock->next;
this->tailBlock->next = newBlock;
}
this->tailBlock = newBlock;
firstAllocatedBlock = firstAllocatedBlock == nullptr ? this->tailBlock : firstAllocatedBlock;
++pr_blockIndexSlotsUsed;
auto& entry = blockIndex.load(std::memory_order_relaxed)->entries[pr_blockIndexFront];
entry.base = currentTailIndex;
entry.block = this->tailBlock;
pr_blockIndexFront = (pr_blockIndexFront + 1) & (pr_blockIndexSize - 1);
}
// Excellent, all allocations succeeded. Reset each block's emptiness before we fill them up, and
// publish the new block index front
auto block = firstAllocatedBlock;
while (true) {
block->ConcurrentQueue::Block::template reset_empty<explicit_context>();
if (block == this->tailBlock) {
break;
}
block = block->next;
}
if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
blockIndex.load(std::memory_order_relaxed)->front.store((pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release);
}
}
// Enqueue, one block at a time
index_t newTailIndex = startTailIndex + static_cast<index_t>(count);
currentTailIndex = startTailIndex;
auto endBlock = this->tailBlock;
this->tailBlock = startBlock;
assert((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0 || firstAllocatedBlock != nullptr || count == 0);
if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0 && firstAllocatedBlock != nullptr) {
this->tailBlock = firstAllocatedBlock;
}
while (true) {
auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
if (details::circular_less_than<index_t>(newTailIndex, stopIndex)) {
stopIndex = newTailIndex;
}
if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
while (currentTailIndex != stopIndex) {
new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++);
}
}
else {
MOODYCAMEL_TRY {
while (currentTailIndex != stopIndex) {
// Must use copy constructor even if move constructor is available
// because we may have to revert if there's an exception.
// Sorry about the horrible templated next line, but it was the only way
// to disable moving *at compile time*, which is important because a type
// may only define a (noexcept) move constructor, and so calls to the
// cctor will not compile, even if they are in an if branch that will never
// be executed
new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst));
++currentTailIndex;
++itemFirst;
}
}
MOODYCAMEL_CATCH (...) {
// Oh dear, an exception's been thrown -- destroy the elements that
// were enqueued so far and revert the entire bulk operation (we'll keep
// any allocated blocks in our linked list for later, though).
auto constructedStopIndex = currentTailIndex;
auto lastBlockEnqueued = this->tailBlock;
pr_blockIndexFront = originalBlockIndexFront;
pr_blockIndexSlotsUsed = originalBlockIndexSlotsUsed;
this->tailBlock = startBlock == nullptr ? firstAllocatedBlock : startBlock;
if (!details::is_trivially_destructible<T>::value) {
auto block = startBlock;
if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
block = firstAllocatedBlock;
}
currentTailIndex = startTailIndex;
while (true) {
auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
if (details::circular_less_than<index_t>(constructedStopIndex, stopIndex)) {
stopIndex = constructedStopIndex;
}
while (currentTailIndex != stopIndex) {
(*block)[currentTailIndex++]->~T();
}
if (block == lastBlockEnqueued) {
break;
}
block = block->next;
}
}
MOODYCAMEL_RETHROW;
}
}
if (this->tailBlock == endBlock) {
assert(currentTailIndex == newTailIndex);
break;
}
this->tailBlock = this->tailBlock->next;
}
if (!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst))) && firstAllocatedBlock != nullptr) {
blockIndex.load(std::memory_order_relaxed)->front.store((pr_blockIndexFront - 1) & (pr_blockIndexSize - 1), std::memory_order_release);
}
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
template<typename It>
size_t dequeue_bulk(It& itemFirst, size_t max)
{
auto tail = this->tailIndex.load(std::memory_order_relaxed);
auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
auto desiredCount = static_cast<size_t>(tail - (this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit));
if (details::circular_less_than<size_t>(0, desiredCount)) {
desiredCount = desiredCount < max ? desiredCount : max;
std::atomic_thread_fence(std::memory_order_acquire);
auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed);
assert(overcommit <= myDequeueCount);
tail = this->tailIndex.load(std::memory_order_acquire);
auto actualCount = static_cast<size_t>(tail - (myDequeueCount - overcommit));
if (details::circular_less_than<size_t>(0, actualCount)) {
actualCount = desiredCount < actualCount ? desiredCount : actualCount;
if (actualCount < desiredCount) {
this->dequeueOvercommit.fetch_add(desiredCount - actualCount, std::memory_order_release);
}
// Get the first index. Note that since there's guaranteed to be at least actualCount elements, this
// will never exceed tail.
auto firstIndex = this->headIndex.fetch_add(actualCount, std::memory_order_acq_rel);
// Determine which block the first element is in
auto localBlockIndex = blockIndex.load(std::memory_order_acquire);
auto localBlockIndexHead = localBlockIndex->front.load(std::memory_order_acquire);
auto headBase = localBlockIndex->entries[localBlockIndexHead].base;
auto firstBlockBaseIndex = firstIndex & ~static_cast<index_t>(BLOCK_SIZE - 1);
auto offset = static_cast<size_t>(static_cast<typename std::make_signed<index_t>::type>(firstBlockBaseIndex - headBase) / BLOCK_SIZE);
auto indexIndex = (localBlockIndexHead + offset) & (localBlockIndex->size - 1);
// Iterate the blocks and dequeue
auto index = firstIndex;
do {
auto firstIndexInBlock = index;
auto endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
endIndex = details::circular_less_than<index_t>(firstIndex + static_cast<index_t>(actualCount), endIndex) ? firstIndex + static_cast<index_t>(actualCount) : endIndex;
auto block = localBlockIndex->entries[indexIndex].block;
if (MOODYCAMEL_NOEXCEPT_ASSIGN(T, T&&, details::deref_noexcept(itemFirst) = std::move((*(*block)[index])))) {
while (index != endIndex) {
auto& el = *((*block)[index]);
*itemFirst++ = std::move(el);
el.~T();
++index;
}
}
else {
MOODYCAMEL_TRY {
while (index != endIndex) {
auto& el = *((*block)[index]);
*itemFirst = std::move(el);
++itemFirst;
el.~T();
++index;
}
}
MOODYCAMEL_CATCH (...) {
// It's too late to revert the dequeue, but we can make sure that all
// the dequeued objects are properly destroyed and the block index
// (and empty count) are properly updated before we propagate the exception
do {
block = localBlockIndex->entries[indexIndex].block;
while (index != endIndex) {
(*block)[index++]->~T();
}
block->ConcurrentQueue::Block::template set_many_empty<explicit_context>(firstIndexInBlock, static_cast<size_t>(endIndex - firstIndexInBlock));
indexIndex = (indexIndex + 1) & (localBlockIndex->size - 1);
firstIndexInBlock = index;
endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
endIndex = details::circular_less_than<index_t>(firstIndex + static_cast<index_t>(actualCount), endIndex) ? firstIndex + static_cast<index_t>(actualCount) : endIndex;
} while (index != firstIndex + actualCount);
MOODYCAMEL_RETHROW;
}
}
block->ConcurrentQueue::Block::template set_many_empty<explicit_context>(firstIndexInBlock, static_cast<size_t>(endIndex - firstIndexInBlock));
indexIndex = (indexIndex + 1) & (localBlockIndex->size - 1);
} while (index != firstIndex + actualCount);
return actualCount;
}
else {
// Wasn't anything to dequeue after all; make the effective dequeue count eventually consistent
this->dequeueOvercommit.fetch_add(desiredCount, std::memory_order_release);
}
}
return 0;
}
private:
struct BlockIndexEntry
{
index_t base;
Block* block;
};
struct BlockIndexHeader
{
size_t size;
std::atomic<size_t> front; // Current slot (not next, like pr_blockIndexFront)
BlockIndexEntry* entries;
void* prev;
};
bool new_block_index(size_t numberOfFilledSlotsToExpose)
{
auto prevBlockSizeMask = pr_blockIndexSize - 1;
// Create the new block
pr_blockIndexSize <<= 1;
auto newRawPtr = static_cast<char*>((Traits::malloc)(sizeof(BlockIndexHeader) + std::alignment_of<BlockIndexEntry>::value - 1 + sizeof(BlockIndexEntry) * pr_blockIndexSize));
if (newRawPtr == nullptr) {
pr_blockIndexSize >>= 1; // Reset to allow graceful retry
return false;
}
auto newBlockIndexEntries = reinterpret_cast<BlockIndexEntry*>(details::align_for<BlockIndexEntry>(newRawPtr + sizeof(BlockIndexHeader)));
// Copy in all the old indices, if any
size_t j = 0;
if (pr_blockIndexSlotsUsed != 0) {
auto i = (pr_blockIndexFront - pr_blockIndexSlotsUsed) & prevBlockSizeMask;
do {
newBlockIndexEntries[j++] = pr_blockIndexEntries[i];
i = (i + 1) & prevBlockSizeMask;
} while (i != pr_blockIndexFront);
}
// Update everything
auto header = new (newRawPtr) BlockIndexHeader;
header->size = pr_blockIndexSize;
header->front.store(numberOfFilledSlotsToExpose - 1, std::memory_order_relaxed);
header->entries = newBlockIndexEntries;
header->prev = pr_blockIndexRaw; // we link the new block to the old one so we can free it later
pr_blockIndexFront = j;
pr_blockIndexEntries = newBlockIndexEntries;
pr_blockIndexRaw = newRawPtr;
blockIndex.store(header, std::memory_order_release);
return true;
}
private:
std::atomic<BlockIndexHeader*> blockIndex;
// To be used by producer only -- consumer must use the ones in referenced by blockIndex
size_t pr_blockIndexSlotsUsed;
size_t pr_blockIndexSize;
size_t pr_blockIndexFront; // Next slot (not current)
BlockIndexEntry* pr_blockIndexEntries;
void* pr_blockIndexRaw;
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
public:
ExplicitProducer* nextExplicitProducer;
private:
#endif
#if MCDBGQ_TRACKMEM
friend struct MemStats;
#endif
};
//////////////////////////////////
// Implicit queue
//////////////////////////////////
struct ImplicitProducer : public ProducerBase
{
ImplicitProducer(ConcurrentQueue* parent) :
ProducerBase(parent, false),
nextBlockIndexCapacity(IMPLICIT_INITIAL_INDEX_SIZE),
blockIndex(nullptr)
{
new_block_index();
}
~ImplicitProducer()
{
// Note that since we're in the destructor we can assume that all enqueue/dequeue operations
// completed already; this means that all undequeued elements are placed contiguously across
// contiguous blocks, and that only the first and last remaining blocks can be only partially
// empty (all other remaining blocks must be completely full).
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
// Unregister ourselves for thread termination notification
if (!this->inactive.load(std::memory_order_relaxed)) {
details::ThreadExitNotifier::unsubscribe(&threadExitListener);
}
#endif
// Destroy all remaining elements!
auto tail = this->tailIndex.load(std::memory_order_relaxed);
auto index = this->headIndex.load(std::memory_order_relaxed);
Block* block = nullptr;
assert(index == tail || details::circular_less_than(index, tail));
bool forceFreeLastBlock = index != tail; // If we enter the loop, then the last (tail) block will not be freed
while (index != tail) {
if ((index & static_cast<index_t>(BLOCK_SIZE - 1)) == 0 || block == nullptr) {
if (block != nullptr && block->dynamicallyAllocated) {
// Free the old block
this->parent->destroy(block);
}
block = get_block_index_entry_for_index(index)->value.load(std::memory_order_relaxed);
}
((*block)[index])->~T();
++index;
}
// Even if the queue is empty, there's still one block that's not on the free list
// (unless the head index reached the end of it, in which case the tail will be poised
// to create a new block).
if (this->tailBlock != nullptr && (forceFreeLastBlock || (tail & static_cast<index_t>(BLOCK_SIZE - 1)) != 0) && this->tailBlock->dynamicallyAllocated) {
this->parent->destroy(this->tailBlock);
}
// Destroy block index
auto localBlockIndex = blockIndex.load(std::memory_order_relaxed);
if (localBlockIndex != nullptr) {
for (size_t i = 0; i != localBlockIndex->capacity; ++i) {
localBlockIndex->index[i]->~BlockIndexEntry();
}
do {
auto prev = localBlockIndex->prev;
localBlockIndex->~BlockIndexHeader();
(Traits::free)(localBlockIndex);
localBlockIndex = prev;
} while (localBlockIndex != nullptr);
}
}
template<AllocationMode allocMode, typename U>
inline bool enqueue(U&& element)
{
index_t currentTailIndex = this->tailIndex.load(std::memory_order_relaxed);
index_t newTailIndex = 1 + currentTailIndex;
if ((currentTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
// We reached the end of a block, start a new one
auto head = this->headIndex.load(std::memory_order_relaxed);
assert(!details::circular_less_than<index_t>(currentTailIndex, head));
if (!details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE) || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value && (MAX_SUBQUEUE_SIZE == 0 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head))) {
return false;
}
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
// Find out where we'll be inserting this block in the block index
BlockIndexEntry* idxEntry;
if (!insert_block_index_entry<allocMode>(idxEntry, currentTailIndex)) {
return false;
}
// Get ahold of a new block
auto newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>();
if (newBlock == nullptr) {
rewind_block_index_tail();
idxEntry->value.store(nullptr, std::memory_order_relaxed);
return false;
}
#if MCDBGQ_TRACKMEM
newBlock->owner = this;
#endif
newBlock->ConcurrentQueue::Block::template reset_empty<implicit_context>();
if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
// May throw, try to insert now before we publish the fact that we have this new block
MOODYCAMEL_TRY {
new ((*newBlock)[currentTailIndex]) T(std::forward<U>(element));
}
MOODYCAMEL_CATCH (...) {
rewind_block_index_tail();
idxEntry->value.store(nullptr, std::memory_order_relaxed);
this->parent->add_block_to_free_list(newBlock);
MOODYCAMEL_RETHROW;
}
}
// Insert the new block into the index
idxEntry->value.store(newBlock, std::memory_order_relaxed);
this->tailBlock = newBlock;
if (!MOODYCAMEL_NOEXCEPT_CTOR(T, U, new (nullptr) T(std::forward<U>(element)))) {
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
}
// Enqueue
new ((*this->tailBlock)[currentTailIndex]) T(std::forward<U>(element));
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
template<typename U>
bool dequeue(U& element)
{
// See ExplicitProducer::dequeue for rationale and explanation
index_t tail = this->tailIndex.load(std::memory_order_relaxed);
index_t overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
if (details::circular_less_than<index_t>(this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit, tail)) {
std::atomic_thread_fence(std::memory_order_acquire);
index_t myDequeueCount = this->dequeueOptimisticCount.fetch_add(1, std::memory_order_relaxed);
assert(overcommit <= myDequeueCount);
tail = this->tailIndex.load(std::memory_order_acquire);
if (details::likely(details::circular_less_than<index_t>(myDequeueCount - overcommit, tail))) {
index_t index = this->headIndex.fetch_add(1, std::memory_order_acq_rel);
// Determine which block the element is in
auto entry = get_block_index_entry_for_index(index);
// Dequeue
auto block = entry->value.load(std::memory_order_relaxed);
auto& el = *((*block)[index]);
if (!MOODYCAMEL_NOEXCEPT_ASSIGN(T, T&&, element = std::move(el))) {
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
// Note: Acquiring the mutex with every dequeue instead of only when a block
// is released is very sub-optimal, but it is, after all, purely debug code.
debug::DebugLock lock(producer->mutex);
#endif
struct Guard {
Block* block;
index_t index;
BlockIndexEntry* entry;
ConcurrentQueue* parent;
~Guard()
{
(*block)[index]->~T();
if (block->ConcurrentQueue::Block::template set_empty<implicit_context>(index)) {
entry->value.store(nullptr, std::memory_order_relaxed);
parent->add_block_to_free_list(block);
}
}
} guard = { block, index, entry, this->parent };
element = std::move(el);
}
else {
element = std::move(el);
el.~T();
if (block->ConcurrentQueue::Block::template set_empty<implicit_context>(index)) {
{
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
// Add the block back into the global free pool (and remove from block index)
entry->value.store(nullptr, std::memory_order_relaxed);
}
this->parent->add_block_to_free_list(block); // releases the above store
}
}
return true;
}
else {
this->dequeueOvercommit.fetch_add(1, std::memory_order_release);
}
}
return false;
}
template<AllocationMode allocMode, typename It>
bool enqueue_bulk(It itemFirst, size_t count)
{
// First, we need to make sure we have enough room to enqueue all of the elements;
// this means pre-allocating blocks and putting them in the block index (but only if
// all the allocations succeeded).
// Note that the tailBlock we start off with may not be owned by us any more;
// this happens if it was filled up exactly to the top (setting tailIndex to
// the first index of the next block which is not yet allocated), then dequeued
// completely (putting it on the free list) before we enqueue again.
index_t startTailIndex = this->tailIndex.load(std::memory_order_relaxed);
auto startBlock = this->tailBlock;
Block* firstAllocatedBlock = nullptr;
auto endBlock = this->tailBlock;
// Figure out how many blocks we'll need to allocate, and do so
size_t blockBaseDiff = ((startTailIndex + count - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1)) - ((startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1));
index_t currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
if (blockBaseDiff > 0) {
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
do {
blockBaseDiff -= static_cast<index_t>(BLOCK_SIZE);
currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
// Find out where we'll be inserting this block in the block index
BlockIndexEntry* idxEntry;
Block* newBlock;
bool indexInserted = false;
auto head = this->headIndex.load(std::memory_order_relaxed);
assert(!details::circular_less_than<index_t>(currentTailIndex, head));
bool full = !details::circular_less_than<index_t>(head, currentTailIndex + BLOCK_SIZE) || (MAX_SUBQUEUE_SIZE != details::const_numeric_max<size_t>::value && (MAX_SUBQUEUE_SIZE == 0 || MAX_SUBQUEUE_SIZE - BLOCK_SIZE < currentTailIndex - head));
if (full || !(indexInserted = insert_block_index_entry<allocMode>(idxEntry, currentTailIndex)) || (newBlock = this->parent->ConcurrentQueue::template requisition_block<allocMode>()) == nullptr) {
// Index allocation or block allocation failed; revert any other allocations
// and index insertions done so far for this operation
if (indexInserted) {
rewind_block_index_tail();
idxEntry->value.store(nullptr, std::memory_order_relaxed);
}
currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
for (auto block = firstAllocatedBlock; block != nullptr; block = block->next) {
currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
idxEntry = get_block_index_entry_for_index(currentTailIndex);
idxEntry->value.store(nullptr, std::memory_order_relaxed);
rewind_block_index_tail();
}
this->parent->add_blocks_to_free_list(firstAllocatedBlock);
this->tailBlock = startBlock;
return false;
}
#if MCDBGQ_TRACKMEM
newBlock->owner = this;
#endif
newBlock->ConcurrentQueue::Block::template reset_empty<implicit_context>();
newBlock->next = nullptr;
// Insert the new block into the index
idxEntry->value.store(newBlock, std::memory_order_relaxed);
// Store the chain of blocks so that we can undo if later allocations fail,
// and so that we can find the blocks when we do the actual enqueueing
if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0 || firstAllocatedBlock != nullptr) {
assert(this->tailBlock != nullptr);
this->tailBlock->next = newBlock;
}
this->tailBlock = newBlock;
endBlock = newBlock;
firstAllocatedBlock = firstAllocatedBlock == nullptr ? newBlock : firstAllocatedBlock;
} while (blockBaseDiff > 0);
}
// Enqueue, one block at a time
index_t newTailIndex = startTailIndex + static_cast<index_t>(count);
currentTailIndex = startTailIndex;
this->tailBlock = startBlock;
assert((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) != 0 || firstAllocatedBlock != nullptr || count == 0);
if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0 && firstAllocatedBlock != nullptr) {
this->tailBlock = firstAllocatedBlock;
}
while (true) {
auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
if (details::circular_less_than<index_t>(newTailIndex, stopIndex)) {
stopIndex = newTailIndex;
}
if (MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))) {
while (currentTailIndex != stopIndex) {
new ((*this->tailBlock)[currentTailIndex++]) T(*itemFirst++);
}
}
else {
MOODYCAMEL_TRY {
while (currentTailIndex != stopIndex) {
new ((*this->tailBlock)[currentTailIndex]) T(details::nomove_if<(bool)!MOODYCAMEL_NOEXCEPT_CTOR(T, decltype(*itemFirst), new (nullptr) T(details::deref_noexcept(itemFirst)))>::eval(*itemFirst));
++currentTailIndex;
++itemFirst;
}
}
MOODYCAMEL_CATCH (...) {
auto constructedStopIndex = currentTailIndex;
auto lastBlockEnqueued = this->tailBlock;
if (!details::is_trivially_destructible<T>::value) {
auto block = startBlock;
if ((startTailIndex & static_cast<index_t>(BLOCK_SIZE - 1)) == 0) {
block = firstAllocatedBlock;
}
currentTailIndex = startTailIndex;
while (true) {
auto stopIndex = (currentTailIndex & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
if (details::circular_less_than<index_t>(constructedStopIndex, stopIndex)) {
stopIndex = constructedStopIndex;
}
while (currentTailIndex != stopIndex) {
(*block)[currentTailIndex++]->~T();
}
if (block == lastBlockEnqueued) {
break;
}
block = block->next;
}
}
currentTailIndex = (startTailIndex - 1) & ~static_cast<index_t>(BLOCK_SIZE - 1);
for (auto block = firstAllocatedBlock; block != nullptr; block = block->next) {
currentTailIndex += static_cast<index_t>(BLOCK_SIZE);
auto idxEntry = get_block_index_entry_for_index(currentTailIndex);
idxEntry->value.store(nullptr, std::memory_order_relaxed);
rewind_block_index_tail();
}
this->parent->add_blocks_to_free_list(firstAllocatedBlock);
this->tailBlock = startBlock;
MOODYCAMEL_RETHROW;
}
}
if (this->tailBlock == endBlock) {
assert(currentTailIndex == newTailIndex);
break;
}
this->tailBlock = this->tailBlock->next;
}
this->tailIndex.store(newTailIndex, std::memory_order_release);
return true;
}
template<typename It>
size_t dequeue_bulk(It& itemFirst, size_t max)
{
auto tail = this->tailIndex.load(std::memory_order_relaxed);
auto overcommit = this->dequeueOvercommit.load(std::memory_order_relaxed);
auto desiredCount = static_cast<size_t>(tail - (this->dequeueOptimisticCount.load(std::memory_order_relaxed) - overcommit));
if (details::circular_less_than<size_t>(0, desiredCount)) {
desiredCount = desiredCount < max ? desiredCount : max;
std::atomic_thread_fence(std::memory_order_acquire);
auto myDequeueCount = this->dequeueOptimisticCount.fetch_add(desiredCount, std::memory_order_relaxed);
assert(overcommit <= myDequeueCount);
tail = this->tailIndex.load(std::memory_order_acquire);
auto actualCount = static_cast<size_t>(tail - (myDequeueCount - overcommit));
if (details::circular_less_than<size_t>(0, actualCount)) {
actualCount = desiredCount < actualCount ? desiredCount : actualCount;
if (actualCount < desiredCount) {
this->dequeueOvercommit.fetch_add(desiredCount - actualCount, std::memory_order_release);
}
// Get the first index. Note that since there's guaranteed to be at least actualCount elements, this
// will never exceed tail.
auto firstIndex = this->headIndex.fetch_add(actualCount, std::memory_order_acq_rel);
// Iterate the blocks and dequeue
auto index = firstIndex;
BlockIndexHeader* localBlockIndex;
auto indexIndex = get_block_index_index_for_index(index, localBlockIndex);
do {
auto blockStartIndex = index;
auto endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
endIndex = details::circular_less_than<index_t>(firstIndex + static_cast<index_t>(actualCount), endIndex) ? firstIndex + static_cast<index_t>(actualCount) : endIndex;
auto entry = localBlockIndex->index[indexIndex];
auto block = entry->value.load(std::memory_order_relaxed);
if (MOODYCAMEL_NOEXCEPT_ASSIGN(T, T&&, details::deref_noexcept(itemFirst) = std::move((*(*block)[index])))) {
while (index != endIndex) {
auto& el = *((*block)[index]);
*itemFirst++ = std::move(el);
el.~T();
++index;
}
}
else {
MOODYCAMEL_TRY {
while (index != endIndex) {
auto& el = *((*block)[index]);
*itemFirst = std::move(el);
++itemFirst;
el.~T();
++index;
}
}
MOODYCAMEL_CATCH (...) {
do {
entry = localBlockIndex->index[indexIndex];
block = entry->value.load(std::memory_order_relaxed);
while (index != endIndex) {
(*block)[index++]->~T();
}
if (block->ConcurrentQueue::Block::template set_many_empty<implicit_context>(blockStartIndex, static_cast<size_t>(endIndex - blockStartIndex))) {
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
entry->value.store(nullptr, std::memory_order_relaxed);
this->parent->add_block_to_free_list(block);
}
indexIndex = (indexIndex + 1) & (localBlockIndex->capacity - 1);
blockStartIndex = index;
endIndex = (index & ~static_cast<index_t>(BLOCK_SIZE - 1)) + static_cast<index_t>(BLOCK_SIZE);
endIndex = details::circular_less_than<index_t>(firstIndex + static_cast<index_t>(actualCount), endIndex) ? firstIndex + static_cast<index_t>(actualCount) : endIndex;
} while (index != firstIndex + actualCount);
MOODYCAMEL_RETHROW;
}
}
if (block->ConcurrentQueue::Block::template set_many_empty<implicit_context>(blockStartIndex, static_cast<size_t>(endIndex - blockStartIndex))) {
{
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
// Note that the set_many_empty above did a release, meaning that anybody who acquires the block
// we're about to free can use it safely since our writes (and reads!) will have happened-before then.
entry->value.store(nullptr, std::memory_order_relaxed);
}
this->parent->add_block_to_free_list(block); // releases the above store
}
indexIndex = (indexIndex + 1) & (localBlockIndex->capacity - 1);
} while (index != firstIndex + actualCount);
return actualCount;
}
else {
this->dequeueOvercommit.fetch_add(desiredCount, std::memory_order_release);
}
}
return 0;
}
private:
// The block size must be > 1, so any number with the low bit set is an invalid block base index
static const index_t INVALID_BLOCK_BASE = 1;
struct BlockIndexEntry
{
std::atomic<index_t> key;
std::atomic<Block*> value;
};
struct BlockIndexHeader
{
size_t capacity;
std::atomic<size_t> tail;
BlockIndexEntry* entries;
BlockIndexEntry** index;
BlockIndexHeader* prev;
};
template<AllocationMode allocMode>
inline bool insert_block_index_entry(BlockIndexEntry*& idxEntry, index_t blockStartIndex)
{
auto localBlockIndex = blockIndex.load(std::memory_order_relaxed); // We're the only writer thread, relaxed is OK
auto newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1);
idxEntry = localBlockIndex->index[newTail];
if (idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE ||
idxEntry->value.load(std::memory_order_relaxed) == nullptr) {
idxEntry->key.store(blockStartIndex, std::memory_order_relaxed);
localBlockIndex->tail.store(newTail, std::memory_order_release);
return true;
}
// No room in the old block index, try to allocate another one!
if (allocMode == CannotAlloc || !new_block_index()) {
return false;
}
localBlockIndex = blockIndex.load(std::memory_order_relaxed);
newTail = (localBlockIndex->tail.load(std::memory_order_relaxed) + 1) & (localBlockIndex->capacity - 1);
idxEntry = localBlockIndex->index[newTail];
assert(idxEntry->key.load(std::memory_order_relaxed) == INVALID_BLOCK_BASE);
idxEntry->key.store(blockStartIndex, std::memory_order_relaxed);
localBlockIndex->tail.store(newTail, std::memory_order_release);
return true;
}
inline void rewind_block_index_tail()
{
auto localBlockIndex = blockIndex.load(std::memory_order_relaxed);
localBlockIndex->tail.store((localBlockIndex->tail.load(std::memory_order_relaxed) - 1) & (localBlockIndex->capacity - 1), std::memory_order_relaxed);
}
inline BlockIndexEntry* get_block_index_entry_for_index(index_t index) const
{
BlockIndexHeader* localBlockIndex;
auto idx = get_block_index_index_for_index(index, localBlockIndex);
return localBlockIndex->index[idx];
}
inline size_t get_block_index_index_for_index(index_t index, BlockIndexHeader*& localBlockIndex) const
{
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
debug::DebugLock lock(mutex);
#endif
index &= ~static_cast<index_t>(BLOCK_SIZE - 1);
localBlockIndex = blockIndex.load(std::memory_order_acquire);
auto tail = localBlockIndex->tail.load(std::memory_order_acquire);
auto tailBase = localBlockIndex->index[tail]->key.load(std::memory_order_relaxed);
assert(tailBase != INVALID_BLOCK_BASE);
// Note: Must use division instead of shift because the index may wrap around, causing a negative
// offset, whose negativity we want to preserve
auto offset = static_cast<size_t>(static_cast<typename std::make_signed<index_t>::type>(index - tailBase) / BLOCK_SIZE);
size_t idx = (tail + offset) & (localBlockIndex->capacity - 1);
assert(localBlockIndex->index[idx]->key.load(std::memory_order_relaxed) == index && localBlockIndex->index[idx]->value.load(std::memory_order_relaxed) != nullptr);
return idx;
}
bool new_block_index()
{
auto prev = blockIndex.load(std::memory_order_relaxed);
size_t prevCapacity = prev == nullptr ? 0 : prev->capacity;
auto entryCount = prev == nullptr ? nextBlockIndexCapacity : prevCapacity;
auto raw = static_cast<char*>((Traits::malloc)(
sizeof(BlockIndexHeader) +
std::alignment_of<BlockIndexEntry>::value - 1 + sizeof(BlockIndexEntry) * entryCount +
std::alignment_of<BlockIndexEntry*>::value - 1 + sizeof(BlockIndexEntry*) * nextBlockIndexCapacity));
if (raw == nullptr) {
return false;
}
auto header = new (raw) BlockIndexHeader;
auto entries = reinterpret_cast<BlockIndexEntry*>(details::align_for<BlockIndexEntry>(raw + sizeof(BlockIndexHeader)));
auto index = reinterpret_cast<BlockIndexEntry**>(details::align_for<BlockIndexEntry*>(reinterpret_cast<char*>(entries) + sizeof(BlockIndexEntry) * entryCount));
if (prev != nullptr) {
auto prevTail = prev->tail.load(std::memory_order_relaxed);
auto prevPos = prevTail;
size_t i = 0;
do {
prevPos = (prevPos + 1) & (prev->capacity - 1);
index[i++] = prev->index[prevPos];
} while (prevPos != prevTail);
assert(i == prevCapacity);
}
for (size_t i = 0; i != entryCount; ++i) {
new (entries + i) BlockIndexEntry;
entries[i].key.store(INVALID_BLOCK_BASE, std::memory_order_relaxed);
index[prevCapacity + i] = entries + i;
}
header->prev = prev;
header->entries = entries;
header->index = index;
header->capacity = nextBlockIndexCapacity;
header->tail.store((prevCapacity - 1) & (nextBlockIndexCapacity - 1), std::memory_order_relaxed);
blockIndex.store(header, std::memory_order_release);
nextBlockIndexCapacity <<= 1;
return true;
}
private:
size_t nextBlockIndexCapacity;
std::atomic<BlockIndexHeader*> blockIndex;
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
public:
details::ThreadExitListener threadExitListener;
private:
#endif
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
public:
ImplicitProducer* nextImplicitProducer;
private:
#endif
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODBLOCKINDEX
mutable debug::DebugMutex mutex;
#endif
#if MCDBGQ_TRACKMEM
friend struct MemStats;
#endif
};
//////////////////////////////////
// Block pool manipulation
//////////////////////////////////
void populate_initial_block_list(size_t blockCount)
{
initialBlockPoolSize = blockCount;
if (initialBlockPoolSize == 0) {
initialBlockPool = nullptr;
return;
}
initialBlockPool = create_array<Block>(blockCount);
if (initialBlockPool == nullptr) {
initialBlockPoolSize = 0;
}
for (size_t i = 0; i < initialBlockPoolSize; ++i) {
initialBlockPool[i].dynamicallyAllocated = false;
}
}
inline Block* try_get_block_from_initial_pool()
{
if (initialBlockPoolIndex.load(std::memory_order_relaxed) >= initialBlockPoolSize) {
return nullptr;
}
auto index = initialBlockPoolIndex.fetch_add(1, std::memory_order_relaxed);
return index < initialBlockPoolSize ? (initialBlockPool + index) : nullptr;
}
inline void add_block_to_free_list(Block* block)
{
#if MCDBGQ_TRACKMEM
block->owner = nullptr;
#endif
freeList.add(block);
}
inline void add_blocks_to_free_list(Block* block)
{
while (block != nullptr) {
auto next = block->next;
add_block_to_free_list(block);
block = next;
}
}
inline Block* try_get_block_from_free_list()
{
return freeList.try_get();
}
// Gets a free block from one of the memory pools, or allocates a new one (if applicable)
template<AllocationMode canAlloc>
Block* requisition_block()
{
auto block = try_get_block_from_initial_pool();
if (block != nullptr) {
return block;
}
block = try_get_block_from_free_list();
if (block != nullptr) {
return block;
}
if (canAlloc == CanAlloc) {
return create<Block>();
}
return nullptr;
}
#if MCDBGQ_TRACKMEM
public:
struct MemStats {
size_t allocatedBlocks;
size_t usedBlocks;
size_t freeBlocks;
size_t ownedBlocksExplicit;
size_t ownedBlocksImplicit;
size_t implicitProducers;
size_t explicitProducers;
size_t elementsEnqueued;
size_t blockClassBytes;
size_t queueClassBytes;
size_t implicitBlockIndexBytes;
size_t explicitBlockIndexBytes;
friend class ConcurrentQueue;
private:
static MemStats getFor(ConcurrentQueue* q)
{
MemStats stats = { 0 };
stats.elementsEnqueued = q->size_approx();
auto block = q->freeList.head_unsafe();
while (block != nullptr) {
++stats.allocatedBlocks;
++stats.freeBlocks;
block = block->freeListNext.load(std::memory_order_relaxed);
}
for (auto ptr = q->producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
bool implicit = dynamic_cast<ImplicitProducer*>(ptr) != nullptr;
stats.implicitProducers += implicit ? 1 : 0;
stats.explicitProducers += implicit ? 0 : 1;
if (implicit) {
auto prod = static_cast<ImplicitProducer*>(ptr);
stats.queueClassBytes += sizeof(ImplicitProducer);
auto head = prod->headIndex.load(std::memory_order_relaxed);
auto tail = prod->tailIndex.load(std::memory_order_relaxed);
auto hash = prod->blockIndex.load(std::memory_order_relaxed);
if (hash != nullptr) {
for (size_t i = 0; i != hash->capacity; ++i) {
if (hash->index[i]->key.load(std::memory_order_relaxed) != ImplicitProducer::INVALID_BLOCK_BASE && hash->index[i]->value.load(std::memory_order_relaxed) != nullptr) {
++stats.allocatedBlocks;
++stats.ownedBlocksImplicit;
}
}
stats.implicitBlockIndexBytes += hash->capacity * sizeof(typename ImplicitProducer::BlockIndexEntry);
for (; hash != nullptr; hash = hash->prev) {
stats.implicitBlockIndexBytes += sizeof(typename ImplicitProducer::BlockIndexHeader) + hash->capacity * sizeof(typename ImplicitProducer::BlockIndexEntry*);
}
}
for (; details::circular_less_than<index_t>(head, tail); head += BLOCK_SIZE) {
//auto block = prod->get_block_index_entry_for_index(head);
++stats.usedBlocks;
}
}
else {
auto prod = static_cast<ExplicitProducer*>(ptr);
stats.queueClassBytes += sizeof(ExplicitProducer);
auto tailBlock = prod->tailBlock;
bool wasNonEmpty = false;
if (tailBlock != nullptr) {
auto block = tailBlock;
do {
++stats.allocatedBlocks;
if (!block->ConcurrentQueue::Block::template is_empty<explicit_context>() || wasNonEmpty) {
++stats.usedBlocks;
wasNonEmpty = wasNonEmpty || block != tailBlock;
}
++stats.ownedBlocksExplicit;
block = block->next;
} while (block != tailBlock);
}
auto index = prod->blockIndex.load(std::memory_order_relaxed);
while (index != nullptr) {
stats.explicitBlockIndexBytes += sizeof(typename ExplicitProducer::BlockIndexHeader) + index->size * sizeof(typename ExplicitProducer::BlockIndexEntry);
index = static_cast<typename ExplicitProducer::BlockIndexHeader*>(index->prev);
}
}
}
auto freeOnInitialPool = q->initialBlockPoolIndex.load(std::memory_order_relaxed) >= q->initialBlockPoolSize ? 0 : q->initialBlockPoolSize - q->initialBlockPoolIndex.load(std::memory_order_relaxed);
stats.allocatedBlocks += freeOnInitialPool;
stats.freeBlocks += freeOnInitialPool;
stats.blockClassBytes = sizeof(Block) * stats.allocatedBlocks;
stats.queueClassBytes += sizeof(ConcurrentQueue);
return stats;
}
};
// For debugging only. Not thread-safe.
MemStats getMemStats()
{
return MemStats::getFor(this);
}
private:
friend struct MemStats;
#endif
//////////////////////////////////
// Producer list manipulation
//////////////////////////////////
ProducerBase* recycle_or_create_producer(bool isExplicit)
{
bool recycled;
return recycle_or_create_producer(isExplicit, recycled);
}
ProducerBase* recycle_or_create_producer(bool isExplicit, bool& recycled)
{
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
debug::DebugLock lock(implicitProdMutex);
#endif
// Try to re-use one first
for (auto ptr = producerListTail.load(std::memory_order_acquire); ptr != nullptr; ptr = ptr->next_prod()) {
if (ptr->inactive.load(std::memory_order_relaxed) && ptr->isExplicit == isExplicit) {
bool expected = true;
if (ptr->inactive.compare_exchange_strong(expected, /* desired */ false, std::memory_order_acquire, std::memory_order_relaxed)) {
// We caught one! It's been marked as activated, the caller can have it
recycled = true;
return ptr;
}
}
}
recycled = false;
return add_producer(isExplicit ? static_cast<ProducerBase*>(create<ExplicitProducer>(this)) : create<ImplicitProducer>(this));
}
ProducerBase* add_producer(ProducerBase* producer)
{
// Handle failed memory allocation
if (producer == nullptr) {
return nullptr;
}
producerCount.fetch_add(1, std::memory_order_relaxed);
// Add it to the lock-free list
auto prevTail = producerListTail.load(std::memory_order_relaxed);
do {
producer->next = prevTail;
} while (!producerListTail.compare_exchange_weak(prevTail, producer, std::memory_order_release, std::memory_order_relaxed));
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
if (producer->isExplicit) {
auto prevTailExplicit = explicitProducers.load(std::memory_order_relaxed);
do {
static_cast<ExplicitProducer*>(producer)->nextExplicitProducer = prevTailExplicit;
} while (!explicitProducers.compare_exchange_weak(prevTailExplicit, static_cast<ExplicitProducer*>(producer), std::memory_order_release, std::memory_order_relaxed));
}
else {
auto prevTailImplicit = implicitProducers.load(std::memory_order_relaxed);
do {
static_cast<ImplicitProducer*>(producer)->nextImplicitProducer = prevTailImplicit;
} while (!implicitProducers.compare_exchange_weak(prevTailImplicit, static_cast<ImplicitProducer*>(producer), std::memory_order_release, std::memory_order_relaxed));
}
#endif
return producer;
}
void reown_producers()
{
// After another instance is moved-into/swapped-with this one, all the
// producers we stole still think their parents are the other queue.
// So fix them up!
for (auto ptr = producerListTail.load(std::memory_order_relaxed); ptr != nullptr; ptr = ptr->next_prod()) {
ptr->parent = this;
}
}
//////////////////////////////////
// Implicit producer hash
//////////////////////////////////
struct ImplicitProducerKVP
{
std::atomic<details::thread_id_t> key;
ImplicitProducer* value; // No need for atomicity since it's only read by the thread that sets it in the first place
ImplicitProducerKVP() { }
ImplicitProducerKVP(ImplicitProducerKVP&& other) MOODYCAMEL_NOEXCEPT
{
key.store(other.key.load(std::memory_order_relaxed), std::memory_order_relaxed);
value = other.value;
}
inline ImplicitProducerKVP& operator=(ImplicitProducerKVP&& other) MOODYCAMEL_NOEXCEPT
{
swap(other);
return *this;
}
inline void swap(ImplicitProducerKVP& other) MOODYCAMEL_NOEXCEPT
{
if (this != &other) {
details::swap_relaxed(key, other.key);
std::swap(value, other.value);
}
}
};
template<typename XT, typename XTraits>
friend void moodycamel::swap(typename ConcurrentQueue<XT, XTraits>::ImplicitProducerKVP&, typename ConcurrentQueue<XT, XTraits>::ImplicitProducerKVP&) MOODYCAMEL_NOEXCEPT;
struct ImplicitProducerHash
{
size_t capacity;
ImplicitProducerKVP* entries;
ImplicitProducerHash* prev;
};
inline void populate_initial_implicit_producer_hash()
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return;
implicitProducerHashCount.store(0, std::memory_order_relaxed);
auto hash = &initialImplicitProducerHash;
hash->capacity = INITIAL_IMPLICIT_PRODUCER_HASH_SIZE;
hash->entries = &initialImplicitProducerHashEntries[0];
for (size_t i = 0; i != INITIAL_IMPLICIT_PRODUCER_HASH_SIZE; ++i) {
initialImplicitProducerHashEntries[i].key.store(details::invalid_thread_id, std::memory_order_relaxed);
}
hash->prev = nullptr;
implicitProducerHash.store(hash, std::memory_order_relaxed);
}
void swap_implicit_producer_hashes(ConcurrentQueue& other)
{
if (INITIAL_IMPLICIT_PRODUCER_HASH_SIZE == 0) return;
// Swap (assumes our implicit producer hash is initialized)
initialImplicitProducerHashEntries.swap(other.initialImplicitProducerHashEntries);
initialImplicitProducerHash.entries = &initialImplicitProducerHashEntries[0];
other.initialImplicitProducerHash.entries = &other.initialImplicitProducerHashEntries[0];
details::swap_relaxed(implicitProducerHashCount, other.implicitProducerHashCount);
details::swap_relaxed(implicitProducerHash, other.implicitProducerHash);
if (implicitProducerHash.load(std::memory_order_relaxed) == &other.initialImplicitProducerHash) {
implicitProducerHash.store(&initialImplicitProducerHash, std::memory_order_relaxed);
}
else {
ImplicitProducerHash* hash;
for (hash = implicitProducerHash.load(std::memory_order_relaxed); hash->prev != &other.initialImplicitProducerHash; hash = hash->prev) {
continue;
}
hash->prev = &initialImplicitProducerHash;
}
if (other.implicitProducerHash.load(std::memory_order_relaxed) == &initialImplicitProducerHash) {
other.implicitProducerHash.store(&other.initialImplicitProducerHash, std::memory_order_relaxed);
}
else {
ImplicitProducerHash* hash;
for (hash = other.implicitProducerHash.load(std::memory_order_relaxed); hash->prev != &initialImplicitProducerHash; hash = hash->prev) {
continue;
}
hash->prev = &other.initialImplicitProducerHash;
}
}
// Only fails (returns nullptr) if memory allocation fails
ImplicitProducer* get_or_add_implicit_producer()
{
// Note that since the data is essentially thread-local (key is thread ID),
// there's a reduced need for fences (memory ordering is already consistent
// for any individual thread), except for the current table itself.
// Start by looking for the thread ID in the current and all previous hash tables.
// If it's not found, it must not be in there yet, since this same thread would
// have added it previously to one of the tables that we traversed.
// Code and algorithm adapted from http://preshing.com/20130605/the-worlds-simplest-lock-free-hash-table
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
debug::DebugLock lock(implicitProdMutex);
#endif
auto id = details::thread_id();
auto hashedId = details::hash_thread_id(id);
auto mainHash = implicitProducerHash.load(std::memory_order_acquire);
for (auto hash = mainHash; hash != nullptr; hash = hash->prev) {
// Look for the id in this hash
auto index = hashedId;
while (true) { // Not an infinite loop because at least one slot is free in the hash table
index &= hash->capacity - 1;
auto probedKey = hash->entries[index].key.load(std::memory_order_relaxed);
if (probedKey == id) {
// Found it! If we had to search several hashes deep, though, we should lazily add it
// to the current main hash table to avoid the extended search next time.
// Note there's guaranteed to be room in the current hash table since every subsequent
// table implicitly reserves space for all previous tables (there's only one
// implicitProducerHashCount).
auto value = hash->entries[index].value;
if (hash != mainHash) {
index = hashedId;
while (true) {
index &= mainHash->capacity - 1;
probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed);
auto empty = details::invalid_thread_id;
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
auto reusable = details::invalid_thread_id2;
if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed)) ||
(probedKey == reusable && mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_acquire))) {
#else
if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed))) {
#endif
mainHash->entries[index].value = value;
break;
}
++index;
}
}
return value;
}
if (probedKey == details::invalid_thread_id) {
break; // Not in this hash table
}
++index;
}
}
// Insert!
auto newCount = 1 + implicitProducerHashCount.fetch_add(1, std::memory_order_relaxed);
while (true) {
if (newCount >= (mainHash->capacity >> 1) && !implicitProducerHashResizeInProgress.test_and_set(std::memory_order_acquire)) {
// We've acquired the resize lock, try to allocate a bigger hash table.
// Note the acquire fence synchronizes with the release fence at the end of this block, and hence when
// we reload implicitProducerHash it must be the most recent version (it only gets changed within this
// locked block).
mainHash = implicitProducerHash.load(std::memory_order_acquire);
if (newCount >= (mainHash->capacity >> 1)) {
auto newCapacity = mainHash->capacity << 1;
while (newCount >= (newCapacity >> 1)) {
newCapacity <<= 1;
}
auto raw = static_cast<char*>((Traits::malloc)(sizeof(ImplicitProducerHash) + std::alignment_of<ImplicitProducerKVP>::value - 1 + sizeof(ImplicitProducerKVP) * newCapacity));
if (raw == nullptr) {
// Allocation failed
implicitProducerHashCount.fetch_add(-1, std::memory_order_relaxed);
implicitProducerHashResizeInProgress.clear(std::memory_order_relaxed);
return nullptr;
}
auto newHash = new (raw) ImplicitProducerHash;
newHash->capacity = newCapacity;
newHash->entries = reinterpret_cast<ImplicitProducerKVP*>(details::align_for<ImplicitProducerKVP>(raw + sizeof(ImplicitProducerHash)));
for (size_t i = 0; i != newCapacity; ++i) {
new (newHash->entries + i) ImplicitProducerKVP;
newHash->entries[i].key.store(details::invalid_thread_id, std::memory_order_relaxed);
}
newHash->prev = mainHash;
implicitProducerHash.store(newHash, std::memory_order_release);
implicitProducerHashResizeInProgress.clear(std::memory_order_release);
mainHash = newHash;
}
else {
implicitProducerHashResizeInProgress.clear(std::memory_order_release);
}
}
// If it's < three-quarters full, add to the old one anyway so that we don't have to wait for the next table
// to finish being allocated by another thread (and if we just finished allocating above, the condition will
// always be true)
if (newCount < (mainHash->capacity >> 1) + (mainHash->capacity >> 2)) {
bool recycled;
auto producer = static_cast<ImplicitProducer*>(recycle_or_create_producer(false, recycled));
if (producer == nullptr) {
implicitProducerHashCount.fetch_add(-1, std::memory_order_relaxed);
return nullptr;
}
if (recycled) {
implicitProducerHashCount.fetch_add(-1, std::memory_order_relaxed);
}
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
producer->threadExitListener.callback = &ConcurrentQueue::implicit_producer_thread_exited_callback;
producer->threadExitListener.userData = producer;
details::ThreadExitNotifier::subscribe(&producer->threadExitListener);
#endif
auto index = hashedId;
while (true) {
index &= mainHash->capacity - 1;
auto probedKey = mainHash->entries[index].key.load(std::memory_order_relaxed);
auto empty = details::invalid_thread_id;
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
auto reusable = details::invalid_thread_id2;
if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed)) ||
(probedKey == reusable && mainHash->entries[index].key.compare_exchange_strong(reusable, id, std::memory_order_acquire))) {
#else
if ((probedKey == empty && mainHash->entries[index].key.compare_exchange_strong(empty, id, std::memory_order_relaxed))) {
#endif
mainHash->entries[index].value = producer;
break;
}
++index;
}
return producer;
}
// Hmm, the old hash is quite full and somebody else is busy allocating a new one.
// We need to wait for the allocating thread to finish (if it succeeds, we add, if not,
// we try to allocate ourselves).
mainHash = implicitProducerHash.load(std::memory_order_acquire);
}
}
#ifdef MOODYCAMEL_CPP11_THREAD_LOCAL_SUPPORTED
void implicit_producer_thread_exited(ImplicitProducer* producer)
{
// Remove from thread exit listeners
details::ThreadExitNotifier::unsubscribe(&producer->threadExitListener);
// Remove from hash
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
debug::DebugLock lock(implicitProdMutex);
#endif
auto hash = implicitProducerHash.load(std::memory_order_acquire);
assert(hash != nullptr); // The thread exit listener is only registered if we were added to a hash in the first place
auto id = details::thread_id();
auto hashedId = details::hash_thread_id(id);
details::thread_id_t probedKey;
// We need to traverse all the hashes just in case other threads aren't on the current one yet and are
// trying to add an entry thinking there's a free slot (because they reused a producer)
for (; hash != nullptr; hash = hash->prev) {
auto index = hashedId;
do {
index &= hash->capacity - 1;
probedKey = hash->entries[index].key.load(std::memory_order_relaxed);
if (probedKey == id) {
hash->entries[index].key.store(details::invalid_thread_id2, std::memory_order_release);
break;
}
++index;
} while (probedKey != details::invalid_thread_id); // Can happen if the hash has changed but we weren't put back in it yet, or if we weren't added to this hash in the first place
}
// Mark the queue as being recyclable
producer->inactive.store(true, std::memory_order_release);
}
static void implicit_producer_thread_exited_callback(void* userData)
{
auto producer = static_cast<ImplicitProducer*>(userData);
auto queue = producer->parent;
queue->implicit_producer_thread_exited(producer);
}
#endif
//////////////////////////////////
// Utility functions
//////////////////////////////////
template<typename U>
static inline U* create_array(size_t count)
{
assert(count > 0);
auto p = static_cast<U*>((Traits::malloc)(sizeof(U) * count));
if (p == nullptr) {
return nullptr;
}
for (size_t i = 0; i != count; ++i) {
new (p + i) U();
}
return p;
}
template<typename U>
static inline void destroy_array(U* p, size_t count)
{
if (p != nullptr) {
assert(count > 0);
for (size_t i = count; i != 0; ) {
(p + --i)->~U();
}
//(Traits::free)(p);
}
}
template<typename U>
static inline U* create()
{
auto p = (Traits::malloc)(sizeof(U));
return p != nullptr ? new (p) U : nullptr;
}
template<typename U, typename A1>
static inline U* create(A1&& a1)
{
auto p = (Traits::malloc)(sizeof(U));
return p != nullptr ? new (p) U(std::forward<A1>(a1)) : nullptr;
}
template<typename U>
static inline void destroy(U* p)
{
if (p != nullptr) {
p->~U();
}
(Traits::free)(p);
}
private:
std::atomic<ProducerBase*> producerListTail;
std::atomic<std::uint32_t> producerCount;
std::atomic<size_t> initialBlockPoolIndex;
Block* initialBlockPool;
size_t initialBlockPoolSize;
#if !MCDBGQ_USEDEBUGFREELIST
FreeList<Block> freeList;
#else
debug::DebugFreeList<Block> freeList;
#endif
std::atomic<ImplicitProducerHash*> implicitProducerHash;
std::atomic<size_t> implicitProducerHashCount; // Number of slots logically used
ImplicitProducerHash initialImplicitProducerHash;
std::array<ImplicitProducerKVP, INITIAL_IMPLICIT_PRODUCER_HASH_SIZE> initialImplicitProducerHashEntries;
std::atomic_flag implicitProducerHashResizeInProgress;
std::atomic<std::uint32_t> nextExplicitConsumerId;
std::atomic<std::uint32_t> globalExplicitConsumerOffset;
#if MCDBGQ_NOLOCKFREE_IMPLICITPRODHASH
debug::DebugMutex implicitProdMutex;
#endif
#ifdef MOODYCAMEL_QUEUE_INTERNAL_DEBUG
std::atomic<ExplicitProducer*> explicitProducers;
std::atomic<ImplicitProducer*> implicitProducers;
#endif
};
template<typename T, typename Traits>
ProducerToken::ProducerToken(ConcurrentQueue<T, Traits>& queue)
: producer(queue.recycle_or_create_producer(true))
{
if (producer != nullptr) {
producer->token = this;
}
}
template<typename T, typename Traits>
ProducerToken::ProducerToken(BlockingConcurrentQueue<T, Traits>& queue)
: producer(reinterpret_cast<ConcurrentQueue<T, Traits>*>(&queue)->recycle_or_create_producer(true))
{
if (producer != nullptr) {
producer->token = this;
}
}
template<typename T, typename Traits>
ConsumerToken::ConsumerToken(ConcurrentQueue<T, Traits>& queue)
: itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr)
{
initialOffset = queue.nextExplicitConsumerId.fetch_add(1, std::memory_order_release);
lastKnownGlobalOffset = -1;
}
template<typename T, typename Traits>
ConsumerToken::ConsumerToken(BlockingConcurrentQueue<T, Traits>& queue)
: itemsConsumedFromCurrent(0), currentProducer(nullptr), desiredProducer(nullptr)
{
initialOffset = reinterpret_cast<ConcurrentQueue<T, Traits>*>(&queue)->nextExplicitConsumerId.fetch_add(1, std::memory_order_release);
lastKnownGlobalOffset = -1;
}
template<typename T, typename Traits>
inline void swap(ConcurrentQueue<T, Traits>& a, ConcurrentQueue<T, Traits>& b) MOODYCAMEL_NOEXCEPT
{
a.swap(b);
}
inline void swap(ProducerToken& a, ProducerToken& b) MOODYCAMEL_NOEXCEPT
{
a.swap(b);
}
inline void swap(ConsumerToken& a, ConsumerToken& b) MOODYCAMEL_NOEXCEPT
{
a.swap(b);
}
template<typename T, typename Traits>
inline void swap(typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP& a, typename ConcurrentQueue<T, Traits>::ImplicitProducerKVP& b) MOODYCAMEL_NOEXCEPT
{
a.swap(b);
}
}
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
| {
"content_hash": "ff56e974e1965d16c337b069d8796bb7",
"timestamp": "",
"source": "github",
"line_count": 3553,
"max_line_length": 389,
"avg_line_length": 42.84632704756544,
"alnum_prop": 0.6503320567813812,
"repo_name": "rharding6373/ddbms",
"id": "03a774406e5360587af5b6be3224ed9111af52af",
"size": "152846",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/concurrentqueue.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "22329"
},
{
"name": "C++",
"bytes": "851961"
},
{
"name": "Makefile",
"bytes": "4055"
},
{
"name": "Python",
"bytes": "243577"
},
{
"name": "Shell",
"bytes": "2670"
}
],
"symlink_target": ""
} |
#include "motoman_driver/industrial_robot_client/motoman_utils.h"
#include "ros/ros.h"
namespace industrial_robot_client
{
namespace motoman_utils
{
bool getJointGroups(const std::string topic_param, std::map<int, RobotGroup> & robot_groups)
{
if(ros::param::has(topic_param))
{
XmlRpc::XmlRpcValue topics_list_rpc;
ros::param::get(topic_param, topics_list_rpc);
std::vector<XmlRpc::XmlRpcValue> topics_list;
ROS_INFO_STREAM("Loading topic list");
ROS_INFO_STREAM("Found " << topics_list_rpc.size() << " topics");
for (int i = 0; i < topics_list_rpc.size(); i++)
{
XmlRpc::XmlRpcValue state_value;
state_value = topics_list_rpc[i];
ROS_INFO_STREAM("Topic(state_value): " << state_value);
topics_list.push_back(state_value);
}
for (int i = 0; i < topics_list.size(); i++)
{
ROS_INFO_STREAM("Loading group: " << topics_list[i]);
RobotGroup rg;
std::vector<std::string> rg_joint_names;
XmlRpc::XmlRpcValue joints;
joints = topics_list[i]["joints"];
for (int jt = 0; jt < joints.size(); jt++)
{
rg_joint_names.push_back(static_cast<std::string>(joints[jt]));
}
XmlRpc::XmlRpcValue group_number;
group_number = topics_list[i]["group"];
int group_number_int = static_cast<int>(group_number);
XmlRpc::XmlRpcValue name;
std::string name_string;
name = topics_list[i]["name"];
name_string = static_cast<std::string>(name);
XmlRpc::XmlRpcValue ns;
std::string ns_string;
ns = topics_list[i]["ns"];
ns_string = static_cast<std::string>(ns);
ROS_DEBUG_STREAM("Setting group: " );
ROS_DEBUG_STREAM(" group number: " << group_number );
ROS_DEBUG_STREAM(" group number(int): " << group_number_int );
ROS_DEBUG_STREAM(" joints_names(size): " << rg_joint_names.size() );
ROS_DEBUG_STREAM(" name: " << name_string );
ROS_DEBUG_STREAM(" ns: " << ns_string );
rg.set_group_id(group_number_int);
rg.set_joint_names(rg_joint_names);
rg.set_name(name_string);
rg.set_ns(ns_string);
robot_groups[group_number] = rg;
}
ROS_INFO_STREAM("Loaded " << robot_groups.size() << " groups");
return true;
}
else
{
ROS_ERROR_STREAM("Failed to find " << topic_param << " parameter");
return false;
}
}
} //motoman_utils
} //industrial_robot_client
| {
"content_hash": "47df5fdaa262f3e7197966b496632130",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 92,
"avg_line_length": 26.41304347826087,
"alnum_prop": 0.6045267489711934,
"repo_name": "Rayal/robotech",
"id": "ed5d9cb5920924ef228442943138d21bb5d3b670",
"size": "4100",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/motoman/motoman_driver/src/industrial_robot_client/motoman_utils.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "170048"
},
{
"name": "C++",
"bytes": "574704"
},
{
"name": "CMake",
"bytes": "60257"
},
{
"name": "Makefile",
"bytes": "41"
},
{
"name": "Objective-C",
"bytes": "1426"
},
{
"name": "Python",
"bytes": "13127"
}
],
"symlink_target": ""
} |
<!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 (version 1.7.0_76) on Sun Mar 22 20:21:12 UTC 2015 -->
<title>ServerCall (grpc-core 0.1.0-SNAPSHOT API)</title>
<meta name="date" content="2015-03-22">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ServerCall (grpc-core 0.1.0-SNAPSHOT API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><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="../../io/grpc/Server.html" title="interface in io.grpc"><span class="strong">Prev Class</span></a></li>
<li><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?io/grpc/ServerCall.html" target="_top">Frames</a></li>
<li><a href="ServerCall.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><a href="#nested_class_summary">Nested</a> | </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">io.grpc</div>
<h2 title="Class ServerCall" class="title">Class ServerCall<ResponseT></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>io.grpc.ServerCall<ResponseT></li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl><dt><span class="strong">Type Parameters:</span></dt><dd><code>ResponseT</code> - parsed type of response message.</dd></dl>
<dl>
<dt>Direct Known Subclasses:</dt>
<dd><a href="../../io/grpc/ServerInterceptors.ForwardingServerCall.html" title="class in io.grpc">ServerInterceptors.ForwardingServerCall</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="strong">ServerCall<ResponseT></span>
extends java.lang.Object</pre>
<div class="block">Encapsulates a single call received from a remote client. Calls may not simply be unary
request-response even though this is the most common pattern. Calls may stream any number of
requests and responses. This API is generally intended for use by generated handlers,
but applications may use it directly if they need to.
<p>Headers must be sent before any payloads, which must be sent before closing.
<p>No generic method for determining message receipt or providing acknowledgement is provided.
Applications are expected to utilize normal payload messages for such signals, as a response
naturally acknowledges its request.
<p>Methods are guaranteed to be non-blocking. Implementations are not required to be thread-safe.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== NESTED CLASS SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="nested_class_summary">
<!-- -->
</a>
<h3>Nested Class Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation">
<caption><span>Nested Classes</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc">ServerCall.Listener</a><<a href="../../io/grpc/ServerCall.Listener.html" title="type parameter in ServerCall.Listener">RequestT</a>></strong></code>
<div class="block">Callbacks for consuming incoming RPC messages.</div>
</td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" 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><strong><a href="../../io/grpc/ServerCall.html#ServerCall()">ServerCall</a></strong>()</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="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.html#close(io.grpc.Status,%20io.grpc.Metadata.Trailers)">close</a></strong>(<a href="../../io/grpc/Status.html" title="class in io.grpc">Status</a> status,
<a href="../../io/grpc/Metadata.Trailers.html" title="class in io.grpc">Metadata.Trailers</a> trailers)</code>
<div class="block">Close the call with the provided status.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.html#isCancelled()">isCancelled</a></strong>()</code>
<div class="block">Returns <code>true</code> when the call is cancelled and the server is encouraged to abort
processing to save resources, since the client will not be processing any further methods.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.html#request(int)">request</a></strong>(int numMessages)</code>
<div class="block">Requests up to the given number of messages from the call to be delivered to
<a href="../../io/grpc/ServerCall.Listener.html#onPayload(RequestT)"><code>ServerCall.Listener.onPayload(Object)</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.html#sendHeaders(io.grpc.Metadata.Headers)">sendHeaders</a></strong>(<a href="../../io/grpc/Metadata.Headers.html" title="class in io.grpc">Metadata.Headers</a> headers)</code>
<div class="block">Send response header metadata prior to sending a response payload.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><strong><a href="../../io/grpc/ServerCall.html#sendPayload(ResponseT)">sendPayload</a></strong>(<a href="../../io/grpc/ServerCall.html" title="type parameter in ServerCall">ResponseT</a> payload)</code>
<div class="block">Send a response message.</div>
</td>
</tr>
</table>
<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>clone, equals, finalize, 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="ServerCall()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>ServerCall</h4>
<pre>public ServerCall()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="request(int)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>request</h4>
<pre>public abstract void request(int numMessages)</pre>
<div class="block">Requests up to the given number of messages from the call to be delivered to
<a href="../../io/grpc/ServerCall.Listener.html#onPayload(RequestT)"><code>ServerCall.Listener.onPayload(Object)</code></a>. Once <code>numMessages</code> have been delivered
no further request messages will be delivered until more messages are requested by
calling this method again.
<p>Servers use this mechanism to provide back-pressure to the client for flow-control.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>numMessages</code> - the requested number of messages to be delivered to the listener.</dd></dl>
</li>
</ul>
<a name="sendHeaders(io.grpc.Metadata.Headers)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sendHeaders</h4>
<pre>public abstract void sendHeaders(<a href="../../io/grpc/Metadata.Headers.html" title="class in io.grpc">Metadata.Headers</a> headers)</pre>
<div class="block">Send response header metadata prior to sending a response payload. This method may
only be called once and cannot be called after calls to <code>Stream#sendPayload</code>
or <code>#close</code>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>headers</code> - metadata to send prior to any response body.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if <code>close</code> has been called or a payload has been sent.</dd></dl>
</li>
</ul>
<a name="sendPayload(java.lang.Object)">
<!-- -->
</a><a name="sendPayload(ResponseT)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>sendPayload</h4>
<pre>public abstract void sendPayload(<a href="../../io/grpc/ServerCall.html" title="type parameter in ServerCall">ResponseT</a> payload)</pre>
<div class="block">Send a response message. Payload messages are the primary form of communication associated with
RPCs. Multiple response messages may exist for streaming calls.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>payload</code> - response message.</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if call is <a href="../../io/grpc/ServerCall.html#close(io.grpc.Status,%20io.grpc.Metadata.Trailers)"><code>close(io.grpc.Status, io.grpc.Metadata.Trailers)</code></a>d</dd></dl>
</li>
</ul>
<a name="close(io.grpc.Status, io.grpc.Metadata.Trailers)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>close</h4>
<pre>public abstract void close(<a href="../../io/grpc/Status.html" title="class in io.grpc">Status</a> status,
<a href="../../io/grpc/Metadata.Trailers.html" title="class in io.grpc">Metadata.Trailers</a> trailers)</pre>
<div class="block">Close the call with the provided status. No further sending or receiving will occur. If <code>status</code> is not equal to <a href="../../io/grpc/Status.html#OK"><code>Status.OK</code></a>, then the call is said to have failed.
<p>If <code>status</code> is not <a href="../../io/grpc/Status.html#CANCELLED"><code>Status.CANCELLED</code></a> and no errors or cancellations are known
to have occured, then a <a href="../../io/grpc/ServerCall.Listener.html#onComplete()"><code>ServerCall.Listener.onComplete()</code></a> notification should be expected.
Otherwise <a href="../../io/grpc/ServerCall.Listener.html#onCancel()"><code>ServerCall.Listener.onCancel()</code></a> has been or will be called.</div>
<dl><dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalStateException</code> - if call is already <code>close</code>d</dd></dl>
</li>
</ul>
<a name="isCancelled()">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>isCancelled</h4>
<pre>public abstract boolean isCancelled()</pre>
<div class="block">Returns <code>true</code> when the call is cancelled and the server is encouraged to abort
processing to save resources, since the client will not be processing any further methods.
Cancellations can be caused by timeouts, explicit cancel by client, network errors, and
similar.
<p>This method may safely be called concurrently from multiple threads.</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><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="../../io/grpc/Server.html" title="interface in io.grpc"><span class="strong">Prev Class</span></a></li>
<li><a href="../../io/grpc/ServerCall.Listener.html" title="class in io.grpc"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?io/grpc/ServerCall.html" target="_top">Frames</a></li>
<li><a href="ServerCall.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><a href="#nested_class_summary">Nested</a> | </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>
| {
"content_hash": "9c4e54d1101d9c0d0905e50fa1585697",
"timestamp": "",
"source": "github",
"line_count": 391,
"max_line_length": 262,
"avg_line_length": 41.388746803069054,
"alnum_prop": 0.6747821788296361,
"repo_name": "meghana0507/grpc-java-poll",
"id": "3e8e3e250c3fbb41ff744ae3d50b3872af33bd4c",
"size": "16183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/build/docs/javadoc/io/grpc/ServerCall.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "675278"
},
{
"name": "C++",
"bytes": "13760110"
},
{
"name": "CMake",
"bytes": "18668"
},
{
"name": "CSS",
"bytes": "3570"
},
{
"name": "Emacs Lisp",
"bytes": "15596"
},
{
"name": "HTML",
"bytes": "7473"
},
{
"name": "Java",
"bytes": "15326237"
},
{
"name": "JavaScript",
"bytes": "2933"
},
{
"name": "Makefile",
"bytes": "590545"
},
{
"name": "Protocol Buffer",
"bytes": "1065012"
},
{
"name": "Python",
"bytes": "967273"
},
{
"name": "Ruby",
"bytes": "38278"
},
{
"name": "Shell",
"bytes": "1540526"
},
{
"name": "VimL",
"bytes": "7500"
}
],
"symlink_target": ""
} |
#include <common.h>
#include <command.h>
#include <malloc.h>
#include <stdio_dev.h>
#include <timestamp.h>
#include <version.h>
#include <net.h>
#include <serial.h>
#include <nand.h>
#include <onenand_uboot.h>
#include <mmc.h>
#include <asm/sections.h>
DECLARE_GLOBAL_DATA_PTR;
#if defined(CONFIG_SYS_I2C)
#include <i2c.h>
#endif
ulong monitor_flash_len;
/*
* Init Utilities
*/
#if !defined(CONFIG_BAUDRATE)
#define CONFIG_BAUDRATE 38400
#endif
static int init_baudrate(void)
{
gd->baudrate = getenv_ulong("baudrate", 10, CONFIG_BAUDRATE);
return 0;
}
/*
* WARNING: this code looks "cleaner" than the PowerPC version, but
* has the disadvantage that you either get nothing, or everything.
* On PowerPC, you might see "DRAM: " before the system hangs - which
* gives a simple yet clear indication which part of the
* initialization if failing.
*/
static int display_dram_config(void)
{
int i;
#ifdef DEBUG
puts("RAM Configuration:\n");
for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
printf("Bank #%d: %08lx ", i, gd->bd->bi_dram[i].start);
print_size(gd->bd->bi_dram[i].size, "\n");
}
#else
ulong size = 0;
for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++)
size += gd->bd->bi_dram[i].size;
puts("DRAM: ");
print_size(size, "\n");
#endif
return 0;
}
#ifndef CONFIG_SYS_NO_FLASH
static void display_flash_config(ulong size)
{
puts("Flash: ");
print_size(size, "\n");
}
#endif /* CONFIG_SYS_NO_FLASH */
#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
#include <pci.h>
static int nds32_pci_init(void)
{
pci_init();
return 0;
}
#endif /* CONFIG_CMD_PCI || CONFIG_PCI */
#if defined(CONFIG_PMU) || defined(CONFIG_PCU)
#ifndef CONFIG_SKIP_LOWLEVEL_INIT
static int pmu_init(void)
{
#if defined(CONFIG_FTPMU010_POWER)
#ifdef __NDS32_N1213_43U1H__ /* AG101: internal definition in toolchain */
ftpmu010_sdram_clk_disable(CONFIG_SYS_FTPMU010_PDLLCR0_HCLKOUTDIS);
ftpmu010_mfpsr_select_dev(FTPMU010_MFPSR_AC97CLKSEL);
ftpmu010_sdramhtc_set(CONFIG_SYS_FTPMU010_SDRAMHTC);
#endif /* __NDS32_N1213_43U1H__ */
#endif
return 0;
}
#endif
#endif
/*
* Breathe some life into the board...
*
* Initialize a serial port as console, and carry out some hardware
* tests.
*
* The first part of initialization is running from Flash memory;
* its main purpose is to initialize the RAM so that we
* can relocate the monitor code to RAM.
*/
/*
* All attempts to come up with a "common" initialization sequence
* that works for all boards and architectures failed: some of the
* requirements are just _too_ different. To get rid of the resulting
* mess of board dependent #ifdef'ed code we now make the whole
* initialization sequence configurable to the user.
*
* The requirements for any new initalization function is simple: it
* receives a pointer to the "global data" structure as it's only
* argument, and returns an integer return code, where 0 means
* "continue" and != 0 means "fatal error, hang the system".
*/
typedef int (init_fnc_t)(void);
void __dram_init_banksize(void)
{
gd->bd->bi_dram[0].start = CONFIG_SYS_SDRAM_BASE;
gd->bd->bi_dram[0].size = gd->ram_size;
}
void dram_init_banksize(void)
__attribute__((weak, alias("__dram_init_banksize")));
init_fnc_t *init_sequence[] = {
#if defined(CONFIG_ARCH_CPU_INIT)
arch_cpu_init, /* basic arch cpu dependent setup */
#endif
#if defined(CONFIG_PMU) || defined(CONFIG_PCU)
#ifndef CONFIG_SKIP_LOWLEVEL_INIT
pmu_init,
#endif
#endif
board_init, /* basic board dependent setup */
#if defined(CONFIG_USE_IRQ)
interrupt_init, /* set up exceptions */
#endif
timer_init, /* initialize timer */
env_init, /* initialize environment */
init_baudrate, /* initialze baudrate settings */
serial_init, /* serial communications setup */
console_init_f, /* stage 1 init of console */
#if defined(CONFIG_DISPLAY_BOARDINFO)
checkboard, /* display board info */
#endif
#if defined(CONFIG_HARD_I2C) || defined(CONFIG_SYS_I2C)
init_func_i2c,
#endif
dram_init, /* configure available RAM banks */
display_dram_config,
NULL,
};
void board_init_f(ulong bootflag)
{
bd_t *bd;
init_fnc_t **init_fnc_ptr;
gd_t *id;
ulong addr, addr_sp;
/* Pointer is writable since we allocated a register for it */
gd = (gd_t *) ((CONFIG_SYS_INIT_SP_ADDR) & ~0x07);
memset((void *)gd, 0, GENERATED_GBL_DATA_SIZE);
gd->mon_len = (unsigned int)(&__bss_end) - (unsigned int)(&_start);
for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) {
if ((*init_fnc_ptr)() != 0)
hang();
}
debug("monitor len: %08lX\n", gd->mon_len);
/*
* Ram is setup, size stored in gd !!
*/
debug("ramsize: %08lX\n", gd->ram_size);
addr = CONFIG_SYS_SDRAM_BASE + gd->ram_size;
/* round down to next 4 kB limit */
addr &= ~(4096 - 1);
debug("Top of RAM usable for U-Boot at: %08lx\n", addr);
#ifdef CONFIG_LCD
#ifdef CONFIG_FB_ADDR
gd->fb_base = CONFIG_FB_ADDR;
#else
/* reserve memory for LCD display (always full pages) */
addr = lcd_setmem(addr);
gd->fb_base = addr;
#endif /* CONFIG_FB_ADDR */
#endif /* CONFIG_LCD */
/*
* reserve memory for U-Boot code, data & bss
* round down to next 4 kB limit
*/
addr -= gd->mon_len;
addr &= ~(4096 - 1);
debug("Reserving %ldk for U-Boot at: %08lx\n", gd->mon_len >> 10, addr);
/*
* reserve memory for malloc() arena
*/
addr_sp = addr - TOTAL_MALLOC_LEN;
debug("Reserving %dk for malloc() at: %08lx\n",
TOTAL_MALLOC_LEN >> 10, addr_sp);
/*
* (permanently) allocate a Board Info struct
* and a permanent copy of the "global" data
*/
addr_sp -= GENERATED_BD_INFO_SIZE;
bd = (bd_t *) addr_sp;
gd->bd = bd;
memset((void *)bd, 0, GENERATED_BD_INFO_SIZE);
debug("Reserving %zu Bytes for Board Info at: %08lx\n",
GENERATED_BD_INFO_SIZE, addr_sp);
addr_sp -= GENERATED_GBL_DATA_SIZE;
id = (gd_t *) addr_sp;
debug("Reserving %zu Bytes for Global Data at: %08lx\n",
GENERATED_GBL_DATA_SIZE, addr_sp);
/* setup stackpointer for exeptions */
gd->irq_sp = addr_sp;
#ifdef CONFIG_USE_IRQ
addr_sp -= (CONFIG_STACKSIZE_IRQ + CONFIG_STACKSIZE_FIQ);
debug("Reserving %zu Bytes for IRQ stack at: %08lx\n",
CONFIG_STACKSIZE_IRQ+CONFIG_STACKSIZE_FIQ, addr_sp);
#endif
/* leave 3 words for abort-stack */
addr_sp -= 12;
/* 8-byte alignment for ABI compliance */
addr_sp &= ~0x07;
debug("New Stack Pointer is: %08lx\n", addr_sp);
gd->bd->bi_baudrate = gd->baudrate;
/* Ram isn't board specific, so move it to board code ... */
dram_init_banksize();
display_dram_config(); /* and display it */
gd->relocaddr = addr;
gd->start_addr_sp = addr_sp;
gd->reloc_off = addr - _TEXT_BASE;
debug("relocation Offset is: %08lx\n", gd->reloc_off);
memcpy(id, (void *)gd, GENERATED_GBL_DATA_SIZE);
relocate_code(addr_sp, id, addr);
/* NOTREACHED - relocate_code() does not return */
}
/*
* This is the next part if the initialization sequence: we are now
* running from RAM and have a "normal" C environment, i. e. global
* data can be written, BSS has been cleared, the stack size in not
* that critical any more, etc.
*/
void board_init_r(gd_t *id, ulong dest_addr)
{
bd_t *bd;
ulong malloc_start;
gd = id;
bd = gd->bd;
gd->flags |= GD_FLG_RELOC; /* tell others: relocation done */
monitor_flash_len = (ulong)&_end - (ulong)&_start;
debug("monitor flash len: %08lX\n", monitor_flash_len);
board_init(); /* Setup chipselects */
#if defined(CONFIG_NEEDS_MANUAL_RELOC)
/*
* We have to relocate the command table manually
*/
fixup_cmdtable(ll_entry_start(cmd_tbl_t, cmd),
ll_entry_count(cmd_tbl_t, cmd));
#endif /* defined(CONFIG_NEEDS_MANUAL_RELOC) */
serial_initialize();
debug("Now running in RAM - U-Boot at: %08lx\n", dest_addr);
/* The Malloc area is immediately below the monitor copy in DRAM */
malloc_start = dest_addr - TOTAL_MALLOC_LEN;
mem_malloc_init(malloc_start, TOTAL_MALLOC_LEN);
#ifndef CONFIG_SYS_NO_FLASH
/* configure available FLASH banks */
gd->bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
gd->bd->bi_flashsize = flash_init();
gd->bd->bi_flashoffset = CONFIG_SYS_FLASH_BASE + gd->bd->bi_flashsize;
if (gd->bd->bi_flashsize)
display_flash_config(gd->bd->bi_flashsize);
#endif /* CONFIG_SYS_NO_FLASH */
#if defined(CONFIG_CMD_NAND)
puts("NAND: ");
nand_init(); /* go init the NAND */
#endif
#if defined(CONFIG_CMD_IDE)
puts("IDE: ");
ide_init();
#endif
#ifdef CONFIG_GENERIC_MMC
puts("MMC: ");
mmc_initialize(gd->bd);
#endif
#if defined(CONFIG_SYS_I2C_ADAPTERS)
i2c_reloc_fixup();
#endif
/* initialize environment */
env_relocate();
#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
puts("PCI: ");
nds32_pci_init();
#endif
stdio_init(); /* get the devices list going. */
jumptable_init();
#if defined(CONFIG_API)
/* Initialize API */
api_init();
#endif
console_init_r(); /* fully init console as a device */
#if defined(CONFIG_ARCH_MISC_INIT)
/* miscellaneous arch dependent initialisations */
arch_misc_init();
#endif
#if defined(CONFIG_MISC_INIT_R)
/* miscellaneous platform dependent initialisations */
misc_init_r();
#endif
#if defined(CONFIG_USE_IRQ)
/* set up exceptions */
interrupt_init();
/* enable exceptions */
enable_interrupts();
#endif
/* Initialize from environment */
load_addr = getenv_ulong("loadaddr", 16, load_addr);
#ifdef CONFIG_BOARD_LATE_INIT
board_late_init();
#endif
#if defined(CONFIG_CMD_NET)
puts("Net: ");
eth_initialize(gd->bd);
#if defined(CONFIG_RESET_PHY_R)
debug("Reset Ethernet PHY\n");
reset_phy();
#endif
#endif
/* main_loop() can return to retry autoboot, if so just run it again. */
for (;;)
main_loop();
/* NOTREACHED - no way out of command loop except booting */
}
| {
"content_hash": "ed106090b0c396711ee4664846ad2f98",
"timestamp": "",
"source": "github",
"line_count": 390,
"max_line_length": 74,
"avg_line_length": 24.671794871794873,
"alnum_prop": 0.6735605903138641,
"repo_name": "EleVenPerfect/S3C2440",
"id": "2d4c6231a3774114366bed986631bb7a59e98587",
"size": "9943",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "bootloader/u-boot-2014.04 for tq2440/arch/nds32/lib/board.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "107623"
},
{
"name": "Awk",
"bytes": "145"
},
{
"name": "C",
"bytes": "53471003"
},
{
"name": "C++",
"bytes": "4794882"
},
{
"name": "CSS",
"bytes": "7584"
},
{
"name": "GDB",
"bytes": "3642"
},
{
"name": "Makefile",
"bytes": "507759"
},
{
"name": "Objective-C",
"bytes": "33048"
},
{
"name": "PHP",
"bytes": "108169"
},
{
"name": "Perl",
"bytes": "213214"
},
{
"name": "Python",
"bytes": "223908"
},
{
"name": "Roff",
"bytes": "197018"
},
{
"name": "Shell",
"bytes": "86972"
},
{
"name": "Tcl",
"bytes": "967"
},
{
"name": "XSLT",
"bytes": "445"
}
],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { JhiLanguageService } from 'ng-jhipster';
import { SessionStorageService } from 'ngx-webstorage';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import { SERVER_API_URL } from 'app/app.constants';
import { Account } from 'app/core/user/account.model';
@Injectable({ providedIn: 'root' })
export class AccountService {
private userIdentity: any;
private authenticated = false;
private authenticationState = new Subject<any>();
constructor(private languageService: JhiLanguageService, private sessionStorage: SessionStorageService, private http: HttpClient) {}
fetch(): Observable<HttpResponse<Account>> {
return this.http.get<Account>(SERVER_API_URL + 'api/account', { observe: 'response' });
}
save(account: any): Observable<HttpResponse<any>> {
return this.http.post(SERVER_API_URL + 'api/account', account, { observe: 'response' });
}
authenticate(identity) {
this.userIdentity = identity;
this.authenticated = identity !== null;
this.authenticationState.next(this.userIdentity);
}
hasAnyAuthority(authorities: string[]): boolean {
if (!this.authenticated || !this.userIdentity || !this.userIdentity.authorities) {
return false;
}
for (let i = 0; i < authorities.length; i++) {
if (this.userIdentity.authorities.includes(authorities[i])) {
return true;
}
}
return false;
}
hasAuthority(authority: string): Promise<boolean> {
if (!this.authenticated) {
return Promise.resolve(false);
}
return this.identity().then(
id => {
return Promise.resolve(id.authorities && id.authorities.includes(authority));
},
() => {
return Promise.resolve(false);
}
);
}
identity(force?: boolean): Promise<Account> {
if (force) {
this.userIdentity = undefined;
}
// check and see if we have retrieved the userIdentity data from the server.
// if we have, reuse it by immediately resolving
if (this.userIdentity) {
return Promise.resolve(this.userIdentity);
}
// retrieve the userIdentity data from the server, update the identity object, and then resolve.
return this.fetch()
.toPromise()
.then(response => {
const account: Account = response.body;
if (account) {
this.userIdentity = account;
this.authenticated = true;
// After retrieve the account info, the language will be changed to
// the user's preferred language configured in the account setting
if (this.userIdentity.langKey) {
const langKey = this.sessionStorage.retrieve('locale') || this.userIdentity.langKey;
this.languageService.changeLanguage(langKey);
}
} else {
this.userIdentity = null;
this.authenticated = false;
}
this.authenticationState.next(this.userIdentity);
return this.userIdentity;
})
.catch(err => {
this.userIdentity = null;
this.authenticated = false;
this.authenticationState.next(this.userIdentity);
return null;
});
}
isAuthenticated(): boolean {
return this.authenticated;
}
isIdentityResolved(): boolean {
return this.userIdentity !== undefined;
}
getAuthenticationState(): Observable<any> {
return this.authenticationState.asObservable();
}
getImageUrl(): string {
return this.isIdentityResolved() ? this.userIdentity.imageUrl : null;
}
}
| {
"content_hash": "078de2e47255c3d0b717a2e9affd8fa7",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 134,
"avg_line_length": 30.948275862068964,
"alnum_prop": 0.6557103064066853,
"repo_name": "iansoftdev/all-blockchain",
"id": "612da02696a5561b5ec7779d8149d041b12f58e0",
"size": "3590",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/webapp/app/core/auth/account.service.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23670"
},
{
"name": "Dockerfile",
"bytes": "328"
},
{
"name": "Gherkin",
"bytes": "179"
},
{
"name": "HTML",
"bytes": "296792"
},
{
"name": "Java",
"bytes": "814900"
},
{
"name": "JavaScript",
"bytes": "999740"
},
{
"name": "Scala",
"bytes": "33739"
},
{
"name": "Shell",
"bytes": "280"
},
{
"name": "TSQL",
"bytes": "104378"
},
{
"name": "TypeScript",
"bytes": "759210"
}
],
"symlink_target": ""
} |
import logging
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.urls import reverse
from seaserv import ccnet_api
from seahub.api2.authentication import TokenAuthentication
from seahub.api2.throttling import UserRateThrottle
from seahub.api2.permissions import IsProVersion
from seahub.api2.utils import api_error
from seahub.api2.endpoints.utils import check_time_period_valid, \
generate_links_header_for_paginator, get_user_name_dict, \
get_user_contact_email_dict
from seahub.base.templatetags.seahub_tags import email2nickname
from seahub.utils.timeutils import datetime_to_isoformat_timestr
logger = logging.getLogger(__name__)
class LoginLogs(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAdminUser, IsProVersion)
throttle_classes = (UserRateThrottle,)
def get(self, request):
if not request.user.admin_permissions.can_view_admin_log():
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
# check the date format, should be like '2015-10-10'
start = request.GET.get('start', None)
end = request.GET.get('end', None)
if not check_time_period_valid(start, end):
error_msg = 'start or end date invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
# Filtering a DateTimeField with dates won't include items on the last day,
# because the bounds are interpreted as '0am on the given date'.
end = end + ' 23:59:59'
result = []
from seahub_extra.sysadmin_extra.models import UserLoginLog
logs = UserLoginLog.objects.filter(login_date__range=(start, end))
for log in logs:
result.append({
'login_time': datetime_to_isoformat_timestr(log.login_date),
'login_ip': log.login_ip,
'name': email2nickname(log.username),
'email':log.username
})
return Response(result)
class AdminLoginLogs(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAdminUser, IsProVersion)
throttle_classes = (UserRateThrottle,)
def _get_admin_user_emails(self):
admin_users = ccnet_api.get_superusers()
admin_user_emails = []
for user in admin_users:
admin_user_emails.append(user.email)
return admin_user_emails
def _get_response_data(self, logs):
user_list = []
for log in logs:
user_list.append(log.username)
name_dict = get_user_name_dict(user_list)
contact_email_dict = get_user_contact_email_dict(user_list)
data = []
for log in logs:
email = log.username
data.append({
'login_time': datetime_to_isoformat_timestr(log.login_date),
'login_ip': log.login_ip,
'login_success': log.login_success,
'email': email,
'name': name_dict[email],
'contact_email': contact_email_dict[email],
})
return data
def get(self, request):
if not request.user.admin_permissions.can_view_admin_log():
return api_error(status.HTTP_403_FORBIDDEN, 'Permission denied.')
try:
page = int(request.GET.get('page', '1'))
per_page = int(request.GET.get('per_page', '100'))
except ValueError:
page = 1
per_page = 100
if page <= 0:
error_msg = 'page invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
if per_page <= 0:
error_msg = 'per_page invalid.'
return api_error(status.HTTP_400_BAD_REQUEST, error_msg)
offset = per_page * (page -1)
from seahub_extra.sysadmin_extra.models import UserLoginLog
admin_user_emails = self._get_admin_user_emails()
all_logs = UserLoginLog.objects.filter(username__in=admin_user_emails)
total_count = all_logs.count()
logs = all_logs[offset:offset+per_page]
data = self._get_response_data(logs)
result = {'data': data, 'total_count': total_count}
resp = Response(result)
## generate `Links` header for paginator
base_url = reverse('api-v2.1-admin-admin-login-logs')
links_header = generate_links_header_for_paginator(base_url,
page, per_page, total_count)
resp['Links'] = links_header
return resp
| {
"content_hash": "3308db42aefa2e0a170da9463a8e52aa",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 83,
"avg_line_length": 34.02857142857143,
"alnum_prop": 0.6351805205709488,
"repo_name": "miurahr/seahub",
"id": "d48a13618e176729747e9cd9d70e62a4ab632fa8",
"size": "4803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "seahub/api2/endpoints/admin/login_logs.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "231001"
},
{
"name": "HTML",
"bytes": "750509"
},
{
"name": "JavaScript",
"bytes": "2430915"
},
{
"name": "Python",
"bytes": "1500021"
},
{
"name": "Shell",
"bytes": "8856"
}
],
"symlink_target": ""
} |
var _elm_lang$dom$Native_Dom = function() {
var fakeNode = {
addEventListener: function() {},
removeEventListener: function() {}
};
var onDocument = on(typeof document !== 'undefined' ? document : fakeNode);
var onWindow = on(typeof window !== 'undefined' ? window : fakeNode);
function on(node)
{
return function(eventName, decoder, toTask)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback) {
function performTask(event)
{
var result = A2(_elm_lang$core$Json_Decode$decodeValue, decoder, event);
if (result.ctor === 'Ok')
{
_elm_lang$core$Native_Scheduler.rawSpawn(toTask(result._0));
}
}
node.addEventListener(eventName, performTask);
return function()
{
node.removeEventListener(eventName, performTask);
};
});
};
}
var rAF = typeof requestAnimationFrame !== 'undefined'
? requestAnimationFrame
: function(callback) { callback(); };
function withNode(id, doStuff)
{
return _elm_lang$core$Native_Scheduler.nativeBinding(function(callback)
{
rAF(function()
{
var node = document.getElementById(id);
if (node === null)
{
callback(_elm_lang$core$Native_Scheduler.fail({ ctor: 'NotFound', _0: id }));
return;
}
callback(_elm_lang$core$Native_Scheduler.succeed(doStuff(node)));
});
});
}
// FOCUS
function focus(id)
{
return withNode(id, function(node) {
node.focus();
return _elm_lang$core$Native_Utils.Tuple0;
});
}
function blur(id)
{
return withNode(id, function(node) {
node.blur();
return _elm_lang$core$Native_Utils.Tuple0;
});
}
// SCROLLING
function getScrollTop(id)
{
return withNode(id, function(node) {
return node.scrollTop;
});
}
function setScrollTop(id, desiredScrollTop)
{
return withNode(id, function(node) {
node.scrollTop = desiredScrollTop;
return _elm_lang$core$Native_Utils.Tuple0;
});
}
function toBottom(id)
{
return withNode(id, function(node) {
node.scrollTop = node.scrollHeight;
return _elm_lang$core$Native_Utils.Tuple0;
});
}
function getScrollLeft(id)
{
return withNode(id, function(node) {
return node.scrollLeft;
});
}
function setScrollLeft(id, desiredScrollLeft)
{
return withNode(id, function(node) {
node.scrollLeft = desiredScrollLeft;
return _elm_lang$core$Native_Utils.Tuple0;
});
}
function toRight(id)
{
return withNode(id, function(node) {
node.scrollLeft = node.scrollWidth;
return _elm_lang$core$Native_Utils.Tuple0;
});
}
// SIZE
function width(options, id)
{
return withNode(id, function(node) {
switch (options.ctor)
{
case 'Content':
return node.scrollWidth;
case 'VisibleContent':
return node.clientWidth;
case 'VisibleContentWithBorders':
return node.offsetWidth;
case 'VisibleContentWithBordersAndMargins':
var rect = node.getBoundingClientRect();
return rect.right - rect.left;
}
});
}
function height(options, id)
{
return withNode(id, function(node) {
switch (options.ctor)
{
case 'Content':
return node.scrollHeight;
case 'VisibleContent':
return node.clientHeight;
case 'VisibleContentWithBorders':
return node.offsetHeight;
case 'VisibleContentWithBordersAndMargins':
var rect = node.getBoundingClientRect();
return rect.bottom - rect.top;
}
});
}
return {
onDocument: F3(onDocument),
onWindow: F3(onWindow),
focus: focus,
blur: blur,
getScrollTop: getScrollTop,
setScrollTop: F2(setScrollTop),
getScrollLeft: getScrollLeft,
setScrollLeft: F2(setScrollLeft),
toBottom: toBottom,
toRight: toRight,
height: F2(height),
width: F2(width)
};
}();
| {
"content_hash": "a4b2383cf93a1ca4e7823ce9c7ab4921",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 81,
"avg_line_length": 19.64835164835165,
"alnum_prop": 0.6926733780760627,
"repo_name": "mxgrn/pairs.one",
"id": "2fee3f0b74362e0c1b288a88132caa81bc0ecfc3",
"size": "3576",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "assets/elm/elm-stuff/packages/elm-lang/dom/1.1.1/src/Native/Dom.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12388"
},
{
"name": "Elixir",
"bytes": "56325"
},
{
"name": "Elm",
"bytes": "595634"
},
{
"name": "HTML",
"bytes": "28945"
},
{
"name": "JavaScript",
"bytes": "128520"
},
{
"name": "Shell",
"bytes": "1202"
}
],
"symlink_target": ""
} |
#ifndef __APP_FASTBOOT_H
#define __APP_FASTBOOT_H
#define MAX_RSP_SIZE 64
#define MAX_GET_VAR_NAME_SIZE 256
int fastboot_init(void *xfer_buffer, unsigned max);
void fastboot_stop(void);
/* register a command handler
* - command handlers will be called if their prefix matches
* - they are expected to call fastboot_okay() or fastboot_fail()
* to indicate success/failure before returning
*/
void fastboot_register(const char *prefix,
void (*handle)(const char *arg, void *data, unsigned size));
/* publish a variable readable by the built-in getvar command */
void fastboot_publish(const char *name, const char *value);
/* only callable from within a command handler */
void fastboot_okay(const char *result);
void fastboot_fail(const char *reason);
void fastboot_info(const char *reason);
#ifdef LGE_WITH_FASTBOOT_MENU
const char *fastboot_get_getvar(const char *arg);
void fastboot_menu_display(void);
void fastboot_info_display(void);
int fastboot_do_unlock(void);
void fastboot_progress_display(const char *s);
void fastboot_menu_init(void);
#else
static inline void fastboot_progress_display(const char *s) { };
#endif
#endif
| {
"content_hash": "4d3ace534d437453265b5560e5b5c2ae",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 69,
"avg_line_length": 29.94871794871795,
"alnum_prop": 0.7371575342465754,
"repo_name": "jaehyek/lk",
"id": "e0ba9701169a5f1a74e840ac6ee0eb9c7805a48d",
"size": "2615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/aboot/fastboot.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "550333"
},
{
"name": "Batchfile",
"bytes": "2356"
},
{
"name": "C",
"bytes": "21547634"
},
{
"name": "C++",
"bytes": "351682"
},
{
"name": "DIGITAL Command Language",
"bytes": "113105"
},
{
"name": "Makefile",
"bytes": "230074"
},
{
"name": "Objective-C",
"bytes": "4534"
},
{
"name": "Perl",
"bytes": "911757"
},
{
"name": "Python",
"bytes": "10626"
},
{
"name": "Shell",
"bytes": "24220"
},
{
"name": "XS",
"bytes": "4319"
},
{
"name": "eC",
"bytes": "3710"
}
],
"symlink_target": ""
} |
package com.ldsmsoft.framework.dao.mybatis.dao;
import com.ldsmsoft.framework.dao.mybatis.model.PermissionBean;
public interface PermissionBeanMapper {
int deleteByPrimaryKey(Long id);
int insert(PermissionBean record);
int insertSelective(PermissionBean record);
PermissionBean selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(PermissionBean record);
int updateByPrimaryKey(PermissionBean record);
} | {
"content_hash": "3d37c2839238020deee06391bd6944c1",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 63,
"avg_line_length": 27,
"alnum_prop": 0.7690631808278867,
"repo_name": "zsming-SQ/Thankni-OMS-BE",
"id": "deade44b7255736fb8d0412307a8f37ad7278aa9",
"size": "459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/ldsmsoft/framework/dao/mybatis/dao/PermissionBeanMapper.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "324755"
},
{
"name": "JavaScript",
"bytes": "55510"
}
],
"symlink_target": ""
} |
<html>
<head><!-- JATSKit extraction from Tag Library - thanks to Mulberry Technologies for making this possible - --></head>
<body>
<h1 id="isbn">
<code><isbn></code>
<b>ISBN</b>
</h1>
<p>International Standard Book Number, the international code for
identifying a particular product form or edition of a publication, typically a monographic publication.</p>
</body>
</html>
| {
"content_hash": "1fe7d94e89e5ed04249241bef42d32ed",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 121,
"avg_line_length": 39,
"alnum_prop": 0.6526806526806527,
"repo_name": "wendellpiez/oXygenJATSframework",
"id": "d07a0fd695ada1c5e52991494e51963b159dfe48",
"size": "429",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "styleguide/descriptions/isbn.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "50472"
},
{
"name": "HTML",
"bytes": "166027"
},
{
"name": "Java",
"bytes": "9417"
},
{
"name": "KiCad",
"bytes": "8952"
},
{
"name": "XProc",
"bytes": "34297"
},
{
"name": "XSLT",
"bytes": "585066"
}
],
"symlink_target": ""
} |
package com.opengamma.financial.analytics.model.bondcurves;
import static com.opengamma.engine.value.ValuePropertyNames.CURRENCY;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValueRequirementNames.CURVE_BUNDLE;
import static com.opengamma.engine.value.ValueRequirementNames.PV01;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Iterables;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivativeVisitor;
import com.opengamma.analytics.financial.provider.calculator.discounting.PV01CurveParametersCalculator;
import com.opengamma.analytics.financial.provider.calculator.issuer.PresentValueCurveSensitivityIssuerCalculator;
import com.opengamma.analytics.financial.provider.description.interestrate.ParameterIssuerProviderInterface;
import com.opengamma.analytics.util.amount.ReferenceAmount;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.model.BondAndBondFutureFunctionUtils;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.money.Currency;
import com.opengamma.util.tuple.Pair;
/**
* Calculates the PV01 of a bond or bond future for all curves to which the instruments are sensitive.
*/
public class BondAndBondFuturePV01Function extends BondAndBondFutureFromCurvesFunction<ParameterIssuerProviderInterface, ReferenceAmount<Pair<String, Currency>>> {
/** The PV01 calculator */
private static final InstrumentDerivativeVisitor<ParameterIssuerProviderInterface, ReferenceAmount<Pair<String, Currency>>> CALCULATOR =
new PV01CurveParametersCalculator<>(PresentValueCurveSensitivityIssuerCalculator.getInstance());
/**
* Sets the value requirement name to {@link ValueRequirementNames#PV01} and
* sets the calculator to {@link PV01CurveParametersCalculator}
*/
public BondAndBondFuturePV01Function() {
super(PV01, CALCULATOR);
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext context, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) throws AsynchronousExecution {
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final ValueProperties properties = desiredValue.getConstraints();
final ZonedDateTime now = ZonedDateTime.now(context.getValuationClock());
final InstrumentDerivative derivative = BondAndBondFutureFunctionUtils.getBondOrBondFutureDerivative(context, target, now, inputs);
final ParameterIssuerProviderInterface issuerCurves = (ParameterIssuerProviderInterface) inputs.getValue(CURVE_BUNDLE);
final String desiredCurveName = properties.getStrictValue(CURVE);
final ReferenceAmount<Pair<String, Currency>> pv01 = derivative.accept(CALCULATOR, issuerCurves);
final Set<ComputedValue> results = new HashSet<>();
boolean curveNameFound = false;
for (final Map.Entry<Pair<String, Currency>, Double> entry : pv01.getMap().entrySet()) {
final String curveName = entry.getKey().getFirst();
if (desiredCurveName.equals(curveName)) {
curveNameFound = true;
}
final ValueProperties curveSpecificProperties = properties.copy()
.withoutAny(CURVE)
.with(CURVE, curveName)
.get();
final ValueSpecification spec = new ValueSpecification(PV01, target.toSpecification(), curveSpecificProperties);
results.add(new ComputedValue(spec, entry.getValue()));
}
if (!curveNameFound) {
final ValueSpecification spec = new ValueSpecification(PV01, target.toSpecification(), properties.copy().with(CURVE, desiredCurveName).get());
return Collections.singleton(new ComputedValue(spec, .0));
}
return results;
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final Set<String> curveNames = desiredValue.getConstraints().getValues(CURVE);
if (curveNames == null || curveNames.size() != 1) {
return null;
}
return super.getRequirements(context, target, desiredValue);
}
@Override
protected Collection<ValueProperties.Builder> getResultProperties(final ComputationTarget target) {
final String currency = FinancialSecurityUtils.getCurrency(target.getTrade().getSecurity()).getCode();
final Collection<ValueProperties.Builder> properties = super.getResultProperties(target);
final Collection<ValueProperties.Builder> result = new HashSet<>();
for (final ValueProperties.Builder builder : properties) {
result.add(builder
.with(CURRENCY, currency)
.withAny(CURVE));
}
return result;
}
}
| {
"content_hash": "8543d3d8e1c654585957806d0bac46f3",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 163,
"avg_line_length": 50.620370370370374,
"alnum_prop": 0.795134443021767,
"repo_name": "codeaudit/OG-Platform",
"id": "8022ac88ded41e39e1290f95570506bdf36ebdf0",
"size": "5604",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/bondcurves/BondAndBondFuturePV01Function.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4064"
},
{
"name": "CSS",
"bytes": "212432"
},
{
"name": "GAP",
"bytes": "1490"
},
{
"name": "Groovy",
"bytes": "11518"
},
{
"name": "HTML",
"bytes": "284313"
},
{
"name": "Java",
"bytes": "80930425"
},
{
"name": "JavaScript",
"bytes": "1528695"
},
{
"name": "PLSQL",
"bytes": "105"
},
{
"name": "PLpgSQL",
"bytes": "13175"
},
{
"name": "Protocol Buffer",
"bytes": "53119"
},
{
"name": "SQLPL",
"bytes": "1004"
},
{
"name": "Shell",
"bytes": "10958"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public interface IGetMappingRequest : IIndexTypePath<GetMappingRequestParameters> { }
public interface IGetMappingRequest<T> : IGetMappingRequest where T : class { }
internal static class GetMappingPathInfo
{
public static void Update(ElasticsearchPathInfo<GetMappingRequestParameters> pathInfo, IGetMappingRequest request)
{
pathInfo.HttpMethod = PathInfoHttpMethod.GET;
}
}
public partial class GetMappingRequest : IndexTypePathBase<GetMappingRequestParameters>, IGetMappingRequest
{
public GetMappingRequest(IndexNameMarker index, TypeNameMarker typeNameMarker) : base(index, typeNameMarker)
{
}
protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<GetMappingRequestParameters> pathInfo)
{
GetMappingPathInfo.Update(pathInfo, this);
}
}
public partial class GetMappingRequest<T> : IndexTypePathBase<GetMappingRequestParameters, T>, IGetMappingRequest
where T : class
{
protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<GetMappingRequestParameters> pathInfo)
{
GetMappingPathInfo.Update(pathInfo, this);
}
}
[DescriptorFor("IndicesGetMapping")]
public partial class GetMappingDescriptor<T> : IndexTypePathDescriptor<GetMappingDescriptor<T>, GetMappingRequestParameters, T>, IGetMappingRequest
where T : class
{
protected override void UpdatePathInfo(IConnectionSettingsValues settings, ElasticsearchPathInfo<GetMappingRequestParameters> pathInfo)
{
GetMappingPathInfo.Update(pathInfo, this);
}
}
}
| {
"content_hash": "7281ca9b9d810256b73817260ddbcf79",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 148,
"avg_line_length": 34.431372549019606,
"alnum_prop": 0.8132118451025057,
"repo_name": "Grastveit/NEST",
"id": "2bb97e14dc32318ef611c566c03f71844227ffcb",
"size": "1758",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Nest/DSL/GetMappingDescriptor.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "7609428"
},
{
"name": "CSS",
"bytes": "17906"
},
{
"name": "F#",
"bytes": "9685"
},
{
"name": "JavaScript",
"bytes": "1490"
},
{
"name": "PowerShell",
"bytes": "103433"
},
{
"name": "Puppet",
"bytes": "85615"
},
{
"name": "Shell",
"bytes": "4202"
},
{
"name": "XSLT",
"bytes": "9157"
}
],
"symlink_target": ""
} |
'''
Simple test script which prints all HTTP responses' URLs and their total
count from a warc file whose path is passed as command line argument.
Does not support gzipped files.
'''
from warcreader import WarcFile
from sys import argv
from io import open
def main():
filename = argv[1]
with open(filename, 'rb') as raw_warc_file:
warc_file = WarcFile(raw_warc_file)
count = 0
for webpage in warc_file:
count += 1
print(webpage.payload)
print('Total count of HTTP responses: %d' % count)
if __name__ == '__main__':
main()
| {
"content_hash": "add6cd499f1af9475c2086057b4a42c6",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 72,
"avg_line_length": 22.8,
"alnum_prop": 0.6701754385964912,
"repo_name": "msvana/warcreader",
"id": "f6bfae608e41cc19d3e5a6da75d1fc83db69ac2b",
"size": "1158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "6942"
}
],
"symlink_target": ""
} |
int main() {
ArrayList* list = ArrayList_new();
printf("list: %d\n", list);
printf("maxSize: %d\n", ArrayList_maxSize(list));
ArrayList_add(list, "foobar");
printf("get: %s\n", ArrayList_get(list, 0));
ArrayList_free(list);
return 0;
}
| {
"content_hash": "a4b558030be65d13cba35f778b73c3b2",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 50,
"avg_line_length": 24.4,
"alnum_prop": 0.6434426229508197,
"repo_name": "itsubaki/viola",
"id": "cc8296e19a67df6fe3df4532e6587059b3810e86",
"size": "285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/violac/util/ArrayListTest.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1895"
},
{
"name": "C++",
"bytes": "73472"
},
{
"name": "CMake",
"bytes": "4690"
},
{
"name": "Shell",
"bytes": "201"
}
],
"symlink_target": ""
} |
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Assets;
using TTC2017.SmartGrids.CIM.IEC61968.Common;
using TTC2017.SmartGrids.CIM.IEC61968.Customers;
using TTC2017.SmartGrids.CIM.IEC61970.Contingency;
using TTC2017.SmartGrids.CIM.IEC61970.ControlArea;
using TTC2017.SmartGrids.CIM.IEC61970.Domain;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCore;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
using TTC2017.SmartGrids.CIM.IEC61970.OperationalLimits;
using TTC2017.SmartGrids.CIM.IEC61970.Outage;
using TTC2017.SmartGrids.CIM.IEC61970.Protection;
using TTC2017.SmartGrids.CIM.IEC61970.StateVariables;
using TTC2017.SmartGrids.CIM.IEC61970.Topology;
using TTC2017.SmartGrids.CIM.IEC61970.Wires;
namespace TTC2017.SmartGrids.CIM.IEC61970.Core
{
public class GeographicalRegionRegionsCollection : ObservableOppositeOrderedSet<IGeographicalRegion, ISubGeographicalRegion>
{
public GeographicalRegionRegionsCollection(IGeographicalRegion parent) :
base(parent)
{
}
private void OnItemDeleted(object sender, System.EventArgs e)
{
this.Remove(((ISubGeographicalRegion)(sender)));
}
protected override void SetOpposite(ISubGeographicalRegion item, IGeographicalRegion parent)
{
if ((parent != null))
{
item.Deleted += this.OnItemDeleted;
item.Region = parent;
}
else
{
item.Deleted -= this.OnItemDeleted;
if ((item.Region == this.Parent))
{
item.Region = parent;
}
}
}
}
}
| {
"content_hash": "939f7ad6347d2f3c656ea68f7a6a344a",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 128,
"avg_line_length": 33.33783783783784,
"alnum_prop": 0.7178759627077422,
"repo_name": "georghinkel/ttc2017smartGrids",
"id": "74dd7bbf9d92425cd6110f934d1aa5d58cc4ef12",
"size": "2902",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "solutions/NMF/Schema/IEC61970/Core/GeographicalRegionRegionsCollection.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "79261108"
},
{
"name": "Java",
"bytes": "38407170"
},
{
"name": "Python",
"bytes": "6055"
},
{
"name": "R",
"bytes": "15405"
},
{
"name": "Rebol",
"bytes": "287"
}
],
"symlink_target": ""
} |
var qrnode = require('../index');
qrnode.detect("https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=Teste", function(result){
console.log("Decode from url:", result);
});
qrnode.detect("qrcode.png", function(result){
console.log("Decode from local file:", result);
}); | {
"content_hash": "d69ab2d94798daa9c3ebeb465fc9f959",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 98,
"avg_line_length": 31.22222222222222,
"alnum_prop": 0.701067615658363,
"repo_name": "alamcordeiro/qrnode",
"id": "6861dbed8c75972023481d2f93bf64560d1d4607",
"size": "281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "102173"
}
],
"symlink_target": ""
} |
package io.ray.streaming.python.stream;
import io.ray.streaming.python.PythonOperator;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a union DataStream.
* <p>This stream does not create a physical operation, it only affects how upstream data are
* connected to downstream data.
*/
public class PythonUnionStream extends PythonDataStream {
private List<PythonDataStream> unionStreams;
public PythonUnionStream(PythonDataStream input, List<PythonDataStream> others) {
// Union stream does not create a physical operation, so we don't have to set partition
// function for it.
super(input, new PythonOperator(
"ray.streaming.operator", "UnionOperator"));
this.unionStreams = new ArrayList<>();
others.forEach(this::addStream);
}
void addStream(PythonDataStream stream) {
if (stream instanceof PythonUnionStream) {
this.unionStreams.addAll(((PythonUnionStream) stream).getUnionStreams());
} else {
this.unionStreams.add(stream);
}
}
public List<PythonDataStream> getUnionStreams() {
return unionStreams;
}
} | {
"content_hash": "4a52633da4bf199e72b9cbd0d142f157",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 93,
"avg_line_length": 30.694444444444443,
"alnum_prop": 0.7339366515837104,
"repo_name": "richardliaw/ray",
"id": "4e115685afc3a3007f8079de1d4f8c4d7d580db0",
"size": "1105",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "streaming/java/streaming-api/src/main/java/io/ray/streaming/python/stream/PythonUnionStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "62178"
},
{
"name": "C++",
"bytes": "4258483"
},
{
"name": "CSS",
"bytes": "8025"
},
{
"name": "Dockerfile",
"bytes": "6292"
},
{
"name": "HTML",
"bytes": "30414"
},
{
"name": "Java",
"bytes": "1263157"
},
{
"name": "JavaScript",
"bytes": "444"
},
{
"name": "Jupyter Notebook",
"bytes": "1615"
},
{
"name": "Makefile",
"bytes": "234"
},
{
"name": "Python",
"bytes": "7515224"
},
{
"name": "Shell",
"bytes": "117425"
},
{
"name": "Starlark",
"bytes": "200955"
},
{
"name": "TypeScript",
"bytes": "149068"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Serilog.Events;
using Serilog.Sinks.PeriodicBatching;
namespace Serilog.LogglyBulkSink
{
public class LogglySink : PeriodicBatchingSink
{
private readonly string _logglyUrl;
public const string LogglyUriFormat = "https://logs-01.loggly.com/bulk/{0}/tag/{1}";
public const double MaxBulkBytes = 4.5 * 1024 * 1024;
private readonly bool _includeDiagnostics;
public LogglySink(string logglyKey, string[] tags, int batchSizeLimit, TimeSpan period, bool includeDiagnostics = false)
: base(batchSizeLimit, period)
{
_includeDiagnostics = includeDiagnostics;
_logglyUrl = string.Format(LogglyUriFormat, logglyKey, string.Join(",", tags));
}
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
foreach (var content in ChunkEvents(events))
{
if (content == null)
{
continue;
}
using (var httpClient = new HttpClient())
{
try
{
await httpClient.PostAsync(_logglyUrl, content);
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Exception posting to loggly {0}", ex));
}
}
}
}
public IEnumerable<StringContent> ChunkEvents(IEnumerable<LogEvent> events)
{
if (events == null)
{
yield break;
}
var jsons = events.Select(EventToJson).Where(_ => !string.IsNullOrWhiteSpace(_)).ToList();
var bytes = 0;
int page = 0;
var chunk = new List<string>();
foreach (var json in jsons)
{
if (bytes > MaxBulkBytes)
{
yield return PackageContent(chunk, bytes, page);
bytes = 0;
page++;
chunk.Clear();
}
bytes += Encoding.UTF8.GetByteCount(json) + 1;
chunk.Add(json);
}
yield return PackageContent(chunk, bytes, page, _includeDiagnostics);
}
public static StringContent PackageContent(List<string> jsons, int bytes, int page, bool includeDiagnostics = false)
{
if (includeDiagnostics)
{
var diagnostic = JsonConvert.SerializeObject(new
{
Event = "LogglyDiagnostics",
Trace = string.Format("EventCount={0}, ByteCount={1}, PageCount={2}", jsons.Count, bytes, page)
});
jsons.Add(diagnostic);
}
return new StringContent(string.Join("\n", jsons), Encoding.UTF8, "application/json");
}
public static string EventToJson(LogEvent logEvent)
{
if (logEvent == null)
{
throw new ArgumentNullException("logEvent");
}
var payload = new Dictionary<string, object>();
try
{
foreach (var key in logEvent.Properties.Keys)
{
int dummy;
if (Int32.TryParse(key, out dummy)) continue;
var propertyValue = logEvent.Properties[key];
var simpleValue = SerilogPropertyFormatter.Simplify(propertyValue);
var safeKey = key.Replace(" ", "").Replace(":", "").Replace("-", "").Replace("_", "");
AddIfNotContains(payload, safeKey, simpleValue);
}
AddIfNotContains(payload, "Level", logEvent.Level.ToString());
AddIfNotContains(payload, "Timestamp", logEvent.Timestamp);
AddIfNotContains(payload, "Raw", logEvent.RenderMessage());
if (logEvent.Exception != null)
{
AddIfNotContains(payload, "Exception", logEvent.Exception);
}
var result = JsonConvert.SerializeObject(payload,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return result;
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Error extracting json from logEvent {0}",ex));
}
return null;
}
public static void AddIfNotContains<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
if (dictionary.ContainsKey(key)) return;
dictionary[key] = value;
}
}
}
| {
"content_hash": "c9526465c1e82c09d5cbedf6effe8b1e",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 128,
"avg_line_length": 35.270833333333336,
"alnum_prop": 0.5142744634770624,
"repo_name": "samirahmed/serlog.logglybulksink",
"id": "f9b8c588b1a8554fc933a4dffe625a013b1282d8",
"size": "5081",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Serilog.LogglyBulkSink/LogglySink.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "16895"
}
],
"symlink_target": ""
} |
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Core.TfsInterop;
using StructureMap;
namespace GitTfs.Commands
{
[Pluggable("branch")]
[Description("branch\n\n" +
" * Display inited remote TFS branches:\n git tfs branch\n\n" +
" * Display remote TFS branches:\n git tfs branch -r\n git tfs branch -r -all\n\n" +
" * Create a TFS branch from current commit:\n git tfs branch $/Repository/ProjectBranchToCreate <myWishedRemoteName> --comment=\"Creation of my branch\"\n\n" +
" * Rename a remote branch:\n git tfs branch --move oldTfsRemoteName newTfsRemoteName\n\n" +
" * Delete a remote branch:\n git tfs branch --delete tfsRemoteName\n git tfs branch --delete --all\n\n" +
" * Initialise an existing remote TFS branch:\n git tfs branch --init $/Repository/ProjectBranch\n git tfs branch --init $/Repository/ProjectBranch myNewBranch\n git tfs branch --init --all\n git tfs branch --init --tfs-parent-branch=$/Repository/ProjectParentBranch $/Repository/ProjectBranch\n")]
[RequiresValidGitRepository]
public class Branch : GitTfsCommand
{
private readonly Globals _globals;
private readonly Help _helper;
private readonly Cleanup _cleanup;
private readonly InitBranch _initBranch;
private readonly Rcheckin _rcheckin;
public bool DisplayRemotes { get; set; }
public bool ManageAll { get; set; }
public bool ShouldRenameRemote { get; set; }
public bool ShouldDeleteRemote { get; set; }
public bool ShouldInitBranch { get; set; }
public string IgnoreRegex { get; set; }
public string ExceptRegex { get; set; }
public bool NoFetch { get; set; }
public string Comment { get; set; }
public string TfsUsername { get; set; }
public string TfsPassword { get; set; }
public string ParentBranch { get; set; }
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "r|remotes", "Display the TFS branches of the current TFS root branch existing on the TFS server", v => DisplayRemotes = (v != null) },
{ "all", "Display (used with option --remotes) the TFS branches of all the root branches existing on the TFS server\n" +
" or Initialize (used with option --init) all existing TFS branches (For TFS 2010 and later)\n" +
" or Delete (used with option --delete) all tfs remotes (for example after lfs migration).", v => ManageAll = (v != null) },
{ "comment=", "Comment used for the creation of the TFS branch ", v => Comment = v },
{ "m|move", "Rename a TFS remote", v => ShouldRenameRemote = (v != null) },
{ "delete", "Delete a TFS remote", v => ShouldDeleteRemote = (v != null) },
{ "init", "Initialize an existing TFS branch", v => ShouldInitBranch = (v != null) },
{ "ignore-regex=", "A regex of files to ignore", v => IgnoreRegex = v },
{ "except-regex=", "A regex of exceptions to ignore-regex", v => ExceptRegex = v},
{ "no-fetch", "Don't fetch changeset for newly initialized branch(es)", v => NoFetch = (v != null) },
{ "b|tfs-parent-branch=", "TFS Parent branch of the TFS branch to clone (TFS 2008 only! And required!!) ex: $/Repository/ProjectParentBranch", v => ParentBranch = v },
{ "u|username=", "TFS username", v => TfsUsername = v },
{ "p|password=", "TFS password", v => TfsPassword = v },
}
.Merge(_globals.OptionSet);
}
}
public Branch(Globals globals, Help helper, Cleanup cleanup, InitBranch initBranch, Rcheckin rcheckin)
{
_globals = globals;
_helper = helper;
_cleanup = cleanup;
_initBranch = initBranch;
_rcheckin = rcheckin;
}
public void SetInitBranchParameters()
{
_initBranch.TfsUsername = TfsUsername;
_initBranch.TfsPassword = TfsPassword;
_initBranch.CloneAllBranches = ManageAll;
_initBranch.ParentBranch = ParentBranch;
_initBranch.IgnoreRegex = IgnoreRegex;
_initBranch.ExceptRegex = ExceptRegex;
_initBranch.NoFetch = NoFetch;
}
public bool IsCommandWellUsed()
{
//Verify that some mutual exclusive options are not used together
return new[] { ShouldDeleteRemote, ShouldInitBranch, ShouldRenameRemote }.Count(b => b) <= 1;
}
public int Run()
{
if (!IsCommandWellUsed())
return _helper.Run(this);
_globals.WarnOnGitVersion();
VerifyCloneAllRepository();
if (ShouldRenameRemote)
return _helper.Run(this);
if(ShouldDeleteRemote)
{
if (!ManageAll)
return _helper.Run(this);
else
return DeleteAllRemotes();
}
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run();
}
return DisplayBranchData();
}
public int Run(string param)
{
if (!IsCommandWellUsed())
return _helper.Run(this);
VerifyCloneAllRepository();
_globals.WarnOnGitVersion();
if (ShouldRenameRemote)
return _helper.Run(this);
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run(param);
}
if (ShouldDeleteRemote)
return DeleteRemote(param);
return CreateRemote(param);
}
public int Run(string param1, string param2)
{
if (!IsCommandWellUsed())
return _helper.Run(this);
VerifyCloneAllRepository();
_globals.WarnOnGitVersion();
if (ShouldDeleteRemote)
return _helper.Run(this);
if (ShouldInitBranch)
{
SetInitBranchParameters();
return _initBranch.Run(param1, param2);
}
if (ShouldRenameRemote)
return RenameRemote(param1, param2);
return CreateRemote(param1, param2);
}
private void VerifyCloneAllRepository()
{
if (!_globals.Repository.HasRemote(GitTfsConstants.DefaultRepositoryId))
return;
if (_globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId).TfsRepositoryPath == GitTfsConstants.TfsRoot)
throw new GitTfsException("error: you can't use the 'branch' command when you have cloned the whole repository '$/' !");
}
private int RenameRemote(string oldRemoteName, string newRemoteName)
{
var newRemoteNameExpected = _globals.Repository.AssertValidBranchName(newRemoteName.ToGitRefName());
if (newRemoteNameExpected != newRemoteName)
Trace.TraceInformation("The name of the branch after renaming will be : " + newRemoteNameExpected);
if (_globals.Repository.HasRemote(newRemoteNameExpected))
{
throw new GitTfsException("error: this remote name is already used!");
}
Trace.TraceInformation("Cleaning before processing rename...");
_cleanup.Run();
_globals.Repository.MoveRemote(oldRemoteName, newRemoteNameExpected);
if (_globals.Repository.RenameBranch(oldRemoteName, newRemoteName) == null)
Trace.TraceWarning("warning: no local branch found to rename");
return GitTfsExitCodes.OK;
}
private int CreateRemote(string tfsPath, string gitBranchNameExpected = null)
{
bool checkInCurrentBranch = false;
tfsPath.AssertValidTfsPath();
Trace.WriteLine("Getting commit informations...");
var commit = _globals.Repository.GetCurrentTfsCommit();
if (commit == null)
{
checkInCurrentBranch = true;
var parents = _globals.Repository.GetLastParentTfsCommits(_globals.Repository.GetCurrentCommit());
if (!parents.Any())
throw new GitTfsException("error : no tfs remote parent found!");
commit = parents.First();
}
var remote = commit.Remote;
Trace.WriteLine("Creating branch in TFS...");
remote.Tfs.CreateBranch(remote.TfsRepositoryPath, tfsPath, commit.ChangesetId, Comment ?? "Creation branch " + tfsPath);
Trace.WriteLine("Init branch in local repository...");
_initBranch.DontCreateGitBranch = true;
var returnCode = _initBranch.Run(tfsPath, gitBranchNameExpected);
if (returnCode != GitTfsExitCodes.OK || !checkInCurrentBranch)
return returnCode;
_rcheckin.RebaseOnto(_initBranch.RemoteCreated.RemoteRef, commit.GitCommit);
_globals.UserSpecifiedRemoteId = _initBranch.RemoteCreated.Id;
return _rcheckin.Run();
}
private int DeleteRemote(string remoteName)
{
var remote = _globals.Repository.ReadTfsRemote(remoteName);
if (remote == null)
{
throw new GitTfsException(string.Format("Error: Remote \"{0}\" not found!", remoteName));
}
Trace.TraceInformation("Cleaning before processing delete...");
_cleanup.Run();
_globals.Repository.DeleteTfsRemote(remote);
return GitTfsExitCodes.OK;
}
private int DeleteAllRemotes()
{
Trace.TraceInformation("Deleting all remotes!!");
Trace.TraceInformation("Cleaning before processing delete...");
_cleanup.Run();
foreach (var remote in _globals.Repository.ReadAllTfsRemotes())
{
_globals.Repository.DeleteTfsRemote(remote);
}
return GitTfsExitCodes.OK;
}
public int DisplayBranchData()
{
// should probably pull this from options so that it is settable from the command-line
const string remoteId = GitTfsConstants.DefaultRepositoryId;
var tfsRemotes = _globals.Repository.ReadAllTfsRemotes();
if (DisplayRemotes)
{
if (!ManageAll)
{
var remote = _globals.Repository.ReadTfsRemote(remoteId);
Trace.TraceInformation("\nTFS branch structure:");
WriteRemoteTfsBranchStructure(remote.Tfs, remote.TfsRepositoryPath, tfsRemotes);
return GitTfsExitCodes.OK;
}
else
{
var remote = tfsRemotes.First(r => r.Id == remoteId);
if (!remote.Tfs.CanGetBranchInformation)
{
throw new GitTfsException("error: this version of TFS doesn't support this functionality");
}
foreach (var branch in remote.Tfs.GetBranches().Where(b => b.IsRoot))
{
var root = remote.Tfs.GetRootTfsBranchForRemotePath(branch.Path);
var visitor = new WriteBranchStructureTreeVisitor(remote.TfsRepositoryPath, tfsRemotes);
root.AcceptVisitor(visitor);
}
return GitTfsExitCodes.OK;
}
}
WriteTfsRemoteDetails(tfsRemotes);
return GitTfsExitCodes.OK;
}
public static void WriteRemoteTfsBranchStructure(ITfsHelper tfsHelper, string tfsRepositoryPath, IEnumerable<IGitTfsRemote> tfsRemotes = null)
{
var root = tfsHelper.GetRootTfsBranchForRemotePath(tfsRepositoryPath);
if (!tfsHelper.CanGetBranchInformation)
{
throw new GitTfsException("error: this version of TFS doesn't support this functionality");
}
var visitor = new WriteBranchStructureTreeVisitor(tfsRepositoryPath, tfsRemotes);
root.AcceptVisitor(visitor);
}
private void WriteTfsRemoteDetails(IEnumerable<IGitTfsRemote> tfsRemotes)
{
Trace.TraceInformation("\nGit-tfs remote details:");
foreach (var remote in tfsRemotes)
{
Trace.TraceInformation("\n {0} -> {1} {2}", remote.Id, remote.TfsUrl, remote.TfsRepositoryPath);
Trace.TraceInformation(" {0} - {1} @ {2}", remote.RemoteRef, remote.MaxCommitHash, remote.MaxChangesetId);
}
}
private class WriteBranchStructureTreeVisitor : IBranchTreeVisitor
{
private readonly string _targetPath;
private readonly IEnumerable<IGitTfsRemote> _tfsRemotes;
public WriteBranchStructureTreeVisitor(string targetPath, IEnumerable<IGitTfsRemote> tfsRemotes = null)
{
_targetPath = targetPath;
_tfsRemotes = tfsRemotes;
}
public void Visit(BranchTree branch, int level)
{
var writer = new StringWriter();
for (var i = 0; i < level; i++)
writer.Write(" | ");
writer.WriteLine();
for (var i = 0; i < level - 1; i++)
writer.Write(" | ");
if (level > 0)
writer.Write(" +-");
writer.Write(" {0}", branch.Path);
if (_tfsRemotes != null)
{
var remote = _tfsRemotes.FirstOrDefault(r => r.TfsRepositoryPath == branch.Path);
if (remote != null)
writer.Write(" -> " + remote.Id);
}
if (branch.Path.Equals(_targetPath))
writer.Write(" [*]");
Trace.TraceInformation(writer.ToString());
}
}
}
}
| {
"content_hash": "d96cb752fe97eee0ff8c3fa9f0b2b281",
"timestamp": "",
"source": "github",
"line_count": 358,
"max_line_length": 336,
"avg_line_length": 40.9804469273743,
"alnum_prop": 0.5625383409447209,
"repo_name": "vzabavnov/git-tfs",
"id": "7d46b6f1f7077c5ae7b3acee840fcd8cac43b43f",
"size": "14671",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/GitTfs/Commands/Branch.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "242"
},
{
"name": "C#",
"bytes": "880457"
},
{
"name": "PowerShell",
"bytes": "7724"
}
],
"symlink_target": ""
} |
from django.dispatch.robustapply import *
import unittest
def noArgument():
pass
def oneArgument(blah):
pass
def twoArgument(blah, other):
pass
class TestCases(unittest.TestCase):
def test01(self):
robustApply(noArgument)
def test02(self):
self.assertRaises(TypeError, robustApply, noArgument, "this")
def test03(self):
self.assertRaises(TypeError, robustApply, oneArgument)
def test04(self):
"""Raise error on duplication of a particular argument"""
self.assertRaises(TypeError, robustApply, oneArgument, "this", blah = "that")
def getSuite():
return unittest.makeSuite(TestCases,'test')
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "b44539acec87b0fee058ba7a74119c03",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 85,
"avg_line_length": 21.647058823529413,
"alnum_prop": 0.6616847826086957,
"repo_name": "diofeher/django-nfa",
"id": "499450eec4873ccf218c58fb63e8a4664424f47a",
"size": "736",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "tests/regressiontests/dispatch/tests/test_robustapply.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "66105"
},
{
"name": "Python",
"bytes": "5174003"
},
{
"name": "Shell",
"bytes": "804"
}
],
"symlink_target": ""
} |
$:.unshift(File.expand_path('../../lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/features', __FILE__))
$:.unshift(File.expand_path('../../../aws-sdk-core/lib', __FILE__))
$:.unshift(File.expand_path('../../../aws-sigv4/lib', __FILE__))
require 'features_helper'
require 'aws-sdk-translate'
Aws::Translate::Client.add_plugin(ApiCallTracker)
| {
"content_hash": "b826518021d4ba329dcfc00748a5bce0",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 72,
"avg_line_length": 40.44444444444444,
"alnum_prop": 0.6291208791208791,
"repo_name": "aws/aws-sdk-ruby",
"id": "f81610b1250aec0d11a66b1493fe4d7f724567ab",
"size": "606",
"binary": false,
"copies": "1",
"ref": "refs/heads/version-3",
"path": "gems/aws-sdk-translate/features/env.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Gherkin",
"bytes": "109092"
},
{
"name": "HTML",
"bytes": "1253"
},
{
"name": "JavaScript",
"bytes": "10266"
},
{
"name": "Mustache",
"bytes": "51225"
},
{
"name": "Ruby",
"bytes": "183956484"
}
],
"symlink_target": ""
} |
package com.senacor.ddt.objectmatrix.excel;
import com.senacor.ddt.objectmatrix.DefaultStringMatrix;
import com.senacor.ddt.objectmatrix.IndexedStringMatrix;
import com.senacor.ddt.objectmatrix.StringMatrix;
public abstract class AbstractExcelStringMatrixTestCase extends AbstractExcelStringMatrixReaderTestCase {
protected StringMatrix stringMatrix;
protected int rowContainingColumnTitles = 0;
protected int columnContainingRowTitles = 0;
protected void setUp() throws Exception {
super.setUp();
stringMatrix =
new DefaultStringMatrix(super.stringMatrixReader, columnContainingRowTitles, rowContainingColumnTitles);
}
protected void tearDown() throws Exception {
this.stringMatrix = null;
super.tearDown();
}
}
| {
"content_hash": "234f7e1c23733f6ef3d88eb715e2186b",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 112,
"avg_line_length": 32.708333333333336,
"alnum_prop": 0.7719745222929937,
"repo_name": "senacor/DDT",
"id": "d6087c272357e846e9304d671a4cdaf6ef5863b7",
"size": "2408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/src/com/senacor/ddt/objectmatrix/excel/AbstractExcelStringMatrixTestCase.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "829719"
}
],
"symlink_target": ""
} |
// Copyright (c) 2010-2011 Zipline Games, Inc. All Rights Reserved.
// http://getmoai.com
#include "pch.h"
#include <contrib/utf8.h>
#include <moaicore/MOAIAnimCurve.h>
#include <moaicore/MOAIDeck.h>
#include <moaicore/MOAIDebugLines.h>
#include <moaicore/MOAIFont.h>
#include <moaicore/MOAIGfxDevice.h>
#include <moaicore/MOAILogMessages.h>
#include <moaicore/MOAINodeMgr.h>
#include <moaicore/MOAIQuadBrush.h>
#include <moaicore/MOAIShaderMgr.h>
#include <moaicore/MOAITextDesigner.h>
#include <moaicore/MOAITextBox.h>
#include <moaicore/MOAITextStyle.h>
#include <moaicore/MOAITextStyler.h>
#define DEFAULT_STYLE_NAME ""
// TODO: font garbage collection
// - ref count glyphs
// - glyph lifecycle
// - glyph page defragmantation
// TODO: bitmap font ripper
// TODO: hit test for characters
//================================================================//
// MOAITextStyleRef
//================================================================//
//----------------------------------------------------------------//
MOAITextStyleRef::MOAITextStyleRef () :
mStyle ( 0 ) {
}
//----------------------------------------------------------------//
MOAITextStyleRef::~MOAITextStyleRef () {
}
//----------------------------------------------------------------//
bool MOAITextStyleRef::NeedsLayout () const {
if ( this->mStyle ) {
return this->mState.NeedsLayout ( *this->mStyle );
}
return false;
}
//----------------------------------------------------------------//
void MOAITextStyleRef::UpdateState () {
if ( this->mStyle ) {
this->mState = *this->mStyle;
}
}
//================================================================//
// local
//================================================================//
//----------------------------------------------------------------//
/** @name clearHighlights
@text Removes all highlights currently associated with the text box.
@in MOAITextBox self
@out nil
*/
int MOAITextBox::_clearHighlights ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
self->ClearHighlights ();
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name getGlyphScale
@text Returns the current glyph scale.
@in MOAITextBox self
@out number glyphScale
*/
int MOAITextBox::_getGlyphScale ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
state.Push ( self->mGlyphScale );
return 1;
}
//----------------------------------------------------------------//
/** @name getLineSpacing
@text Returns the spacing between lines (in pixels).
@in MOAITextBox self
@out number lineScale The size of the spacing in pixels.
*/
int MOAITextBox::_getLineSpacing ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
lua_pushnumber ( state, self->mLineSpacing );
return 1;
}
//----------------------------------------------------------------//
/** @name getRect
@text Returns the two dimensional boundary of the text box.
@in MOAITextBox self
@out number xMin
@out number yMin
@out number xMax
@out number yMax
*/
int MOAITextBox::_getRect ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
USRect rect = self->mFrame;
rect.Bless ();
lua_pushnumber ( state, rect.mXMin );
lua_pushnumber ( state, rect.mYMin );
lua_pushnumber ( state, rect.mXMax );
lua_pushnumber ( state, rect.mYMax );
return 4;
}
//----------------------------------------------------------------//
/** @name getStringBounds
@text Returns the bounding rectange of a given substring on a
single line in the local space of the text box.
@in MOAITextBox self
@in number index Index of the first character in the substring.
@in number size Length of the substring.
@out number xMin Edge of rect or 'nil' is no match found.
@out number yMin Edge of rect or 'nil' is no match found.
@out number xMax Edge of rect or 'nil' is no match found.
@out number yMax Edge of rect or 'nil' is no match found.
*/
int MOAITextBox::_getStringBounds ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UNN" )
u32 index = state.GetValue < u32 >( 2, 1 ) - 1;
u32 size = state.GetValue < u32 >( 3, 0 );
USRect rect;
if ( self->GetBoundsForRange ( index, size, rect )) {
rect.Bless ();
lua_pushnumber ( state, rect.mXMin );
lua_pushnumber ( state, rect.mYMin );
lua_pushnumber ( state, rect.mXMax );
lua_pushnumber ( state, rect.mYMax );
return 4;
}
return 0;
}
//----------------------------------------------------------------//
/** @name getStyle
@text Returns the style associated with a name or, if no name
is given, returns the default style.
@overload
@in MOAITextBox self
@out MOAITextStyle defaultStyle
@overload
@in MOAITextBox self
@in string styleName
@out MOAITextStyle style
*/
int MOAITextBox::_getStyle ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
MOAITextStyle* style = 0;
cc8* styleName = state.GetValue < cc8* >( 2, 0 );
style = self->GetStyle ( styleName );
if ( style ) {
style->PushLuaUserdata ( state );
return 1;
}
return 0;
}
//----------------------------------------------------------------//
/** @name more
@text Returns whether there are additional pages of text below the cursor position that are not visible on the screen.
@in MOAITextBox self
@out boolean isMore If there is additional text below the cursor that is not visible on the screen due to clipping.
*/
int MOAITextBox::_more ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
lua_pushboolean ( L, self->mMore );
return 1;
}
//----------------------------------------------------------------//
/** @name nextPage
@text Advances to the next page of text (if any) or wraps to the start of the text (if at end).
@in MOAITextBox self
@out nil
*/
int MOAITextBox::_nextPage ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
bool reveal = state.GetValue < bool >( 2, true );
self->NextPage ( reveal );
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name reserveCurves
@text Reserves a set of IDs for animation curves to be binding to this text object. See setCurves.
@in MOAITextBox self
@in number nCurves
@out nil
*/
int MOAITextBox::_reserveCurves ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UN" )
u32 total = state.GetValue < u32 >( 2, 0 );
self->ReserveCurves ( total );
return 0;
}
//----------------------------------------------------------------//
/** @name revealAll
@text Displays as much text as will fit in the text box.
@in MOAITextBox self
@out nil
*/
int MOAITextBox::_revealAll ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
self->mReveal = REVEAL_ALL;
return 0;
}
//----------------------------------------------------------------//
/** @name setAlignment
@text Sets the horizontal and/or vertical alignment of the text in the text box.
@in MOAITextBox self
@in enum hAlignment Can be one of LEFT_JUSTIFY, CENTER_JUSTIFY or RIGHT_JUSTIFY.
@in enum vAlignment Can be one of LEFT_JUSTIFY, CENTER_JUSTIFY or RIGHT_JUSTIFY.
@out nil
*/
int MOAITextBox::_setAlignment ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UN" )
self->mHAlign = state.GetValue < u32 >( 2, MOAITextBox::LEFT_JUSTIFY );
self->mVAlign = state.GetValue < u32 >( 3, MOAITextBox::LEFT_JUSTIFY );
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name setCurve
@text Binds an animation curve to the text, where the Y value of the curve indicates the text offset, or clears the curves.
@overload
@in MOAITextBox self
@in number curveID The ID of the curve within this text object.
@in MOAIAnimCurve curve The MOAIAnimCurve to bind to.
@out nil
@overload
@in MOAITextBox self
*/
int MOAITextBox::_setCurve ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
if ( state.GetTop () > 1 ) {
u32 index = state.GetValue < u32 >( 2, 1 ) - 1;
MOAIAnimCurve* curve = state.GetLuaObject < MOAIAnimCurve >( 3, true );
if ( !curve ) return 0;
self->SetCurve ( index, curve );
self->ScheduleLayout ();
}
else {
self->ClearCurves ();
self->ScheduleLayout ();
}
return 0;
}
//----------------------------------------------------------------//
/** @name setGlyphScale
@text Sets the glyph scale. This is a scalar applied to glyphs
as they are positioned in the text box.
@in MOAITextBox self
@opt number glyphScale Default value is 1.
@out number glyphScale
*/
int MOAITextBox::_setGlyphScale ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
self->mGlyphScale = state.GetValue < float >( 2, 1.0f );
return 0;
}
//----------------------------------------------------------------//
/** @name setHighlight
@text Set or clear the highlight color of a sub string in the text.
Only affects text displayed on the current page. Highlight
will automatically clear when layout or page changes.
@overload
@in MOAITextBox self
@in number index Index of the first character in the substring.
@in number size Length of the substring.
@in number r
@in number g
@in number b
@opt number a Default value is 1.
@overload
@in MOAITextBox self
@in number index Index of the first character in the substring.
@in number size Length of the substring.
*/
int MOAITextBox::_setHighlight ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UNN" )
u32 index = state.GetValue < u32 >( 2, 1 ) - 1;
u32 size = state.GetValue < u32 >( 3, 0 );
if ( size ) {
if ( state.GetTop () > 3 ) {
u32 rgba = state.GetColor32 ( 4, 1.0f, 1.0f, 1.0f, 1.0f );
self->SetHighlight ( index, size, rgba );
}
else {
self->SetHighlight ( index, size );
}
}
return 0;
}
//----------------------------------------------------------------//
/** @name setLineSpacing
@text Sets additional space between lines in text units. '0' uses
the default spacing. Valus must be positive.
@in MOAITextBox self
@in number lineSpacing Default value is 0.
*/
int MOAITextBox::_setLineSpacing ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
float lineSpacing = state.GetValue < float >( 2, 0.0f );
self->mLineSpacing = lineSpacing < 0.0f ? 0.0f : lineSpacing;
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name setRect
@text Sets the rectangular area for this text box.
@in MOAITextBox self
@in number x1 The X coordinate of the rect's upper-left point.
@in number y1 The Y coordinate of the rect's upper-left point.
@in number x2 The X coordinate of the rect's lower-right point.
@in number y2 The Y coordinate of the rect's lower-right point.
@out nil
*/
int MOAITextBox::_setRect ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UNNNN" )
float left = state.GetValue < float >( 2, 0.0f );
float top = state.GetValue < float >( 3, 0.0f );
float right = state.GetValue < float >( 4, 0.0f );
float bottom = state.GetValue < float >( 5, 0.0f );
self->SetRect ( left, top, right, bottom );
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name setReveal
@text Sets the number of renderable characters to be shown.
Can range from 0 to any value; values greater than the
number of renderable characters in the current text will
be ignored.
@in MOAITextBox self
@in number reveal The number of renderable characters (i.e. not whitespace) to be shown.
@out nil
*/
int MOAITextBox::_setReveal ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UN" )
self->mReveal = state.GetValue < u32 >( 2, self->mReveal );
self->mSpool = ( float )self->mReveal;
return 0;
}
//----------------------------------------------------------------//
/** @name setSpeed
@text Sets the base spool speed used when creating a spooling MOAIAction with the spool() function.
@in MOAITextBox self
@in number speed The base spooling speed.
@out nil
*/
int MOAITextBox::_setSpeed ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UN" )
self->mSpeed = state.GetValue < float >( 2, self->mSpeed );
return 0;
}
//----------------------------------------------------------------//
/** @name setString
@text Sets the text string to be displayed by this textbox.
@in MOAITextBox self
@in string newStr The new text string to be displayed.
@out nil
*/
int MOAITextBox::_setString ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "US" )
cc8* text = state.GetValue < cc8* >( 2, "" );
self->SetText ( text );
self->ResetStyleMap ();
self->ScheduleLayout ();
self->mMore = ( text && text [ 0 ]);
return 0;
}
//----------------------------------------------------------------//
/** @name setStyle
@text Attaches a style to the textbox and associates a name with it.
If no name is given, sets the default style.
@overload
@in MOAITextBox self
@in MOAITextStyle defaultStyle
@out nil
@overload
@in MOAITextBox self
@in string styleName
@in MOAITextStyle style
@out nil
*/
int MOAITextBox::_setStyle ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
cc8* styleName = state.GetValue < cc8* >( 2, "" );
if ( strlen ( styleName )) {
MOAITextStyle* style = state.GetLuaObject < MOAITextStyle >( 3, true );
self->SetStyle ( styleName, style );
}
else {
MOAITextStyle* style = state.GetLuaObject < MOAITextStyle >( 2, true );
self->SetStyle ( style );
}
self->ResetStyleMap ();
self->ScheduleLayout ();
return 0;
}
//----------------------------------------------------------------//
/** @name setWordBreak
@text Sets the rule for breaking words across lines.
@in MOAITextBox self
@opt number rule One of MOAITextBox.WORD_BREAK_NONE, MOAITextBox.WORD_BREAK_CHAR.
Default is MOAITextBox.WORD_BREAK_NONE.
@out nil
*/
int MOAITextBox::_setWordBreak ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
self->mWordBreak = state.GetValue < u32 >( 2, MOAITextBox::WORD_BREAK_NONE );
return 0;
}
//----------------------------------------------------------------//
/** @name setYFlip
@text Sets the rendering direction for the text. Default assumes
a window style screen space (positive Y moves down the screen). Set
to true to render text for world style coordinate systems (positive
Y moves up the screen).
@in MOAITextBox self
@in number yFlip Whether the vertical rendering direction should be inverted.
@out nil
*/
int MOAITextBox::_setYFlip ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "UB" )
self->mYFlip = state.GetValue < bool >( 2, self->mYFlip );
self->ScheduleUpdate ();
return 0;
}
//----------------------------------------------------------------//
/** @name spool
@text Creates a new MOAIAction which when run has the effect of increasing
the amount of characters revealed from 0 to the length of the string
currently set. The spool action is automatically added to the root
of the action tree, but may be reparented or stopped by the developer.
This function also automatically sets the current number of revealed
characters to 0 (i.e. MOAITextBox:setReveal(0)).
@in MOAITextBox self
@in number yFlip Whether the vertical rendering direction should be inverted.
@out MOAIAction action The new MOAIAction which spools the text when run.
*/
int MOAITextBox::_spool ( lua_State* L ) {
MOAI_LUA_SETUP ( MOAITextBox, "U" )
self->mReveal = state.GetValue < u32 >( 2, 0 );
self->mSpool = ( float )self->mReveal;
self->Start ();
return 1;
}
//================================================================//
// DOXYGEN
//================================================================//
#ifdef DOXYGEN
//----------------------------------------------------------------//
/** @name affirmStyle
@text Returns the textbox's default style. If no default style
exists, creates an empty style, sets it as the default and
returns it.
@in MOAITextBox self
@out MOAITextStyle style
*/
int MOAITextBox::_affirmStyle ( lua_State* L ) {
}
//----------------------------------------------------------------//
/** @name setFont
@text Sets the font to be used by the textbox's default style.
If no default style exists, a default style is created.
@in MOAITextBox self
@in MOAIFont font
@out nil
*/
int MOAITextBox::_setFont ( lua_State* L ) {
}
//----------------------------------------------------------------//
/** @name setTextSize
@text Sets the size to be used by the textbox's default style.
If no default style exists, a default style is created.
@in MOAITextBox self
@in number points The point size to be used by the default style.
@opt number dpi The device DPI (dots per inch of device screen). Default value is 72 (points same as pixels).
@out nil
*/
int MOAITextBox::_setTextSize ( lua_State* L ) {
}
#endif
//================================================================//
// MOAITextBox
//================================================================//
const float MOAITextBox::DEFAULT_SPOOL_SPEED = 24.0f;
//----------------------------------------------------------------//
MOAITextStyle* MOAITextBox::AddAnonymousStyle ( MOAITextStyle* source ) {
MOAITextStyle* style = new MOAITextStyle ();
style->Init ( *source );
MOAITextStyleRef styleRef;
styleRef.mStyle = style;
styleRef.UpdateState ();
this->RetainStyle ( style );
this->mAnonymousStyles.Push ( styleRef );
return style;
}
//----------------------------------------------------------------//
void MOAITextBox::AddHighlight ( u32 base, u32 top, u32 color ) {
// make room for the new highlight
this->ClearHighlight ( base, top );
MOAITextHighlight* highlight = new MOAITextHighlight ();
highlight->mBase = base;
highlight->mTop = top;
highlight->mColor = color;
highlight->mPrev = 0;
highlight->mNext = 0;
if ( !this->mHighlights ) {
this->mHighlights = highlight;
return;
}
MOAITextHighlight* best = 0;
MOAITextHighlight* cursor = this->mHighlights;
for ( ; cursor; cursor = cursor->mNext ) {
if ( cursor->mBase >= base ) break;
best = cursor;
}
if ( best ) {
highlight->mNext = best->mNext;
highlight->mPrev = best;
if ( best->mNext ) {
best->mNext->mPrev = highlight;
}
best->mNext = highlight;
}
else {
highlight->mNext = this->mHighlights;
this->mHighlights = highlight;
if ( highlight->mNext ) {
highlight->mNext->mPrev = highlight;
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::ApplyHighlights () {
u32 totalSprites = this->mSprites.GetTop ();
u32 spriteIdx = 0;
MOAITextHighlight* highlight = this->mHighlights;
while (( spriteIdx < totalSprites ) && highlight ) {
MOAITextSprite& sprite = this->mSprites [ spriteIdx ];
if ( sprite.mIdx >= highlight->mTop ) {
highlight = highlight->mNext;
}
else {
if ( sprite.mIdx >= highlight->mBase ) {
sprite.mRGBA = highlight->mColor;
sprite.mMask |= MOAITextSprite::MASK_COLOR;
}
spriteIdx++;
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::ClearHighlight ( u32 base, u32 top ) {
MOAITextHighlight* highlight = this->mHighlights;
for ( ; highlight; highlight = highlight->mNext ) {
if ( highlight->mTop <= base ) continue;
if ( highlight->mBase >= top ) continue;
// cursor is inside of span
if (( highlight->mBase >= base ) && ( highlight->mTop <= top )) {
highlight->mBase = highlight->mTop;
continue;
}
// cursor contains span
if (( highlight->mBase < base ) && ( highlight->mTop > top )) {
MOAITextHighlight* split = new MOAITextHighlight ();
split->mColor = highlight->mColor;
split->mBase = top;
split->mTop = highlight->mTop;
split->mPrev = highlight;
split->mNext = highlight->mNext;
highlight->mTop = base;
if ( highlight->mNext ) {
highlight->mNext->mPrev = split;
}
highlight->mNext = split;
break;
}
if (( highlight->mBase < base ) && ( base < highlight->mTop )) {
highlight->mTop = base;
continue;
}
if (( highlight->mBase < top ) && ( top < highlight->mTop )) {
highlight->mBase = top;
continue;
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::ClearHighlights () {
MOAITextHighlight* cursor = this->mHighlights;
this->mHighlights = 0;
while ( cursor ) {
MOAITextHighlight* highlight = cursor;
cursor = cursor->mNext;
delete highlight;
}
}
//----------------------------------------------------------------//
bool MOAITextBox::CheckStylesChanged () {
bool status = false;
// TODO: think about keeping list of currently active styles instead of iterating through everything
u32 totalAnonymous = this->mAnonymousStyles.GetTop ();
for ( u32 i = 0; i < totalAnonymous; i++ ) {
MOAITextStyleRef& styleRef = this->mAnonymousStyles [ i ];
if ( styleRef.NeedsLayout ()) {
styleRef.UpdateState ();
status = true;
}
}
StyleSetIt styleSetIt = this->mStyleSet.begin ();
for ( ; styleSetIt != this->mStyleSet.end (); ++styleSetIt ) {
MOAITextStyleRef& styleRef = styleSetIt->second;
if ( styleRef.NeedsLayout ()) {
styleRef.UpdateState ();
status = true;
}
}
return status;
}
//----------------------------------------------------------------//
void MOAITextBox::ClearCurves () {
for ( u32 i = 0; i < this->mCurves.Size (); ++i ) {
this->LuaRelease ( this->mCurves [ i ]);
}
this->mCurves.Clear ();
}
//----------------------------------------------------------------//
void MOAITextBox::CompactHighlights () {
MOAITextHighlight* cursor = this->mHighlights;
while ( cursor ) {
MOAITextHighlight* highlight = cursor;
cursor = highlight->mNext;
// prune empty highlights
if ( highlight->mBase == highlight->mTop ) {
this->RemoveHighlight ( *highlight );
delete highlight;
continue;
}
// gobble up any adjacent (or overlapping) same-colored highlights
// break if we hit a gap or another color
MOAITextHighlight* cursor2 = highlight->mNext;
while ( cursor2 ) {
MOAITextHighlight* highlight2 = cursor2;
cursor2 = highlight2->mNext;
if ( highlight2->mBase != highlight2->mTop ) {
if ( highlight->mColor != highlight2->mColor ) break;
if ( highlight->mTop < highlight2->mBase ) break;
if ( highlight->mTop < highlight2->mTop ) {
highlight->mTop = highlight2->mTop;
}
}
this->RemoveHighlight ( *highlight2 );
delete highlight2;
}
cursor = highlight->mNext;
}
}
//----------------------------------------------------------------//
void MOAITextBox::Draw ( int subPrimID ) {
UNUSED ( subPrimID );
if ( !( this->mFlags & FLAGS_VISIBLE )) return;
if ( this->mReveal ) {
MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get ();
if ( this->mUVTransform ) {
USAffine3D uvMtx = this->mUVTransform->GetLocalToWorldMtx ();
gfxDevice.SetUVTransform ( uvMtx );
}
else {
gfxDevice.SetUVTransform ();
}
this->LoadGfxState ();
if ( !this->mShader ) {
// TODO: this should really come from MOAIFont, which should really be a
// specialized implementation of MOAIDeck...
gfxDevice.SetShaderPreset ( MOAIShaderMgr::FONT_SHADER );
}
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_WORLD_TRANSFORM, this->GetLocalToWorldMtx ());
gfxDevice.SetVertexMtxMode ( MOAIGfxDevice::VTX_STAGE_MODEL, MOAIGfxDevice::VTX_STAGE_PROJ );
gfxDevice.SetUVMtxMode ( MOAIGfxDevice::UV_STAGE_MODEL, MOAIGfxDevice::UV_STAGE_TEXTURE );
MOAIQuadBrush::BindVertexFormat ( gfxDevice );
USColorVec baseColor = gfxDevice.GetPenColor ();
USColorVec blendColor;
u32 rgba0 = 0xffffffff;
u32 rgba1 = 0xffffffff;
u32 size = this->mSprites.GetTop ();
for ( u32 i = 0; ( i < size ) && ( i < this->mReveal ); ++i ) {
const MOAITextSprite& sprite = this->mSprites [ i ];
rgba0 = sprite.mMask & MOAITextSprite::MASK_COLOR ? sprite.mRGBA : sprite.mStyle->mColor;
if ( rgba0 != rgba1 ) {
rgba1 = rgba0;
blendColor.SetRGBA ( rgba0 );
blendColor.Modulate ( baseColor );
gfxDevice.SetPenColor ( blendColor );
}
sprite.mGlyph->Draw ( *sprite.mTexture, sprite.mX, sprite.mY, sprite.mScale );
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::DrawDebug ( int subPrimID ) {
UNUSED ( subPrimID );
this->Layout ();
MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get ();
MOAIDebugLines& debugLines = MOAIDebugLines::Get ();
MOAIDraw& draw = MOAIDraw::Get ();
UNUSED ( draw ); // mystery warning in vs2008
draw.Bind ();
gfxDevice.SetVertexTransform ( MOAIGfxDevice::VTX_WORLD_TRANSFORM, this->GetLocalToWorldMtx ());
gfxDevice.SetVertexMtxMode ( MOAIGfxDevice::VTX_STAGE_MODEL, MOAIGfxDevice::VTX_STAGE_PROJ );
if ( debugLines.Bind ( MOAIDebugLines::TEXT_BOX )) {
draw.DrawRectOutline ( this->mFrame );
}
if ( debugLines.Bind ( MOAIDebugLines::TEXT_BOX_BASELINES )) {
u32 totalLines = this->mLines.GetTop ();
for ( u32 i = 0; i < totalLines; ++i ) {
MOAITextLine& line = this->mLines [ i ];
float y = line.mRect.mYMin + line.mAscent;
draw.DrawLine ( line.mRect.mXMin, y, line.mRect.mXMax, y );
}
}
if ( debugLines.Bind ( MOAIDebugLines::TEXT_BOX_LAYOUT )) {
u32 totalLines = this->mLines.GetTop ();
for ( u32 i = 0; i < totalLines; ++i ) {
MOAITextLine& line = this->mLines [ i ];
draw.DrawRectOutline ( line.mRect );
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::FindSpriteSpan ( u32 idx, u32 size, u32& spanIdx, u32& spanSize ) {
spanSize = 0;
u32 top = this->mSprites.GetTop ();
if ( !top ) return;
if ( this->mSprites [ 0 ].mIdx >= ( idx + size )) return;
if ( this->mSprites [ top - 1 ].mIdx < idx ) return;
for ( u32 i = 0; i < top; ++i ) {
MOAITextSprite& sprite = this->mSprites [ i ];
if ( sprite.mIdx >= idx ) {
spanIdx = i;
spanSize = 1;
break;
}
}
if ( spanSize ) {
u32 max = idx + size;
u32 i = spanIdx + 1;
u32 count = 0;
for ( ; i < top; ++i, ++count ) {
MOAITextSprite& sprite = this->mSprites [ i ];
if ( sprite.mIdx >= max ) break;
}
spanSize = count + 1;
}
}
//----------------------------------------------------------------//
bool MOAITextBox::GetBoundsForRange ( u32 idx, u32 size, USRect& rect ) {
if ( !size ) return false;
this->Layout ();
bool result = false;
u32 spanIdx;
u32 spanSize;
this->FindSpriteSpan ( idx, size, spanIdx, spanSize );
if ( !spanSize ) return false;
u32 end = spanIdx + spanSize;
for ( u32 i = spanIdx; i < end; ++i ) {
MOAITextSprite& sprite = this->mSprites [ i ];
MOAIGlyph& glyph = *sprite.mGlyph;
if ( glyph.mWidth > 0.0f ) {
USRect glyphRect = glyph.GetRect ( sprite.mX, sprite.mY );
if ( result ) {
rect.Grow ( glyphRect );
}
else {
rect = glyphRect;
result = true;
}
}
}
return result;
}
//----------------------------------------------------------------//
u32 MOAITextBox::GetPropBounds ( USBox& bounds ) {
bounds.Init ( this->mFrame.mXMin, this->mFrame.mYMax, this->mFrame.mXMax, this->mFrame.mYMin, 0.0f, 0.0f );
return MOAIProp::BOUNDS_OK;
}
//----------------------------------------------------------------//
MOAITextStyle* MOAITextBox::GetStyle () {
return this->GetStyle ( DEFAULT_STYLE_NAME );
}
//----------------------------------------------------------------//
MOAITextStyle* MOAITextBox::GetStyle ( cc8* styleName ) {
if ( styleName && this->mStyleSet.contains ( styleName )) {
return this->mStyleSet [ styleName ].mStyle;
}
return this->mStyleSet [ DEFAULT_STYLE_NAME ].mStyle;
}
//----------------------------------------------------------------//
bool MOAITextBox::IsDone () {
if ( this->IsActive ()) {
this->Layout ();
return ( this->mReveal >= this->mSprites.GetTop ());
}
return true;
}
//----------------------------------------------------------------//
void MOAITextBox::Layout () {
if ( !this->mText ) {
this->ResetStyleMap ();
this->ResetLayout ();
}
else if ( this->mNeedsLayout ) {
if ( !this->mStyleMap.GetTop ()) {
MOAITextStyler styler;
styler.BuildStyleMap ( *this );
}
this->ResetLayout ();
MOAITextDesigner designer;
designer.Init ( *this );
designer.BuildLayout ();
this->ApplyHighlights ();
}
this->mNeedsLayout = false;
}
//----------------------------------------------------------------//
MOAITextBox::MOAITextBox () :
mLineSpacing ( 0.0f ),
mText ( "" ),
mTextLength ( 0 ),
mHAlign ( LEFT_JUSTIFY ),
mVAlign ( LEFT_JUSTIFY ),
mSpool ( 0.0f ),
mSpeed ( DEFAULT_SPOOL_SPEED ),
mReveal ( REVEAL_ALL ),
mYFlip ( false ),
mGlyphScale ( 1.0f ),
mCurrentPageIdx ( 0 ),
mNextPageIdx ( 0 ),
mNeedsLayout ( false ),
mMore ( false ),
mHighlights ( 0 ),
mWordBreak ( WORD_BREAK_NONE ) {
RTTI_BEGIN
RTTI_EXTEND ( MOAIProp )
RTTI_EXTEND ( MOAIAction )
RTTI_END
this->mFrame.Init ( 0.0f, 0.0f, 0.0f, 0.0f );
this->SetMask ( MOAIProp::CAN_DRAW | MOAIProp::CAN_DRAW_DEBUG );
this->mBlendMode.SetBlend ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
}
//----------------------------------------------------------------//
MOAITextBox::~MOAITextBox () {
this->ClearCurves ();
this->ClearHighlights ();
// TODO: this is a known bug - releasing the dep links here
// will cause plenty o' crashing
// the case seems to be when the text box has ben garbage
// collected but is still in the node manager's update list
// the lua ref stuff is destroyed by the __gc method
// but it's needed by the links
// am wondering if the links are also being orphaned or
// compromised by the gc
this->ResetLayout ();
this->ResetStyleMap ();
this->ResetStyleSet ();
}
//----------------------------------------------------------------//
bool MOAITextBox::More () {
this->Layout ();
if ( this->mReveal < this->mSprites.GetTop ()) {
return true;
}
return this->mMore;
}
//----------------------------------------------------------------//
void MOAITextBox::NextPage ( bool reveal ) {
if ( this->mMore ) {
this->mCurrentPageIdx = this->mNextPageIdx;
}
else {
this->mCurrentPageIdx = 0;
this->mNextPageIdx = 0;
}
this->mReveal = reveal ? REVEAL_ALL : 0;
this->mSpool = 0.0f;
}
//----------------------------------------------------------------//
void MOAITextBox::OnDepNodeUpdate () {
MOAIProp::OnDepNodeUpdate ();
if ( this->CheckStylesChanged ()) {
this->mNeedsLayout = true;
this->RefreshStyleGlyphs ();
}
this->Layout ();
if ( this->mYFlip ) {
USAffine3D mtx;
mtx.ScRoTr ( 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, ( this->mFrame.mYMin + this->mFrame.mYMax ), 0.0f );
this->mLocalToWorldMtx.Prepend ( mtx );
this->mWorldToLocalMtx.Inverse ( this->mLocalToWorldMtx );
}
}
//----------------------------------------------------------------//
void MOAITextBox::OnUpdate ( float step ) {
this->mSpool += ( this->mSpeed * step );
this->mReveal = ( u32 )this->mSpool;
}
//----------------------------------------------------------------//
void MOAITextBox::PushLine ( u32 start, u32 size, const USRect& rect, float ascent ) {
MOAITextLine textLine;
textLine.mStart = start;
textLine.mSize = size;
textLine.mRect = rect;
textLine.mAscent = ascent;
this->mLines.Push ( textLine );
}
//----------------------------------------------------------------//
void MOAITextBox::PushSprite ( u32 idx, MOAIGlyph& glyph, MOAITextStyle& style, float x, float y, float scale ) {
MOAITextSprite textSprite;
textSprite.mIdx = idx;
textSprite.mGlyph = &glyph;
textSprite.mStyle = &style;
textSprite.mX = x;
textSprite.mY = y;
textSprite.mScale = scale;
textSprite.mRGBA = style.mColor;
textSprite.mTexture = style.mFont->GetGlyphTexture ( glyph );
textSprite.mMask = 0;
this->mSprites.Push ( textSprite );
}
//----------------------------------------------------------------//
void MOAITextBox::PushStyleSpan ( int base, int top, MOAITextStyle& style ) {
MOAITextStyleSpan span;
span.mBase = base;
span.mTop = top;
span.mStyle = &style;
this->mStyleMap.Push ( span );
}
//----------------------------------------------------------------//
void MOAITextBox::RefreshStyleGlyphs () {
u32 totalSpans = this->mStyleMap.GetTop ();
if ( !totalSpans ) return;
for ( u32 i = 0; i < totalSpans; ++i ) {
MOAITextStyleSpan& span = this->mStyleMap [ i ];
int idx = span.mBase;
while ( idx < span.mTop ) {
u32 c = u8_nextchar ( this->mText, &idx );
span.mStyle->AffirmGlyph ( c );
}
}
// TODO: think about keeping list of currently active styles instead of iterating through everything
u32 totalAnonymous = this->mAnonymousStyles.GetTop ();
for ( u32 i = 0; i < totalAnonymous; i++ ) {
MOAITextStyleRef& styleRef = this->mAnonymousStyles [ i ];
styleRef.mStyle->mFont->ProcessGlyphs ();
}
StyleSetIt styleSetIt = this->mStyleSet.begin ();
for ( ; styleSetIt != this->mStyleSet.end (); ++styleSetIt ) {
MOAITextStyleRef& styleRef = styleSetIt->second;
styleRef.mStyle->mFont->ProcessGlyphs ();
}
}
//----------------------------------------------------------------//
void MOAITextBox::RegisterLuaClass ( MOAILuaState& state ) {
MOAIProp::RegisterLuaClass ( state );
MOAIAction::RegisterLuaClass ( state );
state.SetField ( -1, "LEFT_JUSTIFY", ( u32 )LEFT_JUSTIFY );
state.SetField ( -1, "CENTER_JUSTIFY", ( u32 )CENTER_JUSTIFY );
state.SetField ( -1, "RIGHT_JUSTIFY", ( u32 )RIGHT_JUSTIFY );
state.SetField ( -1, "WORD_BREAK_NONE", ( u32 )WORD_BREAK_NONE );
state.SetField ( -1, "WORD_BREAK_CHAR", ( u32 )WORD_BREAK_CHAR );
}
//----------------------------------------------------------------//
void MOAITextBox::RegisterLuaFuncs ( MOAILuaState& state ) {
MOAIProp::RegisterLuaFuncs ( state );
MOAIAction::RegisterLuaFuncs ( state );
luaL_Reg regTable [] = {
{ "clearHighlights", _clearHighlights },
{ "getGlyphScale", _getGlyphScale },
{ "getLineSpacing", _getLineSpacing },
{ "getRect", _getRect },
{ "getStringBounds", _getStringBounds },
{ "getStyle", _getStyle },
{ "more", _more },
{ "nextPage", _nextPage },
{ "reserveCurves", _reserveCurves },
{ "revealAll", _revealAll },
{ "setAlignment", _setAlignment },
{ "setCurve", _setCurve },
{ "setGlyphScale", _setGlyphScale },
{ "setHighlight", _setHighlight },
{ "setLineSpacing", _setLineSpacing },
{ "setRect", _setRect },
{ "setReveal", _setReveal },
{ "setSpeed", _setSpeed },
{ "setString", _setString },
{ "setStyle", _setStyle },
{ "setWordBreak", _setWordBreak },
{ "setYFlip", _setYFlip },
{ "spool", _spool },
{ NULL, NULL }
};
luaL_register ( state, 0, regTable );
}
//----------------------------------------------------------------//
void MOAITextBox::ReleaseStyle ( MOAITextStyle* style ) {
if ( style ) {
this->ClearNodeLink ( *style );
}
this->LuaRelease ( style );
}
//----------------------------------------------------------------//
void MOAITextBox::RemoveHighlight ( MOAITextHighlight& highlight ) {
MOAITextHighlight* prev = highlight.mPrev;
MOAITextHighlight* next = highlight.mNext;
if ( prev ) {
prev->mNext = next;
}
else {
this->mHighlights = next;
}
if ( next ) {
next->mPrev = prev;
}
}
//----------------------------------------------------------------//
void MOAITextBox::ReserveCurves ( u32 total ) {
this->ClearCurves ();
this->mCurves.Init ( total );
this->mCurves.Fill ( 0 );
}
//----------------------------------------------------------------//
void MOAITextBox::ResetLayout () {
this->mMore = false;
this->mLines.Reset ();
this->mSprites.Reset ();
}
//----------------------------------------------------------------//
void MOAITextBox::ResetHighlights () {
u32 top = this->mSprites.GetTop ();
for ( u32 i = 0; i > top; ++i ) {
MOAITextSprite& sprite = this->mSprites [ i ];
sprite.mMask = sprite.mMask & ~MOAITextSprite::MASK_COLOR;
}
}
//----------------------------------------------------------------//
void MOAITextBox::ResetStyleMap () {
u32 totalAnonymous = this->mAnonymousStyles.GetTop ();
for ( u32 i = 0; i < totalAnonymous; i++ ) {
this->ReleaseStyle ( this->mAnonymousStyles [ i ].mStyle );
}
this->mAnonymousStyles.Reset ();
this->mStyleMap.Reset ();
}
//----------------------------------------------------------------//
void MOAITextBox::ResetStyleSet () {
StyleSetIt styleSetIt = this->mStyleSet.begin ();
for ( ; styleSetIt != this->mStyleSet.end (); ++styleSetIt ) {
this->ReleaseStyle ( styleSetIt->second.mStyle );
}
this->mStyleSet.clear ();
}
//----------------------------------------------------------------//
void MOAITextBox::RetainStyle ( MOAITextStyle* style ) {
if ( style ) {
this->SetNodeLink ( *style );
}
this->LuaRetain ( style );
}
//----------------------------------------------------------------//
void MOAITextBox::ScheduleLayout () {
this->mNeedsLayout = true;
this->ScheduleUpdate ();
}
//----------------------------------------------------------------//
void MOAITextBox::SerializeIn ( MOAILuaState& state, MOAIDeserializer& serializer ) {
MOAIProp::SerializeIn ( state, serializer );
MOAIAction::SerializeIn ( state, serializer );
}
//----------------------------------------------------------------//
void MOAITextBox::SerializeOut ( MOAILuaState& state, MOAISerializer& serializer ) {
MOAIProp::SerializeOut ( state, serializer );
MOAIAction::SerializeOut ( state, serializer );
}
//----------------------------------------------------------------//
void MOAITextBox::SetCurve ( u32 idx, MOAIAnimCurve* curve ) {
if ( idx > this->mCurves.Size ()) return;
if ( this->mCurves [ idx ] == curve ) return;
this->LuaRetain ( curve );
this->LuaRelease ( this->mCurves [ idx ]);
this->mCurves [ idx ] = curve;
}
//----------------------------------------------------------------//
void MOAITextBox::SetHighlight ( u32 idx, u32 size ) {
if ( !size ) return;
this->ClearHighlight ( idx, idx + size );
this->CompactHighlights ();
this->ResetHighlights ();
this->ApplyHighlights ();
}
//----------------------------------------------------------------//
void MOAITextBox::SetHighlight ( u32 idx, u32 size, u32 color ) {
if ( !size ) return;
this->AddHighlight ( idx, idx + size, color );
this->CompactHighlights ();
this->ResetHighlights ();
this->ApplyHighlights ();
}
//----------------------------------------------------------------//
void MOAITextBox::SetRect ( float left, float top, float right, float bottom ) {
this->mFrame.Init ( left, top, right, bottom );
}
//----------------------------------------------------------------//
void MOAITextBox::SetStyle ( MOAITextStyle* style ) {
this->SetStyle ( DEFAULT_STYLE_NAME, style );
}
//----------------------------------------------------------------//
void MOAITextBox::SetStyle ( cc8* styleName, MOAITextStyle* style ) {
styleName = styleName ? styleName : DEFAULT_STYLE_NAME;
MOAITextStyle* prevStyle = 0;
if ( this->mStyleSet.contains ( styleName )) {
prevStyle = this->mStyleSet [ styleName ].mStyle;
if ( prevStyle == style ) return;
}
this->RetainStyle ( style );
this->ReleaseStyle ( prevStyle );
if ( style ) {
MOAITextStyleRef& styleRef = this->mStyleSet [ styleName ];
styleRef.mStyle = style;
styleRef.UpdateState ();
}
else {
if ( this->mStyleSet.contains ( styleName )) {
this->mStyleSet.erase ( styleName );
}
}
}
//----------------------------------------------------------------//
void MOAITextBox::SetText ( cc8* text ) {
this->mText = text;
this->mTextLength = ( u32 )this->mText.length ();
this->mReveal = REVEAL_ALL;
this->mSpool = 0.0f;
this->mCurrentPageIdx = 0;
this->mNextPageIdx = 0;
this->ResetStyleMap ();
this->ClearHighlights ();
}
| {
"content_hash": "81682b3ffdae8d1f61c707f7e09461e5",
"timestamp": "",
"source": "github",
"line_count": 1490,
"max_line_length": 124,
"avg_line_length": 26.812080536912752,
"alnum_prop": 0.5675093867334168,
"repo_name": "jjimenezg93/ai-behaviours",
"id": "eb4f6637b0b90617fd394a196f9aa6be38a27419",
"size": "39950",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "moai/src/moaicore/MOAITextBox.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2248"
},
{
"name": "C",
"bytes": "133713"
},
{
"name": "C++",
"bytes": "3148460"
},
{
"name": "Lua",
"bytes": "42324"
},
{
"name": "Objective-C",
"bytes": "62841"
},
{
"name": "Objective-C++",
"bytes": "167701"
},
{
"name": "Shell",
"bytes": "1271"
}
],
"symlink_target": ""
} |
Frontend development tutorial
=============================
.. _npm:
npm
---
Shrunk's javascript dependencies are managed with the ``npm`` package manager. After installing
``npm`` through your distro's package manager or the ``nvm`` tool, install the dependencies
by executing::
$ npm i
in ``frontend/``. This will install the dependencies specified in ``package-lock.json``.
Documentation
-------------
To build the documentation for the frontend, run::
$ npm run doc
The documentation will have been placed in ``frontend/docs``. Open the ``index.html`` file there to read the documentation!
Running the Frontend
--------------------
Run the following command in `frontend` in a separate terminal:
$ npm run watch
Now go to 127.0.0.1:5000 in your web browser, and you should be greeted with the go.rutgers.edu login page.
Jinja2
------
Our HTML pages are templated using the `Jinja2
<https://jinja.palletsprojects.com/en/2.11.x/>`__ templating
engine. Jinja is pretty simple, and it shouldn't take long to get the
hang of it. You can peruse the template designer documentation `here
<https://jinja.palletsprojects.com/en/2.11.x/templates/>`__. The
following features are particularly useful:
- `macros <https://jinja.palletsprojects.com/en/2.11.x/templates/#macros>`__
- `template inheritance <https://jinja.palletsprojects.com/en/2.11.x/templates/#template-inheritance>`__
After reading the documentation, you can look at our templates under ``./shrunk/templates`` to get
a feel for how Jinja is used in real life.
Bootstrap
---------
We use the `Bootstrap 4 <https://getbootstrap.com/>`__ CSS library extensively for page layout and styling.
You can find its documentation `here <https://getbootstrap.com/docs/4.4/getting-started/introduction/>`__.
Start with the `overview <https://getbootstrap.com/docs/4.4/layout/overview/>`__ and pay particular
attention to the `grid system <https://getbootstrap.com/docs/4.4/layout/grid/>`__, which is the heart of layout in Shrunk.
SASS
----
`SASS <https://sass-lang.com/>`__ is a superset of CSS that adds
features such as variables, loops, and mixins. Both Bootstrap and our
custom stylesheets are written in SASS. You should have a look at the
`SASS quickstart guide <https://sass-lang.com/guide>`__. If you're already familiar with CSS, SASS
won't look too different. Shrunk's SASS code is located in the
``./shrunk/static/scss`` directory.
Typescript
----------
`Typescript <https://www.typescriptlang.org/>`__ is a superset of
Javascript that adds type checking while maintaining interoperability
with legacy Javascript. All of our frontend code is written in
Typescript. Using Typescript helps make our code more maintainable and
prevents silly bugs (cf. :ref:`python-type-annotations`). You can find the Typescript tutorial `here <https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html>`__.
.. _webpack:
Webpack
-------
To integrate all these technologies, we use the `Webpack
<https://webpack.js.org/>`__ bundler. Webpack is responsible for
compilation of SASS to CSS and of Typescript to JS, minification of
CSS and JS, and resolution of module references in SASS and
Typescript. You can execute Webpack by running::
$ npx webpack --env ENV
where ``ENV`` is one of ``dev`` or ``prod``. In ``dev`` mode, the
output files will include source maps and will not be minified, and
Webpack will watch for changes and automatically recompile modified
files. In ``prod`` mode, output will be minified and source maps will
not be emitted. When you're working on Shrunk, you should probably
execute Webpack in ``dev`` mode and leave it running in the
background.
| {
"content_hash": "b5198b46e6e902deec017f8824ac2245",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 180,
"avg_line_length": 38.536842105263155,
"alnum_prop": 0.7372302649549304,
"repo_name": "oss/shrunk",
"id": "bac5ebf03fc0c16db1432c7b4057031fbd610887",
"size": "3661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/doc/frontend_tutorial.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1058"
},
{
"name": "HTML",
"bytes": "5703"
},
{
"name": "Haskell",
"bytes": "2553"
},
{
"name": "JavaScript",
"bytes": "15039"
},
{
"name": "Less",
"bytes": "7542"
},
{
"name": "Python",
"bytes": "238286"
},
{
"name": "Shell",
"bytes": "6516"
},
{
"name": "TypeScript",
"bytes": "198320"
}
],
"symlink_target": ""
} |
%----------------------------------------------------------------------------------------
%TITLE PAGE
%----------------------------------------------------------------------------------------
{\begingroup % Create the command for including the title page in the document
\hbox{ % Horizontal box
%\hspace*{0.2\textwidth} % Whitespace to the left of the title page
\rule{1pt}{\textheight} % Vertical line
\hspace*{0.05\textwidth} % Whitespace between the vertical line and title page text
\parbox[b]{2\textwidth}{ % Paragraph box which restricts text to less than the width of the page
{\noindent\Huge\bfseries {\color{brown}Scalable-Configurable AXI Switch (SCAS)} \\[4\baselineskip] \LARGE User Guide}\\[2\baselineskip] % Title
{\large \textit{V1.0 December 2013}}\\[4\baselineskip]
%{\Large \textsc{ARCHNTU}} % Author name
\vspace{0.5\textheight} % Whitespace between the title block and the publisher
{\noindent Nanyang Technological University, Singapore}\\[\baselineskip]
}}
\endgroup} | {
"content_hash": "ec9da7f59292212a694df0a26c942a30",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 143,
"avg_line_length": 55.111111111111114,
"alnum_prop": 0.6179435483870968,
"repo_name": "vipinkmenon/fpgadriver",
"id": "e0f2a251075e09639f6223ee5002f2991496b4bd",
"size": "992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/chapters/0.title_page.tex",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "27450"
},
{
"name": "C",
"bytes": "134722"
},
{
"name": "C++",
"bytes": "6930"
},
{
"name": "Makefile",
"bytes": "3332"
},
{
"name": "Shell",
"bytes": "2539"
},
{
"name": "Tcl",
"bytes": "59902"
},
{
"name": "Verilog",
"bytes": "5189401"
}
],
"symlink_target": ""
} |
#include "org_mitk_gui_qt_matchpoint_evaluator_Activator.h"
#include "QmitkMatchPointRegistrationEvaluator.h"
ctkPluginContext* org_mitk_gui_qt_matchpoint_evaluator_Activator::m_Context = nullptr;
void org_mitk_gui_qt_matchpoint_evaluator_Activator::start(
ctkPluginContext* context)
{
BERRY_REGISTER_EXTENSION_CLASS(QmitkMatchPointRegistrationEvaluator, context)
m_Context = context;
}
void org_mitk_gui_qt_matchpoint_evaluator_Activator::stop(
ctkPluginContext* context)
{
Q_UNUSED(context)
m_Context = nullptr;
}
ctkPluginContext* org_mitk_gui_qt_matchpoint_evaluator_Activator::GetContext()
{
return m_Context;
}
| {
"content_hash": "1afc73ab01fbde31ef3434f7c6439d31",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 86,
"avg_line_length": 22.06896551724138,
"alnum_prop": 0.78125,
"repo_name": "fmilano/mitk",
"id": "9be67889948faac4bea6cc4bbdf997b6caeef663",
"size": "1021",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Plugins/org.mitk.gui.qt.matchpoint.evaluator/src/internal/org_mitk_gui_qt_matchpoint_evaluator_Activator.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2668761"
},
{
"name": "C++",
"bytes": "25270216"
},
{
"name": "CSS",
"bytes": "52056"
},
{
"name": "Java",
"bytes": "350330"
},
{
"name": "JavaScript",
"bytes": "47660"
},
{
"name": "Makefile",
"bytes": "742"
},
{
"name": "Objective-C",
"bytes": "509788"
},
{
"name": "Perl",
"bytes": "982"
},
{
"name": "Python",
"bytes": "7545"
},
{
"name": "Shell",
"bytes": "6507"
},
{
"name": "TeX",
"bytes": "1204"
},
{
"name": "XSLT",
"bytes": "15769"
}
],
"symlink_target": ""
} |
#define LOG_TAG "main"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
using namespace cocos2d;
void cocos_android_app_init (JNIEnv* env) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
}
extern "C"
{
bool Java_org_cocos2dx_javascript_AppActivity_nativeIsLandScape(JNIEnv *env, jobject thisz)
{
return SimpleConfigParser::getInstance()->isLanscape();
}
bool Java_org_cocos2dx_javascript_AppActivity_nativeIsDebug(JNIEnv *env, jobject thisz)
{
#if (COCOS2D_DEBUG > 0)
return true;
#else
return false;
#endif
}
}
| {
"content_hash": "8a9500d1cf83c9aa4b4c4fc77dcbe249",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 95,
"avg_line_length": 24.035714285714285,
"alnum_prop": 0.6389301634472511,
"repo_name": "MIKUScallion/fmx-birdcrash",
"id": "16b22fefc371ae24f12a2db742b4c2663676669b",
"size": "855",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "frameworks/runtime-src/proj.android/jni/hellojavascript/main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "7747"
},
{
"name": "C++",
"bytes": "60583"
},
{
"name": "CMake",
"bytes": "10867"
},
{
"name": "HTML",
"bytes": "3640"
},
{
"name": "Java",
"bytes": "231258"
},
{
"name": "JavaScript",
"bytes": "5323092"
},
{
"name": "Makefile",
"bytes": "1120"
},
{
"name": "Objective-C",
"bytes": "36914"
},
{
"name": "Objective-C++",
"bytes": "68395"
}
],
"symlink_target": ""
} |
using Renci.SshNet.Messages.Connection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Renci.SshNet.Tests.Common;
namespace Renci.SshNet.Tests.Classes.Messages.Connection
{
/// <summary>
///This is a test class for ChannelCloseMessageTest and is intended
///to contain all ChannelCloseMessageTest Unit Tests
///</summary>
[TestClass]
public class ChannelCloseMessageTest : TestBase
{
/// <summary>
///A test for ChannelCloseMessage Constructor
///</summary>
[TestMethod]
[Ignore] // placeholder
public void ChannelCloseMessageConstructorTest()
{
ChannelCloseMessage target = new ChannelCloseMessage();
Assert.Inconclusive("TODO: Implement code to verify target");
}
/// <summary>
///A test for ChannelCloseMessage Constructor
///</summary>
[TestMethod]
[Ignore] // placeholder
public void ChannelCloseMessageConstructorTest1()
{
uint localChannelNumber = 0; // TODO: Initialize to an appropriate value
ChannelCloseMessage target = new ChannelCloseMessage(localChannelNumber);
Assert.Inconclusive("TODO: Implement code to verify target");
}
}
}
| {
"content_hash": "201dc84e4ddb488ec8e21151754ebc10",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 85,
"avg_line_length": 34,
"alnum_prop": 0.6547987616099071,
"repo_name": "sshnet/SSH.NET",
"id": "9d3ebc3c0123ee3b937784b3bad87e08820bf576",
"size": "1294",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "src/Renci.SshNet.Tests/Classes/Messages/Connection/ChannelCloseMessageTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "6048979"
}
],
"symlink_target": ""
} |
/**
*/
package org.apache.harmony.test.func.reg.vm.btest3381;
public class Btest3381_1 extends Thread {
public static void main (String[] args) throws Exception {
System.err.println("Start testcase 3381_1...");
Thread t = new Btest3381_1();
t.start();
t.join();
t.interrupt();
System.err.println("Thread was successfully interrupted!");
}
public void run () {}
}
| {
"content_hash": "8c666682f4b0e8ac10ed6def5ac39c4d",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 67,
"avg_line_length": 21.8,
"alnum_prop": 0.5963302752293578,
"repo_name": "freeVM/freeVM",
"id": "21e09a33ad28b001a9b7e213c2fc9f9de4503ef9",
"size": "1248",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "enhanced/buildtest/tests/functional/src/test/functional/org/apache/harmony/test/func/reg/vm/btest3381/Btest3381_1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "116828"
},
{
"name": "C",
"bytes": "17860389"
},
{
"name": "C++",
"bytes": "19007206"
},
{
"name": "CSS",
"bytes": "217777"
},
{
"name": "Java",
"bytes": "152108632"
},
{
"name": "Objective-C",
"bytes": "106412"
},
{
"name": "Objective-J",
"bytes": "11029421"
},
{
"name": "Perl",
"bytes": "305690"
},
{
"name": "Scilab",
"bytes": "34"
},
{
"name": "Shell",
"bytes": "153821"
},
{
"name": "XSLT",
"bytes": "152859"
}
],
"symlink_target": ""
} |
import { SpellCheck16 } from "../../";
export = SpellCheck16;
| {
"content_hash": "63fb8d99f7cced8ba87de4a2ade8a661",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 38,
"avg_line_length": 21,
"alnum_prop": 0.6349206349206349,
"repo_name": "markogresak/DefinitelyTyped",
"id": "d7bf6832bbbd591ce1af6c0857dbcca5b363a994",
"size": "63",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "types/carbon__icons-react/lib/spell-check/16.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "15"
},
{
"name": "Protocol Buffer",
"bytes": "678"
},
{
"name": "TypeScript",
"bytes": "17426898"
}
],
"symlink_target": ""
} |
/* global fetch */
import 'whatwg-fetch'
/**
* Parses the JSON returned by a network request
*
* @param {object} response A response from a network request
*
* @return {object} The parsed JSON from the request
*/
function parseJSON (response) {
return response.json()
}
/**
* Checks if a network request came back fine, and throws an error if not
*
* @param {object} response A response from a network request
*
* @return {object|undefined} Returns either the response, or throws an error
*/
function checkStatus (response) {
if (response.status >= 200 && response.status < 300) {
return response
}
const error = new Error(response.statusText)
error.response = response
throw error
}
/**
* Requests a URL, returning a promise
*
* @param {string} url The URL we want to request
* @param {object} [options] The options we want to pass to "fetch"
*
* @return {object} The response data
*/
export default function request (url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON)
}
| {
"content_hash": "2e636ac5a47f59a4f17ce4c8a1772903",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 77,
"avg_line_length": 24.022222222222222,
"alnum_prop": 0.6725254394079556,
"repo_name": "nypl-spacetime/where",
"id": "1e21c1c2dfdd3cf5393b3f5ee398479c891eaee0",
"size": "1081",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/utils/request.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15387"
},
{
"name": "HTML",
"bytes": "321"
},
{
"name": "JavaScript",
"bytes": "33599"
}
],
"symlink_target": ""
} |
package org.apache.solr.analytics.stream.reservation.read;
import java.io.DataInput;
import java.io.IOException;
/** Abstract class to manage the reading and application of data from a {@link DataInput} stream. */
public abstract class ReductionDataReader<A> {
protected final DataInput inputStream;
protected final A applier;
public ReductionDataReader(DataInput inputStream, A applier) {
this.inputStream = inputStream;
this.applier = applier;
}
/**
* Read a piece of data from the input stream and feed it to the applier.
*
* @throws IOException if an exception occurs while reading from the input stream
*/
public abstract void read() throws IOException;
}
| {
"content_hash": "6ad1aedf78fdab294af56f3f6e55b002",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 100,
"avg_line_length": 30.347826086956523,
"alnum_prop": 0.7464183381088825,
"repo_name": "apache/solr",
"id": "c454c5280761685ae45cb09d937e34d517c40905",
"size": "1499",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "solr/modules/analytics/src/java/org/apache/solr/analytics/stream/reservation/read/ReductionDataReader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "509"
},
{
"name": "Batchfile",
"bytes": "91853"
},
{
"name": "CSS",
"bytes": "234034"
},
{
"name": "Emacs Lisp",
"bytes": "73"
},
{
"name": "HTML",
"bytes": "326277"
},
{
"name": "Handlebars",
"bytes": "7549"
},
{
"name": "Java",
"bytes": "35849436"
},
{
"name": "JavaScript",
"bytes": "17639"
},
{
"name": "Python",
"bytes": "219385"
},
{
"name": "Shell",
"bytes": "279599"
},
{
"name": "XSLT",
"bytes": "35107"
}
],
"symlink_target": ""
} |
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <debug.h>
#include <nuttx/arch.h>
#include <nuttx/fs/fs.h>
#include <nuttx/ramlog.h>
#include <arch/board/board.h>
#include "up_arch.h"
#include "up_internal.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/****************************************************************************
* Private Types
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Name: up_calibratedelay
*
* Description:
* Delay loops are provided for short timing loops. This function, if
* enabled, will just wait for 100 seconds. Using a stopwatch, you can
* can then determine if the timing loops are properly calibrated.
*
****************************************************************************/
#if defined(CONFIG_ARCH_CALIBRATION) && defined(CONFIG_DEBUG)
static void up_calibratedelay(void)
{
int i;
lldbg("Beginning 100s delay\n");
for (i = 0; i < 100; i++)
{
up_mdelay(1000);
}
lldbg("End 100s delay\n");
}
#else
# define up_calibratedelay()
#endif
/****************************************************************************
* Public Functions
****************************************************************************/
/****************************************************************************
* Name: up_initialize
*
* Description:
* up_initialize will be called once during OS initialization after the
* basic OS services have been initialized. The architecture specific
* details of initializing the OS will be handled here. Such things as
* setting up interrupt service routines, starting the clock, and
* registering device drivers are some of the things that are different
* for each processor and hardware platform.
*
* up_initialize is called after the OS initialized but before the user
* initialization logic has been started and before the libraries have
* been initialized. OS services and driver services are available.
*
****************************************************************************/
void up_initialize(void)
{
/* Initialize global variables */
current_regs = NULL;
/* Calibrate the timing loop */
up_calibratedelay();
/* Add any extra memory fragments to the memory manager */
up_addregion();
/* Initialize the interrupt subsystem */
up_irqinitialize();
/* Initialize the power management subsystem. This MCU-specific function
* must be called *very* early in the intialization sequence *before* any
* other device drivers are initialized (since they may attempt to register
* with the power management subsystem).
*/
#ifdef CONFIG_PM
up_pminitialize();
#endif
/* Initialize the DMA subsystem if the weak function up_dmainitialize has been
* brought into the build
*/
#ifdef CONFIG_ARCH_DMA
#ifdef CONFIG_HAVE_WEAKFUNCTIONS
if (up_dmainitialize)
#endif
{
up_dmainitialize();
}
#endif
/* Initialize the system timer interrupt */
#if !defined(CONFIG_SUPPRESS_INTERRUPTS) && !defined(CONFIG_SUPPRESS_TIMER_INTS)
up_timerinit();
#endif
/* Register devices */
#if CONFIG_NFILE_DESCRIPTORS > 0
#if defined(CONFIG_DEV_NULL)
devnull_register(); /* Standard /dev/null */
#endif
#if defined(CONFIG_DEV_ZERO)
devzero_register(); /* Standard /dev/zero */
#endif
#endif /* CONFIG_NFILE_DESCRIPTORS */
/* Initialize the serial device driver */
#ifdef USE_SERIALDRIVER
up_serialinit();
#endif
/* Initialize the console device driver (if it is other than the standard
* serial driver).
*/
#if defined(CONFIG_DEV_LOWCONSOLE)
lowconsole_init();
#elif defined(CONFIG_RAMLOG_CONSOLE)
ramlog_consoleinit();
#endif
/* Initialize the Random Number Generator (RNG) */
#ifdef CONFIG_DEV_RANDOM
up_rnginitialize();
#endif
/* Initialize the system logging device */
#ifdef CONFIG_SYSLOG_CHAR
syslog_initialize();
#endif
#ifdef CONFIG_RAMLOG_SYSLOG
ramlog_sysloginit();
#endif
/* Initialize the network */
up_netinitialize();
/* Initialize USB -- device and/or host */
up_usbinitialize();
up_ledon(LED_IRQSENABLED);
}
| {
"content_hash": "308569bd3d5c8eca33a56e57717d2a7b",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 80,
"avg_line_length": 26.297752808988765,
"alnum_prop": 0.5396282845545823,
"repo_name": "gcds/project_xxx",
"id": "8a1311d591eb2988a339bafb25e33a1891057b95",
"size": "6505",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "nuttx/arch/arm/src/common/up_initialize.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.