code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <map>
// class multimap
// iterator upper_bound(const key_type& k);
// const_iterator upper_bound(const key_type& k) const;
//
// The member function templates find, count, lower_bound, upper_bound, and
// equal_range shall not participate in overload resolution unless the
// qualified-id Compare::is_transparent is valid and denotes a type
#include <map>
#include <cassert>
#include "test_macros.h"
#include "is_transparent.h"
#if TEST_STD_VER <= 11
#error "This test requires is C++14 (or later)"
#else
int main()
{
{
typedef std::multimap<int, double, transparent_less_not_a_type> M;
TEST_IGNORE_NODISCARD M().upper_bound(C2Int{5});
}
}
#endif
| youtube/cobalt | third_party/llvm-project/libcxx/test/std/containers/associative/multimap/multimap.ops/upper_bound3.fail.cpp | C++ | bsd-3-clause | 1,040 |
SQL tables are used to represent abstract operating system concepts, such as running processes.
A table can be used in conjunction with other tables via operations like sub-queries and joins. This allows for a rich data exploration experience. While osquery ships with a default set of tables, osquery provides an API that allows you to create new tables.
You can explore current tables: [https://osquery.io/tables](https://osquery.io/tables). Tables that are up for grabs in terms of development can be found on Github issues using the "virtual tables" + "[up for grabs tag](https://github.com/facebook/osquery/issues?q=is%3Aopen+is%3Aissue+label%3A%22virtual+tables%22)".
## New Table Walkthrough
Let's walk through an exercise where we build a 'time' table. The table will have one row, and that row will have three columns: hour, minute, and second.
Column values (a single row) will be dynamically computed at query time.
**Table specifications**
Under the hood, osquery uses libraries from SQLite core to create "virtual tables". The default API for creating virtual tables is relatively complex. osquery has abstracted this complexity away, allowing you to write a simple table declaration.
To make table-creation simple osquery uses a *table spec* file.
The current specs are organized by operating system in the [specs](https://github.com/facebook/osquery/tree/master/specs) source folder.
For our time exercise, a spec file would look like the following:
```python
# This .table file is called a "spec" and is written in Python
# This syntax (several definitions) is defined in /tools/codegen/gentable/py.
table_name("time")
# Provide a short "one line" description, please use punctuation!
description("Returns the current hour, minutes, and seconds.")
# Define your schema, which accepts a list of Column instances at minimum.
# You may also describe foreign keys and "action" columns.
schema([
# Declare the name, type, and documentation description for each column.
# The supported types are INTEGER, BIGINT, TEXT, DATE, and DATETIME.
Column("hour", INTEGER, "The current hour"),
Column("minutes", INTEGER, "The current minutes past the hour"),
Column("seconds", INTEGER, "The current seconds past the minute"),
])
# Use the "@gen{TableName}" to communicate the C++ symbol name.
implementation("genTime")
```
You can leave the comments out in your production spec. Shoot for simplicity, do NOT go "hard in the paint" and do things like inheritance for Column objects, loops in your table spec, etc.
You might wonder "this syntax looks similar to Python?". Well, it is! The build process actually parses the spec files as Python code and meta-programs necessary C/C++ implementation files.
**Where do I put the spec?**
You may be wondering how osquery handles cross-platform support while still allowing operating-system specific tables. The osquery build process takes care of this by only generating the relevant code based on a directory structure convention.
- Cross-platform: [specs/](https://github.com/facebook/osquery/tree/master/specs/)
- Mac OS X: [specs/darwin/](https://github.com/facebook/osquery/tree/master/specs/darwin)
- General Linux: [specs/linux/](https://github.com/facebook/osquery/tree/master/specs/linux)
- Ubuntu: [specs/ubuntu/](https://github.com/facebook/osquery/tree/master/specs/ubuntu)
- CentOS: [specs/centos/](https://github.com/facebook/osquery/tree/master/specs/centos)
Note: the CMake build provides custom defines for each platform and platform version.
**Creating your implementation**
As indicated in the spec file, our implementation will be in a function called `genTime`. Since this is a very general table and should compile on all supported operating systems we can place it in *osquery/tables/utility/time.cpp*. The directory *osquery/table/* contains the set of *specs* and implementation categories. Place implementations in the corresponding category using your best judgement.
Here is that code for *osquery/tables/utility/time.cpp*:
```cpp
// Copyright 2004-present Facebook. All Rights Reserved.
#include <ctime>
#include <osquery/tables.h>
namespace osquery {
namespace tables {
QueryData genTime(QueryContext &context) {
Row r;
QueryData results;
time_t _time = time(0);
struct tm* now = localtime(&_time);
r["hour"] = INTEGER(now->tm_hour);
r["minutes"] = INTEGER(now->tm_min);
r["seconds"] = INTEGER(now->tm_sec);
results.push_back(r);
return results;
}
}
}
```
Key points to remember:
- Your implementation function should be in the `osquery::tables` namespace.
- Your implementation function should accept on `QueryContext&` parameter and return an instance of `QueryData`
## Using where clauses
The `QueryContext` data type is osquery's abstraction of the underlying SQL engine's query parsing. It is defined in [include/osquery/tables.h](https://github.com/facebook/osquery/blob/master/include/osquery/tables.h).
The most important use of the context is query predicate constraints (e.g., `WHERE col = 'value'`). Some tables MUST have a predicate constraint, others may optionally use the constraints to increase performance.
Examples:
`hash` requires a predicate, since the resultant rows are the hashes of the EQUALS constraint operators (`=`). The table implementation includes:
```cpp
auto paths = context.constraints["path"].getAll(EQUALS);
for (const auto& path_string : paths) {
boost::filesystem::path path = path_string;
[...]
}
```
`processes` optionally uses a predicate. A syscall to list process pids requires few resources. Enumerating "/proc" information and parsing environment/argument uses MANY resources. The table implementation includes:
```cpp
for (auto &pid : pidlist) {
if (!context.constraints["pid"].matches<int>(pid)) {
// Optimize by not searching when a pid is a constraint.
continue;
}
[...]
}
```
## SQL data types
Data types like `QueryData`, `Row`, `DiffResults`, etc. are osquery's built-in data result types. They're all defined in [include/osquery/database/results.h](https://github.com/facebook/osquery/blob/master/include/osquery/database/results.h).
`Row` is just a `typedef` for a `std::map<std::string, std::string>`. That's it. A row of data is just a mapping of strings that represent column names to strings that represent column values. Note that, currently, even if your SQL table type is an `int` and not a `std::string`, we need to cast the ints as strings to comply with the type definition of the `Row` object. They'll be casted back to `int`'s later. This is all handled transparently by osquery's supporting infrastructure as long as you use the macros like `TEXT`, `INTEGER`, `BIGINT`, etc when inserting columns into your row.
`QueryData` is just a `typedef` for a `std::vector<Row>`. Query data is just a list of rows. Simple enough.
To populate the data that will be returned to the user at runtime, your implementation function must generate the data that you'd like to display and populate a `QueryData` map with the appropriate `Rows`. Then, just return the `QueryData`.
In our case, we used system APIs to create a struct of type `tm` which has fields such as `tm_hour`, `tm_min` and `tm_sec` which represent the current time. We can then create our three entries in our `Row` variable: hour, minutes and seconds. Then we push that single row onto the `QueryData` variable and return it. Note that if we wanted our table to have many rows (a more common use-case), we would just push back more `Row` maps onto `results`.
## Building new tables
If you've created a new file, you'll need to make sure that CMake properly builds your code. Open [osquery/tables/CMakeLists.txt](https://github.com/facebook/osquery/blob/master/osquery/tables/CMakeLists.txt). Find the line that defines the library `osquery_tables` and add your file, "utility/time.cpp" to the sources which are compiled by that library.
If your table only works on OS X, find the target called `osquery_tables_darwin` and add your file to that list of sources instead. If your table only works on Linux, find the target called `osquery_tables_linux` and add your implementation file to that list of sources.
Return to the root of the repository and execute `make`. This will generate the appropriate code and link everything properly.
### Testing your table
If your code compiled properly, launch the interactive query console by executing `./build/[darwin|linux]/osquery/osqueryi` and try issuing your new table a command: `SELECT * FROM time;`.
### Getting your query ready for use in osqueryd
You don't have to do anything to make your query work in the osqueryd daemon. All osquery queries work in osqueryd. It's worth noting, however, that osqueryd is a long-running process. If your table leaks memory or uses a lot of systems resources, you will notice poor performance from osqueryd. For more information on ensuring a performant table, see [performance overview](../deployment/performance-safety.md).
When in doubt, use existing open source tables to guide your development.
| sami2316/osquery | docs/wiki/development/creating-tables.md | Markdown | bsd-3-clause | 9,109 |
<!doctype html>
<!-- This file is generated by build.py. -->
<title>Reference for video 240x160.ogv; overflow:hidden; -o-object-fit:fill; -o-object-position:left 1em</title>
<link rel="stylesheet" href="../../support/reftests.css">
<style>
.helper { overflow:hidden }
.helper > * { left:0; top:1em; width:200px; height:200px }
</style>
<div id="ref">
<span class="helper"><img src="../../support/240x160.ogv.png"></span>
</div>
| frivoal/presto-testo | css/image-fit/reftests/video-ogg-wide/hidden_fill_left_1em-ref.html | HTML | bsd-3-clause | 431 |
##########################################################################
#
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
# Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import unittest
import fnmatch
import IECore
import Gaffer
import GafferUI
import GafferTest
import GafferUITest
class NoduleTest( GafferUITest.TestCase ) :
def test( self ) :
class NoduleTestNode( Gaffer.Node ) :
def __init__( self ) :
Gaffer.Node.__init__( self )
self.addChild(
Gaffer.IntPlug( "i" )
)
self.addChild(
Gaffer.Plug( "c" )
)
IECore.registerRunTimeTyped( NoduleTestNode )
n = NoduleTestNode()
ni = GafferUI.Nodule.create( n["i"] )
nc = GafferUI.Nodule.create( n["c"] )
self.failUnless( isinstance( ni, GafferUI.StandardNodule ) )
self.failUnless( isinstance( nc, GafferUI.StandardNodule ) )
Gaffer.Metadata.registerValue( NoduleTestNode, "c", "nodule:type", "GafferUI::CompoundNodule" )
nc = GafferUI.Nodule.create( n["c"] )
self.failUnless( isinstance( nc, GafferUI.CompoundNodule ) )
class NoduleTestNodeSubclass( NoduleTestNode ) :
def __init__( self ) :
NoduleTestNode.__init__( self )
n2 = NoduleTestNode()
nc2 = GafferUI.Nodule.create( n2["c"] )
self.failUnless( isinstance( nc2, GafferUI.CompoundNodule ) )
if __name__ == "__main__":
unittest.main()
| appleseedhq/gaffer | python/GafferUITest/NoduleTest.py | Python | bsd-3-clause | 3,031 |
# Copyright (c) 2008-2016 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""
Natural Neighbor Verification
=============================
Walks through the steps of Natural Neighbor interpolation to validate that the algorithmic
approach taken in MetPy is correct.
"""
###########################################
# Find natural neighbors visual test
#
# A triangle is a natural neighbor for a point if the
# `circumscribed circle <https://en.wikipedia.org/wiki/Circumscribed_circle>`_ of the
# triangle contains that point. It is important that we correctly grab the correct triangles
# for each point before proceeding with the interpolation.
#
# Algorithmically:
#
# 1. We place all of the grid points in a KDTree. These provide worst-case O(n) time
# complexity for spatial searches.
#
# 2. We generate a `Delaunay Triangulation <https://docs.scipy.org/doc/scipy/
# reference/tutorial/spatial.html#delaunay-triangulations>`_
# using the locations of the provided observations.
#
# 3. For each triangle, we calculate its circumcenter and circumradius. Using
# KDTree, we then assign each grid a triangle that has a circumcenter within a
# circumradius of the grid's location.
#
# 4. The resulting dictionary uses the grid index as a key and a set of natural
# neighbor triangles in the form of triangle codes from the Delaunay triangulation.
# This dictionary is then iterated through to calculate interpolation values.
#
# 5. We then traverse the ordered natural neighbor edge vertices for a particular
# grid cell in groups of 3 (n - 1, n, n + 1), and perform calculations to generate
# proportional polygon areas.
#
# Circumcenter of (n - 1), n, grid_location
# Circumcenter of (n + 1), n, grid_location
#
# Determine what existing circumcenters (ie, Delaunay circumcenters) are associated
# with vertex n, and add those as polygon vertices. Calculate the area of this polygon.
#
# 6. Increment the current edges to be checked, i.e.:
# n - 1 = n, n = n + 1, n + 1 = n + 2
#
# 7. Repeat steps 5 & 6 until all of the edge combinations of 3 have been visited.
#
# 8. Repeat steps 4 through 7 for each grid cell.
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import ConvexHull, Delaunay, delaunay_plot_2d, Voronoi, voronoi_plot_2d
from scipy.spatial.distance import euclidean
from metpy.gridding import polygons, triangles
from metpy.gridding.interpolation import nn_point
plt.rcParams['figure.figsize'] = (15, 10)
###########################################
# For a test case, we generate 10 random points and observations, where the
# observation values are just the x coordinate value times the y coordinate
# value divided by 1000.
#
# We then create two test points (grid 0 & grid 1) at which we want to
# estimate a value using natural neighbor interpolation.
#
# The locations of these observations are then used to generate a Delaunay triangulation.
np.random.seed(100)
pts = np.random.randint(0, 100, (10, 2))
xp = pts[:, 0]
yp = pts[:, 1]
zp = (pts[:, 0] * pts[:, 0]) / 1000
tri = Delaunay(pts)
delaunay_plot_2d(tri)
for i, zval in enumerate(zp):
plt.annotate('{} F'.format(zval), xy=(pts[i, 0] + 2, pts[i, 1]))
sim_gridx = [30., 60.]
sim_gridy = [30., 60.]
plt.plot(sim_gridx, sim_gridy, '+', markersize=10)
plt.axes().set_aspect('equal', 'datalim')
plt.title('Triangulation of observations and test grid cell '
'natural neighbor interpolation values')
members, tri_info = triangles.find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy)))
val = nn_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0], tri_info)
plt.annotate('grid 0: {:.3f}'.format(val), xy=(sim_gridx[0] + 2, sim_gridy[0]))
val = nn_point(xp, yp, zp, (sim_gridx[1], sim_gridy[1]), tri, members[1], tri_info)
plt.annotate('grid 1: {:.3f}'.format(val), xy=(sim_gridx[1] + 2, sim_gridy[1]))
###########################################
# Using the circumcenter and circumcircle radius information from
# :func:`metpy.gridding.triangles.find_natural_neighbors`, we can visually
# examine the results to see if they are correct.
def draw_circle(x, y, r, m, label):
nx = x + r * np.cos(np.deg2rad(list(range(360))))
ny = y + r * np.sin(np.deg2rad(list(range(360))))
plt.plot(nx, ny, m, label=label)
members, tri_info = triangles.find_natural_neighbors(tri, list(zip(sim_gridx, sim_gridy)))
delaunay_plot_2d(tri)
plt.plot(sim_gridx, sim_gridy, 'ks', markersize=10)
for i, info in tri_info.items():
x_t = info['cc'][0]
y_t = info['cc'][1]
if i in members[1] and i in members[0]:
draw_circle(x_t, y_t, info['r'], 'm-', str(i) + ': grid 1 & 2')
plt.annotate(str(i), xy=(x_t, y_t), fontsize=15)
elif i in members[0]:
draw_circle(x_t, y_t, info['r'], 'r-', str(i) + ': grid 0')
plt.annotate(str(i), xy=(x_t, y_t), fontsize=15)
elif i in members[1]:
draw_circle(x_t, y_t, info['r'], 'b-', str(i) + ': grid 1')
plt.annotate(str(i), xy=(x_t, y_t), fontsize=15)
else:
draw_circle(x_t, y_t, info['r'], 'k:', str(i) + ': no match')
plt.annotate(str(i), xy=(x_t, y_t), fontsize=9)
plt.axes().set_aspect('equal', 'datalim')
plt.legend()
###########################################
# What?....the circle from triangle 8 looks pretty darn close. Why isn't
# grid 0 included in that circle?
x_t, y_t = tri_info[8]['cc']
r = tri_info[8]['r']
print('Distance between grid0 and Triangle 8 circumcenter:',
euclidean([x_t, y_t], [sim_gridx[0], sim_gridy[0]]))
print('Triangle 8 circumradius:', r)
###########################################
# Lets do a manual check of the above interpolation value for grid 0 (southernmost grid)
# Grab the circumcenters and radii for natural neighbors
cc = np.array([tri_info[m]['cc'] for m in members[0]])
r = np.array([tri_info[m]['r'] for m in members[0]])
print('circumcenters:\n', cc)
print('radii\n', r)
###########################################
# Draw the natural neighbor triangles and their circumcenters. Also plot a `Voronoi diagram
# <https://docs.scipy.org/doc/scipy/reference/tutorial/spatial.html#voronoi-diagrams>`_
# which serves as a complementary (but not necessary)
# spatial data structure that we use here simply to show areal ratios.
# Notice that the two natural neighbor triangle circumcenters are also vertices
# in the Voronoi plot (green dots), and the observations are in the the polygons (blue dots).
vor = Voronoi(list(zip(xp, yp)))
voronoi_plot_2d(vor)
nn_ind = np.array([0, 5, 7, 8])
z_0 = zp[nn_ind]
x_0 = xp[nn_ind]
y_0 = yp[nn_ind]
for x, y, z in zip(x_0, y_0, z_0):
plt.annotate('{}, {}: {:.3f} F'.format(x, y, z), xy=(x, y))
plt.plot(sim_gridx[0], sim_gridy[0], 'k+', markersize=10)
plt.annotate('{}, {}'.format(sim_gridx[0], sim_gridy[0]), xy=(sim_gridx[0] + 2, sim_gridy[0]))
plt.plot(cc[:, 0], cc[:, 1], 'ks', markersize=15, fillstyle='none',
label='natural neighbor\ncircumcenters')
for center in cc:
plt.annotate('{:.3f}, {:.3f}'.format(center[0], center[1]),
xy=(center[0] + 1, center[1] + 1))
tris = tri.points[tri.simplices[members[0]]]
for triangle in tris:
x = [triangle[0, 0], triangle[1, 0], triangle[2, 0], triangle[0, 0]]
y = [triangle[0, 1], triangle[1, 1], triangle[2, 1], triangle[0, 1]]
plt.plot(x, y, ':', linewidth=2)
plt.legend()
plt.axes().set_aspect('equal', 'datalim')
def draw_polygon_with_info(polygon, off_x=0, off_y=0):
"""Draw one of the natural neighbor polygons with some information."""
pts = np.array(polygon)[ConvexHull(polygon).vertices]
for i, pt in enumerate(pts):
plt.plot([pt[0], pts[(i + 1) % len(pts)][0]],
[pt[1], pts[(i + 1) % len(pts)][1]], 'k-')
avex, avey = np.mean(pts, axis=0)
plt.annotate('area: {:.3f}'.format(polygons.area(pts)), xy=(avex + off_x, avey + off_y),
fontsize=12)
cc1 = triangles.circumcenter((53, 66), (15, 60), (30, 30))
cc2 = triangles.circumcenter((34, 24), (53, 66), (30, 30))
draw_polygon_with_info([cc[0], cc1, cc2])
cc1 = triangles.circumcenter((53, 66), (15, 60), (30, 30))
cc2 = triangles.circumcenter((15, 60), (8, 24), (30, 30))
draw_polygon_with_info([cc[0], cc[1], cc1, cc2], off_x=-9, off_y=3)
cc1 = triangles.circumcenter((8, 24), (34, 24), (30, 30))
cc2 = triangles.circumcenter((15, 60), (8, 24), (30, 30))
draw_polygon_with_info([cc[1], cc1, cc2], off_x=-15)
cc1 = triangles.circumcenter((8, 24), (34, 24), (30, 30))
cc2 = triangles.circumcenter((34, 24), (53, 66), (30, 30))
draw_polygon_with_info([cc[0], cc[1], cc1, cc2])
###########################################
# Put all of the generated polygon areas and their affiliated values in arrays.
# Calculate the total area of all of the generated polygons.
areas = np.array([60.434, 448.296, 25.916, 70.647])
values = np.array([0.064, 1.156, 2.809, 0.225])
total_area = np.sum(areas)
print(total_area)
###########################################
# For each polygon area, calculate its percent of total area.
proportions = areas / total_area
print(proportions)
###########################################
# Multiply the percent of total area by the respective values.
contributions = proportions * values
print(contributions)
###########################################
# The sum of this array is the interpolation value!
interpolation_value = np.sum(contributions)
function_output = nn_point(xp, yp, zp, (sim_gridx[0], sim_gridy[0]), tri, members[0], tri_info)
print(interpolation_value, function_output)
###########################################
# The values are slightly different due to truncating the area values in
# the above visual example to the 3rd decimal place.
| metpy/MetPy | v0.5/_downloads/Natural_Neighbor_Verification.py | Python | bsd-3-clause | 9,759 |
package org.javasimon;
/**
* Counter tracks the single integer value and watches its max/min values. It can be used
* for values starting with 0 - in that case min might not be important if counter does not
* go bellow 0. Counter can also start from any other arbitrary number that is set after the
* first change (increment, decrement, set) - this is more typical case for tracking also the
* min value.
* <p/>
* <h3>Initialization</h3>
* When a counter is created, it is set to 0, but its maximum/minimum values are undefined:
* <pre>
* Counter counter = SimonManager.getCounter("com.my.counter");
* System.out.println("counter = " + counter);</pre>
* Output is:
* <pre>
* counter = Simon Counter: [com.my.counter INHERIT] counter=0, max=undef, min=undef</pre>
*
* This behavior allows the counter to be initialized before it is used and its extremes are
* tracked - first initialization also sets max/min (extreme) values:
* <pre>
* Counter counter = SimonManager.getCounter("com.my.counter").set(47);
* System.out.println("counter = " + counter);</pre>
* Output is:
* <pre>
* counter = Simon Counter: [com.my.counter INHERIT] counter=47, max=47, min=47</pre>
*
* <h3>Usage</h3>
* Typical Counter usage is based on {@link #increase()} and {@link #decrease()} methods when
* it is possible to track the monitored value - this can be used for example to count users logged
* in. If the value changes by more than 1 than it is possible to use methods with arguments -
* {@link #increase(long)} and {@link #decrease(long)}. Finally method {@link #set(long)} is
* always available to set the counter to the particular value when needed.
*
* @author <a href="mailto:[email protected]">Richard "Virgo" Richter</a>
*/
public interface Counter extends Simon {
/**
* Increments the counter by one.
*
* @return this
*/
Counter increase();
/**
* Decrements the counter by one.
*
* @return this
*/
Counter decrease();
/**
* Increments the counter by the specified value. Using negative values is possible but may provide
* unexpected results - this method updates only incrementSum, it is decreased when negative number is used.
* Min and max are updated as expected.
*
* @param inc added value
* @return this
*/
Counter increase(long inc);
/**
* Increments the counter by the specified value. Using negative values is possible but may provide
* unexpected results - this method updates only decrementSum, it is decreased when negative number is used.
* Min and max are updated as expected.
*
* @param dec subtracted value
* @return this
*/
Counter decrease(long dec);
/**
* Returns the current value of the counter.
*
* @return counter value
*/
long getCounter();
/**
* Returns minimal value of counter. Updated by {@link #decrease()}, {@link #decrease(long)} and {@link #set(long)}.
*
* @return maximal reached value
*/
long getMin();
/**
* Returns ms timestamp when the min value was reached.
*
* @return ms timestamp of the min value decremented
*/
long getMinTimestamp();
/**
* Returns maximal value of counter. Updated by {@link #increase()}, {@link #increase(long)} and {@link #set(long)}.
*
* @return maximal reached value
*/
long getMax();
/**
* Returns ms timestamp when the max value was reached.
*
* @return ms timestamp of the max value incremented
*/
long getMaxTimestamp();
/**
* Sets the value of the counter to specified value.
*
* @param val new counter value
* @return this
*/
Counter set(long val);
/**
* Returns the sum of all incremented values. If incremented value was negative, sum
* is lowered by this value.
*
* @return sum of all incremented values
*/
long getIncrementSum();
/**
* Returns the sum of all decremented values (as a positive number). If decremented value was negative, sum
* is lowered by this value.
*
* @return sum of all decremented values
*/
long getDecrementSum();
@Override
CounterSample sample();
CounterSample sampleIncrement(Object key);
CounterSample sampleIncrementNoReset(Object key);
}
| dqVM/javasimon-DQ | core/src/main/java/org/javasimon/Counter.java | Java | bsd-3-clause | 4,121 |
<html>
<head>
<title>GB18030 lead 813991</title>
<meta http-equiv='content-type' content='text/html;charset=GB18030'>
<link rel='stylesheet' href='tests.css'>
</head>
<body>
<table>
<caption>Four-byte lead 813991</caption>
<tr><th colspan=2>GB18030<th colspan=3>Unicode
<tr><td>=81399130<td> 90 <td>U+2F3A<td>⼺<td class=u>KANGXI RADICAL BRISTLE
<tr><td>=81399131<td> 91 <td>U+2F3B<td>⼻<td class=u>KANGXI RADICAL STEP
<tr><td>=81399132<td> 92 <td>U+2F3C<td>⼼<td class=u>KANGXI RADICAL HEART
<tr><td>=81399133<td> 93 <td>U+2F3D<td>⼽<td class=u>KANGXI RADICAL HALBERD
<tr><td>=81399134<td> 94 <td>U+2F3E<td>⼾<td class=u>KANGXI RADICAL DOOR
<tr><td>=81399135<td> 95 <td>U+2F3F<td>⼿<td class=u>KANGXI RADICAL HAND
<tr><td>=81399136<td> 96 <td>U+2F40<td>⽀<td class=u>KANGXI RADICAL BRANCH
<tr><td>=81399137<td> 97 <td>U+2F41<td>⽁<td class=u>KANGXI RADICAL RAP
<tr><td>=81399138<td> 98 <td>U+2F42<td>⽂<td class=u>KANGXI RADICAL SCRIPT
<tr><td>=81399139<td> 99 <td>U+2F43<td>⽃<td class=u>KANGXI RADICAL DIPPER
</table>
<p><a href='charset/GB18030.html'>Return</a></p>
</body>
</html>
| frivoal/presto-testo | imported/peter/unicode/comparative/GB18030-813991.html | HTML | bsd-3-clause | 1,218 |
/* Copyright (c) 2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.ql.cli;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.locationtech.geogig.model.NodeRef;
import org.locationtech.geogig.plumbing.LsTreeOp;
import org.locationtech.geogig.plumbing.LsTreeOp.Strategy;
import org.locationtech.geogig.porcelain.CommitOp;
import org.locationtech.geogig.ql.porcelain.QLDelete;
import org.locationtech.geogig.repository.DiffObjectCount;
import org.locationtech.geogig.test.integration.RepositoryTestCase;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
public class QLDeleteIntegrationTest extends RepositoryTestCase {
@Rule
public ExpectedException exception = ExpectedException.none();
@Override
public void setUpInternal() throws Exception {
insertAndAdd(points1);
insertAndAdd(points2);
insertAndAdd(lines1);
insertAndAdd(lines2);
geogig.command(CommitOp.class).call();
insertAndAdd(points3);
insertAndAdd(lines3);
insertAndAdd(points1_modified);
geogig.command(CommitOp.class).call();
}
private Supplier<DiffObjectCount> delete(String query) {
return geogig.command(QLDelete.class).setStatement(query).call();
}
@Test
public void simpleDelete() {
DiffObjectCount res = delete("delete from Points").get();
assertEquals(3, res.getFeaturesRemoved());
assertEquals(ImmutableSet.of(), lsTree("WORK_HEAD:Points"));
assertEquals(ImmutableSet.of(idP1, idP2, idP3), lsTree("STAGE_HEAD:Points"));
assertEquals(ImmutableSet.of(idP1, idP2, idP3), lsTree("HEAD:Points"));
}
@Test
public void simpleFidFilterDelete() {
DiffObjectCount res = delete("delete from Points where @id = 'Points.3'").get();
assertEquals(1, res.getFeaturesRemoved());
assertEquals(ImmutableSet.of(idP1, idP2), lsTree("WORK_HEAD:Points"));
assertEquals(ImmutableSet.of(idP1, idP2, idP3), lsTree("STAGE_HEAD:Points"));
assertEquals(ImmutableSet.of(idP1, idP2, idP3), lsTree("HEAD:Points"));
}
public Set<String> lsTree(String treeIsh) {
List<NodeRef> nodes = Lists.newArrayList(geogig.command(LsTreeOp.class)
.setReference(treeIsh).setStrategy(Strategy.DEPTHFIRST_ONLY_FEATURES).call());
Set<String> ids = new HashSet<>(Lists.transform(nodes, (n) -> n.name()));
return ids;
}
}
| jdgarrett/geogig | src/ql/src/test/java/org/locationtech/geogig/ql/cli/QLDeleteIntegrationTest.java | Java | bsd-3-clause | 2,960 |
require 'spec_helper'
require 'cancan/matchers'
require 'spree/testing_support/ability_helpers'
require 'spree/testing_support/bar_ability'
# Fake ability for testing registration of additional abilities
class FooAbility
include CanCan::Ability
def initialize(_user)
# allow anyone to perform index on Order
can :index, Spree::Order
# allow anyone to update an Order with id of 1
can :update, Spree::Order do |order|
order.id == 1
end
end
end
describe Spree::Ability, type: :model do
let(:user) { build(:user) }
let(:ability) { Spree::Ability.new(user) }
let(:token) { nil }
after(:each) do
Spree::Ability.abilities = Set.new
end
context 'register_ability' do
it 'should add the ability to the list of abilties' do
Spree::Ability.register_ability(FooAbility)
expect(Spree::Ability.new(user).abilities).not_to be_empty
end
it 'should apply the registered abilities permissions' do
Spree::Ability.register_ability(FooAbility)
expect(Spree::Ability.new(user).can?(:update, mock_model(Spree::Order, id: 1))).to be true
end
end
context '#abilities_to_register' do
it 'adds the ability to the list of abilities' do
allow_any_instance_of(Spree::Ability).to receive(:abilities_to_register) { [FooAbility] }
expect(Spree::Ability.new(user).abilities).to include FooAbility
end
it 'applies the registered abilities permissions' do
allow_any_instance_of(Spree::Ability).to receive(:abilities_to_register) { [FooAbility] }
expect(Spree::Ability.new(user).can?(:update, mock_model(Spree::Order, id: 1))).to be true
end
end
context 'for general resource' do
let(:resource) { Object.new }
context 'with admin user' do
before(:each) { allow(user).to receive(:has_spree_role?).and_return(true) }
it_should_behave_like 'access granted'
it_should_behave_like 'index allowed'
end
context 'with customer' do
it_should_behave_like 'access denied'
it_should_behave_like 'no index allowed'
end
end
context 'for admin protected resources' do
let(:resource) { Object.new }
let(:resource_shipment) { Spree::Shipment.new }
let(:resource_product) { Spree::Product.new }
let(:resource_user) { create :user }
let(:resource_order) { Spree::Order.new }
let(:fakedispatch_user) { Spree.user_class.create }
let(:fakedispatch_ability) { Spree::Ability.new(fakedispatch_user) }
context 'with admin user' do
it 'should be able to admin' do
user.spree_roles << Spree::Role.find_or_create_by(name: 'admin')
expect(ability).to be_able_to :admin, resource
expect(ability).to be_able_to :index, resource_order
expect(ability).to be_able_to :show, resource_product
expect(ability).to be_able_to :create, resource_user
end
end
context 'with fakedispatch user' do
it 'should be able to admin on the order and shipment pages' do
user.spree_roles << Spree::Role.find_or_create_by(name: 'bar')
Spree::Ability.register_ability(BarAbility)
expect(ability).not_to be_able_to :admin, resource
expect(ability).to be_able_to :admin, resource_order
expect(ability).to be_able_to :index, resource_order
expect(ability).not_to be_able_to :update, resource_order
# ability.should_not be_able_to :create, resource_order # Fails
expect(ability).to be_able_to :admin, resource_shipment
expect(ability).to be_able_to :index, resource_shipment
expect(ability).to be_able_to :create, resource_shipment
expect(ability).not_to be_able_to :admin, resource_product
expect(ability).not_to be_able_to :update, resource_product
# ability.should_not be_able_to :show, resource_product # Fails
expect(ability).not_to be_able_to :admin, resource_user
expect(ability).not_to be_able_to :update, resource_user
expect(ability).to be_able_to :update, user
# ability.should_not be_able_to :create, resource_user # Fails
# It can create new users if is has access to the :admin, User!!
# TODO: change the Ability class so only users and customers get the extra premissions?
Spree::Ability.remove_ability(BarAbility)
end
end
context 'with customer' do
it 'should not be able to admin' do
expect(ability).not_to be_able_to :admin, resource
expect(ability).not_to be_able_to :admin, resource_order
expect(ability).not_to be_able_to :admin, resource_product
expect(ability).not_to be_able_to :admin, resource_user
end
end
end
context 'as Guest User' do
context 'for Country' do
let(:resource) { Spree::Country.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for OptionType' do
let(:resource) { Spree::OptionType.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for OptionValue' do
let(:resource) { Spree::OptionType.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Order' do
let(:resource) { Spree::Order.new }
context 'requested by same user' do
before(:each) { resource.user = user }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested by other user' do
before(:each) { resource.user = Spree.user_class.new }
it_should_behave_like 'create only'
end
context 'requested with proper token' do
let(:token) { 'TOKEN123' }
before(:each) { allow(resource).to receive_messages guest_token: token }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested with inproper token' do
let(:token) { 'FAIL' }
before(:each) { allow(resource).to receive_messages guest_token: token }
it_should_behave_like 'create only'
end
end
context 'for Product' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for ProductProperty' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Property' do
let(:resource) { Spree::Product.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for State' do
let(:resource) { Spree::State.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Taxons' do
let(:resource) { Spree::Taxon.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Taxonomy' do
let(:resource) { Spree::Taxonomy.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for User' do
context 'requested by same user' do
let(:resource) { user }
it_should_behave_like 'access granted'
it_should_behave_like 'no index allowed'
end
context 'requested by other user' do
let(:resource) { create(:user) }
it_should_behave_like 'create only'
end
end
context 'for Variant' do
let(:resource) { Spree::Variant.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
context 'for Zone' do
let(:resource) { Spree::Zone.new }
context 'requested by any user' do
it_should_behave_like 'read only'
end
end
end
end
| vinayvinsol/spree | core/spec/models/spree/ability_spec.rb | Ruby | bsd-3-clause | 7,925 |
---
title: Number Sequence Game
localeTitle: Игра с числовой последовательностью
---
## Проблема 477: Игра с порядковым номером
Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-477-number-sequence-game/index.md) .
[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) . | otavioarc/freeCodeCamp | guide/russian/certifications/coding-interview-prep/project-euler/problem-477-number-sequence-game/index.md | Markdown | bsd-3-clause | 652 |
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkNodeDepententPointSetInteractor.h"
#include "mitkPointSet.h"
#include "mitkPositionEvent.h"
#include "mitkVtkPropRenderer.h"
#include "mitkStateEvent.h"
#include "mitkInteractionConst.h"
#include "mitkGlobalInteraction.h"
#include "mitkPointOperation.h"
#include "mitkTestingMacros.h"
#include "mitkStandaloneDataStorage.h"
#include "mitkStandardFileLocations.h"
#include "mitkNodePredicateDataType.h"
#include "mitkIOUtil.h"
void SendPositionEvent(mitk::BaseRenderer* sender, int type, int button, int buttonState, int key, const mitk::Point2D& displPosition, const mitk::Point3D& worldPosition)
{
mitk::Event *posEvent = new mitk::PositionEvent(sender, type, button, buttonState, key, displPosition, worldPosition);
mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(posEvent);
delete posEvent;
}
//test related to tutorial Step5.cpp
int mitkNodeDependentPointSetInteractorTest(int argc, char* argv[])
{
MITK_TEST_BEGIN("NodeDependentPointSetInteractor");
// Global interaction must(!) be initialized if used
mitk::GlobalInteraction::GetInstance()->Initialize("global");
// Create a DataStorage
mitk::StandaloneDataStorage::Pointer ds = mitk::StandaloneDataStorage::New();
MITK_TEST_CONDITION_REQUIRED(ds.IsNotNull(),"Instantiating DataStorage");
//read two images and store to datastorage
//these two images are used as node the interactors depend on. If the visibility property of one node if false, the
//associated interactor may not change the data
mitk::DataNode::Pointer node1, node2;
MITK_TEST_CONDITION_REQUIRED(argc >= 3, "Test if a files to load has been specified");
try
{
//file 1
const std::string filename1 = argv[1];
node1 = mitk::IOUtil::Load(filename1, *ds)->GetElement(0);
//file 2
const std::string filename2 = argv[2];
node2 = mitk::IOUtil::Load(filename2, *ds)->GetElement(0);
}
catch(...) {
MITK_TEST_FAILED_MSG(<< "Could not read file for testing");
return EXIT_FAILURE;
}
//check for the two images
mitk::NodePredicateDataType::Pointer predicate(mitk::NodePredicateDataType::New("Image"));
mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDS = ds->GetSubset(predicate);
MITK_TEST_CONDITION_REQUIRED(allImagesInDS->Size()==2,"load images to data storage");
// Create PointSet and a node for it
mitk::PointSet::Pointer pointSet1 = mitk::PointSet::New();
mitk::DataNode::Pointer pointSetNode1 = mitk::DataNode::New();
pointSetNode1->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 1.0f, 0.0f));
pointSetNode1->SetData(pointSet1);
mitk::NodeDepententPointSetInteractor::Pointer interactor1 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode1, node1);
MITK_TEST_CONDITION_REQUIRED(interactor1.IsNotNull(),"Instanciating NodeDependentPointSetInteractor");
// Add the node to the tree
ds->Add(pointSetNode1);
mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor1);
mitk::PointSet::Pointer pointSet2 = mitk::PointSet::New();
mitk::DataNode::Pointer pointSetNode2 = mitk::DataNode::New();
pointSetNode2->AddProperty( "unselectedcolor", mitk::ColorProperty::New(0.0f, 0.0f, 1.0f));
pointSetNode2->SetData(pointSet2);
mitk::NodeDepententPointSetInteractor::Pointer interactor2 = mitk::NodeDepententPointSetInteractor::New("pointsetinteractor", pointSetNode2, node2);
MITK_TEST_CONDITION_REQUIRED(interactor2.IsNotNull(),"Instanciating NodeDependentPointSetInteractor");
// Add the node to the tree
ds->Add(pointSetNode2);
mitk::GlobalInteraction::GetInstance()->AddInteractor(interactor2);
//check for the two pointsets
mitk::NodePredicateDataType::Pointer predicatePS(mitk::NodePredicateDataType::New("PointSet"));
mitk::DataStorage::SetOfObjects::ConstPointer allImagesInDSPS = ds->GetSubset(predicatePS);
MITK_TEST_CONDITION_REQUIRED(allImagesInDSPS->Size()==2,"create associated pointsets to data storage");
//create two RenderWindows
mitk::RenderingManager::Pointer myRenderingManager = mitk::RenderingManager::New();
vtkRenderWindow* vtkRenWin1 = vtkRenderWindow::New();
mitk::VtkPropRenderer::Pointer br1 = mitk::VtkPropRenderer::New("testingBR1", vtkRenWin1, myRenderingManager);
mitk::BaseRenderer::AddInstance(vtkRenWin1,br1);
myRenderingManager->AddRenderWindow(vtkRenWin1);
mitk::BaseRenderer::Pointer renderer1 = mitk::BaseRenderer::GetInstance(vtkRenWin1);
vtkRenderWindow* vtkRenWin2 = vtkRenderWindow::New();
mitk::VtkPropRenderer::Pointer br2 = mitk::VtkPropRenderer::New("testingBR2", vtkRenWin2, myRenderingManager);
mitk::BaseRenderer::AddInstance(vtkRenWin2,br2);
myRenderingManager->AddRenderWindow(vtkRenWin2);
mitk::BaseRenderer::Pointer renderer2 = mitk::BaseRenderer::GetInstance(vtkRenWin2);
//set properties for renderWindow 1 and 2
//1:
node1->SetBoolProperty("visible", true, renderer1);
node2->SetBoolProperty("visible", false, renderer1);
//2:
node1->SetBoolProperty("visible", false, renderer2);
node2->SetBoolProperty("visible", true, renderer2);
//***************************************************
//now start to test if only an event send from renderwindow 1 can interact with interactor 1 and vice versa
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"Checking empty pointset 2.");
//sending an event to interactor1
mitk::Point3D pos3D;
mitk::Point2D pos2D;
pos3D[0]= 10.0; pos3D[1]= 20.0; pos3D[2]= 30.0;
pos2D[0]= 100; pos2D[0]= 200;
//add to pointset 1
SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"1 Checking addition of point to pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==0,"2 Checking empty pointset 2");
//add to pointset 2
SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"3 Checking untouched state of pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"4 Checking addition of point to pointset 2");
//add to pointset 2
SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"5 Checking untouched state of pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"6 Checking addition of point to pointset 2");
//add to pointset 2
SendPositionEvent(renderer2, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"7 Checking untouched state of pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"8 Checking addition of point to pointset 2");
//add to pointset 1
SendPositionEvent(renderer1, mitk::Type_MouseButtonPress, mitk::BS_LeftButton, mitk::BS_ShiftButton, mitk::Key_none, pos2D, pos3D);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"9 Checking addition of point to pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==3,"10 Checking untouched state of pointset 2");
//trying to delete points
mitk::Event* delEvent1 = new mitk::Event(renderer1, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete);
mitk::Event* delEvent2 = new mitk::Event(renderer2, mitk::Type_KeyPress, mitk::BS_NoButton, mitk::BS_NoButton, mitk::Key_Delete);
mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==2,"11 Checking untouched state of pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking detected point in pointset 2");
mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent1);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"11 Checking deleted point in pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==2,"12 Checking untouched state of pointset 2");
mitk::GlobalInteraction::GetInstance()->GetEventMapper()->MapEvent(delEvent2);
MITK_TEST_CONDITION_REQUIRED(pointSet1->GetPointSet()->GetNumberOfPoints()==1,"13 Checking untouched state of pointset 1");
MITK_TEST_CONDITION_REQUIRED(pointSet2->GetPointSet()->GetNumberOfPoints()==1,"14 Checking detected point in pointset 2");
mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor1);
mitk::GlobalInteraction::GetInstance()->RemoveInteractor(interactor2);
delete delEvent1;
delete delEvent2;
myRenderingManager->RemoveRenderWindow(vtkRenWin1);
myRenderingManager->RemoveRenderWindow(vtkRenWin2);
vtkRenWin1->Delete();
vtkRenWin2->Delete();
//destroy RenderingManager
myRenderingManager = NULL;
MITK_TEST_END()
}
| ireicht/MITK-CSI | Modules/Core/test/mitkNodeDependentPointSetInteractorTest.cpp | C++ | bsd-3-clause | 9,877 |
using System.Web;
namespace NServiceKit.MiniProfiler
{
/// <summary>
/// Identifies users based on ip address.
/// </summary>
public class IpAddressIdentity : IUserProvider
{
/// <summary>
/// Returns the paramter HttpRequest's client ip address.
/// </summary>
public string GetUser(HttpRequest request)
{
return request.ServerVariables["REMOTE_ADDR"] ?? "";
}
}
}
| MindTouch/NServiceKit | src/NServiceKit/MiniProfiler/IpAddressProvider.cs | C# | bsd-3-clause | 454 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Workbench.Views
{
/// <summary>
/// Interaction logic for ChessboardView.xaml
/// </summary>
public partial class ChessboardView : UserControl
{
public ChessboardView()
{
InitializeComponent();
}
}
}
| digitalbricklayer/workbench | src/Workbench.UI/Views/ChessboardView.xaml.cs | C# | bsd-3-clause | 656 |
/*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.imagepipeline.cache;
import com.facebook.cache.common.CacheKey;
/**
* Interface for stats tracking for the image cache.
*
* <p>An implementation of this interface, passed to
* {@link com.facebook.imagepipeline.core.ImagePipelineConfig}, will be notified for each
* of the following cache events. Use this to keep cache stats for your app.
*/
public interface ImageCacheStatsTracker {
/** Called whenever decoded images are put into the bitmap cache. */
void onBitmapCachePut();
/** Called on a bitmap cache hit. */
void onBitmapCacheHit(CacheKey cacheKey);
/** Called on a bitmap cache miss. */
void onBitmapCacheMiss();
/** Called whenever encoded images are put into the encoded memory cache. */
void onMemoryCachePut();
/** Called on an encoded memory cache hit. */
void onMemoryCacheHit(CacheKey cacheKey);
/** Called on an encoded memory cache hit. */
void onMemoryCacheMiss();
/**
* Called on an staging area hit.
*
* <p>The staging area stores encoded images. It gets the images before they are written
* to disk cache.
*/
void onStagingAreaHit(CacheKey cacheKey);
/** Called on a staging area miss hit. */
void onStagingAreaMiss();
/** Called on a disk cache hit. */
void onDiskCacheHit();
/** Called on a disk cache miss. */
void onDiskCacheMiss();
/** Called if an exception is thrown on a disk cache read. */
void onDiskCacheGetFail();
/**
* Registers a bitmap cache with this tracker.
*
* <p>Use this method if you need access to the cache itself to compile your stats.
*/
void registerBitmapMemoryCache(CountingMemoryCache<?, ?> bitmapMemoryCache);
/**
* Registers an encoded memory cache with this tracker.
*
* <p>Use this method if you need access to the cache itself to compile your stats.
*/
void registerEncodedMemoryCache(CountingMemoryCache<?, ?> encodedMemoryCache);
}
| MaTriXy/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/cache/ImageCacheStatsTracker.java | Java | bsd-3-clause | 2,232 |
<!DOCTYPE html>
<title>DSK-375732 - http static link element with META element turning prefetching off</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<style>
img{
width:16px;
height:16px;
}
#messages{
position:absolute;
bottom:10px;
height:30%;
overflow:auto;
}
</style>
<script src="res/test.js"></script>
<script>setProtocol(false);</script>
<body>
<?php
$prefix = preg_replace("/\.|:/","x",$_SERVER['REMOTE_ADDR']);
$address = array($prefix.'code'.rand(0,1000000).'.prefetch.osa');
echo '<meta http-equiv="x-dns-prefetch-control" content="off">';
foreach($address as $ad)
echo '<link rel="dns-prefetch" href="http://'.$ad.'/">';
echo '<script>check_dns('.json_encode($address).',0);</script>';
?>
<div id="messages"></div>
</body>
| frivoal/presto-testo | core/standards/DSK-375732/static-link-with-meta-http.php | PHP | bsd-3-clause | 826 |
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "src/core/ext/transport/chttp2/transport/bin_encoder.h"
#include <string.h>
/* This is here for grpc_is_binary_header
* TODO(murgatroid99): Remove this
*/
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include "src/core/lib/slice/slice_string_helpers.h"
#include "src/core/lib/support/string.h"
static int all_ok = 1;
static void expect_slice_eq(grpc_slice expected, grpc_slice slice, char *debug,
int line) {
if (0 != grpc_slice_cmp(slice, expected)) {
char *hs = grpc_dump_slice(slice, GPR_DUMP_HEX | GPR_DUMP_ASCII);
char *he = grpc_dump_slice(expected, GPR_DUMP_HEX | GPR_DUMP_ASCII);
gpr_log(GPR_ERROR, "FAILED:%d: %s\ngot: %s\nwant: %s", line, debug, hs,
he);
gpr_free(hs);
gpr_free(he);
all_ok = 0;
}
grpc_slice_unref(expected);
grpc_slice_unref(slice);
}
static grpc_slice B64(const char *s) {
grpc_slice ss = grpc_slice_from_copied_string(s);
grpc_slice out = grpc_chttp2_base64_encode(ss);
grpc_slice_unref(ss);
return out;
}
static grpc_slice HUFF(const char *s) {
grpc_slice ss = grpc_slice_from_copied_string(s);
grpc_slice out = grpc_chttp2_huffman_compress(ss);
grpc_slice_unref(ss);
return out;
}
#define EXPECT_SLICE_EQ(expected, slice) \
expect_slice_eq( \
grpc_slice_from_copied_buffer(expected, sizeof(expected) - 1), slice, \
#slice, __LINE__);
static void expect_combined_equiv(const char *s, size_t len, int line) {
grpc_slice input = grpc_slice_from_copied_buffer(s, len);
grpc_slice base64 = grpc_chttp2_base64_encode(input);
grpc_slice expect = grpc_chttp2_huffman_compress(base64);
grpc_slice got = grpc_chttp2_base64_encode_and_huffman_compress_impl(input);
if (0 != grpc_slice_cmp(expect, got)) {
char *t = grpc_dump_slice(input, GPR_DUMP_HEX | GPR_DUMP_ASCII);
char *e = grpc_dump_slice(expect, GPR_DUMP_HEX | GPR_DUMP_ASCII);
char *g = grpc_dump_slice(got, GPR_DUMP_HEX | GPR_DUMP_ASCII);
gpr_log(GPR_ERROR, "FAILED:%d:\ntest: %s\ngot: %s\nwant: %s", line, t, g,
e);
gpr_free(t);
gpr_free(e);
gpr_free(g);
all_ok = 0;
}
grpc_slice_unref(input);
grpc_slice_unref(base64);
grpc_slice_unref(expect);
grpc_slice_unref(got);
}
#define EXPECT_COMBINED_EQUIV(x) \
expect_combined_equiv(x, sizeof(x) - 1, __LINE__)
static void expect_binary_header(const char *hdr, int binary) {
if (grpc_is_binary_header(hdr, strlen(hdr)) != binary) {
gpr_log(GPR_ERROR, "FAILED: expected header '%s' to be %s", hdr,
binary ? "binary" : "not binary");
all_ok = 0;
}
}
int main(int argc, char **argv) {
/* Base64 test vectors from RFC 4648, with padding removed */
/* BASE64("") = "" */
EXPECT_SLICE_EQ("", B64(""));
/* BASE64("f") = "Zg" */
EXPECT_SLICE_EQ("Zg", B64("f"));
/* BASE64("fo") = "Zm8" */
EXPECT_SLICE_EQ("Zm8", B64("fo"));
/* BASE64("foo") = "Zm9v" */
EXPECT_SLICE_EQ("Zm9v", B64("foo"));
/* BASE64("foob") = "Zm9vYg" */
EXPECT_SLICE_EQ("Zm9vYg", B64("foob"));
/* BASE64("fooba") = "Zm9vYmE" */
EXPECT_SLICE_EQ("Zm9vYmE", B64("fooba"));
/* BASE64("foobar") = "Zm9vYmFy" */
EXPECT_SLICE_EQ("Zm9vYmFy", B64("foobar"));
EXPECT_SLICE_EQ("wMHCw8TF", B64("\xc0\xc1\xc2\xc3\xc4\xc5"));
/* Huffman encoding tests */
EXPECT_SLICE_EQ("\xf1\xe3\xc2\xe5\xf2\x3a\x6b\xa0\xab\x90\xf4\xff",
HUFF("www.example.com"));
EXPECT_SLICE_EQ("\xa8\xeb\x10\x64\x9c\xbf", HUFF("no-cache"));
EXPECT_SLICE_EQ("\x25\xa8\x49\xe9\x5b\xa9\x7d\x7f", HUFF("custom-key"));
EXPECT_SLICE_EQ("\x25\xa8\x49\xe9\x5b\xb8\xe8\xb4\xbf", HUFF("custom-value"));
EXPECT_SLICE_EQ("\xae\xc3\x77\x1a\x4b", HUFF("private"));
EXPECT_SLICE_EQ(
"\xd0\x7a\xbe\x94\x10\x54\xd4\x44\xa8\x20\x05\x95\x04\x0b\x81\x66\xe0\x82"
"\xa6\x2d\x1b\xff",
HUFF("Mon, 21 Oct 2013 20:13:21 GMT"));
EXPECT_SLICE_EQ(
"\x9d\x29\xad\x17\x18\x63\xc7\x8f\x0b\x97\xc8\xe9\xae\x82\xae\x43\xd3",
HUFF("https://www.example.com"));
/* Various test vectors for combined encoding */
EXPECT_COMBINED_EQUIV("");
EXPECT_COMBINED_EQUIV("f");
EXPECT_COMBINED_EQUIV("fo");
EXPECT_COMBINED_EQUIV("foo");
EXPECT_COMBINED_EQUIV("foob");
EXPECT_COMBINED_EQUIV("fooba");
EXPECT_COMBINED_EQUIV("foobar");
EXPECT_COMBINED_EQUIV("www.example.com");
EXPECT_COMBINED_EQUIV("no-cache");
EXPECT_COMBINED_EQUIV("custom-key");
EXPECT_COMBINED_EQUIV("custom-value");
EXPECT_COMBINED_EQUIV("private");
EXPECT_COMBINED_EQUIV("Mon, 21 Oct 2013 20:13:21 GMT");
EXPECT_COMBINED_EQUIV("https://www.example.com");
EXPECT_COMBINED_EQUIV(
"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f"
"\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f"
"\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f"
"\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f"
"\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f"
"\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f"
"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f"
"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f"
"\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf"
"\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf"
"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf"
"\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf"
"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
"\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff");
expect_binary_header("foo-bin", 1);
expect_binary_header("foo-bar", 0);
expect_binary_header("-bin", 0);
return all_ok ? 0 : 1;
}
| ppietrasa/grpc | test/core/transport/chttp2/bin_encoder_test.c | C | bsd-3-clause | 7,603 |
/*
*************************************************************************
* © 2016 and later: Unicode, Inc. and others.
* License & terms of use: http://www.unicode.org/copyright.html
*************************************************************************
***********************************************************************
* Copyright (C) 1998-2012, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
*
* File date.c
*
* Modification History:
*
* Date Name Description
* 06/11/99 stephen Creation.
* 06/16/99 stephen Modified to use uprint.
* 08/11/11 srl added Parse and milli/second in/out
*******************************************************************************
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "unicode/utypes.h"
#include "unicode/ustring.h"
#include "unicode/uclean.h"
#include "unicode/ucnv.h"
#include "unicode/udat.h"
#include "unicode/ucal.h"
#include "uprint.h"
int main(int argc, char **argv);
#if UCONFIG_NO_FORMATTING || UCONFIG_NO_CONVERSION
int main(int argc, char **argv)
{
printf("%s: Sorry, UCONFIG_NO_FORMATTING or UCONFIG_NO_CONVERSION was turned on (see uconfig.h). No formatting can be done. \n", argv[0]);
return 0;
}
#else
/* Protos */
static void usage(void);
static void version(void);
static void date(UDate when, const UChar *tz, UDateFormatStyle style, const char *format, const char *locale, UErrorCode *status);
static UDate getWhen(const char *millis, const char *seconds, const char *format, const char *locale, UDateFormatStyle style, const char *parse, const UChar *tz, UErrorCode *status);
UConverter *cnv = NULL;
/* The version of date */
#define DATE_VERSION "1.0"
/* "GMT" */
static const UChar GMT_ID [] = { 0x0047, 0x004d, 0x0054, 0x0000 };
#define FORMAT_MILLIS "%"
#define FORMAT_SECONDS "%%"
int
main(int argc,
char **argv)
{
int printUsage = 0;
int printVersion = 0;
int optInd = 1;
char *arg;
const UChar *tz = 0;
UDateFormatStyle style = UDAT_DEFAULT;
UErrorCode status = U_ZERO_ERROR;
const char *format = NULL;
const char *locale = NULL;
char *parse = NULL;
char *seconds = NULL;
char *millis = NULL;
UDate when;
/* parse the options */
for(optInd = 1; optInd < argc; ++optInd) {
arg = argv[optInd];
/* version info */
if(strcmp(arg, "-v") == 0 || strcmp(arg, "--version") == 0) {
printVersion = 1;
}
/* usage info */
else if(strcmp(arg, "-h") == 0 || strcmp(arg, "--help") == 0) {
printUsage = 1;
}
/* display date in gmt */
else if(strcmp(arg, "-u") == 0 || strcmp(arg, "--gmt") == 0) {
tz = GMT_ID;
}
/* display date in gmt */
else if(strcmp(arg, "-f") == 0 || strcmp(arg, "--full") == 0) {
style = UDAT_FULL;
}
/* display date in long format */
else if(strcmp(arg, "-l") == 0 || strcmp(arg, "--long") == 0) {
style = UDAT_LONG;
}
/* display date in medium format */
else if(strcmp(arg, "-m") == 0 || strcmp(arg, "--medium") == 0) {
style = UDAT_MEDIUM;
}
/* display date in short format */
else if(strcmp(arg, "-s") == 0 || strcmp(arg, "--short") == 0) {
style = UDAT_SHORT;
}
else if(strcmp(arg, "-F") == 0 || strcmp(arg, "--format") == 0) {
if ( optInd + 1 < argc ) {
optInd++;
format = argv[optInd];
}
} else if(strcmp(arg, "-r") == 0) {
if ( optInd + 1 < argc ) {
optInd++;
seconds = argv[optInd];
}
} else if(strcmp(arg, "-R") == 0) {
if ( optInd + 1 < argc ) {
optInd++;
millis = argv[optInd];
}
} else if(strcmp(arg, "-P") == 0) {
if ( optInd + 1 < argc ) {
optInd++;
parse = argv[optInd];
}
}
else if (strcmp(arg, "-L") == 0) {
if (optInd + 1 < argc) {
optInd++;
locale = argv[optInd];
}
}
/* POSIX.1 says all arguments after -- are not options */
else if(strcmp(arg, "--") == 0) {
/* skip the -- */
++optInd;
break;
}
/* unrecognized option */
else if(strncmp(arg, "-", strlen("-")) == 0) {
printf("icudate: invalid option -- %s\n", arg+1);
printUsage = 1;
}
/* done with options, display date */
else {
break;
}
}
/* print usage info */
if(printUsage) {
usage();
return 0;
}
/* print version info */
if(printVersion) {
version();
return 0;
}
/* get the 'when' (or now) */
when = getWhen(millis, seconds, format, locale, style, parse, tz, &status);
if(parse != NULL) {
format = FORMAT_MILLIS; /* output in millis */
}
/* print the date */
date(when, tz, style, format, locale, &status);
ucnv_close(cnv);
u_cleanup();
return (U_FAILURE(status) ? 1 : 0);
}
/* Usage information */
static void
usage()
{
puts("Usage: icudate [OPTIONS]");
puts("Options:");
puts(" -h, --help Print this message and exit.");
puts(" -v, --version Print the version number of date and exit.");
puts(" -u, --gmt Display the date in Greenwich Mean Time.");
puts(" -f, --full Use full display format.");
puts(" -l, --long Use long display format.");
puts(" -m, --medium Use medium display format.");
puts(" -s, --short Use short display format.");
puts(" -F <format>, --format <format> Use <format> as the display format.");
puts(" (Special formats: \"%\" alone is Millis since 1970, \"%%\" alone is Seconds since 1970)");
puts(" -r <seconds> Use <seconds> as the time (Epoch 1970) rather than now.");
puts(" -R <millis> Use <millis> as the time (Epoch 1970) rather than now.");
puts(" -P <string> Parse <string> as the time, output in millis format.");
puts(" -L <string> Use the locale <string> instead of the default ICU locale.");
}
/* Version information */
static void
version()
{
UErrorCode status = U_ZERO_ERROR;
const char *tzVer;
int len = 256;
UChar tzName[256];
printf("icudate version %s, created by Stephen F. Booth.\n",
DATE_VERSION);
puts(U_COPYRIGHT_STRING);
tzVer = ucal_getTZDataVersion(&status);
if(U_FAILURE(status)) {
tzVer = u_errorName(status);
}
printf("\n");
printf("ICU Version: %s\n", U_ICU_VERSION);
printf("ICU Data (major+min): %s\n", U_ICUDATA_NAME);
printf("Default Locale: %s\n", uloc_getDefault());
printf("Time Zone Data Version: %s\n", tzVer);
printf("Default Time Zone: ");
status = U_ZERO_ERROR;
u_init(&status);
len = ucal_getDefaultTimeZone(tzName, len, &status);
if(U_FAILURE(status)) {
fprintf(stderr, " ** Error getting default zone: %s\n", u_errorName(status));
}
uprint(tzName, stdout, &status);
printf("\n\n");
}
static int32_t charsToUCharsDefault(UChar *uchars, int32_t ucharsSize, const char*chars, int32_t charsSize, UErrorCode *status) {
int32_t len=-1;
if(U_FAILURE(*status)) return len;
if(cnv==NULL) {
cnv = ucnv_open(NULL, status);
}
if(cnv&&U_SUCCESS(*status)) {
len = ucnv_toUChars(cnv, uchars, ucharsSize, chars,charsSize, status);
}
return len;
}
/* Format the date */
static void
date(UDate when,
const UChar *tz,
UDateFormatStyle style,
const char *format,
const char *locale,
UErrorCode *status )
{
UChar *s = 0;
int32_t len = 0;
UDateFormat *fmt;
UChar uFormat[100];
if(U_FAILURE(*status)) return;
if( format != NULL ) {
if(!strcmp(format,FORMAT_MILLIS)) {
printf("%.0f\n", when);
return;
} else if(!strcmp(format, FORMAT_SECONDS)) {
printf("%.3f\n", when/1000.0);
return;
}
}
fmt = udat_open(style, style, locale, tz, -1,NULL,0, status);
if ( format != NULL ) {
charsToUCharsDefault(uFormat,sizeof(uFormat)/sizeof(uFormat[0]),format,-1,status);
udat_applyPattern(fmt,false,uFormat,-1);
}
len = udat_format(fmt, when, 0, len, 0, status);
if(*status == U_BUFFER_OVERFLOW_ERROR) {
*status = U_ZERO_ERROR;
s = (UChar*) malloc(sizeof(UChar) * (len+1));
if(s == 0) goto finish;
udat_format(fmt, when, s, len + 1, 0, status);
}
if(U_FAILURE(*status)) goto finish;
/* print the date string */
uprint(s, stdout, status);
/* print a trailing newline */
printf("\n");
finish:
if(U_FAILURE(*status)) {
fprintf(stderr, "Error in Print: %s\n", u_errorName(*status));
}
udat_close(fmt);
free(s);
}
static UDate getWhen(const char *millis, const char *seconds, const char *format, const char *locale,
UDateFormatStyle style, const char *parse, const UChar *tz, UErrorCode *status) {
UDateFormat *fmt = NULL;
UChar uFormat[100];
UChar uParse[256];
UDate when=0;
int32_t parsepos = 0;
if(millis != NULL) {
sscanf(millis, "%lf", &when);
return when;
} else if(seconds != NULL) {
sscanf(seconds, "%lf", &when);
return when*1000.0;
}
if(parse!=NULL) {
if( format != NULL ) {
if(!strcmp(format,FORMAT_MILLIS)) {
sscanf(parse, "%lf", &when);
return when;
} else if(!strcmp(format, FORMAT_SECONDS)) {
sscanf(parse, "%lf", &when);
return when*1000.0;
}
}
fmt = udat_open(style, style, locale, tz, -1,NULL,0, status);
if ( format != NULL ) {
charsToUCharsDefault(uFormat,sizeof(uFormat)/sizeof(uFormat[0]), format,-1,status);
udat_applyPattern(fmt,false,uFormat,-1);
}
charsToUCharsDefault(uParse,sizeof(uParse)/sizeof(uParse[0]), parse,-1,status);
when = udat_parse(fmt, uParse, -1, &parsepos, status);
if(U_FAILURE(*status)) {
fprintf(stderr, "Error in Parse: %s\n", u_errorName(*status));
if(parsepos > 0 && parsepos <= (int32_t)strlen(parse)) {
fprintf(stderr, "ERR>\"%s\" @%d\n"
"ERR> %*s^\n",
parse,parsepos,parsepos,"");
}
}
udat_close(fmt);
return when;
} else {
return ucal_getNow();
}
}
#endif
| youtube/cobalt | third_party/icu/source/samples/date/date.c | C | bsd-3-clause | 10,179 |
// Copyright © 2010-2015 The CefSharp Project. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System.Threading.Tasks;
namespace CefSharp
{
/// <summary>
/// Used for managing cookies. The methods may be called on any thread unless otherwise indicated.
/// </summary>
public interface ICookieManager
{
/// <summary>Deletes all cookies that matches all the provided parameters asynchronously. If both <paramref name="url"/> and <paramref name="name"/> are empty, all cookies will be deleted.</summary>
/// <param name="url">The cookie URL. If an empty string is provided, any URL will be matched.</param>
/// <param name="name">The name of the cookie. If an empty string is provided, any URL will be matched.</param>
/// <return>A task that represents the delete operation. The value of the TResult parameter contains false if a non-empty invalid URL is specified, or if cookies cannot be accessed; otherwise, true.</return>
Task<bool> DeleteCookiesAsync(string url, string name);
/// <summary>Sets a cookie given a valid URL and explicit user-provided cookie attributes. This function expects each attribute to be well-formed. It will check for disallowed
/// characters (e.g. the ';' character is disallowed within the cookie value attribute) and will return false without setting
/// the cookie if such characters are found.</summary>
/// <param name="url">The cookie URL</param>
/// <param name="cookie">The cookie</param>
/// <return>A task that represents the cookie set operation. The value of the TResult parameter contains false if the cookie cannot be set (e.g. if illegal charecters such as ';' are used); otherwise true.</return>
Task<bool> SetCookieAsync(string url, Cookie cookie);
/// <summary> Sets the directory path that will be used for storing cookie data. If <paramref name="path"/> is empty data will be stored in
/// memory only. Otherwise, data will be stored at the specified path. To persist session cookies (cookies without an expiry
/// date or validity interval) set <paramref name="persistSessionCookies"/> to true. Session cookies are generally intended to be transient and
/// most Web browsers do not persist them.</summary>
/// <param name="path">The file path to write cookies to.</param>
/// <param name="persistSessionCookies">A flag that determines whether session cookies will be persisted or not.</param>
/// <return> false if a non-empty invalid URL is specified; otherwise, true.</return>
bool SetStoragePath(string path, bool persistSessionCookies);
/// <summary>
/// Set the schemes supported by this manager. By default only "http" and "https" schemes are supported. Must be called before any cookies are accessed.
/// </summary>
/// <param name="schemes">The list of supported schemes.</param>
void SetSupportedSchemes(params string[] schemes);
/// <summary>Visits all cookies using the provided Cookie Visitor. The returned cookies are sorted by longest path, then by earliest creation date.</summary>
/// <param name="visitor">A user-provided Cookie Visitor implementation.</param>
/// <return>Returns false if cookies cannot be accessed; otherwise, true.</return>
bool VisitAllCookies(ICookieVisitor visitor);
/// <summary>Visits a subset of the cookies. The results are filtered by the given url scheme, host, domain and path.
/// If <paramref name="includeHttpOnly"/> is true, HTTP-only cookies will also be included in the results. The returned cookies
/// are sorted by longest path, then by earliest creation date.</summary>
/// <param name="url">The URL to use for filtering a subset of the cookies available.</param>
/// <param name="includeHttpOnly">A flag that determines whether HTTP-only cookies will be shown in results.</param>
/// <param name="visitor">A user-provided Cookie Visitor implementation.</param>
/// <return>Returns false if cookies cannot be accessed; otherwise, true.</return>
bool VisitUrlCookies(string url, bool includeHttpOnly, ICookieVisitor visitor);
/// <summary> Flush the backing store (if any) to disk and execute the specified |handler| on the IO thread when done. Returns </summary>
/// <param name="handler">A user-provided ICompletionCallback implementation.</param>
/// <return>Returns false if cookies cannot be accessed.</return>
bool FlushStore(ICompletionCallback handler);
}
}
| haozhouxu/CefSharp | CefSharp/ICookieManager.cs | C# | bsd-3-clause | 4,725 |
/*****************************************************************************
Copyright (c) 2014, Intel Corp.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************
* Contents: Native high-level C interface to LAPACK function sppsvx
* Author: Intel Corporation
* Generated November 2015
*****************************************************************************/
#include "lapacke_utils.h"
lapack_int LAPACKE_sppsvx( int matrix_layout, char fact, char uplo, lapack_int n,
lapack_int nrhs, float* ap, float* afp, char* equed,
float* s, float* b, lapack_int ldb, float* x,
lapack_int ldx, float* rcond, float* ferr,
float* berr )
{
lapack_int info = 0;
lapack_int* iwork = NULL;
float* work = NULL;
if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) {
LAPACKE_xerbla( "LAPACKE_sppsvx", -1 );
return -1;
}
#ifndef LAPACK_DISABLE_NAN_CHECK
if( LAPACKE_get_nancheck() ) {
/* Optionally check input matrices for NaNs */
if( LAPACKE_lsame( fact, 'f' ) ) {
if( LAPACKE_spp_nancheck( n, afp ) ) {
return -7;
}
}
if( LAPACKE_spp_nancheck( n, ap ) ) {
return -6;
}
if( LAPACKE_sge_nancheck( matrix_layout, n, nrhs, b, ldb ) ) {
return -10;
}
if( LAPACKE_lsame( fact, 'f' ) && LAPACKE_lsame( *equed, 'y' ) ) {
if( LAPACKE_s_nancheck( n, s, 1 ) ) {
return -9;
}
}
}
#endif
/* Allocate memory for working array(s) */
iwork = (lapack_int*)LAPACKE_malloc( sizeof(lapack_int) * MAX(1,n) );
if( iwork == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_0;
}
work = (float*)LAPACKE_malloc( sizeof(float) * MAX(1,3*n) );
if( work == NULL ) {
info = LAPACK_WORK_MEMORY_ERROR;
goto exit_level_1;
}
/* Call middle-level interface */
info = LAPACKE_sppsvx_work( matrix_layout, fact, uplo, n, nrhs, ap, afp,
equed, s, b, ldb, x, ldx, rcond, ferr, berr,
work, iwork );
/* Release memory and exit */
LAPACKE_free( work );
exit_level_1:
LAPACKE_free( iwork );
exit_level_0:
if( info == LAPACK_WORK_MEMORY_ERROR ) {
LAPACKE_xerbla( "LAPACKE_sppsvx", info );
}
return info;
}
| kortschak/OpenBLAS | lapack-netlib/LAPACKE/src/lapacke_sppsvx.c | C | bsd-3-clause | 4,015 |
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "ComponentBuilder.h"
namespace facebook {
namespace react {
ComponentBuilder::ComponentBuilder(
ComponentDescriptorRegistry::Shared const &componentDescriptorRegistry)
: componentDescriptorRegistry_(componentDescriptorRegistry){};
ShadowNode::Unshared ComponentBuilder::build(
ElementFragment const &elementFragment) const {
auto &componentDescriptor =
componentDescriptorRegistry_->at(elementFragment.componentHandle);
auto children = ShadowNode::ListOfShared{};
children.reserve(elementFragment.children.size());
for (auto const &childFragment : elementFragment.children) {
children.push_back(build(childFragment));
}
auto family = componentDescriptor.createFamily(
ShadowNodeFamilyFragment{
elementFragment.tag, elementFragment.surfaceId, nullptr},
nullptr);
auto state = componentDescriptor.createInitialState(
ShadowNodeFragment{elementFragment.props}, family);
auto constShadowNode = componentDescriptor.createShadowNode(
ShadowNodeFragment{
elementFragment.props,
std::make_shared<ShadowNode::ListOfShared const>(children),
state},
family);
if (elementFragment.stateCallback) {
auto newState = componentDescriptor.createState(
*family, elementFragment.stateCallback());
constShadowNode = componentDescriptor.cloneShadowNode(
*constShadowNode,
ShadowNodeFragment{
ShadowNodeFragment::propsPlaceholder(),
ShadowNodeFragment::childrenPlaceholder(),
newState});
}
auto shadowNode = std::const_pointer_cast<ShadowNode>(constShadowNode);
if (elementFragment.referenceCallback) {
elementFragment.referenceCallback(shadowNode);
}
if (elementFragment.finalizeCallback) {
elementFragment.finalizeCallback(*shadowNode);
}
return shadowNode;
}
} // namespace react
} // namespace facebook
| pandiaraj44/react-native | ReactCommon/react/renderer/element/ComponentBuilder.cpp | C++ | bsd-3-clause | 2,095 |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <map>
// class multimap
// iterator find(const key_type& k);
// const_iterator find(const key_type& k) const;
//
// The member function templates find, count, lower_bound, upper_bound, and
// equal_range shall not participate in overload resolution unless the
// qualified-id Compare::is_transparent is valid and denotes a type
#include <map>
#include <cassert>
#include "test_macros.h"
#include "is_transparent.h"
#if TEST_STD_VER <= 11
#error "This test requires is C++14 (or later)"
#else
int main()
{
{
typedef std::multimap<int, double, transparent_less_no_type> M;
TEST_IGNORE_NODISCARD M().find(C2Int{5});
}
}
#endif
| youtube/cobalt | third_party/llvm-project/libcxx/test/std/containers/associative/multimap/multimap.ops/find1.fail.cpp | C++ | bsd-3-clause | 1,016 |
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "Modifier.h"
#include "../OOModelException.h"
#include "ModelBase/src/commands/FieldSet.h"
#include "ModelBase/src/nodes/TypedList.hpp"
template class Model::TypedList<OOModel::Modifier>;
namespace OOModel {
DEFINE_NODE_TYPE_REGISTRATION_METHODS(Modifier)
Modifier::Modifier(Model::Node *parent)
: Super{parent}
{
}
Modifier::Modifier(Model::Node *parent, Model::PersistentStore &store, bool)
: Super{parent}
{
modifiers_ = fromInt( store.loadIntValue() );
}
Modifier::Modifier(Modifiers modifiers)
: Super{nullptr}, modifiers_{modifiers}
{}
Modifier* Modifier::clone() const { return new Modifier{*this}; }
void Modifier::set(Modifiers modifiers, bool enable)
{
execute(new Model::FieldSet<Modifiers>{this, modifiers_,
enable ? modifiers_ | modifiers : modifiers_ & (~modifiers)});
}
void Modifier::clear()
{
execute(new Model::FieldSet<Modifiers>{this, modifiers_, None});
}
void Modifier::save(Model::PersistentStore &store) const
{
store.saveIntValue(modifiers_);
}
void Modifier::load(Model::PersistentStore &store)
{
if (store.currentNodeType() != typeName())
throw OOModelException{"Trying to load a Modifier node from an incompatible node type "
+ store.currentNodeType()};
set(fromInt(store.loadIntValue()));
}
Modifier::Modifiers Modifier::fromInt(int val)
{
//TODO: Do some error checking
return static_cast<Modifiers>(val);
}
}
| lukedirtwalker/Envision | OOModel/src/elements/Modifier.cpp | C++ | bsd-3-clause | 3,212 |
<?php
class Dao_Sqlite_Audit extends Dao_Base_Audit
{
}
| mesa57/spotweb | lib/dao/Sqlite/Dao_Sqlite_Audit.php | PHP | bsd-3-clause | 57 |
/*
* JNPR: stdarg.h,v 1.3 2006/09/15 12:52:34 katta
* $FreeBSD$
*/
#ifndef _MACHINE_STDARG_H_
#define _MACHINE_STDARG_H_
#include <sys/cdefs.h>
#include <sys/_types.h>
#if __GNUC__ >= 3
#ifndef _VA_LIST_DECLARED
#define _VA_LIST_DECLARED
typedef __va_list va_list;
#endif
#define va_start(v,l) __builtin_va_start((v),l)
#define va_end __builtin_va_end
#define va_arg __builtin_va_arg
#define va_copy __builtin_va_copy
#else /* __GNUC__ */
/* ---------------------------------------- */
/* VARARGS for MIPS/GNU CC */
/* ---------------------------------------- */
#include <machine/endian.h>
/* These macros implement varargs for GNU C--either traditional or ANSI. */
/* Define __gnuc_va_list. */
#ifndef __GNUC_VA_LIST
#define __GNUC_VA_LIST
typedef char * __gnuc_va_list;
typedef __gnuc_va_list va_list;
#endif /* ! __GNUC_VA_LIST */
/* If this is for internal libc use, don't define anything but
__gnuc_va_list. */
#ifndef _VA_MIPS_H_ENUM
#define _VA_MIPS_H_ENUM
enum {
__no_type_class = -1,
__void_type_class,
__integer_type_class,
__char_type_class,
__enumeral_type_class,
__boolean_type_class,
__pointer_type_class,
__reference_type_class,
__offset_type_class,
__real_type_class,
__complex_type_class,
__function_type_class,
__method_type_class,
__record_type_class,
__union_type_class,
__array_type_class,
__string_type_class,
__set_type_class,
__file_type_class,
__lang_type_class
};
#endif
/* In GCC version 2, we want an ellipsis at the end of the declaration
of the argument list. GCC version 1 can't parse it. */
#if __GNUC__ > 1
#define __va_ellipsis ...
#else
#define __va_ellipsis
#endif
#define va_start(__AP, __LASTARG) \
(__AP = (__gnuc_va_list) __builtin_next_arg (__LASTARG))
#define va_end(__AP) ((void)0)
/* We cast to void * and then to TYPE * because this avoids
a warning about increasing the alignment requirement. */
/* The __mips64 cases are reversed from the 32 bit cases, because the standard
32 bit calling convention left-aligns all parameters smaller than a word,
whereas the __mips64 calling convention does not (and hence they are
right aligned). */
#ifdef __mips64
#define __va_rounded_size(__TYPE) (((sizeof (__TYPE) + 8 - 1) / 8) * 8)
#define __va_reg_size 8
#if defined(__MIPSEB__) || (BYTE_ORDER == BIG_ENDIAN)
#define va_arg(__AP, __type) \
((__type *) (void *) (__AP = (char *) \
((((__PTRDIFF_TYPE__)__AP + 8 - 1) & -8) \
+ __va_rounded_size (__type))))[-1]
#else /* ! __MIPSEB__ && !BYTE_ORDER == BIG_ENDIAN */
#define va_arg(__AP, __type) \
((__AP = (char *) ((((__PTRDIFF_TYPE__)__AP + 8 - 1) & -8) \
+ __va_rounded_size (__type))), \
*(__type *) (void *) (__AP - __va_rounded_size (__type)))
#endif /* ! __MIPSEB__ && !BYTE_ORDER == BIG_ENDIAN */
#else /* ! __mips64 */
#define __va_rounded_size(__TYPE) \
(((sizeof (__TYPE) + sizeof (int) - 1) / sizeof (int)) * sizeof (int))
#define __va_reg_size 4
#if defined(__MIPSEB__) || (BYTE_ORDER == BIG_ENDIAN)
/* For big-endian machines. */
#define va_arg(__AP, __type) \
((__AP = (char *) ((__alignof__ (__type) > 4 \
? ((__PTRDIFF_TYPE__)__AP + 8 - 1) & -8 \
: ((__PTRDIFF_TYPE__)__AP + 4 - 1) & -4) \
+ __va_rounded_size (__type))), \
*(__type *) (void *) (__AP - __va_rounded_size (__type)))
#else /* ! __MIPSEB__ && !BYTE_ORDER == BIG_ENDIAN */
/* For little-endian machines. */
#define va_arg(__AP, __type) \
((__type *) (void *) (__AP = (char *) ((__alignof__(__type) > 4 \
? ((__PTRDIFF_TYPE__)__AP + 8 - 1) & -8 \
: ((__PTRDIFF_TYPE__)__AP + 4 - 1) & -4) \
+ __va_rounded_size(__type))))[-1]
#endif /* ! __MIPSEB__ && !BYTE_ORDER == BIG_ENDIAN */
#endif /* ! __mips64 */
/* Copy __gnuc_va_list into another variable of this type. */
#define __va_copy(dest, src) (dest) = (src)
#define va_copy(dest, src) (dest) = (src)
#endif /* __GNUC__ */
#endif /* _MACHINE_STDARG_H_ */
| jrobhoward/SCADAbase | sys/mips/include/stdarg.h | C | bsd-3-clause | 3,968 |
<?php
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \common\models\LoginForm */
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
$this->title = 'Login';
$this->params['breadcrumbs'][] = $this->title;
use common\widgets\LoginWidget;
echo LoginWidget::widget();
?>
| AlexReshodko/tmportal | frontend/views/site/login.php | PHP | bsd-3-clause | 312 |
lambda:lang(no):root gamma:first-child chi[or*="ue"]:empty ~ sigma:lang(en) > iota#id1:empty ~ eta[object^="solid 1px "]:lang(no)#id2:nth-child(2)
{color:green} | frivoal/presto-testo | css/selectors/reftests/tc-671.css | CSS | bsd-3-clause | 162 |
import os
import re
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.admin.options import get_content_type_for_model
from django.db import transaction
from django.utils.encoding import force_str
from django_statsd.clients import statsd
import olympia.core.logger
from olympia.amo.celery import task
from olympia.amo.decorators import use_primary_db
from olympia.amo.utils import SafeStorage
from olympia.constants.blocklist import (
MLBF_TIME_CONFIG_KEY,
MLBF_BASE_ID_CONFIG_KEY,
REMOTE_SETTINGS_COLLECTION_MLBF,
)
from olympia.lib.remote_settings import RemoteSettings
from olympia.zadmin.models import set_config
from .mlbf import MLBF
from .models import BlocklistSubmission
from .utils import (
datetime_to_ts,
)
log = olympia.core.logger.getLogger('z.amo.blocklist')
bracket_open_regex = re.compile(r'(?<!\\){')
bracket_close_regex = re.compile(r'(?<!\\)}')
BLOCKLIST_RECORD_MLBF_BASE = 'bloomfilter-base'
@task
@use_primary_db
def process_blocklistsubmission(multi_block_submit_id, **kw):
obj = BlocklistSubmission.objects.get(pk=multi_block_submit_id)
try:
with transaction.atomic():
if obj.action == BlocklistSubmission.ACTION_ADDCHANGE:
# create the blocks from the guids in the multi_block
obj.save_to_block_objects()
elif obj.action == BlocklistSubmission.ACTION_DELETE:
# delete the blocks
obj.delete_block_objects()
except Exception as exc:
# If something failed reset the submission back to Pending.
obj.update(signoff_state=BlocklistSubmission.SIGNOFF_PENDING)
message = f'Exception in task: {exc}'
LogEntry.objects.log_action(
user_id=settings.TASK_USER_ID,
content_type_id=get_content_type_for_model(obj).pk,
object_id=obj.pk,
object_repr=str(obj),
action_flag=CHANGE,
change_message=message,
)
raise exc
@task
def upload_filter(generation_time, is_base=True):
bucket = settings.REMOTE_SETTINGS_WRITER_BUCKET
server = RemoteSettings(
bucket, REMOTE_SETTINGS_COLLECTION_MLBF, sign_off_needed=False
)
mlbf = MLBF.load_from_storage(generation_time)
if is_base:
# clear the collection for the base - we want to be the only filter
server.delete_all_records()
statsd.incr('blocklist.tasks.upload_filter.reset_collection')
# Then the bloomfilter
data = {
'key_format': MLBF.KEY_FORMAT,
'generation_time': generation_time,
'attachment_type': BLOCKLIST_RECORD_MLBF_BASE,
}
storage = SafeStorage(user_media='mlbf_storage')
with storage.open(mlbf.filter_path, 'rb') as filter_file:
attachment = ('filter.bin', filter_file, 'application/octet-stream')
server.publish_attachment(data, attachment)
statsd.incr('blocklist.tasks.upload_filter.upload_mlbf')
statsd.incr('blocklist.tasks.upload_filter.upload_mlbf.base')
else:
# If we have a stash, write that
stash_data = {
'key_format': MLBF.KEY_FORMAT,
'stash_time': generation_time,
'stash': mlbf.stash_json,
}
server.publish_record(stash_data)
statsd.incr('blocklist.tasks.upload_filter.upload_stash')
server.complete_session()
set_config(MLBF_TIME_CONFIG_KEY, generation_time, json_value=True)
if is_base:
set_config(MLBF_BASE_ID_CONFIG_KEY, generation_time, json_value=True)
@task
def cleanup_old_files(*, base_filter_id):
log.info('Starting clean up of old MLBF folders...')
six_months_ago = datetime_to_ts(datetime.now() - timedelta(weeks=26))
base_filter_ts = int(base_filter_id)
storage = SafeStorage(user_media='mlbf_storage')
for dir in storage.listdir(settings.MLBF_STORAGE_PATH)[0]:
dir = force_str(dir)
# skip non-numeric folder names
if not dir.isdigit():
log.info('Skipping %s because not a timestamp', dir)
continue
dir_ts = int(dir)
dir_as_date = datetime.fromtimestamp(dir_ts / 1000)
# delete if >6 months old and <base_filter_id
if dir_ts > six_months_ago:
log.info('Skipping %s because < 6 months old (%s)', dir, dir_as_date)
elif dir_ts > base_filter_ts:
log.info(
'Skipping %s because more recent (%s) than base mlbf (%s)',
dir,
dir_as_date,
datetime.fromtimestamp(base_filter_ts / 1000),
)
else:
log.info('Deleting %s because > 6 months old (%s)', dir, dir_as_date)
storage.rm_stored_dir(os.path.join(settings.MLBF_STORAGE_PATH, dir))
| mozilla/addons-server | src/olympia/blocklist/tasks.py | Python | bsd-3-clause | 4,883 |
<!--! Snippet for a <th> corresponding to a sortable column.
Expects the following variables to be set specifically:
class_ the CSS class for the column
title the title attribute for the column
e.g. <py:with vars="class_ = 'name'; title = 'Name'">
<xi:include href="sortable_th.html" />
</py:with>
Expects the following variables from the context: order, desc, href, reponame, path, stickyrev
-->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:py="http://genshi.edgewall.org/"
xmlns:xi="http://www.w3.org/2001/XInclude" py:strip="">
<th class="$class_${(' desc' if desc else ' asc') if order == class_ else None}">
<a title="${_('Sort by %(col)s %(direction)s', col=class_,
direction=_('(descending)') if order == class_ and not desc else _('(ascending)'))}"
href="${href.browser(reponame, path, rev=stickyrev, order=class_ if class_ != 'name' else None,
desc=1 if class_ == order and not desc else None)}">$title</a>
</th>
</html>
| trac-ja/trac-ja | trac/versioncontrol/templates/sortable_th.html | HTML | bsd-3-clause | 1,056 |
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/scoped_vector.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/test/integration/bookmarks_helper.h"
#include "chrome/browser/sync/test/integration/migration_waiter.h"
#include "chrome/browser/sync/test/integration/migration_watcher.h"
#include "chrome/browser/sync/test/integration/preferences_helper.h"
#include "chrome/browser/sync/test/integration/profile_sync_service_harness.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "chrome/common/pref_names.h"
#include "components/browser_sync/browser/profile_sync_service.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/translate/core/browser/translate_prefs.h"
using bookmarks_helper::AddURL;
using bookmarks_helper::IndexedURL;
using bookmarks_helper::IndexedURLTitle;
using preferences_helper::BooleanPrefMatches;
using preferences_helper::ChangeBooleanPref;
namespace {
// Utility functions to make a model type set out of a small number of
// model types.
syncer::ModelTypeSet MakeSet(syncer::ModelType type) {
return syncer::ModelTypeSet(type);
}
syncer::ModelTypeSet MakeSet(syncer::ModelType type1,
syncer::ModelType type2) {
return syncer::ModelTypeSet(type1, type2);
}
// An ordered list of model types sets to migrate. Used by
// RunMigrationTest().
typedef std::deque<syncer::ModelTypeSet> MigrationList;
// Utility functions to make a MigrationList out of a small number of
// model types / model type sets.
MigrationList MakeList(syncer::ModelTypeSet model_types) {
return MigrationList(1, model_types);
}
MigrationList MakeList(syncer::ModelTypeSet model_types1,
syncer::ModelTypeSet model_types2) {
MigrationList migration_list;
migration_list.push_back(model_types1);
migration_list.push_back(model_types2);
return migration_list;
}
MigrationList MakeList(syncer::ModelType type) {
return MakeList(MakeSet(type));
}
MigrationList MakeList(syncer::ModelType type1,
syncer::ModelType type2) {
return MakeList(MakeSet(type1), MakeSet(type2));
}
class MigrationTest : public SyncTest {
public:
explicit MigrationTest(TestType test_type) : SyncTest(test_type) {}
~MigrationTest() override {}
enum TriggerMethod { MODIFY_PREF, MODIFY_BOOKMARK, TRIGGER_NOTIFICATION };
// Set up sync for all profiles and initialize all MigrationWatchers. This
// helps ensure that all migration events are captured, even if they were to
// occur before a test calls AwaitMigration for a specific profile.
bool SetupSync() override {
if (!SyncTest::SetupSync())
return false;
for (int i = 0; i < num_clients(); ++i) {
MigrationWatcher* watcher = new MigrationWatcher(GetClient(i));
migration_watchers_.push_back(watcher);
}
return true;
}
syncer::ModelTypeSet GetPreferredDataTypes() {
// ProfileSyncService must already have been created before we can call
// GetPreferredDataTypes().
DCHECK(GetSyncService((0)));
syncer::ModelTypeSet preferred_data_types =
GetSyncService((0))->GetPreferredDataTypes();
preferred_data_types.RemoveAll(syncer::ProxyTypes());
// Supervised user data types will be "unready" during this test, so we
// should not request that they be migrated.
preferred_data_types.Remove(syncer::SUPERVISED_USER_SETTINGS);
preferred_data_types.Remove(syncer::SUPERVISED_USER_WHITELISTS);
// Autofill wallet will be unready during this test, so we should not
// request that it be migrated.
preferred_data_types.Remove(syncer::AUTOFILL_WALLET_DATA);
preferred_data_types.Remove(syncer::AUTOFILL_WALLET_METADATA);
// Make sure all clients have the same preferred data types.
for (int i = 1; i < num_clients(); ++i) {
const syncer::ModelTypeSet other_preferred_data_types =
GetSyncService((i))->GetPreferredDataTypes();
EXPECT_EQ(other_preferred_data_types, preferred_data_types);
}
return preferred_data_types;
}
// Returns a MigrationList with every enabled data type in its own
// set.
MigrationList GetPreferredDataTypesList() {
MigrationList migration_list;
const syncer::ModelTypeSet preferred_data_types =
GetPreferredDataTypes();
for (syncer::ModelTypeSet::Iterator it =
preferred_data_types.First(); it.Good(); it.Inc()) {
migration_list.push_back(MakeSet(it.Get()));
}
return migration_list;
}
// Trigger a migration for the given types with the given method.
void TriggerMigration(syncer::ModelTypeSet model_types,
TriggerMethod trigger_method) {
switch (trigger_method) {
case MODIFY_PREF:
// Unlike MODIFY_BOOKMARK, MODIFY_PREF doesn't cause a
// notification to happen (since model association on a
// boolean pref clobbers the local value), so it doesn't work
// for anything but single-client tests.
ASSERT_EQ(1, num_clients());
ASSERT_TRUE(BooleanPrefMatches(prefs::kShowHomeButton));
ChangeBooleanPref(0, prefs::kShowHomeButton);
break;
case MODIFY_BOOKMARK:
ASSERT_TRUE(AddURL(0, IndexedURLTitle(0), GURL(IndexedURL(0))));
break;
case TRIGGER_NOTIFICATION:
TriggerNotification(model_types);
break;
default:
ADD_FAILURE();
}
}
// Block until all clients have completed migration for the given
// types.
void AwaitMigration(syncer::ModelTypeSet migrate_types) {
for (int i = 0; i < num_clients(); ++i) {
MigrationWaiter waiter(migrate_types, migration_watchers_[i]);
waiter.Wait();
ASSERT_FALSE(waiter.TimedOut());
}
}
// Makes sure migration works with the given migration list and
// trigger method.
void RunMigrationTest(const MigrationList& migration_list,
TriggerMethod trigger_method) {
// If we have only one client, turn off notifications to avoid the
// possibility of spurious sync cycles.
bool do_test_without_notifications =
(trigger_method != TRIGGER_NOTIFICATION && num_clients() == 1);
if (do_test_without_notifications) {
DisableNotifications();
}
// Make sure migration hasn't been triggered prematurely.
for (int i = 0; i < num_clients(); ++i) {
ASSERT_TRUE(migration_watchers_[i]->GetMigratedTypes().Empty());
}
// Phase 1: Trigger the migrations on the server.
for (MigrationList::const_iterator it = migration_list.begin();
it != migration_list.end(); ++it) {
TriggerMigrationDoneError(*it);
}
// Phase 2: Trigger each migration individually and wait for it to
// complete. (Multiple migrations may be handled by each
// migration cycle, but there's no guarantee of that, so we have
// to trigger each migration individually.)
for (MigrationList::const_iterator it = migration_list.begin();
it != migration_list.end(); ++it) {
TriggerMigration(*it, trigger_method);
AwaitMigration(*it);
}
// Phase 3: Wait for all clients to catch up.
//
// AwaitQuiescence() will not succeed when notifications are disabled. We
// can safely avoid calling it because we know that, in the single client
// case, there is no one else to wait for.
//
// TODO(rlarocque, 97780): Remove the if condition when the test harness
// supports calling AwaitQuiescence() when notifications are disabled.
if (!do_test_without_notifications) {
AwaitQuiescence();
}
// TODO(rlarocque): It should be possible to re-enable notifications
// here, but doing so makes some windows tests flaky.
}
private:
// Used to keep track of the migration progress for each sync client.
ScopedVector<MigrationWatcher> migration_watchers_;
DISALLOW_COPY_AND_ASSIGN(MigrationTest);
};
class MigrationSingleClientTest : public MigrationTest {
public:
MigrationSingleClientTest() : MigrationTest(SINGLE_CLIENT_LEGACY) {}
~MigrationSingleClientTest() override {}
void RunSingleClientMigrationTest(const MigrationList& migration_list,
TriggerMethod trigger_method) {
ASSERT_TRUE(SetupSync());
RunMigrationTest(migration_list, trigger_method);
}
private:
DISALLOW_COPY_AND_ASSIGN(MigrationSingleClientTest);
};
// The simplest possible migration tests -- a single data type.
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, PrefsOnlyModifyPref) {
RunSingleClientMigrationTest(MakeList(syncer::PREFERENCES), MODIFY_PREF);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, PrefsOnlyModifyBookmark) {
RunSingleClientMigrationTest(MakeList(syncer::PREFERENCES),
MODIFY_BOOKMARK);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
PrefsOnlyTriggerNotification) {
RunSingleClientMigrationTest(MakeList(syncer::PREFERENCES),
TRIGGER_NOTIFICATION);
}
// Nigori is handled specially, so we test that separately.
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, NigoriOnly) {
RunSingleClientMigrationTest(MakeList(syncer::PREFERENCES),
TRIGGER_NOTIFICATION);
}
// A little more complicated -- two data types.
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, BookmarksPrefsIndividually) {
RunSingleClientMigrationTest(
MakeList(syncer::BOOKMARKS, syncer::PREFERENCES),
MODIFY_PREF);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, BookmarksPrefsBoth) {
RunSingleClientMigrationTest(
MakeList(MakeSet(syncer::BOOKMARKS, syncer::PREFERENCES)),
MODIFY_BOOKMARK);
}
// Two data types with one being nigori.
// See crbug.com/124480.
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
DISABLED_PrefsNigoriIndividiaully) {
RunSingleClientMigrationTest(
MakeList(syncer::PREFERENCES, syncer::NIGORI),
TRIGGER_NOTIFICATION);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, PrefsNigoriBoth) {
RunSingleClientMigrationTest(
MakeList(MakeSet(syncer::PREFERENCES, syncer::NIGORI)),
MODIFY_PREF);
}
// The whole shebang -- all data types.
// http://crbug.com/403778
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
DISABLED_AllTypesIndividually) {
ASSERT_TRUE(SetupClients());
RunSingleClientMigrationTest(GetPreferredDataTypesList(), MODIFY_BOOKMARK);
}
// http://crbug.com/403778
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
DISABLED_AllTypesIndividuallyTriggerNotification) {
ASSERT_TRUE(SetupClients());
RunSingleClientMigrationTest(GetPreferredDataTypesList(),
TRIGGER_NOTIFICATION);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, AllTypesAtOnce) {
ASSERT_TRUE(SetupClients());
RunSingleClientMigrationTest(MakeList(GetPreferredDataTypes()),
MODIFY_PREF);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
AllTypesAtOnceTriggerNotification) {
ASSERT_TRUE(SetupClients());
RunSingleClientMigrationTest(MakeList(GetPreferredDataTypes()),
TRIGGER_NOTIFICATION);
}
// All data types plus nigori.
// See crbug.com/124480.
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest,
DISABLED_AllTypesWithNigoriIndividually) {
ASSERT_TRUE(SetupClients());
MigrationList migration_list = GetPreferredDataTypesList();
migration_list.push_front(MakeSet(syncer::NIGORI));
RunSingleClientMigrationTest(migration_list, MODIFY_BOOKMARK);
}
IN_PROC_BROWSER_TEST_F(MigrationSingleClientTest, AllTypesWithNigoriAtOnce) {
ASSERT_TRUE(SetupClients());
syncer::ModelTypeSet all_types = GetPreferredDataTypes();
all_types.Put(syncer::NIGORI);
RunSingleClientMigrationTest(MakeList(all_types), MODIFY_PREF);
}
class MigrationTwoClientTest : public MigrationTest {
public:
MigrationTwoClientTest() : MigrationTest(TWO_CLIENT_LEGACY) {}
~MigrationTwoClientTest() override {}
// Helper function that verifies that preferences sync still works.
void VerifyPrefSync() {
ASSERT_TRUE(BooleanPrefMatches(prefs::kShowHomeButton));
ChangeBooleanPref(0, prefs::kShowHomeButton);
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
ASSERT_TRUE(BooleanPrefMatches(prefs::kShowHomeButton));
}
void RunTwoClientMigrationTest(const MigrationList& migration_list,
TriggerMethod trigger_method) {
ASSERT_TRUE(SetupSync());
// Make sure pref sync works before running the migration test.
VerifyPrefSync();
RunMigrationTest(migration_list, trigger_method);
// Make sure pref sync still works after running the migration
// test.
VerifyPrefSync();
}
private:
DISALLOW_COPY_AND_ASSIGN(MigrationTwoClientTest);
};
// Easiest possible test of migration errors: triggers a server
// migration on one datatype, then modifies some other datatype.
IN_PROC_BROWSER_TEST_F(MigrationTwoClientTest, MigratePrefsThenModifyBookmark) {
RunTwoClientMigrationTest(MakeList(syncer::PREFERENCES),
MODIFY_BOOKMARK);
}
// Triggers a server migration on two datatypes, then makes a local
// modification to one of them.
IN_PROC_BROWSER_TEST_F(MigrationTwoClientTest,
MigratePrefsAndBookmarksThenModifyBookmark) {
RunTwoClientMigrationTest(
MakeList(syncer::PREFERENCES, syncer::BOOKMARKS),
MODIFY_BOOKMARK);
}
// Migrate every datatype in sequence; the catch being that the server
// will only tell the client about the migrations one at a time.
// TODO(rsimha): This test takes longer than 60 seconds, and will cause tree
// redness due to sharding.
// Re-enable this test after syncer::kInitialBackoffShortRetrySeconds is reduced
// to zero.
IN_PROC_BROWSER_TEST_F(MigrationTwoClientTest,
DISABLED_MigrationHellWithoutNigori) {
ASSERT_TRUE(SetupClients());
MigrationList migration_list = GetPreferredDataTypesList();
// Let the first nudge be a datatype that's neither prefs nor
// bookmarks.
migration_list.push_front(MakeSet(syncer::THEMES));
RunTwoClientMigrationTest(migration_list, MODIFY_BOOKMARK);
}
// See crbug.com/124480.
IN_PROC_BROWSER_TEST_F(MigrationTwoClientTest,
DISABLED_MigrationHellWithNigori) {
ASSERT_TRUE(SetupClients());
MigrationList migration_list = GetPreferredDataTypesList();
// Let the first nudge be a datatype that's neither prefs nor
// bookmarks.
migration_list.push_front(MakeSet(syncer::THEMES));
// Pop off one so that we don't migrate all data types; the syncer
// freaks out if we do that (see http://crbug.com/94882).
ASSERT_GE(migration_list.size(), 2u);
ASSERT_NE(MakeSet(syncer::NIGORI), migration_list.back());
migration_list.back() = MakeSet(syncer::NIGORI);
RunTwoClientMigrationTest(migration_list, MODIFY_BOOKMARK);
}
class MigrationReconfigureTest : public MigrationTwoClientTest {
public:
MigrationReconfigureTest() {}
void SetUpCommandLine(base::CommandLine* cl) override {
AddTestSwitches(cl);
// Do not add optional datatypes.
}
~MigrationReconfigureTest() override {}
private:
DISALLOW_COPY_AND_ASSIGN(MigrationReconfigureTest);
};
} // namespace
| danakj/chromium | chrome/browser/sync/test/integration/migration_test.cc | C++ | bsd-3-clause | 15,557 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/>
<meta name="description" content="W3C SVG 1.1 2nd Edition Object Mini Test Suite"/>
<title>
SVG 1.1 2nd Edition Test (<object>): filters-conv-05-f.svg
</title>
<link href="harness_mini.css" rel="stylesheet" type="text/css" />
<link rel="prev" href="filters-conv-04-f.html" />
<link rel="index" href="index.html" />
<link rel="next" href="filters-diffuse-01-f.html" />
<script src="../resources/testharnessreport.js"></script>
</head>
<body class="bodytext">
<div class="linkbar">
<p>
<a href="filters-conv-04-f.html" rel="prev">filters-conv-04-f ←</a>
<a href="index.html" rel="index">index</a>
<a href="filters-diffuse-01-f.html" rel="next">→ filters-diffuse-01-f</a>
</p>
</div>
<table border="0" align="center" cellspacing="0" cellpadding="10">
<tr>
<td align="center" colspan="3">
<table border="0" cellpadding="8">
<tr class="navbar">
<td align="center">
SVG Image
</td>
<td align="center">
PNG Image
</td>
</tr>
<tr>
<td align="right">
<object data="../../svg/filters-conv-05-f.svg" width="480" height="360" type="image/svg+xml"><p style="font-size:300%;color:red">FAIL</p></object>
</td>
<td align="left">
<img alt="raster image of filters-conv-05-f.svg" src="../../png/filters-conv-05-f.png" width="480" height="360"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div>
<h4 id="operatorscript" onclick="var t = document.getElementById('operatortext'); t.style.display=(t.style.display=='none' ? 'inline' : 'none');">
<em>Operator script (click here to toggle)</em>
</h4>
<div id="operatortext" style="display:none">
<p>
Run the test. No interaction required.
</p>
</div>
</div>
<h4 id="passcriteria">
Pass Criteria
</h4>
<div>
<p>
You should see three filtered images, each result should be slightly different, if they all look the same the test has failed.
The rendered picture should match the reference image.
</p>
</div>
<br />
<div class="linkbar">
<p>
<a href="filters-conv-04-f.html" rel="prev">filters-conv-04-f ←</a>
<a href="index.html" rel="index">index</a>
<a href="filters-diffuse-01-f.html" rel="next">→ filters-diffuse-01-f</a>
</p>
</div>
</body>
</html>
| frivoal/presto-testo | SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/filters-conv-05-f.html | HTML | bsd-3-clause | 2,875 |
/ _____) _ | |
( (____ _____ ____ _| |_ _____ ____| |__
\____ \| ___ | (_ _) ___ |/ ___) _ \
_____) ) ____| | | || |_| ____( (___| | | |
(______/|_____)_|_|_| \__)_____)\____)_| |_|
(C)2013 Semtech
SX1272/76 radio drivers plus Ping-Pong firmware and LoRaWAN node firmware implementation.
=====================================
1. Introduction
----------------
The aim of this project is to show examples of the LoRaWAN specification endpoint firmware
implementation.
**REMARK 1:** *The Semtech implementation is a EU868 band Class A and Class C endpoint
implementation fully compatible with LoRaWAN 1.0 specification.*
**REMARK 2:** *The Class C normal operation has been tested using the Actility servers.*
**REMARK 3:** *The Class C Multicast messages handling is not yet tested.*
**Note:**
*The IBM 'LoRaWAN in C' implementation supports the Class A profile and partial
Class B support (beacon synchronization).*
*A port of the IBM 'LoRaWAN in C' can be found on [MBED Semtech Team page](http://developer.mbed.org/teams/Semtech/)
project [LoRaWAN-lmic-app](http://developer.mbed.org/teams/Semtech/code/LoRaWAN-lmic-app/)*
2. System schematic and definitions
------------------------------------
The available supported hardware platforms schematics and LoRaMac specification
can be found in the Doc directory.
3. Acknowledgements
-------------------
The mbed (https://mbed.org/) project was used at the beginning as source of
inspiration.
This program uses the AES algorithm implementation (http://www.gladman.me.uk/)
by Brian Gladman.
This program uses the CMAC algorithm implementation
(http://www.cse.chalmers.se/research/group/dcs/masters/contikisec/) by
Lander Casado, Philippas Tsigas.
4. Dependencies
----------------
This program depends on specific hardware platforms. Currently the supported
platforms are:
- Bleeper-72
MCU : STM32L151RD - 384K FLASH, 48K RAM, Timers, SPI, I2C,
USART,
USB 2.0 full-speed device/host/OTG controller,
DAC, ADC, DMA
RADIO : SX1272
ANTENNA : Connector for external antenna
BUTTONS : 1 Reset, 16 position encoder
LEDS : 3
SENSORS : Temperature
GPS : Possible through pin header GPS module connection
SDCARD : Yes
EXTENSION HEADER : Yes, 12 pins
REMARK : None.
- Bleeper-76
MCU : STM32L151RD - 384K FLASH, 48K RAM, Timers, SPI, I2C,
USART,
USB 2.0 full-speed device/host/OTG controller,
DAC, ADC, DMA
RADIO : SX1276
ANTENNA : Connector for external antennas (LF+HF)
BUTTONS : 1 Reset, 16 position encoder
LEDS : 3
SENSORS : Temperature
GPS : Possible through pin header GPS module connection
SDCARD : No
EXTENSION HEADER : Yes, 12 pins
REMARK : None.
- LoRaMote
MCU : STM32L151CB - 128K FLASH, 10K RAM, Timers, SPI, I2C,
USART,
USB 2.0 full-speed device/host/OTG controller,
DAC, ADC, DMA
RADIO : SX1272
ANTENNA : Printed circuit antenna
BUTTONS : No
LEDS : 3
SENSORS : Proximity, Magnetic, 3 axis Accelerometer, Pressure,
Temperature
GPS : Yes, UP501 module
SDCARD : No
EXTENSION HEADER : Yes, 20 pins
REMARK : The MCU and Radio are on an IMST iM880A module
- SensorNode
MCU : STM32L151C8 - 64K FLASH, 10K RAM, Timers, SPI, I2C,
USART,
USB 2.0 full-speed device/host/OTG controller,
DAC, ADC, DMA
RADIO : SX1276
ANTENNA : Printed circuit antenna
BUTTONS : Power ON/OFF, General purpose button
LEDS : 3
SENSORS : Proximity, Magnetic, 3 axis Accelerometer, Pressure,
Temperature
GPS : Yes, SIM39EA module
SDCARD : No
EXTENSION No
REMARK : The MCU and Radio are on an NYMTEK Cherry-LCC module
- SK-iM880A ( IMST starter kit )
MCU : STM32L151CB - 128K FLASH, 10K RAM, Timers, SPI, I2C,
USART,
USB 2.0 full-speed device/host/OTG controller,
DAC, ADC, DMA
RADIO : SX1272
ANTENNA : Connector for external antenna
BUTTONS : 1 Reset, 3 buttons + 2 DIP-Switch
LEDS : 3
SENSORS : Potentiometer
GPS : Possible through pin header GPS module connection
SDCARD : No
EXTENSION HEADER : Yes, all IMST iM880A module pins
REMARK : None
5. Usage
---------
Projects for CooCox-CoIDE (partial), Ride7 and Keil Integrated Development Environments are available.
One project is available per application and for each hardware platform in each
development environment. Different targets/configurations have been created in
the different projects in order to select different options such as the usage or
not of a bootloader and the radio frequency band to be used.
6. Changelog
-------------
2015-08-07, v3.3
* General
1. Added the support for LoRaWAN Class C devices.
2. Implemented the radios errata note workarounds. SX1276 errata 2.3 "Receiver Spurious Reception of a LoRa Signal" is not yet implemented.
3. Increased FSK SyncWord timeout value in order to listen for longer time if a down link is available or not. Makes FSK downlink more reliable.
4. Increased the UART USB FIFO buffer size in order to handle bigger chunks of data.
* LoRaWAN
1. Renamed data rates as per LoRaWAN specification.
2. Added the support for LoRaWAN Class C devices.
3. Handling of the MAC commands was done incorrectly the condition to verify the length of the buffer has changed from < to <=.
4. Added the possibility to change the channel mask and number of repetitions trough SRV_MAC_LINK_ADR_REQ command when ADR is disabled.
5. Corrected Rx1DrOffset management. In previous version DR1 was missing for all offsets.
6. Changed confirmed messages function to use default datarate when ADR control is off.
7. After a Join accept the node falls back to the default datarate. Enables the user to Join a network using a different datarate from its own default one.
8. Corrected default FSK channel frequency.
9. Solved a firmware freezing when one of the following situations arrived in OnRxDone callback: bad address, bad MIC, bad frame. (Pull request #10)
10. Moved the MAC commands processing to the right places. FOpts field before the Payload and Port 0 just after the decryption. (Pull request #9)
11. Weird conditions to check datarate on cmd mac SRV_MAC_NEW_CHANNEL_REQ (Pull request #7)
12. Ignore join accept message if already joined (Pull request #6)
13. Channel index verification should use OR on SRV_MAC_NEW_CHANNEL_REQ command (Pull request #5)
14. Corrected the CFList management on JoinAccept. The for loop indexes were wrong. (Pull request #4)
15. Correction of AES key size (Pull request #3)
2015-04-30, v3.2
* General
1. Updated LoRaMac implementation according to LoRaWAN R1.0 specification
2. General cosmetics corrections
3. Added the support of packed structures when using IAR tool chain
4. Timers: Added a function to get the time in us.
5. Timers: Added a typedef for time variables (TimerTime_t)
6. Radios: Changed the TimeOnAir radio function to return a uint32_t value instead of a double. The value is in us.
7. Radios: Corrected the 250 kHz bandwidth choice for the FSK modem
8. GPS: Added a function that returns if the GPS has a fix or not.
9. GPS: Changed the GetPosition functions to return a latitude and longitude of 0 and altitude of 65535 when no GPS fix.
* LoRaWAN
1. Removed support for previous LoRaMac/LoRaWAN specifications
2. Added missing MAC commands and updated others when necessary
* Corrected the Port 0 MAC commands decryption
* Changed the way the upper layer is notified. Now it is only notified
when all the operations are finished.
When a ClassA Tx cycle starts a timer is launched to check every second if everything is finished.
* Added a new parameter to LoRaMacEventFlags structure that indicates on which Rx window the data has been received.
* Added a new parameter to LoRaMacEventFlags structure that indicates if there is applicative data on the received payload.
* Corrected ADR MAC command behaviour
* DutyCycle enforcement implementation (EU868 PHY only)
**REMARK 1** *The regulatory duty cycle enforcement is enabled by default
which means that for lower data rates the node may not transmit a new
frame as quickly as requested.
The formula used to compute the node idle time is*
*Toff = TimeOnAir / DutyCycle - TxTimeOnAir*
*Eaxample:*
*A device just transmitted a 0.5 s long frame on one default channel.
This channel is in a sub-band allowing 1% duty-cycle. Therefore this
whole sub-band (868 MHz - 868.6 MHz) will be unavailable for 49.5 s.*
**REMARK 2** *The duty cycle enforcement can be disabled for test
purposes by calling the LoRaMacSetDutyCycleOn function with false
parameter.*
* Implemented aggregated duty cycle management
* Added a function to create new channels
* Implemented the missing features on the JoinAccept MAC command
* Updated LoRaMacJoinDecrypt function to handle the CFList field.
3. Due to duty cycle management the applicative API has changed.
All applications must be updated accordingly.
4. Added the possibility to chose to use either public or private networks
2015-01-30, v3.1
* General
1. Started to add support for CooCox CoIDE Integrated Development Environment.
Currently only LoRaMote and SensorNode platform projects are available.
2. Updated GCC compiler linker scripts.
3. Added the support of different tool chains for the HardFault_Handler function.
4. Corrected Radio drivers I&Q signals inversion to be possible in Rx and in Tx.
Added some missing radio state machine initialization.
5. Changed the RSSI values type from int8_t to int16_t. We can have RSSI values below -128 dBm.
6. Corrected SNR computation on RxDone interrupt.
7. Updated radio API to support FHSS and CAD handling.
8. Corrected in SetRxConfig function the FSK modem preamble register name.
9. Added an invalid bandwidth to the Bandwidths table in order to avoid an error
when selecting 250 kHz bandwidth when using FSK modem.
10. Corrected RTC alarm setup which could be set to an invalid date.
11. Added another timer in order increment the tick counter without blocking the normal timer count.
12. Added the possibility to switch between low power timers and normal timers on the fly.
13. I2C driver corrected the 2 bytes internal address management.
Corrected buffer read function when more that 1 byte was to be read.
Added a function to wait for the I2C bus to become IDLE.
14. Added an I2C EEPROM driver.
15. Corrected and improved USB Virtual COM Port management files.
Corrected the USB CDC and USB UART drivers.
16. Added the possibility to analyze a hard fault interrupt.
* LoRaMac
1. Corrected RxWindow2 Datarate management.
2. SrvAckRequested variable was never reset.
3. Corrected tstIndoor applications for LoRaMac R3.0 support.
4. LoRaMac added the possibility to configure almost all the MAC parameters.
5. Corrected the LoRaMacSetNextChannel function.
6. Corrected the port 0 MAC command decoding.
7. Changed all structures declarations to be packed.
8. Corrected the Acknowledgement retries management when only 1 trial is needed.
Before the device was issuing at least 2 trials.
9. Corrected server mac new channel req answer.
10. Added the functions to read the Up and Down Link sequence counters.
11. Corrected SRV_MAC_RX2_SETUP_REQ frequency handling. Added a 100 multiplication.
12. Corrected SRV_MAC_NEW_CHANNEL_REQ. Removed the DutyCycle parameter decoding.
13. Automatically activate the channel once it is created.
14. Corrected NbRepTimeoutTimer initial value. RxWindow2Delay already contains RxWindow1Delay in it.
2014-07-18, v3.0
* General
1. Added to Radio API the possibility to select the modem.
2. Corrected RSSI reading formulas as well as changed the RSSI and SNR values from double to int8_t type.
3. Changed radio callbacks events to timeout when it is a timeout event and error when it is a CRC error.
4. Radio API updated.
5. Updated ping-pong applications.
6. Updated tx-cw applications.
7. Updated LoRaMac applications in order to handle LoRaMac returned functions calls status.
8. Updated LoRaMac applications to toggle LED2 each time there is an application payload down link.
9. Updated tstIndoor application to handle correctly more than 6 channels.
10. Changed the MPL3115 altitude variable from unsigned to signed value.
11. Replaced the usage of pow(2, n) by defining POW2 functions. Saves ~2 KBytes of code.
12. Corrected an issue potentially arriving when LOW_POWER_MODE_ENABLE wasn't defined.
A timer interrupt could be generated while the TimerList could already be emptied.
* LoRaMac
1. Implemented LoRaMac specification R3.0 changes.
2. MAC commands implemented
* LinkCheckReq **YES**
* LinkCheckAns **YES**
* LinkADRReq **YES**
* LinkADRAns **YES**
* DutyCycleReq **YES**
* DutyCycleAns **YES**
* Rx2SetupReq **YES**
* Rx2SetupAns **YES**
* DevStatusReq **YES**
* DevStatusAns **YES**
* JoinReq **YES**
* JoinAccept **YES**
* NewChannelReq **YES**
* NewChannelAns **YES**
3. Features implemented
* Possibility to shut-down the device **YES**
Possible by issuing DutyCycleReq MAC command.
* Duty cycle management enforcement **NO**
* Acknowledgements retries **YES**
* Unconfirmed messages retries **YES**
2014-07-10, v2.3.RC2
* General
1. Corrected all radios antenna switch low power mode handling.
2. SX1276: Corrected antenna switch control.
2014-06-06, v2.3.RC1
* General
1. Added the support for SX1276 radio.
2. Radio continuous reception mode correction.
3. Radio driver RxDone callback function API has changed ( size parameter is no more a pointer).
Previous function prototype:
void ( *RxDone )( uint8_t *payload, uint16_t *size, double rssi, double snr, uint8_t rawSnr );
New function prototype:
void ( *RxDone )( uint8_t *payload, uint16_t size, double rssi, double snr, uint8_t rawSnr );
4. Added Bleeper-76 and SensorNode platforms support.
5. Added to the radio drivers a function that generates a random value from
RSSI readings.
6. Added a project to transmit a continuous wave and a project to measure the
the radio sensitivity.
7. Added a bootloader project for the LoRaMote and SensorNode platforms.
8. The LoRaMac application for Bleeper platforms now sends the Selector and LED status plus the sensors values.
* The application payload for the Bleeper platforms is as follows:
LoRaMac port 1:
{ 0xX0/0xX1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
---------- ---------- ---------- ---------- ----
| | | | |
SELECTOR/LED PRESSURE TEMPERATURE ALTITUDE BATTERY
MSB nibble = SELECTOR (barometric)
LSB bit = LED
9. Redefined rand() and srand() standard C functions. These functions are
redefined in order to get the same behaviour across different compiler
tool chains implementations.
10. GPS driver improvements. Made independent of the board platform.
11. Simplified the RTC management.
12. Added a function to the timer driver that checks if a timer is already in
the list or not.
13. Added the UART Overrun bit exception handling to the UART driver.
14. Removed dependency of spi-board files to the "__builtin_ffs" function.
This function is only available on GNU compiler tool suite. Removed --gnu
compiler option from Keil projects. Added own __ffs function
implementation to utilities.h file.
15. Removed obsolete class1 devices support.
16. Known bugs correction.
* LoRaMac
1. MAC commands implemented
* LinkCheckReq **YES**
* LinkCheckAns **YES**
* LinkADRReq **YES**
* LinkADRAns **YES**
* DutyCycleReq **YES** (LoRaMac specification R2.2.1)
* DutyCycleAns **YES** (LoRaMac specification R2.2.1)
* Rx2SetupReq **YES** (LoRaMac specification R2.2.1)
* Rx2SetupAns **YES** (LoRaMac specification R2.2.1)
* DevStatusReq **YES**
* DevStatusAns **YES**
* JoinReq **YES**
* JoinAccept **YES** (LoRaMac specification R2.2.1)
* NewChannelReq **YES** (LoRaMac specification R2.2.1)
* NewChannelAns **YES** (LoRaMac specification R2.2.1)
2. Features implemented
* Possibility to shut-down the device **YES**
Possible by issuing DutyCycleReq MAC command.
* Duty cycle management enforcement **NO**
* Acknowledgements retries **WORK IN PROGRESS**
Not fully debugged. Disabled by default.
* Unconfirmed messages retries **WORK IN PROGRESS** (LoRaMac specification R2.2.1)
3. Implemented LoRaMac specification R2.2.1 changes.
4. Due to new specification the LoRaMacInitNwkIds LoRaMac API function had
to be modified.
Previous function prototype:
void LoRaMacInitNwkIds( uint32_t devAddr, uint8_t *nwkSKey, uint8_t *appSKey );
New function prototype:
void LoRaMacInitNwkIds( uint32_t netID, uint32_t devAddr, uint8_t *nwkSKey, uint8_t *appSKey );
5. Changed the LoRaMac channels management.
6. LoRaMac channels definition has been moved to LoRaMac-board.h file
located in each specific board directory.
2014-04-07, v2.2
* General
1. Added IMST SK-iM880A starter kit board support to the project.
* The application payload for the SK-iM880A platform is as follows:
LoRaMac port 3:
{ 0x00/0x01, 0x00, 0x00, 0x00 }
---------- ----- ----------
| | |
LED POTI VDD
2. Ping-Pong applications have been split per supported board.
3. Corrected the SX1272 output power management.
Added a variable to store the current Radio channel.
Added missing FSK bit definition.
4. Made fifo functions coding style coherent with the project.
5. UART driver is now independent of the used MCU
2014-03-28, v2.1
* General
1. The timers and RTC management has been rewritten.
2. Improved the UART and UP501 GPS drivers.
3. Corrected GPIO pin names management.
4. Corrected the antenna switch management in the SX1272 driver.
5. Added to the radio driver the possibility to choose the preamble length
and rxSingle symbol timeout in reception.
6. Added Hex coder selector driver for the Bleeper board.
7. Changed copyright Unicode character to (C) in all source files.
* LoRaMac
1. MAC commands implemented
* LinkCheckReq **YES**
* LinkCheckAns **YES**
* LinkADRReq **YES**
* LinkADRAns **YES**
* DevStatusReq **YES**
* DevStatusAns **YES**
* JoinReq **YES**
* JoinAccept **YES**
2. Added acknowledgements retries management.
Split the LoRaMacSendOnChannel function in LoRaMacPrepareFrame and
LoRaMacSendFrameOnChannel. LoRaMacSendOnChannel now calls the 2 newly
defined functions.
**WARNING**: By default the acknowledgement retries specific code isn't
enabled. The current http://iot.semtech.com server version doesn't support
it.
3. Corrected issues on JoinRequest and JoinAccept MAC commands.
Added LORAMAC_EVENT_INFO_STATUS_MAC_ERROR event info status.
2014-02-21, v2.0
* General
1. The LoRaMac applications now sends the LED status plus the sensors values.
For the LoRaMote platform the application also sends the GPS coordinates.
* The application payload for the Bleeper platform is as follows:
LoRaMac port 1:
{ 0x00/0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
---------- ---------- ---------- ---------- ----
| | | | |
LED PRESSURE TEMPERATURE ALTITUDE BATTERY
(barometric)
* The application payload for the LoRaMote platform is as follows:
LoRaMac port 2:
{ 0x00/0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
---------- ---------- ---------- ---------- ---- ---------------- ---------------- ----------
| | | | | | | |
LED PRESSURE TEMPERATURE ALTITUDE BATTERY LATITUDE LONGITUDE ALTITUDE
(barometric) (gps)
2. Adapted applications to the new MAC layer API.
3. Added sensors drivers implementation.
4. Corrected new or known issues.
* LoRaMac
1. MAC commands implemented
* LinkCheckReq **YES**
* LinkCheckAns **YES**
* LinkADRReq **YES**
* LinkADRAns **YES**
* DevStatusReq **YES**
* DevStatusAns **YES**
* JoinReq **YES (Not tested)**
* JoinAccept **YES (Not tested)**
2. New MAC layer application API implementation.
* Timers and RTC.
1. Still some issues. They will be corrected on next revisions of the firmware.
2014-01-24, v1.1
* LoRaMac
1. MAC commands implemented
* LinkCheckReq **NO**
* LinkCheckAns **NO**
* LinkADRReq **YES**
* LinkADRAns **YES**
* DevStatusReq **YES**
* DevStatusAns **YES**
2. Implemented an application LED control
If the server sends on port 1 an application payload of one byte with
the following contents:
0: LED off
1: LED on
The node transmits periodically on port 1 the LED status on 1st byte and
the message "Hello World!!!!" the array looks like:
{ 0, 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '!', '!', '!' }
* Timers and RTC.
1. Corrected issues existing in the previous version
2. Known bugs are:
* There is an issue when launching an asynchronous Timer. Will be solved
in a future version
2014-01-20, v1.1.RC1
* Added Doc directory. The directory contains:
1. LoRa MAC specification
2. Bleeper board schematic
* LoRaMac has been updated according to Release1 of the specification. Main changes are:
1. MAC API changed.
2. Frame format.
3. ClassA first ADR implementation.
4. MAC commands implemented
* LinkCheckReq **NO**
* LinkCheckAns **NO**
* LinkADRReq **YES**
* LinkADRAns **NO**
* DevStatusReq **NO**
* DevStatusAns **NO**
* Timers and RTC rewriting. Known bugs are:
1. The Radio wakeup time is taken in account for all timings.
2. When opening the second reception window the microcontroller sometimes doesn't enter in low power mode.
2013-11-28, v1.0
* Initial version of the LoRa MAC node firmware implementation.
| tdautc19841202/LoRaMac-node | readme.md | Markdown | bsd-3-clause | 25,552 |
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/core/SkStrokerPriv.h"
#include "include/private/SkMacros.h"
#include "include/private/SkTo.h"
#include "src/core/SkGeometry.h"
#include "src/core/SkPathPriv.h"
#include "src/core/SkPointPriv.h"
#include <utility>
enum {
kTangent_RecursiveLimit,
kCubic_RecursiveLimit,
kConic_RecursiveLimit,
kQuad_RecursiveLimit
};
// quads with extreme widths (e.g. (0,1) (1,6) (0,3) width=5e7) recurse to point of failure
// largest seen for normal cubics : 5, 26
// largest seen for normal quads : 11
static const int kRecursiveLimits[] = { 5*3, 26*3, 11*3, 11*3 }; // 3x limits seen in practice
static_assert(0 == kTangent_RecursiveLimit, "cubic_stroke_relies_on_tangent_equalling_zero");
static_assert(1 == kCubic_RecursiveLimit, "cubic_stroke_relies_on_cubic_equalling_one");
static_assert(SK_ARRAY_COUNT(kRecursiveLimits) == kQuad_RecursiveLimit + 1,
"recursive_limits_mismatch");
#if defined SK_DEBUG && QUAD_STROKE_APPROX_EXTENDED_DEBUGGING
int gMaxRecursion[SK_ARRAY_COUNT(kRecursiveLimits)] = { 0 };
#endif
#ifndef DEBUG_QUAD_STROKER
#define DEBUG_QUAD_STROKER 0
#endif
#if DEBUG_QUAD_STROKER
/* Enable to show the decisions made in subdividing the curve -- helpful when the resulting
stroke has more than the optimal number of quadratics and lines */
#define STROKER_RESULT(resultType, depth, quadPts, format, ...) \
SkDebugf("[%d] %s " format "\n", depth, __FUNCTION__, __VA_ARGS__), \
SkDebugf(" " #resultType " t=(%g,%g)\n", quadPts->fStartT, quadPts->fEndT), \
resultType
#define STROKER_DEBUG_PARAMS(...) , __VA_ARGS__
#else
#define STROKER_RESULT(resultType, depth, quadPts, format, ...) \
resultType
#define STROKER_DEBUG_PARAMS(...)
#endif
static inline bool degenerate_vector(const SkVector& v) {
return !SkPointPriv::CanNormalize(v.fX, v.fY);
}
static bool set_normal_unitnormal(const SkPoint& before, const SkPoint& after, SkScalar scale,
SkScalar radius,
SkVector* normal, SkVector* unitNormal) {
if (!unitNormal->setNormalize((after.fX - before.fX) * scale,
(after.fY - before.fY) * scale)) {
return false;
}
SkPointPriv::RotateCCW(unitNormal);
unitNormal->scale(radius, normal);
return true;
}
static bool set_normal_unitnormal(const SkVector& vec,
SkScalar radius,
SkVector* normal, SkVector* unitNormal) {
if (!unitNormal->setNormalize(vec.fX, vec.fY)) {
return false;
}
SkPointPriv::RotateCCW(unitNormal);
unitNormal->scale(radius, normal);
return true;
}
///////////////////////////////////////////////////////////////////////////////
struct SkQuadConstruct { // The state of the quad stroke under construction.
SkPoint fQuad[3]; // the stroked quad parallel to the original curve
SkPoint fTangentStart; // a point tangent to fQuad[0]
SkPoint fTangentEnd; // a point tangent to fQuad[2]
SkScalar fStartT; // a segment of the original curve
SkScalar fMidT; // "
SkScalar fEndT; // "
bool fStartSet; // state to share common points across structs
bool fEndSet; // "
bool fOppositeTangents; // set if coincident tangents have opposite directions
// return false if start and end are too close to have a unique middle
bool init(SkScalar start, SkScalar end) {
fStartT = start;
fMidT = (start + end) * SK_ScalarHalf;
fEndT = end;
fStartSet = fEndSet = false;
return fStartT < fMidT && fMidT < fEndT;
}
bool initWithStart(SkQuadConstruct* parent) {
if (!init(parent->fStartT, parent->fMidT)) {
return false;
}
fQuad[0] = parent->fQuad[0];
fTangentStart = parent->fTangentStart;
fStartSet = true;
return true;
}
bool initWithEnd(SkQuadConstruct* parent) {
if (!init(parent->fMidT, parent->fEndT)) {
return false;
}
fQuad[2] = parent->fQuad[2];
fTangentEnd = parent->fTangentEnd;
fEndSet = true;
return true;
}
};
class SkPathStroker {
public:
SkPathStroker(const SkPath& src,
SkScalar radius, SkScalar miterLimit, SkPaint::Cap,
SkPaint::Join, SkScalar resScale,
bool canIgnoreCenter);
bool hasOnlyMoveTo() const { return 0 == fSegmentCount; }
SkPoint moveToPt() const { return fFirstPt; }
void moveTo(const SkPoint&);
void lineTo(const SkPoint&, const SkPath::Iter* iter = nullptr);
void quadTo(const SkPoint&, const SkPoint&);
void conicTo(const SkPoint&, const SkPoint&, SkScalar weight);
void cubicTo(const SkPoint&, const SkPoint&, const SkPoint&);
void close(bool isLine) { this->finishContour(true, isLine); }
void done(SkPath* dst, bool isLine) {
this->finishContour(false, isLine);
dst->swap(fOuter);
}
SkScalar getResScale() const { return fResScale; }
bool isCurrentContourEmpty() const {
return fInner.isZeroLengthSincePoint(0) &&
fOuter.isZeroLengthSincePoint(fFirstOuterPtIndexInContour);
}
private:
SkScalar fRadius;
SkScalar fInvMiterLimit;
SkScalar fResScale;
SkScalar fInvResScale;
SkScalar fInvResScaleSquared;
SkVector fFirstNormal, fPrevNormal, fFirstUnitNormal, fPrevUnitNormal;
SkPoint fFirstPt, fPrevPt; // on original path
SkPoint fFirstOuterPt;
int fFirstOuterPtIndexInContour;
int fSegmentCount;
bool fPrevIsLine;
bool fCanIgnoreCenter;
SkStrokerPriv::CapProc fCapper;
SkStrokerPriv::JoinProc fJoiner;
SkPath fInner, fOuter, fCusper; // outer is our working answer, inner is temp
enum StrokeType {
kOuter_StrokeType = 1, // use sign-opposite values later to flip perpendicular axis
kInner_StrokeType = -1
} fStrokeType;
enum ResultType {
kSplit_ResultType, // the caller should split the quad stroke in two
kDegenerate_ResultType, // the caller should add a line
kQuad_ResultType, // the caller should (continue to try to) add a quad stroke
};
enum ReductionType {
kPoint_ReductionType, // all curve points are practically identical
kLine_ReductionType, // the control point is on the line between the ends
kQuad_ReductionType, // the control point is outside the line between the ends
kDegenerate_ReductionType, // the control point is on the line but outside the ends
kDegenerate2_ReductionType, // two control points are on the line but outside ends (cubic)
kDegenerate3_ReductionType, // three areas of max curvature found (for cubic)
};
enum IntersectRayType {
kCtrlPt_RayType,
kResultType_RayType,
};
int fRecursionDepth; // track stack depth to abort if numerics run amok
bool fFoundTangents; // do less work until tangents meet (cubic)
bool fJoinCompleted; // previous join was not degenerate
void addDegenerateLine(const SkQuadConstruct* );
static ReductionType CheckConicLinear(const SkConic& , SkPoint* reduction);
static ReductionType CheckCubicLinear(const SkPoint cubic[4], SkPoint reduction[3],
const SkPoint** tanPtPtr);
static ReductionType CheckQuadLinear(const SkPoint quad[3], SkPoint* reduction);
ResultType compareQuadConic(const SkConic& , SkQuadConstruct* ) const;
ResultType compareQuadCubic(const SkPoint cubic[4], SkQuadConstruct* );
ResultType compareQuadQuad(const SkPoint quad[3], SkQuadConstruct* );
void conicPerpRay(const SkConic& , SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const;
void conicQuadEnds(const SkConic& , SkQuadConstruct* ) const;
bool conicStroke(const SkConic& , SkQuadConstruct* );
bool cubicMidOnLine(const SkPoint cubic[4], const SkQuadConstruct* ) const;
void cubicPerpRay(const SkPoint cubic[4], SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const;
void cubicQuadEnds(const SkPoint cubic[4], SkQuadConstruct* );
void cubicQuadMid(const SkPoint cubic[4], const SkQuadConstruct* , SkPoint* mid) const;
bool cubicStroke(const SkPoint cubic[4], SkQuadConstruct* );
void init(StrokeType strokeType, SkQuadConstruct* , SkScalar tStart, SkScalar tEnd);
ResultType intersectRay(SkQuadConstruct* , IntersectRayType STROKER_DEBUG_PARAMS(int) ) const;
bool ptInQuadBounds(const SkPoint quad[3], const SkPoint& pt) const;
void quadPerpRay(const SkPoint quad[3], SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const;
bool quadStroke(const SkPoint quad[3], SkQuadConstruct* );
void setConicEndNormal(const SkConic& ,
const SkVector& normalAB, const SkVector& unitNormalAB,
SkVector* normalBC, SkVector* unitNormalBC);
void setCubicEndNormal(const SkPoint cubic[4],
const SkVector& normalAB, const SkVector& unitNormalAB,
SkVector* normalCD, SkVector* unitNormalCD);
void setQuadEndNormal(const SkPoint quad[3],
const SkVector& normalAB, const SkVector& unitNormalAB,
SkVector* normalBC, SkVector* unitNormalBC);
void setRayPts(const SkPoint& tPt, SkVector* dxy, SkPoint* onPt, SkPoint* tangent) const;
static bool SlightAngle(SkQuadConstruct* );
ResultType strokeCloseEnough(const SkPoint stroke[3], const SkPoint ray[2],
SkQuadConstruct* STROKER_DEBUG_PARAMS(int depth) ) const;
ResultType tangentsMeet(const SkPoint cubic[4], SkQuadConstruct* );
void finishContour(bool close, bool isLine);
bool preJoinTo(const SkPoint&, SkVector* normal, SkVector* unitNormal,
bool isLine);
void postJoinTo(const SkPoint&, const SkVector& normal,
const SkVector& unitNormal);
void line_to(const SkPoint& currPt, const SkVector& normal);
};
///////////////////////////////////////////////////////////////////////////////
bool SkPathStroker::preJoinTo(const SkPoint& currPt, SkVector* normal,
SkVector* unitNormal, bool currIsLine) {
SkASSERT(fSegmentCount >= 0);
SkScalar prevX = fPrevPt.fX;
SkScalar prevY = fPrevPt.fY;
if (!set_normal_unitnormal(fPrevPt, currPt, fResScale, fRadius, normal, unitNormal)) {
if (SkStrokerPriv::CapFactory(SkPaint::kButt_Cap) == fCapper) {
return false;
}
/* Square caps and round caps draw even if the segment length is zero.
Since the zero length segment has no direction, set the orientation
to upright as the default orientation */
normal->set(fRadius, 0);
unitNormal->set(1, 0);
}
if (fSegmentCount == 0) {
fFirstNormal = *normal;
fFirstUnitNormal = *unitNormal;
fFirstOuterPt.set(prevX + normal->fX, prevY + normal->fY);
fOuter.moveTo(fFirstOuterPt.fX, fFirstOuterPt.fY);
fInner.moveTo(prevX - normal->fX, prevY - normal->fY);
} else { // we have a previous segment
fJoiner(&fOuter, &fInner, fPrevUnitNormal, fPrevPt, *unitNormal,
fRadius, fInvMiterLimit, fPrevIsLine, currIsLine);
}
fPrevIsLine = currIsLine;
return true;
}
void SkPathStroker::postJoinTo(const SkPoint& currPt, const SkVector& normal,
const SkVector& unitNormal) {
fJoinCompleted = true;
fPrevPt = currPt;
fPrevUnitNormal = unitNormal;
fPrevNormal = normal;
fSegmentCount += 1;
}
void SkPathStroker::finishContour(bool close, bool currIsLine) {
if (fSegmentCount > 0) {
SkPoint pt;
if (close) {
fJoiner(&fOuter, &fInner, fPrevUnitNormal, fPrevPt,
fFirstUnitNormal, fRadius, fInvMiterLimit,
fPrevIsLine, currIsLine);
fOuter.close();
if (fCanIgnoreCenter) {
// If we can ignore the center just make sure the larger of the two paths
// is preserved and don't add the smaller one.
if (fInner.getBounds().contains(fOuter.getBounds())) {
fInner.swap(fOuter);
}
} else {
// now add fInner as its own contour
fInner.getLastPt(&pt);
fOuter.moveTo(pt.fX, pt.fY);
fOuter.reversePathTo(fInner);
fOuter.close();
}
} else { // add caps to start and end
// cap the end
fInner.getLastPt(&pt);
fCapper(&fOuter, fPrevPt, fPrevNormal, pt,
currIsLine ? &fInner : nullptr);
fOuter.reversePathTo(fInner);
// cap the start
fCapper(&fOuter, fFirstPt, -fFirstNormal, fFirstOuterPt,
fPrevIsLine ? &fInner : nullptr);
fOuter.close();
}
if (!fCusper.isEmpty()) {
fOuter.addPath(fCusper);
fCusper.rewind();
}
}
// since we may re-use fInner, we rewind instead of reset, to save on
// reallocating its internal storage.
fInner.rewind();
fSegmentCount = -1;
fFirstOuterPtIndexInContour = fOuter.countPoints();
}
///////////////////////////////////////////////////////////////////////////////
SkPathStroker::SkPathStroker(const SkPath& src,
SkScalar radius, SkScalar miterLimit,
SkPaint::Cap cap, SkPaint::Join join, SkScalar resScale,
bool canIgnoreCenter)
: fRadius(radius)
, fResScale(resScale)
, fCanIgnoreCenter(canIgnoreCenter) {
/* This is only used when join is miter_join, but we initialize it here
so that it is always defined, to fis valgrind warnings.
*/
fInvMiterLimit = 0;
if (join == SkPaint::kMiter_Join) {
if (miterLimit <= SK_Scalar1) {
join = SkPaint::kBevel_Join;
} else {
fInvMiterLimit = SkScalarInvert(miterLimit);
}
}
fCapper = SkStrokerPriv::CapFactory(cap);
fJoiner = SkStrokerPriv::JoinFactory(join);
fSegmentCount = -1;
fFirstOuterPtIndexInContour = 0;
fPrevIsLine = false;
// Need some estimate of how large our final result (fOuter)
// and our per-contour temp (fInner) will be, so we don't spend
// extra time repeatedly growing these arrays.
//
// 3x for result == inner + outer + join (swag)
// 1x for inner == 'wag' (worst contour length would be better guess)
fOuter.incReserve(src.countPoints() * 3);
fOuter.setIsVolatile(true);
fInner.incReserve(src.countPoints());
fInner.setIsVolatile(true);
// TODO : write a common error function used by stroking and filling
// The '4' below matches the fill scan converter's error term
fInvResScale = SkScalarInvert(resScale * 4);
fInvResScaleSquared = fInvResScale * fInvResScale;
fRecursionDepth = 0;
}
void SkPathStroker::moveTo(const SkPoint& pt) {
if (fSegmentCount > 0) {
this->finishContour(false, false);
}
fSegmentCount = 0;
fFirstPt = fPrevPt = pt;
fJoinCompleted = false;
}
void SkPathStroker::line_to(const SkPoint& currPt, const SkVector& normal) {
fOuter.lineTo(currPt.fX + normal.fX, currPt.fY + normal.fY);
fInner.lineTo(currPt.fX - normal.fX, currPt.fY - normal.fY);
}
static bool has_valid_tangent(const SkPath::Iter* iter) {
SkPath::Iter copy = *iter;
SkPath::Verb verb;
SkPoint pts[4];
while ((verb = copy.next(pts))) {
switch (verb) {
case SkPath::kMove_Verb:
return false;
case SkPath::kLine_Verb:
if (pts[0] == pts[1]) {
continue;
}
return true;
case SkPath::kQuad_Verb:
case SkPath::kConic_Verb:
if (pts[0] == pts[1] && pts[0] == pts[2]) {
continue;
}
return true;
case SkPath::kCubic_Verb:
if (pts[0] == pts[1] && pts[0] == pts[2] && pts[0] == pts[3]) {
continue;
}
return true;
case SkPath::kClose_Verb:
case SkPath::kDone_Verb:
return false;
}
}
return false;
}
void SkPathStroker::lineTo(const SkPoint& currPt, const SkPath::Iter* iter) {
bool teenyLine = SkPointPriv::EqualsWithinTolerance(fPrevPt, currPt, SK_ScalarNearlyZero * fInvResScale);
if (SkStrokerPriv::CapFactory(SkPaint::kButt_Cap) == fCapper && teenyLine) {
return;
}
if (teenyLine && (fJoinCompleted || (iter && has_valid_tangent(iter)))) {
return;
}
SkVector normal, unitNormal;
if (!this->preJoinTo(currPt, &normal, &unitNormal, true)) {
return;
}
this->line_to(currPt, normal);
this->postJoinTo(currPt, normal, unitNormal);
}
void SkPathStroker::setQuadEndNormal(const SkPoint quad[3], const SkVector& normalAB,
const SkVector& unitNormalAB, SkVector* normalBC, SkVector* unitNormalBC) {
if (!set_normal_unitnormal(quad[1], quad[2], fResScale, fRadius, normalBC, unitNormalBC)) {
*normalBC = normalAB;
*unitNormalBC = unitNormalAB;
}
}
void SkPathStroker::setConicEndNormal(const SkConic& conic, const SkVector& normalAB,
const SkVector& unitNormalAB, SkVector* normalBC, SkVector* unitNormalBC) {
setQuadEndNormal(conic.fPts, normalAB, unitNormalAB, normalBC, unitNormalBC);
}
void SkPathStroker::setCubicEndNormal(const SkPoint cubic[4], const SkVector& normalAB,
const SkVector& unitNormalAB, SkVector* normalCD, SkVector* unitNormalCD) {
SkVector ab = cubic[1] - cubic[0];
SkVector cd = cubic[3] - cubic[2];
bool degenerateAB = degenerate_vector(ab);
bool degenerateCD = degenerate_vector(cd);
if (degenerateAB && degenerateCD) {
goto DEGENERATE_NORMAL;
}
if (degenerateAB) {
ab = cubic[2] - cubic[0];
degenerateAB = degenerate_vector(ab);
}
if (degenerateCD) {
cd = cubic[3] - cubic[1];
degenerateCD = degenerate_vector(cd);
}
if (degenerateAB || degenerateCD) {
DEGENERATE_NORMAL:
*normalCD = normalAB;
*unitNormalCD = unitNormalAB;
return;
}
SkAssertResult(set_normal_unitnormal(cd, fRadius, normalCD, unitNormalCD));
}
void SkPathStroker::init(StrokeType strokeType, SkQuadConstruct* quadPts, SkScalar tStart,
SkScalar tEnd) {
fStrokeType = strokeType;
fFoundTangents = false;
quadPts->init(tStart, tEnd);
}
// returns the distance squared from the point to the line
static SkScalar pt_to_line(const SkPoint& pt, const SkPoint& lineStart, const SkPoint& lineEnd) {
SkVector dxy = lineEnd - lineStart;
SkVector ab0 = pt - lineStart;
SkScalar numer = dxy.dot(ab0);
SkScalar denom = dxy.dot(dxy);
SkScalar t = sk_ieee_float_divide(numer, denom);
if (t >= 0 && t <= 1) {
SkPoint hit;
hit.fX = lineStart.fX * (1 - t) + lineEnd.fX * t;
hit.fY = lineStart.fY * (1 - t) + lineEnd.fY * t;
return SkPointPriv::DistanceToSqd(hit, pt);
} else {
return SkPointPriv::DistanceToSqd(pt, lineStart);
}
}
/* Given a cubic, determine if all four points are in a line.
Return true if the inner points is close to a line connecting the outermost points.
Find the outermost point by looking for the largest difference in X or Y.
Given the indices of the outermost points, and that outer_1 is greater than outer_2,
this table shows the index of the smaller of the remaining points:
outer_2
0 1 2 3
outer_1 ----------------
0 | - 2 1 1
1 | - - 0 0
2 | - - - 0
3 | - - - -
If outer_1 == 0 and outer_2 == 1, the smaller of the remaining indices (2 and 3) is 2.
This table can be collapsed to: (1 + (2 >> outer_2)) >> outer_1
Given three indices (outer_1 outer_2 mid_1) from 0..3, the remaining index is:
mid_2 == (outer_1 ^ outer_2 ^ mid_1)
*/
static bool cubic_in_line(const SkPoint cubic[4]) {
SkScalar ptMax = -1;
int outer1 SK_INIT_TO_AVOID_WARNING;
int outer2 SK_INIT_TO_AVOID_WARNING;
for (int index = 0; index < 3; ++index) {
for (int inner = index + 1; inner < 4; ++inner) {
SkVector testDiff = cubic[inner] - cubic[index];
SkScalar testMax = SkTMax(SkScalarAbs(testDiff.fX), SkScalarAbs(testDiff.fY));
if (ptMax < testMax) {
outer1 = index;
outer2 = inner;
ptMax = testMax;
}
}
}
SkASSERT(outer1 >= 0 && outer1 <= 2);
SkASSERT(outer2 >= 1 && outer2 <= 3);
SkASSERT(outer1 < outer2);
int mid1 = (1 + (2 >> outer2)) >> outer1;
SkASSERT(mid1 >= 0 && mid1 <= 2);
SkASSERT(outer1 != mid1 && outer2 != mid1);
int mid2 = outer1 ^ outer2 ^ mid1;
SkASSERT(mid2 >= 1 && mid2 <= 3);
SkASSERT(mid2 != outer1 && mid2 != outer2 && mid2 != mid1);
SkASSERT(((1 << outer1) | (1 << outer2) | (1 << mid1) | (1 << mid2)) == 0x0f);
SkScalar lineSlop = ptMax * ptMax * 0.00001f; // this multiplier is pulled out of the air
return pt_to_line(cubic[mid1], cubic[outer1], cubic[outer2]) <= lineSlop
&& pt_to_line(cubic[mid2], cubic[outer1], cubic[outer2]) <= lineSlop;
}
/* Given quad, see if all there points are in a line.
Return true if the inside point is close to a line connecting the outermost points.
Find the outermost point by looking for the largest difference in X or Y.
Since the XOR of the indices is 3 (0 ^ 1 ^ 2)
the missing index equals: outer_1 ^ outer_2 ^ 3
*/
static bool quad_in_line(const SkPoint quad[3]) {
SkScalar ptMax = -1;
int outer1 SK_INIT_TO_AVOID_WARNING;
int outer2 SK_INIT_TO_AVOID_WARNING;
for (int index = 0; index < 2; ++index) {
for (int inner = index + 1; inner < 3; ++inner) {
SkVector testDiff = quad[inner] - quad[index];
SkScalar testMax = SkTMax(SkScalarAbs(testDiff.fX), SkScalarAbs(testDiff.fY));
if (ptMax < testMax) {
outer1 = index;
outer2 = inner;
ptMax = testMax;
}
}
}
SkASSERT(outer1 >= 0 && outer1 <= 1);
SkASSERT(outer2 >= 1 && outer2 <= 2);
SkASSERT(outer1 < outer2);
int mid = outer1 ^ outer2 ^ 3;
const float kCurvatureSlop = 0.000005f; // this multiplier is pulled out of the air
SkScalar lineSlop = ptMax * ptMax * kCurvatureSlop;
return pt_to_line(quad[mid], quad[outer1], quad[outer2]) <= lineSlop;
}
static bool conic_in_line(const SkConic& conic) {
return quad_in_line(conic.fPts);
}
SkPathStroker::ReductionType SkPathStroker::CheckCubicLinear(const SkPoint cubic[4],
SkPoint reduction[3], const SkPoint** tangentPtPtr) {
bool degenerateAB = degenerate_vector(cubic[1] - cubic[0]);
bool degenerateBC = degenerate_vector(cubic[2] - cubic[1]);
bool degenerateCD = degenerate_vector(cubic[3] - cubic[2]);
if (degenerateAB & degenerateBC & degenerateCD) {
return kPoint_ReductionType;
}
if (degenerateAB + degenerateBC + degenerateCD == 2) {
return kLine_ReductionType;
}
if (!cubic_in_line(cubic)) {
*tangentPtPtr = degenerateAB ? &cubic[2] : &cubic[1];
return kQuad_ReductionType;
}
SkScalar tValues[3];
int count = SkFindCubicMaxCurvature(cubic, tValues);
int rCount = 0;
// Now loop over the t-values, and reject any that evaluate to either end-point
for (int index = 0; index < count; ++index) {
SkScalar t = tValues[index];
if (0 >= t || t >= 1) {
continue;
}
SkEvalCubicAt(cubic, t, &reduction[rCount], nullptr, nullptr);
if (reduction[rCount] != cubic[0] && reduction[rCount] != cubic[3]) {
++rCount;
}
}
if (rCount == 0) {
return kLine_ReductionType;
}
static_assert(kQuad_ReductionType + 1 == kDegenerate_ReductionType, "enum_out_of_whack");
static_assert(kQuad_ReductionType + 2 == kDegenerate2_ReductionType, "enum_out_of_whack");
static_assert(kQuad_ReductionType + 3 == kDegenerate3_ReductionType, "enum_out_of_whack");
return (ReductionType) (kQuad_ReductionType + rCount);
}
SkPathStroker::ReductionType SkPathStroker::CheckConicLinear(const SkConic& conic,
SkPoint* reduction) {
bool degenerateAB = degenerate_vector(conic.fPts[1] - conic.fPts[0]);
bool degenerateBC = degenerate_vector(conic.fPts[2] - conic.fPts[1]);
if (degenerateAB & degenerateBC) {
return kPoint_ReductionType;
}
if (degenerateAB | degenerateBC) {
return kLine_ReductionType;
}
if (!conic_in_line(conic)) {
return kQuad_ReductionType;
}
// SkFindConicMaxCurvature would be a better solution, once we know how to
// implement it. Quad curvature is a reasonable substitute
SkScalar t = SkFindQuadMaxCurvature(conic.fPts);
if (0 == t) {
return kLine_ReductionType;
}
conic.evalAt(t, reduction, nullptr);
return kDegenerate_ReductionType;
}
SkPathStroker::ReductionType SkPathStroker::CheckQuadLinear(const SkPoint quad[3],
SkPoint* reduction) {
bool degenerateAB = degenerate_vector(quad[1] - quad[0]);
bool degenerateBC = degenerate_vector(quad[2] - quad[1]);
if (degenerateAB & degenerateBC) {
return kPoint_ReductionType;
}
if (degenerateAB | degenerateBC) {
return kLine_ReductionType;
}
if (!quad_in_line(quad)) {
return kQuad_ReductionType;
}
SkScalar t = SkFindQuadMaxCurvature(quad);
if (0 == t || 1 == t) {
return kLine_ReductionType;
}
*reduction = SkEvalQuadAt(quad, t);
return kDegenerate_ReductionType;
}
void SkPathStroker::conicTo(const SkPoint& pt1, const SkPoint& pt2, SkScalar weight) {
const SkConic conic(fPrevPt, pt1, pt2, weight);
SkPoint reduction;
ReductionType reductionType = CheckConicLinear(conic, &reduction);
if (kPoint_ReductionType == reductionType) {
/* If the stroke consists of a moveTo followed by a degenerate curve, treat it
as if it were followed by a zero-length line. Lines without length
can have square and round end caps. */
this->lineTo(pt2);
return;
}
if (kLine_ReductionType == reductionType) {
this->lineTo(pt2);
return;
}
if (kDegenerate_ReductionType == reductionType) {
this->lineTo(reduction);
SkStrokerPriv::JoinProc saveJoiner = fJoiner;
fJoiner = SkStrokerPriv::JoinFactory(SkPaint::kRound_Join);
this->lineTo(pt2);
fJoiner = saveJoiner;
return;
}
SkASSERT(kQuad_ReductionType == reductionType);
SkVector normalAB, unitAB, normalBC, unitBC;
if (!this->preJoinTo(pt1, &normalAB, &unitAB, false)) {
this->lineTo(pt2);
return;
}
SkQuadConstruct quadPts;
this->init(kOuter_StrokeType, &quadPts, 0, 1);
(void) this->conicStroke(conic, &quadPts);
this->init(kInner_StrokeType, &quadPts, 0, 1);
(void) this->conicStroke(conic, &quadPts);
this->setConicEndNormal(conic, normalAB, unitAB, &normalBC, &unitBC);
this->postJoinTo(pt2, normalBC, unitBC);
}
void SkPathStroker::quadTo(const SkPoint& pt1, const SkPoint& pt2) {
const SkPoint quad[3] = { fPrevPt, pt1, pt2 };
SkPoint reduction;
ReductionType reductionType = CheckQuadLinear(quad, &reduction);
if (kPoint_ReductionType == reductionType) {
/* If the stroke consists of a moveTo followed by a degenerate curve, treat it
as if it were followed by a zero-length line. Lines without length
can have square and round end caps. */
this->lineTo(pt2);
return;
}
if (kLine_ReductionType == reductionType) {
this->lineTo(pt2);
return;
}
if (kDegenerate_ReductionType == reductionType) {
this->lineTo(reduction);
SkStrokerPriv::JoinProc saveJoiner = fJoiner;
fJoiner = SkStrokerPriv::JoinFactory(SkPaint::kRound_Join);
this->lineTo(pt2);
fJoiner = saveJoiner;
return;
}
SkASSERT(kQuad_ReductionType == reductionType);
SkVector normalAB, unitAB, normalBC, unitBC;
if (!this->preJoinTo(pt1, &normalAB, &unitAB, false)) {
this->lineTo(pt2);
return;
}
SkQuadConstruct quadPts;
this->init(kOuter_StrokeType, &quadPts, 0, 1);
(void) this->quadStroke(quad, &quadPts);
this->init(kInner_StrokeType, &quadPts, 0, 1);
(void) this->quadStroke(quad, &quadPts);
this->setQuadEndNormal(quad, normalAB, unitAB, &normalBC, &unitBC);
this->postJoinTo(pt2, normalBC, unitBC);
}
// Given a point on the curve and its derivative, scale the derivative by the radius, and
// compute the perpendicular point and its tangent.
void SkPathStroker::setRayPts(const SkPoint& tPt, SkVector* dxy, SkPoint* onPt,
SkPoint* tangent) const {
if (!dxy->setLength(fRadius)) {
dxy->set(fRadius, 0);
}
SkScalar axisFlip = SkIntToScalar(fStrokeType); // go opposite ways for outer, inner
onPt->fX = tPt.fX + axisFlip * dxy->fY;
onPt->fY = tPt.fY - axisFlip * dxy->fX;
if (tangent) {
tangent->fX = onPt->fX + dxy->fX;
tangent->fY = onPt->fY + dxy->fY;
}
}
// Given a conic and t, return the point on curve, its perpendicular, and the perpendicular tangent.
// Returns false if the perpendicular could not be computed (because the derivative collapsed to 0)
void SkPathStroker::conicPerpRay(const SkConic& conic, SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const {
SkVector dxy;
conic.evalAt(t, tPt, &dxy);
if (dxy.fX == 0 && dxy.fY == 0) {
dxy = conic.fPts[2] - conic.fPts[0];
}
this->setRayPts(*tPt, &dxy, onPt, tangent);
}
// Given a conic and a t range, find the start and end if they haven't been found already.
void SkPathStroker::conicQuadEnds(const SkConic& conic, SkQuadConstruct* quadPts) const {
if (!quadPts->fStartSet) {
SkPoint conicStartPt;
this->conicPerpRay(conic, quadPts->fStartT, &conicStartPt, &quadPts->fQuad[0],
&quadPts->fTangentStart);
quadPts->fStartSet = true;
}
if (!quadPts->fEndSet) {
SkPoint conicEndPt;
this->conicPerpRay(conic, quadPts->fEndT, &conicEndPt, &quadPts->fQuad[2],
&quadPts->fTangentEnd);
quadPts->fEndSet = true;
}
}
// Given a cubic and t, return the point on curve, its perpendicular, and the perpendicular tangent.
void SkPathStroker::cubicPerpRay(const SkPoint cubic[4], SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const {
SkVector dxy;
SkPoint chopped[7];
SkEvalCubicAt(cubic, t, tPt, &dxy, nullptr);
if (dxy.fX == 0 && dxy.fY == 0) {
const SkPoint* cPts = cubic;
if (SkScalarNearlyZero(t)) {
dxy = cubic[2] - cubic[0];
} else if (SkScalarNearlyZero(1 - t)) {
dxy = cubic[3] - cubic[1];
} else {
// If the cubic inflection falls on the cusp, subdivide the cubic
// to find the tangent at that point.
SkChopCubicAt(cubic, chopped, t);
dxy = chopped[3] - chopped[2];
if (dxy.fX == 0 && dxy.fY == 0) {
dxy = chopped[3] - chopped[1];
cPts = chopped;
}
}
if (dxy.fX == 0 && dxy.fY == 0) {
dxy = cPts[3] - cPts[0];
}
}
setRayPts(*tPt, &dxy, onPt, tangent);
}
// Given a cubic and a t range, find the start and end if they haven't been found already.
void SkPathStroker::cubicQuadEnds(const SkPoint cubic[4], SkQuadConstruct* quadPts) {
if (!quadPts->fStartSet) {
SkPoint cubicStartPt;
this->cubicPerpRay(cubic, quadPts->fStartT, &cubicStartPt, &quadPts->fQuad[0],
&quadPts->fTangentStart);
quadPts->fStartSet = true;
}
if (!quadPts->fEndSet) {
SkPoint cubicEndPt;
this->cubicPerpRay(cubic, quadPts->fEndT, &cubicEndPt, &quadPts->fQuad[2],
&quadPts->fTangentEnd);
quadPts->fEndSet = true;
}
}
void SkPathStroker::cubicQuadMid(const SkPoint cubic[4], const SkQuadConstruct* quadPts,
SkPoint* mid) const {
SkPoint cubicMidPt;
this->cubicPerpRay(cubic, quadPts->fMidT, &cubicMidPt, mid, nullptr);
}
// Given a quad and t, return the point on curve, its perpendicular, and the perpendicular tangent.
void SkPathStroker::quadPerpRay(const SkPoint quad[3], SkScalar t, SkPoint* tPt, SkPoint* onPt,
SkPoint* tangent) const {
SkVector dxy;
SkEvalQuadAt(quad, t, tPt, &dxy);
if (dxy.fX == 0 && dxy.fY == 0) {
dxy = quad[2] - quad[0];
}
setRayPts(*tPt, &dxy, onPt, tangent);
}
// Find the intersection of the stroke tangents to construct a stroke quad.
// Return whether the stroke is a degenerate (a line), a quad, or must be split.
// Optionally compute the quad's control point.
SkPathStroker::ResultType SkPathStroker::intersectRay(SkQuadConstruct* quadPts,
IntersectRayType intersectRayType STROKER_DEBUG_PARAMS(int depth)) const {
const SkPoint& start = quadPts->fQuad[0];
const SkPoint& end = quadPts->fQuad[2];
SkVector aLen = quadPts->fTangentStart - start;
SkVector bLen = quadPts->fTangentEnd - end;
/* Slopes match when denom goes to zero:
axLen / ayLen == bxLen / byLen
(ayLen * byLen) * axLen / ayLen == (ayLen * byLen) * bxLen / byLen
byLen * axLen == ayLen * bxLen
byLen * axLen - ayLen * bxLen ( == denom )
*/
SkScalar denom = aLen.cross(bLen);
if (denom == 0 || !SkScalarIsFinite(denom)) {
quadPts->fOppositeTangents = aLen.dot(bLen) < 0;
return STROKER_RESULT(kDegenerate_ResultType, depth, quadPts, "denom == 0");
}
quadPts->fOppositeTangents = false;
SkVector ab0 = start - end;
SkScalar numerA = bLen.cross(ab0);
SkScalar numerB = aLen.cross(ab0);
if ((numerA >= 0) == (numerB >= 0)) { // if the control point is outside the quad ends
// if the perpendicular distances from the quad points to the opposite tangent line
// are small, a straight line is good enough
SkScalar dist1 = pt_to_line(start, end, quadPts->fTangentEnd);
SkScalar dist2 = pt_to_line(end, start, quadPts->fTangentStart);
if (SkTMax(dist1, dist2) <= fInvResScaleSquared) {
return STROKER_RESULT(kDegenerate_ResultType, depth, quadPts,
"SkTMax(dist1=%g, dist2=%g) <= fInvResScaleSquared", dist1, dist2);
}
return STROKER_RESULT(kSplit_ResultType, depth, quadPts,
"(numerA=%g >= 0) == (numerB=%g >= 0)", numerA, numerB);
}
// check to see if the denominator is teeny relative to the numerator
// if the offset by one will be lost, the ratio is too large
numerA /= denom;
bool validDivide = numerA > numerA - 1;
if (validDivide) {
if (kCtrlPt_RayType == intersectRayType) {
SkPoint* ctrlPt = &quadPts->fQuad[1];
// the intersection of the tangents need not be on the tangent segment
// so 0 <= numerA <= 1 is not necessarily true
ctrlPt->fX = start.fX * (1 - numerA) + quadPts->fTangentStart.fX * numerA;
ctrlPt->fY = start.fY * (1 - numerA) + quadPts->fTangentStart.fY * numerA;
}
return STROKER_RESULT(kQuad_ResultType, depth, quadPts,
"(numerA=%g >= 0) != (numerB=%g >= 0)", numerA, numerB);
}
quadPts->fOppositeTangents = aLen.dot(bLen) < 0;
// if the lines are parallel, straight line is good enough
return STROKER_RESULT(kDegenerate_ResultType, depth, quadPts,
"SkScalarNearlyZero(denom=%g)", denom);
}
// Given a cubic and a t-range, determine if the stroke can be described by a quadratic.
SkPathStroker::ResultType SkPathStroker::tangentsMeet(const SkPoint cubic[4],
SkQuadConstruct* quadPts) {
this->cubicQuadEnds(cubic, quadPts);
return this->intersectRay(quadPts, kResultType_RayType STROKER_DEBUG_PARAMS(fRecursionDepth));
}
// Intersect the line with the quad and return the t values on the quad where the line crosses.
static int intersect_quad_ray(const SkPoint line[2], const SkPoint quad[3], SkScalar roots[2]) {
SkVector vec = line[1] - line[0];
SkScalar r[3];
for (int n = 0; n < 3; ++n) {
r[n] = (quad[n].fY - line[0].fY) * vec.fX - (quad[n].fX - line[0].fX) * vec.fY;
}
SkScalar A = r[2];
SkScalar B = r[1];
SkScalar C = r[0];
A += C - 2 * B; // A = a - 2*b + c
B -= C; // B = -(b - c)
return SkFindUnitQuadRoots(A, 2 * B, C, roots);
}
// Return true if the point is close to the bounds of the quad. This is used as a quick reject.
bool SkPathStroker::ptInQuadBounds(const SkPoint quad[3], const SkPoint& pt) const {
SkScalar xMin = SkTMin(SkTMin(quad[0].fX, quad[1].fX), quad[2].fX);
if (pt.fX + fInvResScale < xMin) {
return false;
}
SkScalar xMax = SkTMax(SkTMax(quad[0].fX, quad[1].fX), quad[2].fX);
if (pt.fX - fInvResScale > xMax) {
return false;
}
SkScalar yMin = SkTMin(SkTMin(quad[0].fY, quad[1].fY), quad[2].fY);
if (pt.fY + fInvResScale < yMin) {
return false;
}
SkScalar yMax = SkTMax(SkTMax(quad[0].fY, quad[1].fY), quad[2].fY);
if (pt.fY - fInvResScale > yMax) {
return false;
}
return true;
}
static bool points_within_dist(const SkPoint& nearPt, const SkPoint& farPt, SkScalar limit) {
return SkPointPriv::DistanceToSqd(nearPt, farPt) <= limit * limit;
}
static bool sharp_angle(const SkPoint quad[3]) {
SkVector smaller = quad[1] - quad[0];
SkVector larger = quad[1] - quad[2];
SkScalar smallerLen = SkPointPriv::LengthSqd(smaller);
SkScalar largerLen = SkPointPriv::LengthSqd(larger);
if (smallerLen > largerLen) {
using std::swap;
swap(smaller, larger);
largerLen = smallerLen;
}
if (!smaller.setLength(largerLen)) {
return false;
}
SkScalar dot = smaller.dot(larger);
return dot > 0;
}
SkPathStroker::ResultType SkPathStroker::strokeCloseEnough(const SkPoint stroke[3],
const SkPoint ray[2], SkQuadConstruct* quadPts STROKER_DEBUG_PARAMS(int depth)) const {
SkPoint strokeMid = SkEvalQuadAt(stroke, SK_ScalarHalf);
// measure the distance from the curve to the quad-stroke midpoint, compare to radius
if (points_within_dist(ray[0], strokeMid, fInvResScale)) { // if the difference is small
if (sharp_angle(quadPts->fQuad)) {
return STROKER_RESULT(kSplit_ResultType, depth, quadPts,
"sharp_angle (1) =%g,%g, %g,%g, %g,%g",
quadPts->fQuad[0].fX, quadPts->fQuad[0].fY,
quadPts->fQuad[1].fX, quadPts->fQuad[1].fY,
quadPts->fQuad[2].fX, quadPts->fQuad[2].fY);
}
return STROKER_RESULT(kQuad_ResultType, depth, quadPts,
"points_within_dist(ray[0]=%g,%g, strokeMid=%g,%g, fInvResScale=%g)",
ray[0].fX, ray[0].fY, strokeMid.fX, strokeMid.fY, fInvResScale);
}
// measure the distance to quad's bounds (quick reject)
// an alternative : look for point in triangle
if (!ptInQuadBounds(stroke, ray[0])) { // if far, subdivide
return STROKER_RESULT(kSplit_ResultType, depth, quadPts,
"!pt_in_quad_bounds(stroke=(%g,%g %g,%g %g,%g), ray[0]=%g,%g)",
stroke[0].fX, stroke[0].fY, stroke[1].fX, stroke[1].fY, stroke[2].fX, stroke[2].fY,
ray[0].fX, ray[0].fY);
}
// measure the curve ray distance to the quad-stroke
SkScalar roots[2];
int rootCount = intersect_quad_ray(ray, stroke, roots);
if (rootCount != 1) {
return STROKER_RESULT(kSplit_ResultType, depth, quadPts,
"rootCount=%d != 1", rootCount);
}
SkPoint quadPt = SkEvalQuadAt(stroke, roots[0]);
SkScalar error = fInvResScale * (SK_Scalar1 - SkScalarAbs(roots[0] - 0.5f) * 2);
if (points_within_dist(ray[0], quadPt, error)) { // if the difference is small, we're done
if (sharp_angle(quadPts->fQuad)) {
return STROKER_RESULT(kSplit_ResultType, depth, quadPts,
"sharp_angle (2) =%g,%g, %g,%g, %g,%g",
quadPts->fQuad[0].fX, quadPts->fQuad[0].fY,
quadPts->fQuad[1].fX, quadPts->fQuad[1].fY,
quadPts->fQuad[2].fX, quadPts->fQuad[2].fY);
}
return STROKER_RESULT(kQuad_ResultType, depth, quadPts,
"points_within_dist(ray[0]=%g,%g, quadPt=%g,%g, error=%g)",
ray[0].fX, ray[0].fY, quadPt.fX, quadPt.fY, error);
}
// otherwise, subdivide
return STROKER_RESULT(kSplit_ResultType, depth, quadPts, "%s", "fall through");
}
SkPathStroker::ResultType SkPathStroker::compareQuadCubic(const SkPoint cubic[4],
SkQuadConstruct* quadPts) {
// get the quadratic approximation of the stroke
this->cubicQuadEnds(cubic, quadPts);
ResultType resultType = this->intersectRay(quadPts, kCtrlPt_RayType
STROKER_DEBUG_PARAMS(fRecursionDepth) );
if (resultType != kQuad_ResultType) {
return resultType;
}
// project a ray from the curve to the stroke
SkPoint ray[2]; // points near midpoint on quad, midpoint on cubic
this->cubicPerpRay(cubic, quadPts->fMidT, &ray[1], &ray[0], nullptr);
return this->strokeCloseEnough(quadPts->fQuad, ray, quadPts
STROKER_DEBUG_PARAMS(fRecursionDepth));
}
SkPathStroker::ResultType SkPathStroker::compareQuadConic(const SkConic& conic,
SkQuadConstruct* quadPts) const {
// get the quadratic approximation of the stroke
this->conicQuadEnds(conic, quadPts);
ResultType resultType = this->intersectRay(quadPts, kCtrlPt_RayType
STROKER_DEBUG_PARAMS(fRecursionDepth) );
if (resultType != kQuad_ResultType) {
return resultType;
}
// project a ray from the curve to the stroke
SkPoint ray[2]; // points near midpoint on quad, midpoint on conic
this->conicPerpRay(conic, quadPts->fMidT, &ray[1], &ray[0], nullptr);
return this->strokeCloseEnough(quadPts->fQuad, ray, quadPts
STROKER_DEBUG_PARAMS(fRecursionDepth));
}
SkPathStroker::ResultType SkPathStroker::compareQuadQuad(const SkPoint quad[3],
SkQuadConstruct* quadPts) {
// get the quadratic approximation of the stroke
if (!quadPts->fStartSet) {
SkPoint quadStartPt;
this->quadPerpRay(quad, quadPts->fStartT, &quadStartPt, &quadPts->fQuad[0],
&quadPts->fTangentStart);
quadPts->fStartSet = true;
}
if (!quadPts->fEndSet) {
SkPoint quadEndPt;
this->quadPerpRay(quad, quadPts->fEndT, &quadEndPt, &quadPts->fQuad[2],
&quadPts->fTangentEnd);
quadPts->fEndSet = true;
}
ResultType resultType = this->intersectRay(quadPts, kCtrlPt_RayType
STROKER_DEBUG_PARAMS(fRecursionDepth));
if (resultType != kQuad_ResultType) {
return resultType;
}
// project a ray from the curve to the stroke
SkPoint ray[2];
this->quadPerpRay(quad, quadPts->fMidT, &ray[1], &ray[0], nullptr);
return this->strokeCloseEnough(quadPts->fQuad, ray, quadPts
STROKER_DEBUG_PARAMS(fRecursionDepth));
}
void SkPathStroker::addDegenerateLine(const SkQuadConstruct* quadPts) {
const SkPoint* quad = quadPts->fQuad;
SkPath* path = fStrokeType == kOuter_StrokeType ? &fOuter : &fInner;
path->lineTo(quad[2].fX, quad[2].fY);
}
bool SkPathStroker::cubicMidOnLine(const SkPoint cubic[4], const SkQuadConstruct* quadPts) const {
SkPoint strokeMid;
this->cubicQuadMid(cubic, quadPts, &strokeMid);
SkScalar dist = pt_to_line(strokeMid, quadPts->fQuad[0], quadPts->fQuad[2]);
return dist < fInvResScaleSquared;
}
bool SkPathStroker::cubicStroke(const SkPoint cubic[4], SkQuadConstruct* quadPts) {
if (!fFoundTangents) {
ResultType resultType = this->tangentsMeet(cubic, quadPts);
if (kQuad_ResultType != resultType) {
if ((kDegenerate_ResultType == resultType
|| points_within_dist(quadPts->fQuad[0], quadPts->fQuad[2],
fInvResScale)) && cubicMidOnLine(cubic, quadPts)) {
addDegenerateLine(quadPts);
return true;
}
} else {
fFoundTangents = true;
}
}
if (fFoundTangents) {
ResultType resultType = this->compareQuadCubic(cubic, quadPts);
if (kQuad_ResultType == resultType) {
SkPath* path = fStrokeType == kOuter_StrokeType ? &fOuter : &fInner;
const SkPoint* stroke = quadPts->fQuad;
path->quadTo(stroke[1].fX, stroke[1].fY, stroke[2].fX, stroke[2].fY);
return true;
}
if (kDegenerate_ResultType == resultType) {
if (!quadPts->fOppositeTangents) {
addDegenerateLine(quadPts);
return true;
}
}
}
if (!SkScalarIsFinite(quadPts->fQuad[2].fX) || !SkScalarIsFinite(quadPts->fQuad[2].fY)) {
return false; // just abort if projected quad isn't representable
}
#if QUAD_STROKE_APPROX_EXTENDED_DEBUGGING
SkDEBUGCODE(gMaxRecursion[fFoundTangents] = SkTMax(gMaxRecursion[fFoundTangents],
fRecursionDepth + 1));
#endif
if (++fRecursionDepth > kRecursiveLimits[fFoundTangents]) {
return false; // just abort if projected quad isn't representable
}
SkQuadConstruct half;
if (!half.initWithStart(quadPts)) {
addDegenerateLine(quadPts);
--fRecursionDepth;
return true;
}
if (!this->cubicStroke(cubic, &half)) {
return false;
}
if (!half.initWithEnd(quadPts)) {
addDegenerateLine(quadPts);
--fRecursionDepth;
return true;
}
if (!this->cubicStroke(cubic, &half)) {
return false;
}
--fRecursionDepth;
return true;
}
bool SkPathStroker::conicStroke(const SkConic& conic, SkQuadConstruct* quadPts) {
ResultType resultType = this->compareQuadConic(conic, quadPts);
if (kQuad_ResultType == resultType) {
const SkPoint* stroke = quadPts->fQuad;
SkPath* path = fStrokeType == kOuter_StrokeType ? &fOuter : &fInner;
path->quadTo(stroke[1].fX, stroke[1].fY, stroke[2].fX, stroke[2].fY);
return true;
}
if (kDegenerate_ResultType == resultType) {
addDegenerateLine(quadPts);
return true;
}
#if QUAD_STROKE_APPROX_EXTENDED_DEBUGGING
SkDEBUGCODE(gMaxRecursion[kConic_RecursiveLimit] = SkTMax(gMaxRecursion[kConic_RecursiveLimit],
fRecursionDepth + 1));
#endif
if (++fRecursionDepth > kRecursiveLimits[kConic_RecursiveLimit]) {
return false; // just abort if projected quad isn't representable
}
SkQuadConstruct half;
(void) half.initWithStart(quadPts);
if (!this->conicStroke(conic, &half)) {
return false;
}
(void) half.initWithEnd(quadPts);
if (!this->conicStroke(conic, &half)) {
return false;
}
--fRecursionDepth;
return true;
}
bool SkPathStroker::quadStroke(const SkPoint quad[3], SkQuadConstruct* quadPts) {
ResultType resultType = this->compareQuadQuad(quad, quadPts);
if (kQuad_ResultType == resultType) {
const SkPoint* stroke = quadPts->fQuad;
SkPath* path = fStrokeType == kOuter_StrokeType ? &fOuter : &fInner;
path->quadTo(stroke[1].fX, stroke[1].fY, stroke[2].fX, stroke[2].fY);
return true;
}
if (kDegenerate_ResultType == resultType) {
addDegenerateLine(quadPts);
return true;
}
#if QUAD_STROKE_APPROX_EXTENDED_DEBUGGING
SkDEBUGCODE(gMaxRecursion[kQuad_RecursiveLimit] = SkTMax(gMaxRecursion[kQuad_RecursiveLimit],
fRecursionDepth + 1));
#endif
if (++fRecursionDepth > kRecursiveLimits[kQuad_RecursiveLimit]) {
return false; // just abort if projected quad isn't representable
}
SkQuadConstruct half;
(void) half.initWithStart(quadPts);
if (!this->quadStroke(quad, &half)) {
return false;
}
(void) half.initWithEnd(quadPts);
if (!this->quadStroke(quad, &half)) {
return false;
}
--fRecursionDepth;
return true;
}
void SkPathStroker::cubicTo(const SkPoint& pt1, const SkPoint& pt2,
const SkPoint& pt3) {
const SkPoint cubic[4] = { fPrevPt, pt1, pt2, pt3 };
SkPoint reduction[3];
const SkPoint* tangentPt;
ReductionType reductionType = CheckCubicLinear(cubic, reduction, &tangentPt);
if (kPoint_ReductionType == reductionType) {
/* If the stroke consists of a moveTo followed by a degenerate curve, treat it
as if it were followed by a zero-length line. Lines without length
can have square and round end caps. */
this->lineTo(pt3);
return;
}
if (kLine_ReductionType == reductionType) {
this->lineTo(pt3);
return;
}
if (kDegenerate_ReductionType <= reductionType && kDegenerate3_ReductionType >= reductionType) {
this->lineTo(reduction[0]);
SkStrokerPriv::JoinProc saveJoiner = fJoiner;
fJoiner = SkStrokerPriv::JoinFactory(SkPaint::kRound_Join);
if (kDegenerate2_ReductionType <= reductionType) {
this->lineTo(reduction[1]);
}
if (kDegenerate3_ReductionType == reductionType) {
this->lineTo(reduction[2]);
}
this->lineTo(pt3);
fJoiner = saveJoiner;
return;
}
SkASSERT(kQuad_ReductionType == reductionType);
SkVector normalAB, unitAB, normalCD, unitCD;
if (!this->preJoinTo(*tangentPt, &normalAB, &unitAB, false)) {
this->lineTo(pt3);
return;
}
SkScalar tValues[2];
int count = SkFindCubicInflections(cubic, tValues);
SkScalar lastT = 0;
for (int index = 0; index <= count; ++index) {
SkScalar nextT = index < count ? tValues[index] : 1;
SkQuadConstruct quadPts;
this->init(kOuter_StrokeType, &quadPts, lastT, nextT);
(void) this->cubicStroke(cubic, &quadPts);
this->init(kInner_StrokeType, &quadPts, lastT, nextT);
(void) this->cubicStroke(cubic, &quadPts);
lastT = nextT;
}
SkScalar cusp = SkFindCubicCusp(cubic);
if (cusp > 0) {
SkPoint cuspLoc;
SkEvalCubicAt(cubic, cusp, &cuspLoc, nullptr, nullptr);
fCusper.addCircle(cuspLoc.fX, cuspLoc.fY, fRadius);
}
// emit the join even if one stroke succeeded but the last one failed
// this avoids reversing an inner stroke with a partial path followed by another moveto
this->setCubicEndNormal(cubic, normalAB, unitAB, &normalCD, &unitCD);
this->postJoinTo(pt3, normalCD, unitCD);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#include "src/core/SkPaintDefaults.h"
SkStroke::SkStroke() {
fWidth = SK_Scalar1;
fMiterLimit = SkPaintDefaults_MiterLimit;
fResScale = 1;
fCap = SkPaint::kDefault_Cap;
fJoin = SkPaint::kDefault_Join;
fDoFill = false;
}
SkStroke::SkStroke(const SkPaint& p) {
fWidth = p.getStrokeWidth();
fMiterLimit = p.getStrokeMiter();
fResScale = 1;
fCap = (uint8_t)p.getStrokeCap();
fJoin = (uint8_t)p.getStrokeJoin();
fDoFill = SkToU8(p.getStyle() == SkPaint::kStrokeAndFill_Style);
}
SkStroke::SkStroke(const SkPaint& p, SkScalar width) {
fWidth = width;
fMiterLimit = p.getStrokeMiter();
fResScale = 1;
fCap = (uint8_t)p.getStrokeCap();
fJoin = (uint8_t)p.getStrokeJoin();
fDoFill = SkToU8(p.getStyle() == SkPaint::kStrokeAndFill_Style);
}
void SkStroke::setWidth(SkScalar width) {
SkASSERT(width >= 0);
fWidth = width;
}
void SkStroke::setMiterLimit(SkScalar miterLimit) {
SkASSERT(miterLimit >= 0);
fMiterLimit = miterLimit;
}
void SkStroke::setCap(SkPaint::Cap cap) {
SkASSERT((unsigned)cap < SkPaint::kCapCount);
fCap = SkToU8(cap);
}
void SkStroke::setJoin(SkPaint::Join join) {
SkASSERT((unsigned)join < SkPaint::kJoinCount);
fJoin = SkToU8(join);
}
///////////////////////////////////////////////////////////////////////////////
// If src==dst, then we use a tmp path to record the stroke, and then swap
// its contents with src when we're done.
class AutoTmpPath {
public:
AutoTmpPath(const SkPath& src, SkPath** dst) : fSrc(src) {
if (&src == *dst) {
*dst = &fTmpDst;
fSwapWithSrc = true;
} else {
(*dst)->reset();
fSwapWithSrc = false;
}
}
~AutoTmpPath() {
if (fSwapWithSrc) {
fTmpDst.swap(*const_cast<SkPath*>(&fSrc));
}
}
private:
SkPath fTmpDst;
const SkPath& fSrc;
bool fSwapWithSrc;
};
void SkStroke::strokePath(const SkPath& src, SkPath* dst) const {
SkASSERT(dst);
SkScalar radius = SkScalarHalf(fWidth);
AutoTmpPath tmp(src, &dst);
if (radius <= 0) {
return;
}
// If src is really a rect, call our specialty strokeRect() method
{
SkRect rect;
bool isClosed;
SkPath::Direction dir;
if (src.isRect(&rect, &isClosed, &dir) && isClosed) {
this->strokeRect(rect, dst, dir);
// our answer should preserve the inverseness of the src
if (src.isInverseFillType()) {
SkASSERT(!dst->isInverseFillType());
dst->toggleInverseFillType();
}
return;
}
}
// We can always ignore centers for stroke and fill convex line-only paths
// TODO: remove the line-only restriction
bool ignoreCenter = fDoFill && (src.getSegmentMasks() == SkPath::kLine_SegmentMask) &&
src.isLastContourClosed() && src.isConvex();
SkPathStroker stroker(src, radius, fMiterLimit, this->getCap(), this->getJoin(),
fResScale, ignoreCenter);
SkPath::Iter iter(src, false);
SkPath::Verb lastSegment = SkPath::kMove_Verb;
for (;;) {
SkPoint pts[4];
switch (iter.next(pts)) {
case SkPath::kMove_Verb:
stroker.moveTo(pts[0]);
break;
case SkPath::kLine_Verb:
stroker.lineTo(pts[1], &iter);
lastSegment = SkPath::kLine_Verb;
break;
case SkPath::kQuad_Verb:
stroker.quadTo(pts[1], pts[2]);
lastSegment = SkPath::kQuad_Verb;
break;
case SkPath::kConic_Verb: {
stroker.conicTo(pts[1], pts[2], iter.conicWeight());
lastSegment = SkPath::kConic_Verb;
break;
} break;
case SkPath::kCubic_Verb:
stroker.cubicTo(pts[1], pts[2], pts[3]);
lastSegment = SkPath::kCubic_Verb;
break;
case SkPath::kClose_Verb:
if (SkPaint::kButt_Cap != this->getCap()) {
/* If the stroke consists of a moveTo followed by a close, treat it
as if it were followed by a zero-length line. Lines without length
can have square and round end caps. */
if (stroker.hasOnlyMoveTo()) {
stroker.lineTo(stroker.moveToPt());
goto ZERO_LENGTH;
}
/* If the stroke consists of a moveTo followed by one or more zero-length
verbs, then followed by a close, treat is as if it were followed by a
zero-length line. Lines without length can have square & round end caps. */
if (stroker.isCurrentContourEmpty()) {
ZERO_LENGTH:
lastSegment = SkPath::kLine_Verb;
break;
}
}
stroker.close(lastSegment == SkPath::kLine_Verb);
break;
case SkPath::kDone_Verb:
goto DONE;
}
}
DONE:
stroker.done(dst, lastSegment == SkPath::kLine_Verb);
if (fDoFill && !ignoreCenter) {
if (SkPathPriv::CheapIsFirstDirection(src, SkPathPriv::kCCW_FirstDirection)) {
dst->reverseAddPath(src);
} else {
dst->addPath(src);
}
} else {
// Seems like we can assume that a 2-point src would always result in
// a convex stroke, but testing has proved otherwise.
// TODO: fix the stroker to make this assumption true (without making
// it slower that the work that will be done in computeConvexity())
#if 0
// this test results in a non-convex stroke :(
static void test(SkCanvas* canvas) {
SkPoint pts[] = { 146.333328, 192.333328, 300.333344, 293.333344 };
SkPaint paint;
paint.setStrokeWidth(7);
paint.setStrokeCap(SkPaint::kRound_Cap);
canvas->drawLine(pts[0].fX, pts[0].fY, pts[1].fX, pts[1].fY, paint);
}
#endif
#if 0
if (2 == src.countPoints()) {
dst->setIsConvex(true);
}
#endif
}
// our answer should preserve the inverseness of the src
if (src.isInverseFillType()) {
SkASSERT(!dst->isInverseFillType());
dst->toggleInverseFillType();
}
}
static SkPath::Direction reverse_direction(SkPath::Direction dir) {
static const SkPath::Direction gOpposite[] = { SkPath::kCCW_Direction, SkPath::kCW_Direction };
return gOpposite[dir];
}
static void addBevel(SkPath* path, const SkRect& r, const SkRect& outer, SkPath::Direction dir) {
SkPoint pts[8];
if (SkPath::kCW_Direction == dir) {
pts[0].set(r.fLeft, outer.fTop);
pts[1].set(r.fRight, outer.fTop);
pts[2].set(outer.fRight, r.fTop);
pts[3].set(outer.fRight, r.fBottom);
pts[4].set(r.fRight, outer.fBottom);
pts[5].set(r.fLeft, outer.fBottom);
pts[6].set(outer.fLeft, r.fBottom);
pts[7].set(outer.fLeft, r.fTop);
} else {
pts[7].set(r.fLeft, outer.fTop);
pts[6].set(r.fRight, outer.fTop);
pts[5].set(outer.fRight, r.fTop);
pts[4].set(outer.fRight, r.fBottom);
pts[3].set(r.fRight, outer.fBottom);
pts[2].set(r.fLeft, outer.fBottom);
pts[1].set(outer.fLeft, r.fBottom);
pts[0].set(outer.fLeft, r.fTop);
}
path->addPoly(pts, 8, true);
}
void SkStroke::strokeRect(const SkRect& origRect, SkPath* dst,
SkPath::Direction dir) const {
SkASSERT(dst != nullptr);
dst->reset();
SkScalar radius = SkScalarHalf(fWidth);
if (radius <= 0) {
return;
}
SkScalar rw = origRect.width();
SkScalar rh = origRect.height();
if ((rw < 0) ^ (rh < 0)) {
dir = reverse_direction(dir);
}
SkRect rect(origRect);
rect.sort();
// reassign these, now that we know they'll be >= 0
rw = rect.width();
rh = rect.height();
SkRect r(rect);
r.outset(radius, radius);
SkPaint::Join join = (SkPaint::Join)fJoin;
if (SkPaint::kMiter_Join == join && fMiterLimit < SK_ScalarSqrt2) {
join = SkPaint::kBevel_Join;
}
switch (join) {
case SkPaint::kMiter_Join:
dst->addRect(r, dir);
break;
case SkPaint::kBevel_Join:
addBevel(dst, rect, r, dir);
break;
case SkPaint::kRound_Join:
dst->addRoundRect(r, radius, radius, dir);
break;
default:
break;
}
if (fWidth < SkMinScalar(rw, rh) && !fDoFill) {
r = rect;
r.inset(radius, radius);
dst->addRect(r, reverse_direction(dir));
}
}
| youtube/cobalt | third_party/skia/src/core/SkStroke.cpp | C++ | bsd-3-clause | 61,114 |
---
title: Brute Force Algorithms
localeTitle: Алгоритмы грубой силы
---
## Алгоритмы грубой силы
Алгоритмы Brute Force ссылаются на стиль программирования, который не содержит ярлыков для повышения производительности, но вместо этого полагается на полную вычислительную мощность, чтобы попробовать все возможности, пока не будет найдено решение проблемы.
Классическим примером является проблема коммивояжера (TSP). Предположим, что продавец должен посетить 10 городов по всей стране. Как определить порядок, в котором следует посещать города, чтобы минимизировать общее пройденное расстояние? Решение грубой силы просто вычисляет общее расстояние для каждого возможного маршрута, а затем выбирает самый короткий. Это не особенно эффективно, потому что можно устранить множество возможных маршрутов с помощью умных алгоритмов.
Другой пример: 5-значный пароль, в худшем случае - 10 5 попыток взлома.
Сложность времени грубой силы равна **O (n \* m)** . Итак, если бы мы искали строку из «n» символов в строке символов «m» с использованием грубой силы, это потребовало бы n \* m попыток.
#### Дополнительная информация:
[Википедия](https://en.wikipedia.org/wiki/Brute-force_search) | otavioarc/freeCodeCamp | guide/russian/algorithms/brute-force-algorithms/index.md | Markdown | bsd-3-clause | 2,044 |
<?php
/**
* Base include file for SimpleTest
* @package SimpleTest
* @subpackage WebTester
* @version $Id: authentication.php 2011 2011-04-29 08:22:48Z pp11 $
*/
/**
* include http class
*/
require_once(dirname(__FILE__) . '/http.php');
/**
* Represents a single security realm's identity.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleRealm {
private $type;
private $root;
private $username;
private $password;
/**
* Starts with the initial entry directory.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
function SimpleRealm($type, $url) {
$this->type = $type;
$this->root = $url->getBasePath();
$this->username = false;
$this->password = false;
}
/**
* Adds another location to the realm.
* @param SimpleUrl $url Somewhere in realm.
* @access public
*/
function stretch($url) {
$this->root = $this->getCommonPath($this->root, $url->getPath());
}
/**
* Finds the common starting path.
* @param string $first Path to compare.
* @param string $second Path to compare.
* @return string Common directories.
* @access private
*/
protected function getCommonPath($first, $second) {
$first = explode('/', $first);
$second = explode('/', $second);
for ($i = 0; $i < min(count($first), count($second)); $i++) {
if ($first[$i] != $second[$i]) {
return implode('/', array_slice($first, 0, $i)) . '/';
}
}
return implode('/', $first) . '/';
}
/**
* Sets the identity to try within this realm.
* @param string $username Username in authentication dialog.
* @param string $username Password in authentication dialog.
* @access public
*/
function setIdentity($username, $password) {
$this->username = $username;
$this->password = $password;
}
/**
* Accessor for current identity.
* @return string Last succesful username.
* @access public
*/
function getUsername() {
return $this->username;
}
/**
* Accessor for current identity.
* @return string Last succesful password.
* @access public
*/
function getPassword() {
return $this->password;
}
/**
* Test to see if the URL is within the directory
* tree of the realm.
* @param SimpleUrl $url URL to test.
* @return boolean True if subpath.
* @access public
*/
function isWithin($url) {
if ($this->isIn($this->root, $url->getBasePath())) {
return true;
}
if ($this->isIn($this->root, $url->getBasePath() . $url->getPage() . '/')) {
return true;
}
return false;
}
/**
* Tests to see if one string is a substring of
* another.
* @param string $part Small bit.
* @param string $whole Big bit.
* @return boolean True if the small bit is
* in the big bit.
* @access private
*/
protected function isIn($part, $whole) {
return strpos($whole, $part) === 0;
}
}
/**
* Manages security realms.
* @package SimpleTest
* @subpackage WebTester
*/
class SimpleAuthenticator {
private $realms;
/**
* Clears the realms.
* @access public
*/
function SimpleAuthenticator() {
$this->restartSession();
}
/**
* Starts with no realms set up.
* @access public
*/
function restartSession() {
$this->realms = array();
}
/**
* Adds a new realm centered the current URL.
* Browsers privatey wildly on their behaviour in this
* regard. Mozilla ignores the realm and presents
* only when challenged, wasting bandwidth. IE
* just carries on presenting until a new challenge
* occours. SimpleTest tries to follow the spirit of
* the original standards committee and treats the
* base URL as the root of a file tree shaped realm.
* @param SimpleUrl $url Base of realm.
* @param string $type Authentication type for this
* realm. Only Basic authentication
* is currently supported.
* @param string $realm Name of realm.
* @access public
*/
function addRealm($url, $type, $realm) {
$this->realms[$url->getHost()][$realm] = new SimpleRealm($type, $url);
}
/**
* Sets the current identity to be presented
* against that realm.
* @param string $host Server hosting realm.
* @param string $realm Name of realm.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
function setIdentityForRealm($host, $realm, $username, $password) {
if (isset($this->realms[$host][$realm])) {
$this->realms[$host][$realm]->setIdentity($username, $password);
}
}
/**
* Finds the name of the realm by comparing URLs.
* @param SimpleUrl $url URL to test.
* @return SimpleRealm Name of realm.
* @access private
*/
protected function findRealmFromUrl($url) {
if (! isset($this->realms[$url->getHost()])) {
return false;
}
foreach ($this->realms[$url->getHost()] as $name => $realm) {
if ($realm->isWithin($url)) {
return $realm;
}
}
return false;
}
/**
* Presents the appropriate headers for this location.
* @param SimpleHttpRequest $request Request to modify.
* @param SimpleUrl $url Base of realm.
* @access public
*/
function addHeaders(&$request, $url) {
if ($url->getUsername() && $url->getPassword()) {
$username = $url->getUsername();
$password = $url->getPassword();
} elseif ($realm = $this->findRealmFromUrl($url)) {
$username = $realm->getUsername();
$password = $realm->getPassword();
} else {
return;
}
$this->addBasicHeaders($request, $username, $password);
}
/**
* Presents the appropriate headers for this
* location for basic authentication.
* @param SimpleHttpRequest $request Request to modify.
* @param string $username Username for realm.
* @param string $password Password for realm.
* @access public
*/
static function addBasicHeaders(&$request, $username, $password) {
if ($username && $password) {
$request->addHeaderLine(
'Authorization: Basic ' . base64_encode("$username:$password"));
}
}
}
?> | sgabalda/may17php | www/teatro/simpletest/authentication.php | PHP | gpl-3.0 | 7,350 |
/*
* Copyright 2004-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "pcy_int.h"
/* Policy Node routines */
void policy_data_free(X509_POLICY_DATA *data)
{
if (data == NULL)
return;
ASN1_OBJECT_free(data->valid_policy);
/* Don't free qualifiers if shared */
if (!(data->flags & POLICY_DATA_FLAG_SHARED_QUALIFIERS))
sk_POLICYQUALINFO_pop_free(data->qualifier_set, POLICYQUALINFO_free);
sk_ASN1_OBJECT_pop_free(data->expected_policy_set, ASN1_OBJECT_free);
OPENSSL_free(data);
}
/*
* Create a data based on an existing policy. If 'id' is NULL use the OID in
* the policy, otherwise use 'id'. This behaviour covers the two types of
* data in RFC3280: data with from a CertificatePolicies extension and
* additional data with just the qualifiers of anyPolicy and ID from another
* source.
*/
X509_POLICY_DATA *policy_data_new(POLICYINFO *policy,
const ASN1_OBJECT *cid, int crit)
{
X509_POLICY_DATA *ret;
ASN1_OBJECT *id;
if (policy == NULL && cid == NULL)
return NULL;
if (cid) {
id = OBJ_dup(cid);
if (id == NULL)
return NULL;
} else
id = NULL;
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL) {
X509V3err(X509V3_F_POLICY_DATA_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->expected_policy_set = sk_ASN1_OBJECT_new_null();
if (ret->expected_policy_set == NULL) {
OPENSSL_free(ret);
ASN1_OBJECT_free(id);
X509V3err(X509V3_F_POLICY_DATA_NEW, ERR_R_MALLOC_FAILURE);
return NULL;
}
if (crit)
ret->flags = POLICY_DATA_FLAG_CRITICAL;
if (id)
ret->valid_policy = id;
else {
ret->valid_policy = policy->policyid;
policy->policyid = NULL;
}
if (policy) {
ret->qualifier_set = policy->qualifiers;
policy->qualifiers = NULL;
}
return ret;
}
| ibc/MediaSoup | worker/deps/openssl/openssl/crypto/x509v3/pcy_data.c | C | isc | 2,294 |
#!/bin/bash
REPOSITORY=$1
TARGET_TAG=$2
# get authorization token
TOKEN=$(curl -s "https://auth.docker.io/token?service=registry.docker.io&scope=repository:$REPOSITORY:pull" | jq -r .token)
# find all tags
ALL_TAGS=$(curl -s -H "Authorization: Bearer $TOKEN" https://index.docker.io/v2/$REPOSITORY/tags/list | jq -r .tags[])
# get image digest for target
TARGET_DIGEST=$(curl -s -D - -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" https://index.docker.io/v2/$REPOSITORY/manifests/$TARGET_TAG | grep Docker-Content-Digest | cut -d ' ' -f 2)
# for each tags
for tag in ${ALL_TAGS[@]}; do
# get image digest
digest=$(curl -s -D - -H "Authorization: Bearer $TOKEN" -H "Accept: application/vnd.docker.distribution.manifest.v2+json" https://index.docker.io/v2/$REPOSITORY/manifests/$tag | grep Docker-Content-Digest | cut -d ' ' -f 2)
# check digest
if [[ $TARGET_DIGEST = $digest ]]; then
echo "$tag $digest"
fi
done | ShaopengLiu1/Atac-seq_Quality_Control_pipe | pipe_code_TaRGET_local/find_image_ID_digest.sh | Shell | mit | 984 |
#!/bin/sh
_=[[
. "${0%%/*}/regress.sh"
exec runlua "$0" "$@"
]]
require"regress".export".*"
local dbg = require"_cqueues.debug"
local function checkconv(timeout)
local ms = dbg.f2ms(timeout)
info("%g -> %gms", timeout, ms)
check(ms / 1000 >= timeout, "conversion lost time (%g > %dms)", timeout, ms)
local ts = dbg.f2ts(timeout)
info("%g -> { %d, %d }", timeout, ts.tv_sec, ts.tv_nsec)
check(ts.tv_sec + (ts.tv_nsec * 1000000000) >= timeout, "conversion lost time (%g > { %d, %d })", timeout, ts.tv_sec, ts.tv_nsec)
end
local main = cqueues.new()
local function checksleep(timeout, noloop)
local start, elapsed
info("sleeping for %gs (noloop:%s)", timeout, noloop and "yes" or "no")
if noloop then
local start = cqueues.monotime()
cqueues.poll(timeout)
elapsed = cqueues.monotime() - start
else
check(main:wrap(function ()
local start = cqueues.monotime()
cqueues.poll(timeout)
elapsed = cqueues.monotime() - start
end):loop())
end
info("%gs elapsed", elapsed)
check(elapsed >= timeout, "sleep too short (%g < %g)", elapsed, timeout)
end
for _, noloop in ipairs{ false, true } do
for _, timeout in ipairs{ 0.1, 1e-4, 1e-5, 1e-10, 1e-11, 0.9999, 0.999999999, 0.9999999999, 0.9, 1.0, 1.1, 2.0 } do
if not noloop then checkconv(timeout) end
checksleep(timeout, noloop)
end
end
local INT_MAX = dbg.INT_MAX
for _, timeout in ipairs{ INT_MAX + 1, INT_MAX * 2, INT_MAX + 0.9999 } do
local ms, is_int_max = dbg.f2ms(timeout)
info("%g -> %d", timeout, ms)
check(is_int_max, "%g didn't clamp", timeout)
end
for _, timeout in ipairs{ 2^63 } do
local ts, is_long_max = dbg.f2ts(timeout)
info("%g -> { %g, %g }", timeout, ts.tv_sec, ts.tv_nsec)
check(is_long_max, "%g didn't clamp", timeout)
end
say("OK")
| bigcrush/cqueues | regress/75-sleep-1s-broken.lua | Lua | mit | 1,752 |
require "forwardable"
module Lita
# A wrapper object that provides the primary interface for handlers to
# respond to incoming chat messages.
class Response
extend Forwardable
# The incoming message.
# @return [Message] The message.
attr_accessor :message
# A hash of arbitrary data that can be populated by Lita extensions.
# @return [Hash] The extensions data.
# @since 3.2.0
attr_accessor :extensions
# The pattern the incoming message matched.
# @return [Regexp] The pattern.
attr_accessor :pattern
# @!method args
# @see Message#args
# @!method reply(*strings)
# @see Message#reply
# @!method reply_privately(*strings)
# @see Message#reply_privately
# @!method reply_with_mention(*strings)
# @see Message#reply_with_mention
# @!method user
# @see Message#user
# @!method private_message?
# @see Message#private_message?
# @since 4.5.0
def_delegators :message, :args, :reply, :reply_privately,
:reply_with_mention, :user, :private_message?, :command?
# @!method room
# @see Message#room_object
# @since 4.5.0
def_delegator :message, :room_object, :room
# @param message [Message] The incoming message.
# @param pattern [Regexp] The pattern the incoming message matched.
def initialize(message, pattern)
self.message = message
self.extensions = {}
self.pattern = pattern
end
# An array of matches from scanning the message against the route pattern.
# @return [Array<String>, Array<Array<String>>] The array of matches.
def matches
@matches ||= message.match(pattern)
end
# A +MatchData+ object from running the pattern against the message body.
# @return [MatchData] The +MatchData+.
def match_data
@match_data ||= pattern.match(message.body)
end
end
end
| brodock/lita | lib/lita/response.rb | Ruby | mit | 1,894 |
Planchette
==========
Planchette is a boilerplate for front-end prototypes.

Installation
------------
Create a new project folder and remove boilerplate repo:
```
git clone --depth=1 ssh://[email protected]/penrosestudio/planchette.git new-project
cd new-project
rm -rf .git
```
Install dependencies:
```
npm install
```
Usage
-----
Run ```gulp watch``` for building. Build folder is available at localhost:8000
Bootstrap components are at localhost:8000/components.html
| Joshuwar/gallery-demo | README.md | Markdown | mit | 584 |
<?php
namespace TypiCMS\Modules\Blocks\Providers;
use Lang;
use View;
use Config;
use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\Application;
// Model
use TypiCMS\Modules\Blocks\Models\Block;
// Repo
use TypiCMS\Modules\Blocks\Repositories\EloquentBlock;
// Cache
use TypiCMS\Modules\Blocks\Repositories\CacheDecorator;
use TypiCMS\Services\Cache\LaravelCache;
// Form
use TypiCMS\Modules\Blocks\Services\Form\BlockForm;
use TypiCMS\Modules\Blocks\Services\Form\BlockFormLaravelValidator;
class ModuleProvider extends ServiceProvider
{
public function boot()
{
// Bring in the routes
require __DIR__ . '/../routes.php';
// Add dirs
View::addLocation(__DIR__ . '/../Views');
Lang::addNamespace('blocks', __DIR__ . '/../lang');
Config::addNamespace('blocks', __DIR__ . '/../config');
}
public function register()
{
$app = $this->app;
/**
* Sidebar view composer
*/
$app->view->composer('admin._sidebar', 'TypiCMS\Modules\Blocks\Composers\SidebarViewComposer');
$app->bind('TypiCMS\Modules\Blocks\Repositories\BlockInterface', function (Application $app) {
$repository = new EloquentBlock(new Block);
if (! Config::get('app.cache')) {
return $repository;
}
$laravelCache = new LaravelCache($app['cache'], 'blocks', 10);
return new CacheDecorator($repository, $laravelCache);
});
$app->bind('TypiCMS\Modules\Blocks\Services\Form\BlockForm', function (Application $app) {
return new BlockForm(
new BlockFormLaravelValidator($app['validator']),
$app->make('TypiCMS\Modules\Blocks\Repositories\BlockInterface')
);
});
$app->before(function ($request, $response) {
require __DIR__ . '/../breadcrumbs.php';
});
}
}
| yaoshanliang/TypiCMS | app/TypiCMS/Modules/Blocks/Providers/ModuleProvider.php | PHP | mit | 1,947 |
---
layout: post
title: Developer Testimonial
date: 2013-07-18 21:00
author: julia.king
comments: true
categories: [older]
product: certification
doctype: blog
---
Our Partner's developers say integrating to AvaTax is a breeze.
<iframe width="473" height="266" src="http://www.youtube.com/embed/nAuMcuosE_I" rel="0" frameborder="0" allowfullscreen></iframe>
Try it today! Sign up for our<a href="/avatax/"> API Free Trial</a>.
| balasuar/developer-dot | _posts/2013-07-18-developer-testimonial.md | Markdown | mit | 444 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="da" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="14"/>
<source>About MMXIV</source>
<translation>Om MMXIV</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="53"/>
<source><b>MMXIV</b> version</source>
<translation><b>MMXIV</b> version</translation>
</message>
<message>
<location filename="../forms/aboutdialog.ui" line="85"/>
<source>Copyright © 2011-2013 MMXIV Developers
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file license.txt or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="14"/>
<source>Address Book</source>
<translation>Adressebog</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="20"/>
<source>These are your MMXIV addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Dette er dine MMXIVadresser til at modtage betalinger med. Du kan give en forskellig adresse til hver afsender, så du kan holde styr på hvem der betaler dig.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="33"/>
<source>Double-click to edit address or label</source>
<translation>Dobbeltklik for at redigere adresse eller mærkat</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="57"/>
<source>Create a new address</source>
<translation>Opret en ny adresse</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="60"/>
<source>&New Address...</source>
<translation>&Ny adresse ...</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="71"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adresse til systemets udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="74"/>
<source>&Copy to Clipboard</source>
<translation>&Kopier til Udklipsholder</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="85"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="96"/>
<source>Sign a message to prove you own this address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="99"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="110"/>
<source>Delete the currently selected address from the list. Only sending addresses can be deleted.</source>
<translation>Slet den valgte adresse fra listen. Kun adresser brugt til afsendelse kan slettes.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="113"/>
<source>&Delete</source>
<translation>&Slet</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="61"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="62"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="63"/>
<source>Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="64"/>
<source>Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="281"/>
<source>Export Address Book Data</source>
<translation>Eksporter Adressekartoteketsdata</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="282"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*. csv)</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="295"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="77"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../addresstablemodel.cpp" line="113"/>
<source>(no label)</source>
<translation>(ingen etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="26"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="32"/>
<location filename="../forms/askpassphrasedialog.ui" line="97"/>
<source>TextLabel</source>
<translation>TekstEtiket</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="50"/>
<source>Enter passphrase</source>
<translation>Indtast adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="64"/>
<source>New passphrase</source>
<translation>Ny adgangskode</translation>
</message>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="78"/>
<source>Repeat new passphrase</source>
<translation>Gentag ny adgangskode</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="34"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Indtast den nye adgangskode til tegnebogen.<br/>Brug venligst en adgangskode på <b>10 eller flere tilfældige tegn</b>, eller <b>otte eller flere ord</b>.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="35"/>
<source>Encrypt wallet</source>
<translation>Krypter tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="38"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at låse tegnebogen op.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="43"/>
<source>Unlock wallet</source>
<translation>Lås tegnebog op</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="46"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denne funktion har brug for din tegnebogs kodeord for at dekryptere tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="51"/>
<source>Decrypt wallet</source>
<translation>Dekryptér tegnebog</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="54"/>
<source>Change passphrase</source>
<translation>Skift adgangskode</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="55"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Indtast den gamle og nye adgangskode til tegnebogen.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="101"/>
<source>Confirm wallet encryption</source>
<translation>Bekræft tegnebogskryptering</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="102"/>
<source>WARNING: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR MMXIVS</b>!
Are you sure you wish to encrypt your wallet?</source>
<translation>ADVARSEL: Hvis du krypterer din tegnebog og mister dit kodeord vil du <b>miste alle dine MMXIVS</b>!
Er du sikker på at du ønsker at kryptere din tegnebog?</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="111"/>
<location filename="../askpassphrasedialog.cpp" line="160"/>
<source>Wallet encrypted</source>
<translation>Tegnebog krypteret</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="112"/>
<source>MMXIV will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your MMXIVs from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="208"/>
<location filename="../askpassphrasedialog.cpp" line="232"/>
<source>Warning: The Caps Lock key is on.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="117"/>
<location filename="../askpassphrasedialog.cpp" line="124"/>
<location filename="../askpassphrasedialog.cpp" line="166"/>
<location filename="../askpassphrasedialog.cpp" line="172"/>
<source>Wallet encryption failed</source>
<translation>Tegnebogskryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="118"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Tegnebogskryptering mislykkedes på grund af en intern fejl. Din tegnebog blev ikke krypteret.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="125"/>
<location filename="../askpassphrasedialog.cpp" line="173"/>
<source>The supplied passphrases do not match.</source>
<translation>De angivne kodeord stemmer ikke overens.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="136"/>
<source>Wallet unlock failed</source>
<translation>Tegnebogsoplåsning mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="137"/>
<location filename="../askpassphrasedialog.cpp" line="148"/>
<location filename="../askpassphrasedialog.cpp" line="167"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Det angivne kodeord for tegnebogsdekrypteringen er forkert.</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="147"/>
<source>Wallet decryption failed</source>
<translation>Tegnebogsdekryptering mislykkedes</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="161"/>
<source>Wallet passphrase was succesfully changed.</source>
<translation>Tegnebogskodeord blev ændret.</translation>
</message>
</context>
<context>
<name>MMXIVGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="69"/>
<source>MMXIV Wallet</source>
<translation>MMXIV Tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="142"/>
<location filename="../bitcoingui.cpp" line="464"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserer med netværk ...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="145"/>
<source>Block chain synchronization in progress</source>
<translation>Blokkæde synkronisering i gang</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="176"/>
<source>&Overview</source>
<translation>&Oversigt</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="177"/>
<source>Show general overview of wallet</source>
<translation>Vis generel oversigt over tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="182"/>
<source>&Transactions</source>
<translation>&Transaktioner</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="183"/>
<source>Browse transaction history</source>
<translation>Gennemse transaktionshistorik</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="188"/>
<source>&Address Book</source>
<translation>&Adressebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="189"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Rediger listen over gemte adresser og etiketter</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="194"/>
<source>&Receive coins</source>
<translation>&Modtag coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="195"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Vis listen over adresser for at modtage betalinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="200"/>
<source>&Send coins</source>
<translation>&Send coins</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="201"/>
<source>Send coins to a MMXIV address</source>
<translation>Send coins til en MMXIVadresse</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="206"/>
<source>Sign &message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="207"/>
<source>Prove you control an address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="226"/>
<source>E&xit</source>
<translation>&Luk</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="227"/>
<source>Quit application</source>
<translation>Afslut program</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="230"/>
<source>&About %1</source>
<translation>&Om %1</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="231"/>
<source>Show information about MMXIV</source>
<translation>Vis oplysninger om MMXIV</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="233"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="234"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="236"/>
<source>&Options...</source>
<translation>&Indstillinger ...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="237"/>
<source>Modify configuration options for MMXIV</source>
<translation>Rediger konfigurationsindstillinger af MMXIV</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="239"/>
<source>Open &MMXIV</source>
<translation>Åbn &MMXIV</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="240"/>
<source>Show the MMXIV window</source>
<translation>Vis MMXIVvinduet</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="241"/>
<source>&Export...</source>
<translation>&Eksporter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="242"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="243"/>
<source>&Encrypt Wallet</source>
<translation>&Kryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="244"/>
<source>Encrypt or decrypt wallet</source>
<translation>Kryptér eller dekryptér tegnebog</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="246"/>
<source>&Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="247"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="248"/>
<source>&Change Passphrase</source>
<translation>&Skift adgangskode</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="249"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Skift kodeord anvendt til tegnebogskryptering</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="272"/>
<source>&File</source>
<translation>&Fil</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="281"/>
<source>&Settings</source>
<translation>&Indstillinger</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="287"/>
<source>&Help</source>
<translation>&Hjælp</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="294"/>
<source>Tabs toolbar</source>
<translation>Faneværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="305"/>
<source>Actions toolbar</source>
<translation>Handlingsværktøjslinje</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="317"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="407"/>
<source>MMXIV-qt</source>
<translation>MMXIV-qt</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="449"/>
<source>%n active connection(s) to MMXIV network</source>
<translation><numerusform>%n aktiv(e) forbindelse(r) til MMXIVnetværket</numerusform><numerusform>%n aktiv(e) forbindelse(r) til MMXIVnetværket</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="475"/>
<source>Downloaded %1 of %2 blocks of transaction history.</source>
<translation>Downloadet %1 af %2 blokke af transaktionshistorie.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="487"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>Downloadet %1 blokke af transaktionshistorie.</translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="502"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n sekund(er) siden</numerusform><numerusform>%n sekund(er) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="506"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n minut(ter) siden</numerusform><numerusform>%n minut(ter) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="510"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n time(r) siden</numerusform><numerusform>%n time(r) siden</numerusform></translation>
</message>
<message numerus="yes">
<location filename="../bitcoingui.cpp" line="514"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n dag(e) siden</numerusform><numerusform>%n dag(e) siden</numerusform></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="520"/>
<source>Up to date</source>
<translation>Opdateret</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="525"/>
<source>Catching up...</source>
<translation>Indhenter...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="533"/>
<source>Last received block was generated %1.</source>
<translation>Sidst modtagne blok blev genereret %1.</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="597"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>Denne transaktion er over størrelsesbegrænsningen. Du kan stadig sende den for et gebyr på %1 som går til de noder der behandler din transaktion, og som hjælper med at støtte netværket. Ønsker du at betale gebyret?</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="602"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="629"/>
<source>Sent transaction</source>
<translation>Afsendt transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="630"/>
<source>Incoming transaction</source>
<translation>Indgående transaktion</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="631"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dato: %1
Beløb: %2
Type: %3
Adresse: %4
</translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="751"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>ulåst</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="759"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Tegnebog er <b>krypteret</b> og i øjeblikket <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="782"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoingui.cpp" line="785"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>DisplayOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="270"/>
<source>&Unit to show amounts in: </source>
<translation>&Enhed at vise beløb i: </translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="274"/>
<source>Choose the default subdivision unit to show in the interface, and when sending coins</source>
<translation>Vælg den standard underopdelingsenhed som skal vises i brugergrænsefladen, og når du sender coins</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="281"/>
<source>Display addresses in transaction list</source>
<translation>Vis adresser i transaktionensliste</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="14"/>
<source>Edit Address</source>
<translation>Rediger Adresse</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="25"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="35"/>
<source>The label associated with this address book entry</source>
<translation>Etiketten forbundet med denne post i adressekartoteket</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="42"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location filename="../forms/editaddressdialog.ui" line="52"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>Adressen tilknyttet til denne post i adressekartoteket. Dette kan kun ændres for afsendelsesadresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="20"/>
<source>New receiving address</source>
<translation>Ny modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="24"/>
<source>New sending address</source>
<translation>Ny afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="27"/>
<source>Edit receiving address</source>
<translation>Rediger modtagelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="31"/>
<source>Edit sending address</source>
<translation>Rediger afsendelsesadresse</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="91"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den indtastede adresse "%1" er allerede i adressebogen.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="96"/>
<source>The entered address "%1" is not a valid MMXIV address.</source>
<translation>Den indtastede adresse "%1" er ikke en gyldig MMXIVadresse.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="101"/>
<source>Could not unlock wallet.</source>
<translation>Kunne ikke låse tegnebog op.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="106"/>
<source>New key generation failed.</source>
<translation>Ny nøglegenerering mislykkedes.</translation>
</message>
</context>
<context>
<name>MainOptionsPage</name>
<message>
<location filename="../optionsdialog.cpp" line="170"/>
<source>&Start MMXIV on window system startup</source>
<translation>&Start MMXIV når systemet startes</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="171"/>
<source>Automatically start MMXIV after the computer is turned on</source>
<translation>Start MMXIV automatisk efter at computeren er tændt</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="175"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimer til systembakken i stedet for proceslinjen</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="176"/>
<source>Show only a tray icon after minimizing the window</source>
<translation>Vis kun et systembakkeikon efter minimering af vinduet</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="180"/>
<source>Map port using &UPnP</source>
<translation>Konfigurer port vha. &UPnP</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="181"/>
<source>Automatically open the MMXIV client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Åbn MMXIVklient-porten på routeren automatisk. Dette virker kun når din router understøtter UPnP og UPnP er aktiveret.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="185"/>
<source>M&inimize on close</source>
<translation>M&inimer ved lukning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="186"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Minimer i stedet for at afslutte programmet når vinduet lukkes. Når denne indstilling er valgt vil programmet kun blive lukket når du har valgt Afslut i menuen.</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="190"/>
<source>&Connect through SOCKS4 proxy:</source>
<translation>&Forbind gennem SOCKS4 proxy:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="191"/>
<source>Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)</source>
<translation>Opret forbindelse til Bitconnetværket via en SOCKS4 proxy (f.eks. ved tilslutning gennem Tor)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="196"/>
<source>Proxy &IP: </source>
<translation>Proxy-&IP:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="202"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>IP-adressen på proxyen (f.eks. 127.0.0.1)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="205"/>
<source>&Port: </source>
<translation>&Port:</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="211"/>
<source>Port of the proxy (e.g. 1234)</source>
<translation>Porten på proxyen (f.eks. 1234)</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="217"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="223"/>
<source>Pay transaction &fee</source>
<translation>Betal transaktions&gebyr</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="226"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>MessagePage</name>
<message>
<location filename="../forms/messagepage.ui" line="14"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="20"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="38"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adresse som betalingen skal sendes til (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="48"/>
<source>Choose adress from address book</source>
<translation>Vælg adresse fra adressebog</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="58"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="71"/>
<source>Paste address from clipboard</source>
<translation>Indsæt adresse fra udklipsholderen</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="81"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="93"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="105"/>
<source>Click "Sign Message" to get signature</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="117"/>
<source>Sign a message to prove you own this address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="120"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/messagepage.ui" line="131"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopier den valgte adresse til systemets udklipsholder</translation>
</message>
<message>
<location filename="../forms/messagepage.ui" line="134"/>
<source>&Copy to Clipboard</source>
<translation>&Kopier til Udklipsholder</translation>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<location filename="../messagepage.cpp" line="89"/>
<location filename="../messagepage.cpp" line="101"/>
<source>Error signing</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../messagepage.cpp" line="74"/>
<source>%1 is not a valid address.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../messagepage.cpp" line="89"/>
<source>Private key for %1 is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../messagepage.cpp" line="101"/>
<source>Sign failed</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../optionsdialog.cpp" line="79"/>
<source>Main</source>
<translation>Generelt</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="84"/>
<source>Display</source>
<translation>Visning</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="104"/>
<source>Options</source>
<translation>Indstillinger</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="40"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="47"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="54"/>
<source>Number of transactions:</source>
<translation>Antal transaktioner:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="61"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="68"/>
<source>Unconfirmed:</source>
<translation>Ubekræftede:</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="75"/>
<source>0 BTC</source>
<translation>0 BTC</translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="82"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Ubuntu'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Wallet</span></p></body></html></translation>
</message>
<message>
<location filename="../forms/overviewpage.ui" line="122"/>
<source><b>Recent transactions</b></source>
<translation><b>Nyeste transaktioner</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="103"/>
<source>Your current balance</source>
<translation>Din nuværende saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Summen af transaktioner, der endnu ikke er bekræftet, og endnu ikke er inkluderet i den nuværende saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="111"/>
<source>Total number of transactions in wallet</source>
<translation>Samlede antal transaktioner i tegnebogen</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="14"/>
<source>Dialog</source>
<translation>Dialog</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="32"/>
<source>QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="52"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="67"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="102"/>
<source>BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="118"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="141"/>
<source>Message:</source>
<translation>Besked:</translation>
</message>
<message>
<location filename="../forms/qrcodedialog.ui" line="183"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>Save Image...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="101"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="14"/>
<location filename="../sendcoinsdialog.cpp" line="122"/>
<location filename="../sendcoinsdialog.cpp" line="127"/>
<location filename="../sendcoinsdialog.cpp" line="132"/>
<location filename="../sendcoinsdialog.cpp" line="137"/>
<location filename="../sendcoinsdialog.cpp" line="143"/>
<location filename="../sendcoinsdialog.cpp" line="148"/>
<location filename="../sendcoinsdialog.cpp" line="153"/>
<source>Send Coins</source>
<translation>Send Coins</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="64"/>
<source>Send to multiple recipients at once</source>
<translation>Send til flere modtagere på én gang</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="67"/>
<source>&Add recipient...</source>
<translation>&Tilføj modtager...</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="84"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="87"/>
<source>Clear all</source>
<translation>Ryd alle</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="106"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="113"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="144"/>
<source>Confirm the send action</source>
<translation>Bekræft afsendelsen</translation>
</message>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="147"/>
<source>&Send</source>
<translation>&Afsend</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="94"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> til %2 (%3)</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="99"/>
<source>Confirm send coins</source>
<translation>Bekræft afsendelse af coins</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source>Are you sure you want to send %1?</source>
<translation>Er du sikker på at du vil sende %1?</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="100"/>
<source> and </source>
<translation> og </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="123"/>
<source>The recepient address is not valid, please recheck.</source>
<translation>Modtagerens adresse er ikke gyldig. Tjek venligst adressen igen.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="128"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Beløbet til betaling skal være større end 0.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="133"/>
<source>Amount exceeds your balance</source>
<translation>Beløbet overstiger din saldo</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="138"/>
<source>Total exceeds your balance when the %1 transaction fee is included</source>
<translation>Totalen overstiger din saldo når %1 transaktionsgebyr er inkluderet</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="144"/>
<source>Duplicate address found, can only send to each address once in one send operation</source>
<translation>Duplikeret adresse fundet. Du kan kun sende til hver adresse en gang pr. afsendelse.</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="149"/>
<source>Error: Transaction creation failed </source>
<translation>Fejl: Oprettelse af transaktionen mislykkedes </translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="154"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fejl: Transaktionen blev afvist. Dette kan ske hvis nogle af dine coins i din tegnebog allerede var brugt, som hvis du brugte en kopi af wallet.dat og dine coins er blevet brugt i kopien, men ikke er markeret som brugt her.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="14"/>
<source>Form</source>
<translation>Formular</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="29"/>
<source>A&mount:</source>
<translation>B&eløb:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="42"/>
<source>Pay &To:</source>
<translation>Betal &Til:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="66"/>
<location filename="../sendcoinsentry.cpp" line="26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Indtast en etiket for denne adresse for at føje den til din adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="75"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="93"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adresse som betalingen skal sendes til (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="103"/>
<source>Choose address from address book</source>
<translation>Vælg adresse fra adressebog</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="113"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="120"/>
<source>Paste address from clipboard</source>
<translation>Indsæt adresse fra udklipsholderen</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="130"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location filename="../forms/sendcoinsentry.ui" line="137"/>
<source>Remove this recipient</source>
<translation>Fjern denne modtager</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="25"/>
<source>Enter a MMXIV address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Indtast en MMXIVadresse (f.eks. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="18"/>
<source>Open for %1 blocks</source>
<translation>Åben for %1 blokke</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="20"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="26"/>
<source>%1/offline?</source>
<translation>%1/offline?</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="28"/>
<source>%1/unconfirmed</source>
<translation>%1/ubekræftet</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="30"/>
<source>%1 confirmations</source>
<translation>%1 bekræftelser</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="47"/>
<source><b>Status:</b> </source>
<translation><b>Status:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="52"/>
<source>, has not been successfully broadcast yet</source>
<translation>, er ikke blevet transmitteret endnu</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="54"/>
<source>, broadcast through %1 node</source>
<translation>, transmitteret via %1 node</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="56"/>
<source>, broadcast through %1 nodes</source>
<translation>, transmitteret via %1 noder</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="60"/>
<source><b>Date:</b> </source>
<translation><b>Dato:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="67"/>
<source><b>Source:</b> Generated<br></source>
<translation><b>Kilde:</b> Genereret<br></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="73"/>
<location filename="../transactiondesc.cpp" line="90"/>
<source><b>From:</b> </source>
<translation><b>Fra:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="90"/>
<source>unknown</source>
<translation>ukendt</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="91"/>
<location filename="../transactiondesc.cpp" line="114"/>
<location filename="../transactiondesc.cpp" line="173"/>
<source><b>To:</b> </source>
<translation><b>Til:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="94"/>
<source> (yours, label: </source>
<translation> (din, etiket:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="96"/>
<source> (yours)</source>
<translation> (din)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="131"/>
<location filename="../transactiondesc.cpp" line="145"/>
<location filename="../transactiondesc.cpp" line="190"/>
<location filename="../transactiondesc.cpp" line="207"/>
<source><b>Credit:</b> </source>
<translation><b>Kredit:</b> </translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="133"/>
<source>(%1 matures in %2 more blocks)</source>
<translation>(%1 modnes i %2 blokke mere)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="137"/>
<source>(not accepted)</source>
<translation>(ikke accepteret)</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="181"/>
<location filename="../transactiondesc.cpp" line="189"/>
<location filename="../transactiondesc.cpp" line="204"/>
<source><b>Debit:</b> </source>
<translation><b>Debet:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="195"/>
<source><b>Transaction fee:</b> </source>
<translation><b>Transaktionsgebyr:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="211"/>
<source><b>Net amount:</b> </source>
<translation><b>Nettobeløb:</b></translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="217"/>
<source>Message:</source>
<translation>Besked:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="219"/>
<source>Comment:</source>
<translation>Kommentar:</translation>
</message>
<message>
<location filename="../transactiondesc.cpp" line="221"/>
<source>Transaction ID:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactiondesc.cpp" line="224"/>
<source>Generated coins must wait 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, it will change to "not accepted" and not be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Genererede coins skal vente 120 blokke, før de kan blive brugt. Da du genererede denne blok blev det transmitteret til netværket, for at blive føjet til blokkæden. Hvis det mislykkes at komme ind i kæden, vil den skifte til "ikke godkendt", og ikke blive kunne bruges. Dette kan lejlighedsvis ske, hvis en anden node genererer en blok inden for få sekunder af din.</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="14"/>
<source>Transaction details</source>
<translation>Transaktionsdetaljer</translation>
</message>
<message>
<location filename="../forms/transactiondescdialog.ui" line="20"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Denne rude viser en detaljeret beskrivelse af transaktionen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="213"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="274"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Åben for %n blok(ke)</numerusform><numerusform>Åben for %n blok(ke)</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="277"/>
<source>Open until %1</source>
<translation>Åben indtil %1</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="280"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="283"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Ubekræftet (%1 af %2 bekræftelser)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="286"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekræftet (%1 bekræftelser)</translation>
</message>
<message numerus="yes">
<location filename="../transactiontablemodel.cpp" line="295"/>
<source>Mined balance will be available in %n more blocks</source>
<translation><numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform><numerusform>Minerede balance vil være tilgængelig om %n blok(ke)</numerusform></translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="301"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Denne blok blev ikke modtaget af nogen andre noder, og vil formentlig ikke blive accepteret!</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="304"/>
<source>Generated but not accepted</source>
<translation>Genereret, men ikke accepteret</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="347"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="349"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="352"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="354"/>
<source>Payment to yourself</source>
<translation>Betaling til dig selv</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="356"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="394"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="593"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transactionsstatus. Hold musen over dette felt for at vise antallet af bekræftelser.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="595"/>
<source>Date and time that the transaction was received.</source>
<translation>Dato og tid for at transaktionen blev modtaget.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="597"/>
<source>Type of transaction.</source>
<translation>Type af transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="599"/>
<source>Destination address of transaction.</source>
<translation>Destinationsadresse for transaktion.</translation>
</message>
<message>
<location filename="../transactiontablemodel.cpp" line="601"/>
<source>Amount removed from or added to balance.</source>
<translation>Beløb fjernet eller tilføjet balance.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="55"/>
<location filename="../transactionview.cpp" line="71"/>
<source>All</source>
<translation>Alle</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="56"/>
<source>Today</source>
<translation>I dag</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="57"/>
<source>This week</source>
<translation>Denne uge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="58"/>
<source>This month</source>
<translation>Denne måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="59"/>
<source>Last month</source>
<translation>Sidste måned</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="60"/>
<source>This year</source>
<translation>Dette år</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="61"/>
<source>Range...</source>
<translation>Interval...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="72"/>
<source>Received with</source>
<translation>Modtaget med</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="74"/>
<source>Sent to</source>
<translation>Sendt til</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="76"/>
<source>To yourself</source>
<translation>Til dig selv</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="77"/>
<source>Mined</source>
<translation>Minerede</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="78"/>
<source>Other</source>
<translation>Andet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="84"/>
<source>Enter address or label to search</source>
<translation>Indtast adresse eller etiket for at søge</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="90"/>
<source>Min amount</source>
<translation>Min. beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="124"/>
<source>Copy address</source>
<translation>Kopier adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="125"/>
<source>Copy label</source>
<translation>Kopier etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="126"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactionview.cpp" line="127"/>
<source>Edit label</source>
<translation>Rediger etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="128"/>
<source>Show details...</source>
<translation>Vis detaljer...</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="268"/>
<source>Export Transaction Data</source>
<translation>Eksportér Transaktionsdata</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="269"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommasepareret fil (*.csv)</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="277"/>
<source>Confirmed</source>
<translation>Bekræftet</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="278"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="279"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="280"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="281"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="282"/>
<source>Amount</source>
<translation>Beløb</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="283"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Error exporting</source>
<translation>Fejl under eksport</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="287"/>
<source>Could not write to file %1.</source>
<translation>Kunne ikke skrive til filen %1.</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="382"/>
<source>Range:</source>
<translation>Interval:</translation>
</message>
<message>
<location filename="../transactionview.cpp" line="390"/>
<source>to</source>
<translation>til</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="145"/>
<source>Sending...</source>
<translation>Sender...</translation>
</message>
</context>
<context>
<name>MMXIV-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="3"/>
<source>MMXIV version</source>
<translation>MMXIVversion</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="4"/>
<source>Usage:</source>
<translation>Anvendelse:</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="5"/>
<source>Send command to -server or MMXIVd</source>
<translation>Send kommando til -server eller MMXIVd
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="6"/>
<source>List commands</source>
<translation>Liste over kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="7"/>
<source>Get help for a command</source>
<translation>Få hjælp til en kommando
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="8"/>
<source>Options:</source>
<translation>Indstillinger:
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="9"/>
<source>Specify configuration file (default: mmxiv.conf)</source>
<translation>Angiv konfigurationsfil (standard: mmxiv.conf)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="10"/>
<source>Specify pid file (default: MMXIVd.pid)</source>
<translation>Angiv pid-fil (default: MMXIVd.pid)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="11"/>
<source>Generate coins</source>
<translation>Generér coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="12"/>
<source>Don't generate coins</source>
<translation>Generér ikke coins
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="13"/>
<source>Start minimized</source>
<translation>Start minimeret
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="14"/>
<source>Specify data directory</source>
<translation>Angiv databibliotek
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="15"/>
<source>Specify connection timeout (in milliseconds)</source>
<translation>Angiv tilslutningstimeout (i millisekunder)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="16"/>
<source>Connect through socks4 proxy</source>
<translation>Tilslut via SOCKS4 proxy
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="17"/>
<source>Allow DNS lookups for addnode and connect</source>
<translation>Tillad DNS-opslag for addnode og connect
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="18"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="19"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="20"/>
<source>Add a node to connect to</source>
<translation>Tilføj en node til at forbinde til
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="21"/>
<source>Connect only to the specified node</source>
<translation>Tilslut kun til den angivne node
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="22"/>
<source>Don't accept connections from outside</source>
<translation>Acceptér ikke forbindelser udefra
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="23"/>
<source>Don't bootstrap list of peers using DNS</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="24"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="25"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="28"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 10000)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="29"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 10000)</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="30"/>
<source>Don't attempt to use UPnP to map the listening port</source>
<translation>Forsøg ikke at bruge UPnP til at konfigurere den lyttende port</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="31"/>
<source>Attempt to use UPnP to map the listening port</source>
<translation>Forsøg at bruge UPnP til at kofnigurere den lyttende port</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="32"/>
<source>Fee per kB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="33"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter kommandolinje- og JSON-RPC-kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="34"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kør i baggrunden som en service, og acceptér kommandoer
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="35"/>
<source>Use the test network</source>
<translation>Brug test-netværket
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="36"/>
<source>Output extra debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="37"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="39"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="40"/>
<source>Username for JSON-RPC connections</source>
<translation>Brugernavn til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="41"/>
<source>Password for JSON-RPC connections</source>
<translation>Password til JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="42"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332)</source>
<translation>Lyt til JSON-RPC-forbindelser på <port> (standard: 8332)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="43"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillad JSON-RPC-forbindelser fra bestemt IP-adresse
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="44"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Send kommandoer til node, der kører på <ip> (standard: 127.0.0.1)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="45"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Sæt nøglepoolstørrelse til <n> (standard: 100)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="46"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Gennemsøg blokkæden for manglende tegnebogstransaktioner
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="47"/>
<source>
SSL options: (see the MMXIV Wiki for SSL setup instructions)</source>
<translation>
SSL-indstillinger: (se MMXIV Wiki for SSL opsætningsinstruktioner)</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="50"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Brug OpenSSL (https) for JSON-RPC-forbindelser
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="51"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Servercertifikat-fil (standard: server.cert)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="52"/>
<source>Server private key (default: server.pem)</source>
<translation>Server private nøgle (standard: server.pem)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="53"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Acceptabele ciphers (standard: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="56"/>
<source>This help message</source>
<translation>Denne hjælpebesked
</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="57"/>
<source>Cannot obtain a lock on data directory %s. MMXIV is probably already running.</source>
<translation>Kan låse data-biblioteket %s. MMXIV kører sikkert allerede.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="60"/>
<source>Loading addresses...</source>
<translation>Indlæser adresser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="61"/>
<source>Error loading addr.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="63"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="65"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="66"/>
<source>Error loading wallet.dat: Wallet requires newer version of MMXIV</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="67"/>
<source>Wallet needed to be rewritten: restart MMXIV to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="68"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="62"/>
<source>Loading block index...</source>
<translation>Indlæser blok-indeks...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="64"/>
<source>Loading wallet...</source>
<translation>Indlæser tegnebog...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="69"/>
<source>Rescanning...</source>
<translation>Genindlæser...</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="70"/>
<source>Done loading</source>
<translation>Indlæsning gennemført</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="71"/>
<source>Invalid -proxy address</source>
<translation>Ugyldig -proxy adresse</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="72"/>
<source>Invalid amount for -paytxfee=<amount></source>
<translation>Ugyldigt beløb for -paytxfee=<amount></translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="73"/>
<source>Warning: -paytxfee is set very high. This is the transaction fee you will pay if you send a transaction.</source>
<translation>Advarsel:-paytxfee er sat meget højt. Dette er det gebyr du vil betale, hvis du sender en transaktion.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="76"/>
<source>Error: CreateThread(StartNode) failed</source>
<translation>Fejl: CreateThread(StartNode) mislykkedes</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="77"/>
<source>Warning: Disk space is low </source>
<translation>Advarsel: Diskplads er lav </translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="78"/>
<source>Unable to bind to port %d on this computer. MMXIV is probably already running.</source>
<translation>Kunne ikke binde sig til port %d på denne computer. MMXIV kører sikkert allerede.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="81"/>
<source>Warning: Please check that your computer's date and time are correct. If your clock is wrong MMXIV will not work properly.</source>
<translation>Advarsel: Undersøg venligst at din computers dato og klokkeslet er korrekt indstillet. Hvis der er fejl i disse vil MMXIV ikke fungere korrekt.</translation>
</message>
<message>
<location filename="../bitcoinstrings.cpp" line="84"/>
<source>beta</source>
<translation>beta</translation>
</message>
</context>
</TS> | snowballdaemons/BALLS | src/qt/locale/bitcoin_da.ts | TypeScript | mit | 86,034 |
local dpdk = require "dpdk"
local ns = require "namespaces"
local test1 = ns:get("test1")
local test2 = ns:get("test2")
local test3 = ns:get()
function master()
assert(test1 == ns:get("test1"))
assert(test2 == ns:get("test2"))
assert(test3 ~= test and test3 ~= test2)
test2.number = 5
test2.string = "foo"
test2.table = { hello = "world", { 1 } }
for i = 1, 100 do
test3[tostring(i)] = i
end
assert(test1.lock and test2.lock)
assert(test1.lock ~= test2.lock)
dpdk.launchLua("slave", test1, test2, test3):wait()
assert(test3["66"] == 66) -- must not block
end
function slave(test1Arg, test2Arg, test3Arg)
-- serializing should kill our namespaces
assert(test1Arg == test1)
assert(test2Arg == test2)
assert(test3Arg == test3)
assert(test2.number == 5)
assert(test2.string == "foo")
assert(test2.table[1][1] == 1)
assert(test3.number == nil)
local seen = {}
test3:forEach(function(key, val) seen[key] = val end)
for i = 1, 100 do
assert(seen[tostring(i)] == i)
end
-- must release the lock properly
local ok = pcall(test3.forEach, test3, function(key, val) error() end)
assert(not ok)
end
| werpat/MoonGen | test/core/test-namespaces-standalone.lua | Lua | mit | 1,121 |
require 'spec_helper'
module Refinery
module MyPlugin
class Engine < ::Rails::Engine
isolate_namespace ::Refinery
::Refinery::Plugin.register do |plugin|
plugin.name = "my_plugin"
plugin.hide_from_menu = true
end
end
end
module MyOtherPlugin
class Engine < ::Rails::Engine
isolate_namespace ::Refinery
::Refinery::Plugin.register do |plugin|
plugin.name = "my_other_plugin"
plugin.hide_from_menu = true
end
end
end
::I18n.backend.store_translations :en, :refinery => {
:plugins => {
:my_plugin => {
:title => "my plugin"
},
:my_other_plugin => {
:title => "my other plugin"
}
}
}
describe Plugins do
before do
# First, deactivate all.
subject.class.set_active([])
end
describe '#activate' do
it "activates a plugin" do
subject.class.activate("my_plugin")
expect(subject.class.active.names).to include("my_plugin")
end
it "only activates the same plugin once" do
subject.class.activate("my_other_plugin")
subject.class.activate("my_other_plugin")
expect(subject.class.active.names.count("my_other_plugin")).to eq(1)
end
it "doesn't deactivate the first plugin when another is activated" do
subject.class.activate("my_plugin")
subject.class.activate("my_other_plugin")
expect(subject.class.active.names).to include("my_plugin")
expect(subject.class.active.names).to include("my_other_plugin")
end
end
describe '#deactivate' do
it "deactivates a plugin" do
subject.class.activate("my_plugin")
subject.class.deactivate("my_plugin")
expect(subject.class.active.count).to eq(0)
end
end
describe '#set_active' do
it "activates a single plugin" do
subject.class.set_active(%w(my_plugin))
expect(subject.class.active.names).to include("my_plugin")
end
it "activates a list of plugins" do
subject.class.set_active(%w(my_plugin my_other_plugin))
expect(subject.class.active.names).to include("my_plugin")
expect(subject.class.active.names).to include("my_plugin")
expect(subject.class.active.count).to eq(2)
end
it "deactivates the initial plugins when another set is set_active" do
subject.class.set_active(%w(my_plugin))
subject.class.set_active(%w(my_other_plugin))
expect(subject.class.active.names).not_to include("my_plugin")
expect(subject.class.active.names).to include("my_other_plugin")
expect(subject.class.active.count).to eq(1)
end
end
describe '#registered' do
it 'identifies as Refinery::Plugins' do
expect(subject.class.registered.class).to eq(subject.class)
end
end
describe '#active' do
it 'identifies as Refinery::Plugins' do
expect(subject.class.active.class).to eq(subject.class)
end
it 'only contains items that are registered' do
subject.class.set_active(%w(my_plugin))
expect(subject.class.active.any?).to be_truthy
expect(subject.class.active.all?{ |p| subject.class.registered.include?(p)}).to be_truthy
end
end
describe '#always_allowed' do
it 'should identify as Refinery::Plugins' do
expect(subject.class.always_allowed.class).to eq(subject.class)
end
it 'only contains items that are always allowed' do
expect(subject.class.always_allowed.any?).to be_truthy
expect(subject.class.always_allowed.all? { |p| p.always_allow_access }).to be_truthy
end
end
describe '#in_menu' do
it 'identifies as Refinery::Plugins' do
expect(subject.class.registered.in_menu.class).to eq(subject.class)
end
it 'only contains items that are in the menu' do
expect(subject.class.registered.in_menu.any?).to be_truthy
expect(subject.class.registered.in_menu.all? { |p| !p.hide_from_menu }).to be_truthy
end
end
describe ".find_by_name" do
it "finds plugin by given name" do
subject.class.set_active(%w(my_plugin))
expect(subject.class.active.find_by_name("my_plugin").name).to eq("my_plugin")
end
end
describe ".find_by_title" do
it "finds plugin by given title" do
subject.class.set_active(%w(my_plugin))
expect(subject.class.active.find_by_title("my plugin").title).to eq("my plugin")
end
end
end
end
| kappiah/refinerycms | core/spec/lib/refinery/plugins_spec.rb | Ruby | mit | 4,569 |
/*
Copyright 2016 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package driver
import (
"strconv"
"strings"
"sync"
rspb "k8s.io/helm/pkg/proto/hapi/release"
)
var _ Driver = (*Memory)(nil)
// MemoryDriverName is the string name of this driver.
const MemoryDriverName = "Memory"
// Memory is the in-memory storage driver implementation.
type Memory struct {
sync.RWMutex
cache map[string]records
}
// NewMemory initializes a new memory driver.
func NewMemory() *Memory {
return &Memory{cache: map[string]records{}}
}
// Name returns the name of the driver.
func (mem *Memory) Name() string {
return MemoryDriverName
}
// Get returns the release named by key or returns ErrReleaseNotFound.
func (mem *Memory) Get(key string) (*rspb.Release, error) {
defer unlock(mem.rlock())
switch elems := strings.Split(key, ".v"); len(elems) {
case 2:
name, ver := elems[0], elems[1]
if _, err := strconv.Atoi(ver); err != nil {
return nil, ErrInvalidKey(key)
}
if recs, ok := mem.cache[name]; ok {
if r := recs.Get(key); r != nil {
return r.rls, nil
}
}
return nil, ErrReleaseNotFound(key)
default:
return nil, ErrInvalidKey(key)
}
}
// List returns the list of all releases such that filter(release) == true
func (mem *Memory) List(filter func(*rspb.Release) bool) ([]*rspb.Release, error) {
defer unlock(mem.rlock())
var ls []*rspb.Release
for _, recs := range mem.cache {
recs.Iter(func(_ int, rec *record) bool {
if filter(rec.rls) {
ls = append(ls, rec.rls)
}
return true
})
}
return ls, nil
}
// Query returns the set of releases that match the provided set of labels
func (mem *Memory) Query(keyvals map[string]string) ([]*rspb.Release, error) {
defer unlock(mem.rlock())
var lbs labels
lbs.init()
lbs.fromMap(keyvals)
var ls []*rspb.Release
for _, recs := range mem.cache {
recs.Iter(func(_ int, rec *record) bool {
// A query for a release name that doesn't exist (has been deleted)
// can cause rec to be nil.
if rec == nil {
return false
}
if rec.lbs.match(lbs) {
ls = append(ls, rec.rls)
}
return true
})
}
return ls, nil
}
// Create creates a new release or returns ErrReleaseExists.
func (mem *Memory) Create(key string, rls *rspb.Release) error {
defer unlock(mem.wlock())
if recs, ok := mem.cache[rls.Name]; ok {
if err := recs.Add(newRecord(key, rls)); err != nil {
return err
}
mem.cache[rls.Name] = recs
return nil
}
mem.cache[rls.Name] = records{newRecord(key, rls)}
return nil
}
// Update updates a release or returns ErrReleaseNotFound.
func (mem *Memory) Update(key string, rls *rspb.Release) error {
defer unlock(mem.wlock())
if rs, ok := mem.cache[rls.Name]; ok && rs.Exists(key) {
rs.Replace(key, newRecord(key, rls))
return nil
}
return ErrReleaseNotFound(rls.Name)
}
// Delete deletes a release or returns ErrReleaseNotFound.
func (mem *Memory) Delete(key string) (*rspb.Release, error) {
defer unlock(mem.wlock())
elems := strings.Split(key, ".v")
if len(elems) != 2 {
return nil, ErrInvalidKey(key)
}
name, ver := elems[0], elems[1]
if _, err := strconv.Atoi(ver); err != nil {
return nil, ErrInvalidKey(key)
}
if recs, ok := mem.cache[name]; ok {
if r := recs.Remove(key); r != nil {
// recs.Remove changes the slice reference, so we have to re-assign it.
mem.cache[name] = recs
return r.rls, nil
}
}
return nil, ErrReleaseNotFound(key)
}
// wlock locks mem for writing
func (mem *Memory) wlock() func() {
mem.Lock()
return func() { mem.Unlock() }
}
// rlock locks mem for reading
func (mem *Memory) rlock() func() {
mem.RLock()
return func() { mem.RUnlock() }
}
// unlock calls fn which reverses a mem.rlock or mem.wlock. e.g:
// ```defer unlock(mem.rlock())```, locks mem for reading at the
// call point of defer and unlocks upon exiting the block.
func unlock(fn func()) { fn() }
| skuid/helm-value-store | vendor/k8s.io/helm/pkg/storage/driver/memory.go | GO | mit | 4,412 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_serial_port::read_some</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../basic_serial_port.html" title="basic_serial_port">
<link rel="prev" href="operator_eq_.html" title="basic_serial_port::operator=">
<link rel="next" href="read_some/overload1.html" title="basic_serial_port::read_some (1 of 2 overloads)">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator_eq_.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_serial_port.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="read_some/overload1.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.basic_serial_port.read_some"></a><a class="link" href="read_some.html" title="basic_serial_port::read_some">basic_serial_port::read_some</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idm61586"></a>
Read some data from the serial port.
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_some/overload1.html" title="basic_serial_port::read_some (1 of 2 overloads)">read_some</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="read_some/overload1.html" title="basic_serial_port::read_some (1 of 2 overloads)">more...</a></em></span>
<span class="keyword">template</span><span class="special"><</span>
<span class="keyword">typename</span> <a class="link" href="../MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">></span>
<span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <a class="link" href="read_some/overload2.html" title="basic_serial_port::read_some (2 of 2 overloads)">read_some</a><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
<span class="emphasis"><em>» <a class="link" href="read_some/overload2.html" title="basic_serial_port::read_some (2 of 2 overloads)">more...</a></em></span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2016 Christopher
M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="operator_eq_.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../basic_serial_port.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="read_some/overload1.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| throughnet/throughnet | src/libs/asio/doc/asio/reference/basic_serial_port/read_some.html | HTML | mit | 4,520 |
<?php
defined('C5_EXECUTE') or die("Access Denied.");
class CollectionAttributeKey extends Concrete5_Model_CollectionAttributeKey {}
class CollectionAttributeValue extends Concrete5_Model_CollectionAttributeValue {} | mrogelja/aca-architecte-website | concrete/models/attribute/categories/collection.php | PHP | mit | 215 |
module Fog
module Compute
class ProfitBricks
class Real
# Deletes the specified IP Block
#
# ==== Parameters
# * ip_block_id<~String> - UUID of the IP Block
#
# ==== Returns
# * response<~Excon::Response> - No response parameters
# (HTTP/1.1 202 Accepted)
#
# {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v2/#delete-ip-block]
def delete_ip_block(ip_block_id)
request(
:expects => [202],
:method => 'DELETE',
:path => "/ipblocks/#{ip_block_id}"
)
end
end
class Mock
def delete_ip_block(ip_block_id)
response = Excon::Response.new
response.status = 202
if ip_block = data[:ip_blocks]["items"].find do |attribute|
attribute["id"] == ip_block_id
end
else
raise Fog::Errors::NotFound, "The requested IP Block could not be found"
end
response
end
end
end
end
end
| jonpstone/portfolio-project-rails-mean-movie-reviews | vendor/bundle/ruby/2.3.0/gems/fog-profitbricks-4.1.1/lib/fog/profitbricks/requests/compute/delete_ip_block.rb | Ruby | mit | 1,094 |
package telemetry
import (
"time"
"github.com/influxdata/influxdb/v2/prometheus"
dto "github.com/prometheus/client_model/go"
)
const (
// just in case the definition of time.Nanosecond changes from 1.
nsPerMillisecond = int64(time.Millisecond / time.Nanosecond)
)
var _ prometheus.Transformer = (*AddTimestamps)(nil)
// AddTimestamps enriches prometheus metrics by adding timestamps.
type AddTimestamps struct {
now func() time.Time
}
// Transform adds now as a timestamp to all metrics.
func (a *AddTimestamps) Transform(mfs []*dto.MetricFamily) []*dto.MetricFamily {
now := a.now
if now == nil {
now = time.Now
}
nowMilliseconds := now().UnixNano() / nsPerMillisecond
for i := range mfs {
for j := range mfs[i].Metric {
mfs[i].Metric[j].TimestampMs = &nowMilliseconds
}
}
return mfs
}
| influxdb/influxdb | telemetry/timestamps.go | GO | mit | 816 |
---
title: Automated Deployment
permalink: /docs/deployment/automated/
---
There are a number of ways to easily automate the deployment of a Jekyll site.
## Continuous Integration Service
One of the easiest ways to set up an automated deployment flow is by using a
CI.
These services run a script when there's a commit on your Git repository.
You might want this script to build the site, run tests over the output then deploy it to the
service of your choice.
We have guides for the following providers:
* [GitHub Actions]({{ '/docs/continuous-integration/github-actions/' | relative_url }})
* [Travis CI]({{ '/docs/continuous-integration/travis-ci/' | relative_url }})
* [CircleCI]({{ '/docs/continuous-integration/circleci/' | relative_url }})
* [Buddy]({{ '/docs/continuous-integration/buddyworks/' | relative_url }})
* [Razorops CI/CD]({{ '/docs/continuous-integration/razorops/' | relative_url }})
## Git post-receive hook
To have a remote server handle the deploy for you every time you push changes using Git, you can create a user account which has all the public keys that are authorized to deploy in its `authorized_keys` file. With that in place, setting up the post-receive hook is done as follows:
```sh
laptop$ ssh [email protected]
server$ mkdir myrepo.git
server$ cd myrepo.git
server$ git --bare init
server$ cp hooks/post-receive.sample hooks/post-receive
server$ mkdir /var/www/myrepo
```
Next, add the following lines to hooks/post-receive and be sure Jekyll is
installed on the server:
```bash
#!/bin/bash -l
# Install Ruby Gems to ~/gems
export GEM_HOME=$HOME/gems
export PATH=$GEM_HOME/bin:$PATH
TMP_GIT_CLONE=$HOME/tmp/myrepo
GEMFILE=$TMP_GIT_CLONE/Gemfile
PUBLIC_WWW=/var/www/myrepo
git clone $GIT_DIR $TMP_GIT_CLONE
BUNDLE_GEMFILE=$GEMFILE bundle install
BUNDLE_GEMFILE=$GEMFILE bundle exec jekyll build -s $TMP_GIT_CLONE -d $PUBLIC_WWW
rm -Rf $TMP_GIT_CLONE
exit
```
Finally, run the following command on any users laptop that needs to be able to
deploy using this hook:
```sh
laptops$ git remote add deploy [email protected]:~/myrepo.git
```
Deploying is now as easy as telling nginx or Apache to look at
`/var/www/myrepo` and running the following:
```sh
laptops$ git push deploy master
```
| fulldecent/jekyll | docs/_docs/deployment/automated.md | Markdown | mit | 2,244 |
# SRANDMEMBER *key*
**TIME COMPLEXITY**:
O(1)
**DESCRIPTION**:
Return a random element from a Set, without removing the element. If the Set is
empty or the key does not exist, a nil object is returned.
The SPOP command does a similar work but the returned element is popped
(removed) from the Set.
**RETURN VALUE**:
Bulk reply
| supasate/try.redis | redis-doc/srandmember.markdown | Markdown | mit | 331 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import cint
@frappe.whitelist()
def add(doctype, name, user=None, read=1, write=0, share=0, everyone=0, flags=None):
"""Share the given document with a user."""
if not user:
user = frappe.session.user
if not (flags or {}).get("ignore_share_permission"):
check_share_permission(doctype, name)
share_name = get_share_name(doctype, name, user, everyone)
if share_name:
doc = frappe.get_doc("DocShare", share_name)
else:
doc = frappe.new_doc("DocShare")
doc.update({
"user": user,
"share_doctype": doctype,
"share_name": name,
"everyone": cint(everyone)
})
if flags:
doc.flags.update(flags)
doc.update({
# always add read, since you are adding!
"read": 1,
"write": cint(write),
"share": cint(share)
})
doc.save(ignore_permissions=True)
return doc
def remove(doctype, name, user, flags=None):
share_name = frappe.db.get_value("DocShare", {"user": user, "share_name": name,
"share_doctype": doctype})
if share_name:
frappe.delete_doc("DocShare", share_name, flags=flags)
@frappe.whitelist()
def set_permission(doctype, name, user, permission_to, value=1, everyone=0):
"""Set share permission."""
check_share_permission(doctype, name)
share_name = get_share_name(doctype, name, user, everyone)
value = int(value)
if not share_name:
if value:
share = add(doctype, name, user, everyone=everyone, **{permission_to: 1})
else:
# no share found, nothing to remove
share = {}
pass
else:
share = frappe.get_doc("DocShare", share_name)
share.flags.ignore_permissions = True
share.set(permission_to, value)
if not value:
# un-set higher-order permissions too
if permission_to=="read":
share.read = share.write = share.share = 0
share.save()
if not (share.read or share.write or share.share):
share.delete()
share = {}
return share
@frappe.whitelist()
def get_users(doctype, name):
"""Get list of users with which this document is shared"""
return frappe.db.sql("""select
`name`, `user`, `read`, `write`, `share`, `everyone`
from
tabDocShare
where
share_doctype=%s and share_name=%s""",
(doctype, name), as_dict=True)
def get_shared(doctype, user=None, rights=None):
"""Get list of shared document names for given user and DocType.
:param doctype: DocType of which shared names are queried.
:param user: User for which shared names are queried.
:param rights: List of rights for which the document is shared. List of `read`, `write`, `share`"""
if not user:
user = frappe.session.user
if not rights:
rights = ["read"]
condition = " and ".join(["`{0}`=1".format(right) for right in rights])
return frappe.db.sql_list("""select share_name from tabDocShare
where (user=%s {everyone}) and share_doctype=%s and {condition}""".format(
condition=condition, everyone="or everyone=1" if user!="Guest" else ""),
(user, doctype))
def get_shared_doctypes(user=None):
"""Return list of doctypes in which documents are shared for the given user."""
if not user:
user = frappe.session.user
return frappe.db.sql_list("select distinct share_doctype from tabDocShare where (user=%s or everyone=1)", user)
def get_share_name(doctype, name, user, everyone):
if cint(everyone):
share_name = frappe.db.get_value("DocShare", {"everyone": 1, "share_name": name,
"share_doctype": doctype})
else:
share_name = frappe.db.get_value("DocShare", {"user": user, "share_name": name,
"share_doctype": doctype})
return share_name
def check_share_permission(doctype, name):
"""Check if the user can share with other users"""
if not frappe.has_permission(doctype, ptype="share", doc=name):
frappe.throw(_("No permission to {0} {1} {2}".format("share", doctype, name)), frappe.PermissionError)
| bcornwellmott/frappe | frappe/share.py | Python | mit | 3,922 |
define({main:{"es-UY":{identity:{version:{_number:"$Revision: 11914 $",_cldrVersion:"29"},language:"es",territory:"UY"},dates:{calendars:{gregorian:{months:{format:{abbreviated:{1:"ene.",2:"feb.",3:"mar.",4:"abr.",5:"may.",6:"jun.",7:"jul.",8:"ago.",9:"set.",10:"oct.",11:"nov.",12:"dic."},narrow:{1:"e",2:"f",3:"m",4:"a",5:"m",6:"j",7:"j",8:"a",9:"s",10:"o",11:"n",12:"d"},wide:{1:"enero",2:"febrero",3:"marzo",4:"abril",5:"mayo",6:"junio",7:"julio",8:"agosto",9:"setiembre",10:"octubre",11:"noviembre",
12:"diciembre"}},"stand-alone":{abbreviated:{1:"Ene.",2:"Feb.",3:"Mar.",4:"Abr.",5:"May.",6:"Jun.",7:"Jul.",8:"Ago.",9:"Set.",10:"Oct.",11:"Nov.",12:"Dic."},narrow:{1:"e",2:"f",3:"m",4:"a",5:"m",6:"j",7:"j",8:"a",9:"s",10:"o",11:"n",12:"d"},wide:{1:"Enero",2:"Febrero",3:"Marzo",4:"Abril",5:"Mayo",6:"Junio",7:"Julio",8:"Agosto",9:"Setiembre",10:"Octubre",11:"Noviembre",12:"Diciembre"}}},days:{format:{abbreviated:{sun:"dom.",mon:"lun.",tue:"mar.",wed:"mié.",thu:"jue.",fri:"vie.",sat:"sáb."},narrow:{sun:"d",
mon:"l",tue:"m",wed:"m",thu:"j",fri:"v",sat:"s"},wide:{sun:"domingo",mon:"lunes",tue:"martes",wed:"miércoles",thu:"jueves",fri:"viernes",sat:"sábado"}},"stand-alone":{abbreviated:{sun:"dom.",mon:"lun.",tue:"mar.",wed:"mié.",thu:"jue.",fri:"vie.",sat:"sáb."},narrow:{sun:"D",mon:"L",tue:"M",wed:"M",thu:"J",fri:"V",sat:"S"},wide:{sun:"domingo",mon:"lunes",tue:"martes",wed:"miércoles",thu:"jueves",fri:"viernes",sat:"sábado"}}},dayPeriods:{format:{wide:{am:"a.m.",pm:"p.m."}}},eras:{eraAbbr:{0:"a. C.",
1:"d. C."}},dateFormats:{full:"EEEE, d 'de' MMMM 'de' y","long":"d 'de' MMMM 'de' y",medium:"d MMM y","short":"d/M/yy"},timeFormats:{full:"HH:mm:ss zzzz","long":"HH:mm:ss z",medium:"HH:mm:ss","short":"HH:mm"},dateTimeFormats:{full:"{1}, {0}","long":"{1}, {0}",medium:"{1} {0}","short":"{1} {0}",availableFormats:{d:"d",E:"ccc",Ed:"E d",Ehm:"E, h:mm a",EHm:"E, HH:mm",Ehms:"E, h:mm:ss a",EHms:"E, HH:mm:ss",Gy:"y G",GyMMM:"MMM y G",GyMMMd:"d 'de' MMM 'de' y G",GyMMMEd:"E, d MMM y G",GyMMMM:"MMMM 'de' y G",
GyMMMMd:"d 'de' MMMM 'de' y G",GyMMMMEd:"E, d 'de' MMMM 'de' y G",h:"h a",H:"HH",hm:"h:mm a",Hm:"HH:mm",hms:"h:mm:ss a",Hms:"HH:mm:ss",hmsv:"h:mm:ss a v",Hmsv:"H:mm:ss v",hmsvvvv:"h:mm:ss a (vvvv)",Hmsvvvv:"H:mm:ss (vvvv)",hmv:"h:mm a v",Hmv:"H:mm v",M:"L",Md:"d/M",MEd:"E, d/M",MMd:"d/M",MMdd:"d/M",MMM:"LLL",MMMd:"d MMM",MMMdd:"dd-MMM",MMMEd:"E, d MMM",MMMMd:"d 'de' MMMM",MMMMEd:"E, d 'de' MMMM",ms:"mm:ss",y:"y",yM:"M/y",yMd:"d/M/y",yMEd:"E d/M/y",yMM:"M/y",yMMM:"MMMM 'de' y",yMMMd:"d 'de' MMMM 'de' y",
yMMMEd:"E, d 'de' MMM 'de' y",yMMMM:"MMMM 'de' y",yMMMMd:"d 'de' MMMM 'de' y",yMMMMEd:"EEE, d 'de' MMMM 'de' y",yQQQ:"QQQ 'de' y",yQQQQ:"QQQQ 'de' y"},appendItems:{Timezone:"{0} {1}"}}}},fields:{year:{"relative-type--1":"el año pasado","relative-type-0":"este año","relative-type-1":"el próximo año","relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} año","relativeTimePattern-count-other":"dentro de {0} años"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} año",
"relativeTimePattern-count-other":"hace {0} años"}},month:{"relative-type--1":"el mes pasado","relative-type-0":"este mes","relative-type-1":"el próximo mes","relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} mes","relativeTimePattern-count-other":"dentro de {0} meses"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} mes","relativeTimePattern-count-other":"hace {0} meses"}},week:{"relative-type--1":"la semana pasada","relative-type-0":"esta semana","relative-type-1":"la próxima semana",
"relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} semana","relativeTimePattern-count-other":"dentro de {0} semanas"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} semana","relativeTimePattern-count-other":"hace {0} semanas"}},day:{"relative-type--1":"ayer","relative-type-0":"hoy","relative-type-1":"mañana","relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} día","relativeTimePattern-count-other":"dentro de {0} días"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} día",
"relativeTimePattern-count-other":"hace {0} días"}},sun:{"relative-type--1":"el domingo pasado"},mon:{"relative-type--1":"el lunes pasado"},tue:{"relative-type--1":"el martes pasado"},wed:{"relative-type--1":"el miércoles pasado"},thu:{"relative-type--1":"el jueves pasado"},fri:{"relative-type--1":"el viernes pasado"},sat:{"relative-type--1":"el sábado pasado"},hour:{"relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} hora","relativeTimePattern-count-other":"dentro de {0} horas"},
"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} hora","relativeTimePattern-count-other":"hace {0} horas"}},minute:{"relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} minuto","relativeTimePattern-count-other":"dentro de {0} minutos"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} minuto","relativeTimePattern-count-other":"hace {0} minutos"}},second:{"relative-type-0":"ahora","relativeTime-type-future":{"relativeTimePattern-count-one":"dentro de {0} segundo",
"relativeTimePattern-count-other":"dentro de {0} segundos"},"relativeTime-type-past":{"relativeTimePattern-count-one":"hace {0} segundo","relativeTimePattern-count-other":"hace {0} segundos"}}}},numbers:{defaultNumberingSystem:"latn",otherNumberingSystems:{"native":"latn"},"symbols-numberSystem-latn":{decimal:",",group:".",percentSign:"%",plusSign:"+",minusSign:"-",exponential:"E",perMille:"‰",infinity:"∞",nan:"NaN"},"decimalFormats-numberSystem-latn":{standard:"#,##0.###","long":{decimalFormat:{"1000-count-one":"0 mil",
"1000-count-other":"0 mil","10000-count-one":"00 mil","10000-count-other":"00 mil","100000-count-one":"000 mil","100000-count-other":"000 mil","1000000-count-one":"0 millón","1000000-count-other":"0 millones","10000000-count-one":"00 millones","10000000-count-other":"00 millones","100000000-count-one":"000 millones","100000000-count-other":"000 millones","1000000000-count-one":"0 mil millones","1000000000-count-other":"0 mil millones","10000000000-count-one":"00 mil millones","10000000000-count-other":"00 mil millones",
"100000000000-count-one":"000 mil millones","100000000000-count-other":"000 mil millones","1000000000000-count-one":"0 billón","1000000000000-count-other":"0 billones","10000000000000-count-one":"00 billones","10000000000000-count-other":"00 billones","100000000000000-count-one":"000 billones","100000000000000-count-other":"000 billones"}},"short":{decimalFormat:{"1000-count-one":"0","1000-count-other":"0","10000-count-one":"00k","10000-count-other":"00k","100000-count-one":"000k","100000-count-other":"000k",
"1000000-count-one":"0 M","1000000-count-other":"0 M","10000000-count-one":"00 M","10000000-count-other":"00 M","100000000-count-one":"000 M","100000000-count-other":"000 M","1000000000-count-one":"0k M","1000000000-count-other":"0k M","10000000000-count-one":"00k M","10000000000-count-other":"00k M","100000000000-count-one":"000k M","100000000000-count-other":"000k M","1000000000000-count-one":"0 B","1000000000000-count-other":"0 B","10000000000000-count-one":"00 B","10000000000000-count-other":"00 B",
"100000000000000-count-one":"000 B","100000000000000-count-other":"000 B"}}},"percentFormats-numberSystem-latn":{standard:"#,##0 %"},"currencyFormats-numberSystem-latn":{standard:"¤ #,##0.00","unitPattern-count-one":"{0} {1}","unitPattern-count-other":"{0} {1}"},currencies:{AUD:{displayName:"dólar australiano",symbol:"AUD"},BRL:{displayName:"real brasileño",symbol:"BRL"},CAD:{displayName:"dólar canadiense",symbol:"CAD"},CHF:{displayName:"franco suizo",symbol:"CHF"},CNY:{displayName:"yuan",symbol:"CNY"},
CZK:{displayName:"corona checa",symbol:"CZK"},DKK:{displayName:"corona danesa",symbol:"DKK"},EUR:{displayName:"euro",symbol:"EUR"},GBP:{displayName:"libra británica",symbol:"GBP"},HKD:{displayName:"dólar hongkonés",symbol:"HKD"},HUF:{displayName:"forinto húngaro",symbol:"HUF"},IDR:{displayName:"rupia indonesia",symbol:"IDR"},INR:{displayName:"rupia india",symbol:"INR"},JPY:{displayName:"yen",symbol:"JPY"},KRW:{displayName:"won surcoreano",symbol:"KRW"},MXN:{displayName:"peso mexicano",symbol:"MXN"},
NOK:{displayName:"corona noruega",symbol:"NOK"},PLN:{displayName:"esloti",symbol:"PLN"},RUB:{displayName:"rublo ruso",symbol:"RUB"},SAR:{displayName:"rial saudí",symbol:"SAR"},SEK:{displayName:"corona sueca",symbol:"SEK"},THB:{displayName:"bat",symbol:"THB"},TRY:{displayName:"lira turca",symbol:"TRY"},TWD:{displayName:"nuevo dólar taiwanés",symbol:"TWD"},USD:{displayName:"dólar estadounidense",symbol:"US$"},ZAR:{displayName:"rand",symbol:"ZAR"}}}}}}); | crmouli/crmouli.github.io | js/libs/oj/v3.0.0/resources/nls/es-UY/localeElements.js | JavaScript | mit | 8,790 |
<a href='https://github.com/angular/angular.js/edit/v1.3.x/src/Angular.js?message=docs(ng)%3A%20describe%20your%20change...#L95' class='improve-docs btn btn-primary'><i class="glyphicon glyphicon-edit"> </i>Improve this Doc</a>
<h1>
<code>ng</code>
</h1>
<h1 id="ng-core-module-">ng (core module)</h1>
<p>The ng module is loaded by default when an AngularJS application is started. The module itself
contains the essential components for an AngularJS application to function. The table below
lists a high level breakdown of each of the services/factories, filters, directives and testing
components available within this core module.</p>
<div doc-module-components="ng"></div>
<div class="component-breakdown">
<h2>Module Components</h2>
<div>
<h3 class="component-heading" id="function">Function</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/function/angular.lowercase">angular.lowercase</a></td>
<td><p>Converts the specified string to lowercase.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.uppercase">angular.uppercase</a></td>
<td><p>Converts the specified string to uppercase.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.forEach">angular.forEach</a></td>
<td><p>Invokes the <code>iterator</code> function once for each item in <code>obj</code> collection, which can be either an
object or an array. The <code>iterator</code> function is invoked with <code>iterator(value, key, obj)</code>, where <code>value</code>
is the value of an object property or an array element, <code>key</code> is the object property key or
array element index and obj is the <code>obj</code> itself. Specifying a <code>context</code> for the function is optional.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.extend">angular.extend</a></td>
<td><p>Extends the destination object <code>dst</code> by copying own enumerable properties from the <code>src</code> object(s)
to <code>dst</code>. You can specify multiple <code>src</code> objects. If you want to preserve original objects, you can do so
by passing an empty object as the target: <code>var object = angular.extend({}, object1, object2)</code>.
Note: Keep in mind that <code>angular.extend</code> does not support recursive merge (deep copy).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.noop">angular.noop</a></td>
<td><p>A function that performs no operations. This function can be useful when writing code in the
functional style.</p>
<pre><code class="lang-js">function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</code></pre>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.identity">angular.identity</a></td>
<td><p>A function that returns its first argument. This function is useful when writing code in the
functional style.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isUndefined">angular.isUndefined</a></td>
<td><p>Determines if a reference is undefined.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isDefined">angular.isDefined</a></td>
<td><p>Determines if a reference is defined.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isObject">angular.isObject</a></td>
<td><p>Determines if a reference is an <code>Object</code>. Unlike <code>typeof</code> in JavaScript, <code>null</code>s are not
considered to be objects. Note that JavaScript arrays are objects.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isString">angular.isString</a></td>
<td><p>Determines if a reference is a <code>String</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isNumber">angular.isNumber</a></td>
<td><p>Determines if a reference is a <code>Number</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isDate">angular.isDate</a></td>
<td><p>Determines if a value is a date.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isArray">angular.isArray</a></td>
<td><p>Determines if a reference is an <code>Array</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isFunction">angular.isFunction</a></td>
<td><p>Determines if a reference is a <code>Function</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.isElement">angular.isElement</a></td>
<td><p>Determines if a reference is a DOM element (or wrapped jQuery element).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.copy">angular.copy</a></td>
<td><p>Creates a deep copy of <code>source</code>, which should be an object or an array.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.equals">angular.equals</a></td>
<td><p>Determines if two objects or two values are equivalent. Supports value types, regular
expressions, arrays and objects.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.bind">angular.bind</a></td>
<td><p>Returns a function which calls function <code>fn</code> bound to <code>self</code> (<code>self</code> becomes the <code>this</code> for
<code>fn</code>). You can supply optional <code>args</code> that are prebound to the function. This feature is also
known as <a href="http://en.wikipedia.org/wiki/Partial_application">partial application</a>, as
distinguished from <a href="http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application">function currying</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.toJson">angular.toJson</a></td>
<td><p>Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
stripped since angular uses this notation internally.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.fromJson">angular.fromJson</a></td>
<td><p>Deserializes a JSON string.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.bootstrap">angular.bootstrap</a></td>
<td><p>Use this function to manually start up angular application.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.reloadWithDebugInfo">angular.reloadWithDebugInfo</a></td>
<td><p>Use this function to reload the current application with debug information turned on.
This takes precedence over a call to <code>$compileProvider.debugInfoEnabled(false)</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.injector">angular.injector</a></td>
<td><p>Creates an injector object that can be used for retrieving services as well as for
dependency injection (see <a href="guide/di">dependency injection</a>).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.element">angular.element</a></td>
<td><p>Wraps a raw DOM element or HTML string as a <a href="http://jquery.com">jQuery</a> element.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/function/angular.module">angular.module</a></td>
<td><p>The <code>angular.module</code> is a global place for creating, registering and retrieving Angular
modules.
All modules (angular core or 3rd party) that should be available to an application must be
registered using this mechanism.</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="directive">Directive</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/directive/ngApp">ngApp</a></td>
<td><p>Use this directive to <strong>auto-bootstrap</strong> an AngularJS application. The <code>ngApp</code> directive
designates the <strong>root element</strong> of the application and is typically placed near the root element
of the page - e.g. on the <code><body></code> or <code><html></code> tags.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/a">a</a></td>
<td><p>Modifies the default behavior of the html A tag so that the default action is prevented when
the href attribute is empty.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngHref">ngHref</a></td>
<td><p>Using Angular markup like <code>{{hash}}</code> in an href attribute will
make the link go to the wrong URL if the user clicks it before
Angular has a chance to replace the <code>{{hash}}</code> markup with its
value. Until Angular replaces the markup the link will be broken
and will most likely return a 404 error.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngSrc">ngSrc</a></td>
<td><p>Using Angular markup like <code>{{hash}}</code> in a <code>src</code> attribute doesn't
work right: The browser will fetch from the URL with the literal
text <code>{{hash}}</code> until Angular replaces the expression inside
<code>{{hash}}</code>. The <code>ngSrc</code> directive solves this problem.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngSrcset">ngSrcset</a></td>
<td><p>Using Angular markup like <code>{{hash}}</code> in a <code>srcset</code> attribute doesn't
work right: The browser will fetch from the URL with the literal
text <code>{{hash}}</code> until Angular replaces the expression inside
<code>{{hash}}</code>. The <code>ngSrcset</code> directive solves this problem.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngDisabled">ngDisabled</a></td>
<td><p>We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:</p>
<pre><code class="lang-html"><div ng-init="scope = { isDisabled: false }">
<button disabled="{{scope.isDisabled}}">Disabled</button>
</div>
</code></pre>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngChecked">ngChecked</a></td>
<td><p>The HTML specification does not require browsers to preserve the values of boolean attributes
such as checked. (Their presence means true and their absence means false.)
If we put an Angular interpolation expression into such an attribute then the
binding information would be lost when the browser removes the attribute.
The <code>ngChecked</code> directive solves this problem for the <code>checked</code> attribute.
This complementary directive is not removed by the browser and so provides
a permanent reliable place to store the binding information.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngReadonly">ngReadonly</a></td>
<td><p>The HTML specification does not require browsers to preserve the values of boolean attributes
such as readonly. (Their presence means true and their absence means false.)
If we put an Angular interpolation expression into such an attribute then the
binding information would be lost when the browser removes the attribute.
The <code>ngReadonly</code> directive solves this problem for the <code>readonly</code> attribute.
This complementary directive is not removed by the browser and so provides
a permanent reliable place to store the binding information.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngSelected">ngSelected</a></td>
<td><p>The HTML specification does not require browsers to preserve the values of boolean attributes
such as selected. (Their presence means true and their absence means false.)
If we put an Angular interpolation expression into such an attribute then the
binding information would be lost when the browser removes the attribute.
The <code>ngSelected</code> directive solves this problem for the <code>selected</code> attribute.
This complementary directive is not removed by the browser and so provides
a permanent reliable place to store the binding information.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngOpen">ngOpen</a></td>
<td><p>The HTML specification does not require browsers to preserve the values of boolean attributes
such as open. (Their presence means true and their absence means false.)
If we put an Angular interpolation expression into such an attribute then the
binding information would be lost when the browser removes the attribute.
The <code>ngOpen</code> directive solves this problem for the <code>open</code> attribute.
This complementary directive is not removed by the browser and so provides
a permanent reliable place to store the binding information.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngForm">ngForm</a></td>
<td><p>Nestable alias of <a href="api/ng/directive/form"><code>form</code></a> directive. HTML
does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
sub-group of controls needs to be determined.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/form">form</a></td>
<td><p>Directive that instantiates
<a href="api/ng/type/form.FormController">FormController</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/textarea">textarea</a></td>
<td><p>HTML textarea element control with angular data-binding. The data-binding and validation
properties of this element are exactly the same as those of the
<a href="api/ng/directive/input">input element</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/input">input</a></td>
<td><p>HTML input element control. When used together with <a href="api/ng/directive/ngModel"><code>ngModel</code></a>, it provides data-binding,
input state control, and validation.
Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngModel">ngModel</a></td>
<td><p>The <code>ngModel</code> directive binds an <code>input</code>,<code>select</code>, <code>textarea</code> (or custom form control) to a
property on the scope using <a href="api/ng/type/ngModel.NgModelController">NgModelController</a>,
which is created and exposed by this directive.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngChange">ngChange</a></td>
<td><p>Evaluate the given expression when the user changes the input.
The expression is evaluated immediately, unlike the JavaScript onchange event
which only triggers at the end of a change (usually, when the user leaves the
form element or presses the return key).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngList">ngList</a></td>
<td><p>Text input that converts between a delimited string and an array of strings. The default
delimiter is a comma followed by a space - equivalent to <code>ng-list=", "</code>. You can specify a custom
delimiter as the value of the <code>ngList</code> attribute - for example, <code>ng-list=" | "</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngValue">ngValue</a></td>
<td><p>Binds the given expression to the value of <code>option</code> or <code>input[radio]</code>, so
that when the element is selected, the <code>ngModel</code> of that element is set to
the bound value.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngModelOptions">ngModelOptions</a></td>
<td><p>Allows tuning how model updates are done. Using <code>ngModelOptions</code> you can specify a custom list of
events that will trigger a model update and/or a debouncing delay so that the actual update only
takes place when a timer expires; this timer will be reset after another change takes place.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngBind">ngBind</a></td>
<td><p>The <code>ngBind</code> attribute tells Angular to replace the text content of the specified HTML element
with the value of a given expression, and to update the text content when the value of that
expression changes.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngBindTemplate">ngBindTemplate</a></td>
<td><p>The <code>ngBindTemplate</code> directive specifies that the element
text content should be replaced with the interpolation of the template
in the <code>ngBindTemplate</code> attribute.
Unlike <code>ngBind</code>, the <code>ngBindTemplate</code> can contain multiple <code>{{</code> <code>}}</code>
expressions. This directive is needed since some HTML elements
(such as TITLE and OPTION) cannot contain SPAN elements.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngBindHtml">ngBindHtml</a></td>
<td><p>Creates a binding that will innerHTML the result of evaluating the <code>expression</code> into the current
element in a secure way. By default, the innerHTML-ed content will be sanitized using the <a href="api/ngSanitize/service/$sanitize">$sanitize</a> service. To utilize this functionality, ensure that <code>$sanitize</code>
is available, for example, by including <a href="api/ngSanitize"><code>ngSanitize</code></a> in your module's dependencies (not in
core Angular). In order to use <a href="api/ngSanitize"><code>ngSanitize</code></a> in your module's dependencies, you need to
include "angular-sanitize.js" in your application.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngClass">ngClass</a></td>
<td><p>The <code>ngClass</code> directive allows you to dynamically set CSS classes on an HTML element by databinding
an expression that represents all classes to be added.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngClassOdd">ngClassOdd</a></td>
<td><p>The <code>ngClassOdd</code> and <code>ngClassEven</code> directives work exactly as
<a href="api/ng/directive/ngClass">ngClass</a>, except they work in
conjunction with <code>ngRepeat</code> and take effect only on odd (even) rows.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngClassEven">ngClassEven</a></td>
<td><p>The <code>ngClassOdd</code> and <code>ngClassEven</code> directives work exactly as
<a href="api/ng/directive/ngClass">ngClass</a>, except they work in
conjunction with <code>ngRepeat</code> and take effect only on odd (even) rows.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngCloak">ngCloak</a></td>
<td><p>The <code>ngCloak</code> directive is used to prevent the Angular html template from being briefly
displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
directive to avoid the undesirable flicker effect caused by the html template display.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngController">ngController</a></td>
<td><p>The <code>ngController</code> directive attaches a controller class to the view. This is a key aspect of how angular
supports the principles behind the Model-View-Controller design pattern.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngCsp">ngCsp</a></td>
<td><p>Enables <a href="https://developer.mozilla.org/en/Security/CSP">CSP (Content Security Policy)</a> support.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngClick">ngClick</a></td>
<td><p>The ngClick directive allows you to specify custom behavior when
an element is clicked.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngDblclick">ngDblclick</a></td>
<td><p>The <code>ngDblclick</code> directive allows you to specify custom behavior on a dblclick event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMousedown">ngMousedown</a></td>
<td><p>The ngMousedown directive allows you to specify custom behavior on mousedown event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMouseup">ngMouseup</a></td>
<td><p>Specify custom behavior on mouseup event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMouseover">ngMouseover</a></td>
<td><p>Specify custom behavior on mouseover event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMouseenter">ngMouseenter</a></td>
<td><p>Specify custom behavior on mouseenter event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMouseleave">ngMouseleave</a></td>
<td><p>Specify custom behavior on mouseleave event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngMousemove">ngMousemove</a></td>
<td><p>Specify custom behavior on mousemove event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngKeydown">ngKeydown</a></td>
<td><p>Specify custom behavior on keydown event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngKeyup">ngKeyup</a></td>
<td><p>Specify custom behavior on keyup event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngKeypress">ngKeypress</a></td>
<td><p>Specify custom behavior on keypress event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngSubmit">ngSubmit</a></td>
<td><p>Enables binding angular expressions to onsubmit events.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngFocus">ngFocus</a></td>
<td><p>Specify custom behavior on focus event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngBlur">ngBlur</a></td>
<td><p>Specify custom behavior on blur event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngCopy">ngCopy</a></td>
<td><p>Specify custom behavior on copy event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngCut">ngCut</a></td>
<td><p>Specify custom behavior on cut event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngPaste">ngPaste</a></td>
<td><p>Specify custom behavior on paste event.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngIf">ngIf</a></td>
<td><p>The <code>ngIf</code> directive removes or recreates a portion of the DOM tree based on an
{expression}. If the expression assigned to <code>ngIf</code> evaluates to a false
value then the element is removed from the DOM, otherwise a clone of the
element is reinserted into the DOM.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngInclude">ngInclude</a></td>
<td><p>Fetches, compiles and includes an external HTML fragment.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngInit">ngInit</a></td>
<td><p>The <code>ngInit</code> directive allows you to evaluate an expression in the
current scope.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngNonBindable">ngNonBindable</a></td>
<td><p>The <code>ngNonBindable</code> directive tells Angular not to compile or bind the contents of the current
DOM element. This is useful if the element contains what appears to be Angular directives and
bindings but which should be ignored by Angular. This could be the case if you have a site that
displays snippets of code, for instance.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngPluralize">ngPluralize</a></td>
<td><p><code>ngPluralize</code> is a directive that displays messages according to en-US localization rules.
These rules are bundled with angular.js, but can be overridden
(see <a href="guide/i18n">Angular i18n</a> dev guide). You configure ngPluralize directive
by specifying the mappings between
<a href="http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html">plural categories</a>
and the strings to be displayed.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngRepeat">ngRepeat</a></td>
<td><p>The <code>ngRepeat</code> directive instantiates a template once per item from a collection. Each template
instance gets its own scope, where the given loop variable is set to the current collection item,
and <code>$index</code> is set to the item index or key.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngShow">ngShow</a></td>
<td><p>The <code>ngShow</code> directive shows or hides the given HTML element based on the expression
provided to the <code>ngShow</code> attribute. The element is shown or hidden by removing or adding
the <code>.ng-hide</code> CSS class onto the element. The <code>.ng-hide</code> CSS class is predefined
in AngularJS and sets the display style to none (using an !important flag).
For CSP mode please add <code>angular-csp.css</code> to your html file (see <a href="api/ng/directive/ngCsp">ngCsp</a>).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngHide">ngHide</a></td>
<td><p>The <code>ngHide</code> directive shows or hides the given HTML element based on the expression
provided to the <code>ngHide</code> attribute. The element is shown or hidden by removing or adding
the <code>ng-hide</code> CSS class onto the element. The <code>.ng-hide</code> CSS class is predefined
in AngularJS and sets the display style to none (using an !important flag).
For CSP mode please add <code>angular-csp.css</code> to your html file (see <a href="api/ng/directive/ngCsp">ngCsp</a>).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngStyle">ngStyle</a></td>
<td><p>The <code>ngStyle</code> directive allows you to set CSS style on an HTML element conditionally.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngSwitch">ngSwitch</a></td>
<td><p>The <code>ngSwitch</code> directive is used to conditionally swap DOM structure on your template based on a scope expression.
Elements within <code>ngSwitch</code> but without <code>ngSwitchWhen</code> or <code>ngSwitchDefault</code> directives will be preserved at the location
as specified in the template.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/ngTransclude">ngTransclude</a></td>
<td><p>Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/script">script</a></td>
<td><p>Load the content of a <code><script></code> element into <a href="api/ng/service/$templateCache"><code>$templateCache</code></a>, so that the
template can be used by <a href="api/ng/directive/ngInclude"><code>ngInclude</code></a>,
<a href="api/ngRoute/directive/ngView"><code>ngView</code></a>, or <a href="guide/directive">directives</a>. The type of the
<code><script></code> element must be specified as <code>text/ng-template</code>, and a cache name for the template must be
assigned through the element's <code>id</code>, which can then be used as a directive's <code>templateUrl</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/directive/select">select</a></td>
<td><p>HTML <code>SELECT</code> element with angular data-binding.</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="object">Object</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/object/angular.version">angular.version</a></td>
<td><p>An object that contains information about the current AngularJS version. This object has the
following properties:</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="type">Type</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/type/angular.Module">angular.Module</a></td>
<td><p>Interface for configuring angular <a href="api/ng/function/angular.module">modules</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/type/$cacheFactory.Cache">$cacheFactory.Cache</a></td>
<td><p>A cache object used to store and retrieve data, primarily used by
<a href="api/ng/service/$http">$http</a> and the <a href="api/ng/directive/script">script</a> directive to cache
templates and other data.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/type/$compile.directive.Attributes">$compile.directive.Attributes</a></td>
<td><p>A shared object between directive compile / linking functions which contains normalized DOM
element attributes. The values reflect current binding state <code>{{ }}</code>. The normalization is
needed since all of these are treated as equivalent in Angular:</p>
</td>
</tr>
<tr>
<td><a href="api/ng/type/form.FormController">form.FormController</a></td>
<td><p><code>FormController</code> keeps track of all its controls and nested forms as well as the state of them,
such as being valid/invalid or dirty/pristine.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/type/ngModel.NgModelController">ngModel.NgModelController</a></td>
<td><p><code>NgModelController</code> provides API for the <code>ng-model</code> directive. The controller contains
services for data-binding, validation, CSS updates, and value formatting and parsing. It
purposefully does not contain any logic which deals with DOM rendering or listening to
DOM events. Such DOM related logic should be provided by other directives which make use of
<code>NgModelController</code> for data-binding.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/type/$rootScope.Scope">$rootScope.Scope</a></td>
<td><p>A root scope can be retrieved using the <a href="api/ng/service/$rootScope">$rootScope</a> key from the
<a href="api/auto/service/$injector">$injector</a>. Child scopes are created using the
<a href="api/ng/type/$rootScope.Scope#$new">$new()</a> method. (Most scopes are created automatically when
compiled HTML template is executed.)</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="provider">Provider</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/provider/$anchorScrollProvider">$anchorScrollProvider</a></td>
<td><p>Use <code>$anchorScrollProvider</code> to disable automatic scrolling whenever
<a href="api/ng/service/$location#hash">$location.hash()</a> changes.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$animateProvider">$animateProvider</a></td>
<td><p>Default implementation of $animate that doesn't perform any animations, instead just
synchronously performs DOM
updates and calls done() callbacks.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$compileProvider">$compileProvider</a></td>
<td></td>
</tr>
<tr>
<td><a href="api/ng/provider/$controllerProvider">$controllerProvider</a></td>
<td><p>The <a href="api/ng/service/$controller">$controller service</a> is used by Angular to create new
controllers.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$filterProvider">$filterProvider</a></td>
<td><p>Filters are just functions which transform input to an output. However filters need to be
Dependency Injected. To achieve this a filter definition consists of a factory function which is
annotated with dependencies and is responsible for creating a filter function.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$httpProvider">$httpProvider</a></td>
<td><p>Use <code>$httpProvider</code> to change the default behavior of the <a href="api/ng/service/$http">$http</a> service.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$interpolateProvider">$interpolateProvider</a></td>
<td><p>Used for configuring the interpolation markup. Defaults to <code>{{</code> and <code>}}</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$locationProvider">$locationProvider</a></td>
<td><p>Use the <code>$locationProvider</code> to configure how the application deep linking paths are stored.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$logProvider">$logProvider</a></td>
<td><p>Use the <code>$logProvider</code> to configure how the application logs messages</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$parseProvider">$parseProvider</a></td>
<td><p><code>$parseProvider</code> can be used for configuring the default behavior of the <a href="api/ng/service/$parse">$parse</a>
service.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$rootScopeProvider">$rootScopeProvider</a></td>
<td><p>Provider for the $rootScope service.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$sceDelegateProvider">$sceDelegateProvider</a></td>
<td><p>The <code>$sceDelegateProvider</code> provider allows developers to configure the <a href="api/ng/service/$sceDelegate">$sceDelegate</a> service. This allows one to get/set the whitelists and blacklists used to ensure
that the URLs used for sourcing Angular templates are safe. Refer <a href="api/ng/provider/$sceDelegateProvider#resourceUrlWhitelist">$sceDelegateProvider.resourceUrlWhitelist</a> and
<a href="api/ng/provider/$sceDelegateProvider#resourceUrlBlacklist">$sceDelegateProvider.resourceUrlBlacklist</a></p>
</td>
</tr>
<tr>
<td><a href="api/ng/provider/$sceProvider">$sceProvider</a></td>
<td><p>The $sceProvider provider allows developers to configure the <a href="api/ng/service/$sce">$sce</a> service.</p>
<ul>
<li>enable/disable Strict Contextual Escaping (SCE) in a module</li>
<li>override the default implementation with a custom delegate</li>
</ul>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="service">Service</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/service/$anchorScroll">$anchorScroll</a></td>
<td><p>When called, it checks the current value of <a href="api/ng/service/$location#hash">$location.hash()</a> and
scrolls to the related element, according to the rules specified in the
<a href="http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document">Html5 spec</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$animate">$animate</a></td>
<td><p>The $animate service provides rudimentary DOM manipulation functions to
insert, remove and move elements within the DOM, as well as adding and removing classes.
This service is the core service used by the ngAnimate $animator service which provides
high-level animation hooks for CSS and JavaScript.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$cacheFactory">$cacheFactory</a></td>
<td><p>Factory that constructs <a href="api/ng/type/$cacheFactory.Cache">Cache</a> objects and gives access to
them.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$templateCache">$templateCache</a></td>
<td><p>The first time a template is used, it is loaded in the template cache for quick retrieval. You
can load templates directly into the cache in a <code>script</code> tag, or by consuming the
<code>$templateCache</code> service directly.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$compile">$compile</a></td>
<td><p>Compiles an HTML string or DOM into a template and produces a template function, which
can then be used to link <a href="api/ng/type/$rootScope.Scope"><code>scope</code></a> and the template together.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$controller">$controller</a></td>
<td><p><code>$controller</code> service is responsible for instantiating controllers.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$document">$document</a></td>
<td><p>A <a href="api/ng/function/angular.element">jQuery or jqLite</a> wrapper for the browser's <code>window.document</code> object.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$exceptionHandler">$exceptionHandler</a></td>
<td><p>Any uncaught exception in angular expressions is delegated to this service.
The default implementation simply delegates to <code>$log.error</code> which logs it into
the browser console.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$filter">$filter</a></td>
<td><p>Filters are used for formatting data displayed to the user.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$http">$http</a></td>
<td><p>The <code>$http</code> service is a core Angular service that facilitates communication with the remote
HTTP servers via the browser's <a href="https://developer.mozilla.org/en/xmlhttprequest">XMLHttpRequest</a>
object or via <a href="http://en.wikipedia.org/wiki/JSONP">JSONP</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$httpBackend">$httpBackend</a></td>
<td><p>HTTP backend used by the <a href="api/ng/service/$http">service</a> that delegates to
XMLHttpRequest object or JSONP and deals with browser incompatibilities.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$interpolate">$interpolate</a></td>
<td><p>Compiles a string with markup into an interpolation function. This service is used by the
HTML <a href="api/ng/service/$compile">$compile</a> service for data binding. See
<a href="api/ng/provider/$interpolateProvider">$interpolateProvider</a> for configuring the
interpolation markup.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$interval">$interval</a></td>
<td><p>Angular's wrapper for <code>window.setInterval</code>. The <code>fn</code> function is executed every <code>delay</code>
milliseconds.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$locale">$locale</a></td>
<td><p>$locale service provides localization rules for various Angular components. As of right now the
only public api is:</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$location">$location</a></td>
<td><p>The $location service parses the URL in the browser address bar (based on the
<a href="https://developer.mozilla.org/en/window.location">window.location</a>) and makes the URL
available to your application. Changes to the URL in the address bar are reflected into
$location service and changes to $location are reflected into the browser address bar.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$log">$log</a></td>
<td><p>Simple service for logging. Default implementation safely writes the message
into the browser's console (if present).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$parse">$parse</a></td>
<td><p>Converts Angular <a href="guide/expression">expression</a> into a function.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$q">$q</a></td>
<td><p>A promise/deferred implementation inspired by <a href="https://github.com/kriskowal/q">Kris Kowal's Q</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$rootElement">$rootElement</a></td>
<td><p>The root element of Angular application. This is either the element where <a href="api/ng/directive/ngApp">ngApp</a> was declared or the element passed into
<a href="api/ng/function/angular.bootstrap"><code>angular.bootstrap</code></a>. The element represent the root element of application. It is also the
location where the applications <a href="api/auto/service/$injector">$injector</a> service gets
published, it can be retrieved using <code>$rootElement.injector()</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$rootScope">$rootScope</a></td>
<td><p>Every application has a single root <a href="api/ng/type/$rootScope.Scope">scope</a>.
All other scopes are descendant scopes of the root scope. Scopes provide separation
between the model and the view, via a mechanism for watching the model for changes.
They also provide an event emission/broadcast and subscription facility. See the
<a href="guide/scope">developer guide on scopes</a>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$sceDelegate">$sceDelegate</a></td>
<td><p><code>$sceDelegate</code> is a service that is used by the <code>$sce</code> service to provide <a href="api/ng/service/$sce">Strict
Contextual Escaping (SCE)</a> services to AngularJS.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$sce">$sce</a></td>
<td><p><code>$sce</code> is a service that provides Strict Contextual Escaping services to AngularJS.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$templateRequest">$templateRequest</a></td>
<td><p>The <code>$templateRequest</code> service downloads the provided template using <code>$http</code> and, upon success,
stores the contents inside of <code>$templateCache</code>. If the HTTP request fails or the response data
of the HTTP request is empty then a <code>$compile</code> error will be thrown (the exception can be thwarted
by setting the 2nd parameter of the function to true).</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$timeout">$timeout</a></td>
<td><p>Angular's wrapper for <code>window.setTimeout</code>. The <code>fn</code> function is wrapped into a try/catch
block and delegates any exceptions to
<a href="api/ng/service/$exceptionHandler">$exceptionHandler</a> service.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/service/$window">$window</a></td>
<td><p>A reference to the browser's <code>window</code> object. While <code>window</code>
is globally available in JavaScript, it causes testability problems, because
it is a global variable. In angular we always refer to it through the
<code>$window</code> service, so it may be overridden, removed or mocked for testing.</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="input">Input</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/input/input[text]">input[text]</a></td>
<td><p>Standard HTML text input with angular data binding, inherited by most of the <code>input</code> elements.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[date]">input[date]</a></td>
<td><p>Input with date validation and transformation. In browsers that do not yet support
the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
date format (yyyy-MM-dd), for example: <code>2009-01-06</code>. Since many
modern browsers do not yet support this input type, it is important to provide cues to users on the
expected input format via a placeholder or label.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[dateTimeLocal]">input[dateTimeLocal]</a></td>
<td><p>Input with datetime validation and transformation. In browsers that do not yet support
the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
local datetime format (yyyy-MM-ddTHH:mm:ss), for example: <code>2010-12-28T14:57:00</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[time]">input[time]</a></td>
<td><p>Input with time validation and transformation. In browsers that do not yet support
the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
local time format (HH:mm:ss), for example: <code>14:57:00</code>. Model must be a Date object. This binding will always output a
Date object to the model of January 1, 1970, or local date <code>new Date(1970, 0, 1, HH, mm, ss)</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[week]">input[week]</a></td>
<td><p>Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
week format (yyyy-W##), for example: <code>2013-W02</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[month]">input[month]</a></td>
<td><p>Input with month validation and transformation. In browsers that do not yet support
the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
month format (yyyy-MM), for example: <code>2009-01</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[number]">input[number]</a></td>
<td><p>Text input with number validation and transformation. Sets the <code>number</code> validation
error if not a valid number.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[url]">input[url]</a></td>
<td><p>Text input with URL validation. Sets the <code>url</code> validation error key if the content is not a
valid URL.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[email]">input[email]</a></td>
<td><p>Text input with email validation. Sets the <code>email</code> validation error key if not a valid email
address.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[radio]">input[radio]</a></td>
<td><p>HTML radio button.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/input/input[checkbox]">input[checkbox]</a></td>
<td><p>HTML checkbox.</p>
</td>
</tr>
</table>
</div>
<div>
<h3 class="component-heading" id="filter">Filter</h3>
<table class="definition-table">
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr>
<td><a href="api/ng/filter/filter">filter</a></td>
<td><p>Selects a subset of items from <code>array</code> and returns it as a new array.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/currency">currency</a></td>
<td><p>Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
symbol for current locale is used.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/number">number</a></td>
<td><p>Formats a number as text.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/date">date</a></td>
<td><p>Formats <code>date</code> to a string based on the requested <code>format</code>.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/json">json</a></td>
<td><p>Allows you to convert a JavaScript object into JSON string.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/lowercase">lowercase</a></td>
<td><p>Converts string to lowercase.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/uppercase">uppercase</a></td>
<td><p>Converts string to uppercase.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/limitTo">limitTo</a></td>
<td><p>Creates a new array or string containing only a specified number of elements. The elements
are taken from either the beginning or the end of the source array, string or number, as specified by
the value and sign (positive or negative) of <code>limit</code>. If a number is used as input, it is
converted to a string.</p>
</td>
</tr>
<tr>
<td><a href="api/ng/filter/orderBy">orderBy</a></td>
<td><p>Orders a specified <code>array</code> by the <code>expression</code> predicate. It is ordered alphabetically
for strings and numerically for numbers. Note: if you notice numbers are not being sorted
correctly, make sure they are actually being saved as numbers and not strings.</p>
</td>
</tr>
</table>
</div>
</div>
| jeros-mz/angular.mobile.prototype | scripts/angular/docs/partials/api/ng.html | HTML | mit | 49,835 |
/*
* @author Valentin Simonov / http://va.lent.in/
*/
using TouchScript.Gestures;
using UnityEditor;
using UnityEngine;
namespace TouchScript.Editor.Gestures
{
[CustomEditor(typeof(PressGesture), true)]
internal sealed class PressGestureEditor : GestureEditor
{
private static readonly GUIContent IGNORE_CHILDREN = new GUIContent("Ignore Children", "If selected this gesture ignores touch points from children.");
private SerializedProperty ignoreChildren;
protected override void OnEnable()
{
base.OnEnable();
ignoreChildren = serializedObject.FindProperty("ignoreChildren");
}
public override void OnInspectorGUI()
{
serializedObject.UpdateIfDirtyOrScript();
EditorGUILayout.PropertyField(ignoreChildren, IGNORE_CHILDREN);
serializedObject.ApplyModifiedProperties();
base.OnInspectorGUI();
}
}
}
| zhutaorun/TouchScript | TouchScript.Editor/Gestures/PressGestureEditor.cs | C# | mit | 960 |
# Lighting models
## Exercise
As a warm up, we will start with the very simplest lighting model, which is called "flat shading". In flat shading, the light reflected from any surface to the detector is assumed to be constant. That is, there is some parameter called `kA` which just determines the color of each fragment.
<a href="/open/light-1" target="_blank">The files `vertex.glsl` and `fragment.glsl` have been provided</a> as well as the appropriate uniform and attribute variables for the camera. Apply the model, view and projection transformation matrices as in the `GEOM 1` exercise.
***
## Aside on the nature of rendering
Physically, images are formed by the interaction of lightwaves with some detector (like a camera CCD, eyeball retina, etc.). These lightwaves are formed by the interaction of the electromagnetic field with different materials. These interactions include reflection, transmission, absorption and emission of electromagnetic radiation. In human terms, visible light waves are high frequency (with wavelengths on the order of nanometers), and travel at incredible speeds, so to us humans light's wave-like nature is imperceptible. As a result, physical images can be well approximated using geometrical objects, which replaces light waves with "rays".
The physical interpretation of a ray in geometric optics is that it is a line perpendicular to the wave front representing the amount of energy in the wave at some particular frequency, ignoring polarization. Natural light is composed of infinitely many different frequencies, however human vision can only distinguish between three different classes of frequencies: red, green and blue (though rarely there are some mutants who can see up to 4 or 5 different types of colors). As a result, if we are rendering images we only need to track the amount of energy in the red, green and blue color bands for each ray when we are ray tracing the image.
In high end computer graphics, ray tracing is widely used to generate physically realistic images. But for interactive applications like games, even the ray tracing approximation of light is still too slow. Instead, real time applications must usually make do with even more limited models of light transport and interactions. In this section and its sequels, we will discuss a few classical models of light transport and you will get to try implementing them as an exercise. These models make different assumptions about the types of materials they represent, which lead to different looking surfaces. Since they are physically motivated, they are generally consistent with what would be expected from a realistic theory of light. Moreover, despite being over-simplified, they are quite capable of producing compelling images and often serve as a useful starting point for developing newer or customized models of light.
| 1wheel/shader-school | exercises/light-1/README.md | Markdown | mit | 2,864 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Example to override functions from API_Controller
* TODO: link with real data
*/
class Users extends API_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('user_model', 'users');
}
// [GET] /users
protected function get_items()
{
$params = $this->input->get();
$data = $this->users->get_many_by($params);
$this->to_response($data);
}
// [GET] /users/{id}
protected function get_item($id)
{
$data = $this->users->get($id);
$this->to_response($data);
}
}
| jiji262/codeigniter_boilerplate | application/modules/api_v1/controllers/Users.php | PHP | mit | 598 |
/**
* @fileoverview Tests for constructor-super rule.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/constructor-super");
var RuleTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester();
ruleTester.run("constructor-super", rule, {
valid: [
// non derived classes.
{ code: "class A { }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { constructor() { } }", parserOptions: { ecmaVersion: 6 } },
// inherit from non constructors.
// those are valid if we don't define the constructor.
{ code: "class A extends null { }", parserOptions: { ecmaVersion: 6 } },
// derived classes.
{ code: "class A extends B { }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { if (true) { super(); } else { super(); } } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends (class B {}) { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends (B = C) { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends (B || C) { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends (a ? B : C) { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends (B, C) { constructor() { super(); } }", parserOptions: { ecmaVersion: 6 } },
// nested.
{ code: "class A { constructor() { class B extends C { constructor() { super(); } } } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { super(); class C extends D { constructor() { super(); } } } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { super(); class C { constructor() { } } } }", parserOptions: { ecmaVersion: 6 } },
// ignores out of constructors.
{ code: "class A { b() { super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "function a() { super(); }", parserOptions: { ecmaVersion: 6 } },
// multi code path.
{ code: "class A extends B { constructor() { a ? super() : super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { if (a) super(); else super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { switch (a) { case 0: super(); break; default: super(); } } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { try {} finally { super(); } } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends B { constructor() { if (a) throw Error(); super(); } }", parserOptions: { ecmaVersion: 6 } },
// returning value is a substitute of 'super()'.
{ code: "class A extends B { constructor() { if (true) return a; super(); } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A extends null { constructor() { return a; } }", parserOptions: { ecmaVersion: 6 } },
{ code: "class A { constructor() { return a; } }", parserOptions: { ecmaVersion: 6 } },
// https://github.com/eslint/eslint/issues/5261
{ code: "class A extends B { constructor(a) { super(); for (const b of a) { this.a(); } } }", parserOptions: { ecmaVersion: 6 } },
// https://github.com/eslint/eslint/issues/5319
{ code: "class Foo extends Object { constructor(method) { super(); this.method = method || function() {}; } }", parserOptions: { ecmaVersion: 6 } },
// https://github.com/eslint/eslint/issues/5394
{
code: [
"class A extends Object {",
" constructor() {",
" super();",
" for (let i = 0; i < 0; i++);",
" }",
"}"
].join("\n"),
parserOptions: {ecmaVersion: 6}
},
// https://github.com/eslint/eslint/issues/5894
{ code: "class A { constructor() { return; super(); } }", parserOptions: {ecmaVersion: 6} }
],
invalid: [
// non derived classes.
{
code: "class A { constructor() { super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected 'super()'.", type: "CallExpression"}]
},
// inherit from non constructors.
{
code: "class A extends null { constructor() { super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected 'super()' because 'super' is not a constructor.", type: "CallExpression"}]
},
{
code: "class A extends null { constructor() { } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
{
code: "class A extends 100 { constructor() { super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected 'super()' because 'super' is not a constructor.", type: "CallExpression"}]
},
{
code: "class A extends 'test' { constructor() { super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected 'super()' because 'super' is not a constructor.", type: "CallExpression"}]
},
// derived classes.
{
code: "class A extends B { constructor() { } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { for (var a of b) super.foo(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
// nested execution scope.
{
code: "class A extends B { constructor() { function c() { super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { var c = function() { super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { var c = () => super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { class C extends D { constructor() { super(); } } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition", column: 21}]
},
{
code: "class A extends B { constructor() { var C = class extends D { constructor() { super(); } } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition", column: 21}]
},
{
code: "class A extends B { constructor() { super(); class C extends D { constructor() { } } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition", column: 66}]
},
{
code: "class A extends B { constructor() { super(); var C = class extends D { constructor() { } } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition", column: 72}]
},
// lacked in some code path.
{
code: "class A extends B { constructor() { if (a) super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { if (a); else super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { a && super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { switch (a) { case 0: super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { switch (a) { case 0: break; default: super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { try { super(); } catch (err) {} } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { try { a; } catch (err) { super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
{
code: "class A extends B { constructor() { if (a) return; super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"}]
},
// duplicate.
{
code: "class A extends B { constructor() { super(); super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected duplicate 'super()'.", type: "CallExpression", column: 46}]
},
{
code: "class A extends B { constructor() { super() || super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected duplicate 'super()'.", type: "CallExpression", column: 48}]
},
{
code: "class A extends B { constructor() { if (a) super(); super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected duplicate 'super()'.", type: "CallExpression", column: 53}]
},
{
code: "class A extends B { constructor() { switch (a) { case 0: super(); default: super(); } } }",
parserOptions: { ecmaVersion: 6 },
errors: [{ message: "Unexpected duplicate 'super()'.", type: "CallExpression", column: 76}]
},
{
code: "class A extends B { constructor(a) { while (a) super(); } }",
parserOptions: { ecmaVersion: 6 },
errors: [
{ message: "Lacked a call of 'super()' in some code paths.", type: "MethodDefinition"},
{ message: "Unexpected duplicate 'super()'.", type: "CallExpression", column: 48}
]
},
// ignores `super()` on unreachable paths.
{
code: "class A extends B { constructor() { return; super(); } }",
parserOptions: {ecmaVersion: 6},
errors: [{ message: "Expected to call 'super()'.", type: "MethodDefinition"}]
}
]
});
| lemonmade/eslint | tests/lib/rules/constructor-super.js | JavaScript | mit | 12,258 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
function plural(n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'es-CO',
[
['a. m.', 'p. m.'],
,
],
,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],
['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA']
],
[
['d', 'l', 'm', 'm', 'j', 'v', 's'], ['dom.', 'lun.', 'mar.', 'mié.', 'jue.', 'vie.', 'sáb.'],
['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
['DO', 'LU', 'MA', 'MI', 'JU', 'VI', 'SA']
],
[
['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'
],
[
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre',
'octubre', 'noviembre', 'diciembre'
]
],
[
['E', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'ene.', 'feb.', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sept.', 'oct.', 'nov.',
'dic.'
],
[
'enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre',
'octubre', 'noviembre', 'diciembre'
]
],
[['a. C.', 'd. C.'], , ['antes de Cristo', 'después de Cristo']], 0, [6, 0],
['d/MM/yy', 'd/MM/y', 'd \'de\' MMMM \'de\' y', 'EEEE, d \'de\' MMMM \'de\' y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
[
'{1}, {0}',
,
,
],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '¤ #,##0.00', '#E0'], '$', 'peso colombiano', {
'AUD': [, '$'],
'BRL': [, 'R$'],
'CAD': [, '$'],
'CNY': [, '¥'],
'COP': ['$'],
'ESP': ['₧'],
'EUR': [, '€'],
'FKP': [, 'FK£'],
'GBP': [, '£'],
'HKD': [, '$'],
'ILS': [, '₪'],
'INR': [, '₹'],
'JPY': [, '¥'],
'KRW': [, '₩'],
'MXN': [, '$'],
'NZD': [, '$'],
'RON': [, 'L'],
'SSP': [, 'SD£'],
'SYP': [, 'S£'],
'TWD': [, 'NT$'],
'USD': ['US$', '$'],
'VEF': [, 'BsF'],
'VND': [, '₫'],
'XAF': [],
'XCD': [, '$'],
'XOF': []
},
plural
];
| rkirov/angular | packages/common/locales/es-CO.ts | TypeScript | mit | 2,566 |
<?php
/*
* This file is part of the Elcodi package.
*
* Copyright (c) 2014-2016 Elcodi Networks S.L.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Feel free to edit as you please, and have fun.
*
* @author Marc Morera <[email protected]>
* @author Aldo Chiecchia <[email protected]>
* @author Elcodi Team <[email protected]>
*/
namespace Elcodi\Component\Product\Tests\UnitTest\StockUpdater;
use PHPUnit_Framework_TestCase;
use Prophecy\Argument;
use Elcodi\Component\Product\ElcodiProductStock;
use Elcodi\Component\Product\StockUpdater\PurchasableStockUpdater;
use Elcodi\Component\Product\StockUpdater\VariantStockUpdater;
/**
* Class VariantStockUpdaterTest.
*/
class VariantStockUpdaterTest extends PHPUnit_Framework_TestCase
{
/**
* Test update stock with a no variant.
*/
public function testUpdateStockNoProduct()
{
$objectManager = $this->prophesize('Doctrine\Common\Persistence\ObjectManager');
$variantStockUpdater = new VariantStockUpdater($objectManager->reveal());
$this->assertFalse(
$variantStockUpdater->updateStock(
$this
->prophesize('Elcodi\Component\Product\Entity\Interfaces\PurchasableInterface')
->reveal(),
0,
false
)
);
$this->assertFalse(
$variantStockUpdater->updateStock(
$this
->prophesize('Elcodi\Component\Product\Entity\Interfaces\VariantInterface')
->reveal(),
0,
false
)
);
}
/**
* Test update stock.
*
* @dataProvider dataUpdateStock
*/
public function testUpdateStock(
$actualStock,
$stockToDecrease,
$newStock,
$flush,
$result
) {
$variant = $this->prophesize('Elcodi\Component\Product\Entity\Interfaces\VariantInterface');
$variant
->getStock()
->willReturn($actualStock);
if (!is_null($newStock)) {
$variant->setStock($newStock)->shouldBeCalled();
}
$variant = $variant->reveal();
$objectManager = $this->prophesize('Doctrine\Common\Persistence\ObjectManager');
if ($flush) {
$objectManager->flush(Argument::any());
}
$variantStockUpdater = new VariantStockUpdater($objectManager->reveal());
$this->assertEquals(
$result,
$variantStockUpdater->updateStock(
$variant,
$stockToDecrease
)
);
$purchasableStockUpdater = new PurchasableStockUpdater();
$purchasableStockUpdater->addPurchasableStockUpdater($variantStockUpdater);
$this->assertEquals(
$result,
$purchasableStockUpdater->updateStock(
$variant,
$stockToDecrease
)
);
}
/**
* Data for testUpdateStock.
*/
public function dataUpdateStock()
{
$infStock = ElcodiProductStock::INFINITE_STOCK;
return [
'All ok' => [3, 1, 2, true, 1],
'infinite stock' => [$infStock, 1, null, false, false],
'We decrease more than existing elements' => [2, 3, 0, true, 2],
];
}
}
| MicHaeLann/new_best365 | vendor/elcodi/elcodi/src/Elcodi/Component/Product/Tests/UnitTest/StockUpdater/VariantStockUpdaterTest.php | PHP | mit | 3,428 |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.CognitiveServices.Language.LUIS.Authoring.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Response when adding a labeled example utterance.
/// </summary>
public partial class LabelExampleResponse
{
/// <summary>
/// Initializes a new instance of the LabelExampleResponse class.
/// </summary>
public LabelExampleResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the LabelExampleResponse class.
/// </summary>
/// <param name="utteranceText">The example utterance.</param>
/// <param name="exampleId">The newly created sample ID.</param>
public LabelExampleResponse(string utteranceText = default(string), int? exampleId = default(int?))
{
UtteranceText = utteranceText;
ExampleId = exampleId;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the example utterance.
/// </summary>
[JsonProperty(PropertyName = "UtteranceText")]
public string UtteranceText { get; set; }
/// <summary>
/// Gets or sets the newly created sample ID.
/// </summary>
[JsonProperty(PropertyName = "ExampleId")]
public int? ExampleId { get; set; }
}
}
| jamestao/azure-sdk-for-net | src/SDKs/CognitiveServices/dataPlane/Language/LUIS/Authoring/Generated/Models/LabelExampleResponse.cs | C# | mit | 1,902 |
class PeopleHaveLastNames < ActiveRecord::Migration
def self.up
add_column "people", "hobbies", :string
end
def self.down
remove_column "people", "hobbies"
end
end
| brian-thrillist/hacktiverecord | test/migrations/to_copy_with_name_collision/1_people_have_hobbies.rb | Ruby | mit | 181 |
//@program
var NOW = 1
, READY = false
, READY_BUFFER = []
, PRESENCE_SUFFIX = '-pnpres'
, DEF_WINDOWING = 10 // MILLISECONDS.
, DEF_TIMEOUT = 10000 // MILLISECONDS.
, DEF_SUB_TIMEOUT = 310 // SECONDS.
, DEF_KEEPALIVE = 60 // SECONDS (FOR TIMESYNC).
, SECOND = 1000 // A THOUSAND MILLISECONDS.
, URLBIT = '/'
, PARAMSBIT = '&'
, PRESENCE_HB_THRESHOLD = 5
, PRESENCE_HB_DEFAULT = 30
, SDK_VER = VERSION
, REPL = /{([\w\-]+)}/g;
/**
* UTILITIES
*/
function unique() { return'x'+ ++NOW+''+(+new Date) }
function rnow() { return+new Date }
/**
* NEXTORIGIN
* ==========
* var next_origin = nextorigin();
*/
var nextorigin = (function() {
var max = 20
, ori = Math.floor(Math.random() * max);
return function( origin, failover ) {
return origin.indexOf('pubsub.') > 0
&& origin.replace(
'pubsub', 'ps' + (
failover ? uuid().split('-')[0] :
(++ori < max? ori : ori=1)
) ) || origin;
}
})();
/**
* Build Url
* =======
*
*/
function build_url( url_components, url_params ) {
var url = url_components.join(URLBIT)
, params = [];
if (!url_params) return url;
each( url_params, function( key, value ) {
var value_str = (typeof value == 'object')?JSON['stringify'](value):value;
(typeof value != 'undefined' &&
value != null && encode(value_str).length > 0
) && params.push(key + "=" + encode(value_str));
} );
url += "?" + params.join(PARAMSBIT);
return url;
}
/**
* UPDATER
* =======
* var timestamp = unique();
*/
function updater( fun, rate ) {
var timeout
, last = 0
, runnit = function() {
if (last + rate > rnow()) {
clearTimeout(timeout);
timeout = setTimeout( runnit, rate );
}
else {
last = rnow();
fun();
}
};
return runnit;
}
/**
* GREP
* ====
* var list = grep( [1,2,3], function(item) { return item % 2 } )
*/
function grep( list, fun ) {
var fin = [];
each( list || [], function(l) { fun(l) && fin.push(l) } );
return fin
}
/**
* SUPPLANT
* ========
* var text = supplant( 'Hello {name}!', { name : 'John' } )
*/
function supplant( str, values ) {
return str.replace( REPL, function( _, match ) {
return values[match] || _
} );
}
/**
* timeout
* =======
* timeout( function(){}, 100 );
*/
function timeout( fun, wait ) {
return setTimeout( fun, wait );
}
/**
* uuid
* ====
* var my_uuid = uuid();
*/
function uuid(callback) {
var u = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
if (callback) callback(u);
return u;
}
function isArray(arg) {
if (arg && !("length" in arg)) {
var foo = Array.isArray;
var bar = Array.isArray(arg);
}
return !!arg && typeof arg !== 'string' && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number")
//return !!arg && (Array.isArray && Array.isArray(arg) || typeof(arg.length) === "number")
}
/**
* EACH
* ====
* each( [1,2,3], function(item) { } )
*/
function each( o, f) {
if ( !o || !f ) return;
if ( isArray(o) )
for ( var i = 0, l = o.length; i < l; )
f.call( o[i], o[i], i++ );
else
for ( var i in o )
o.hasOwnProperty &&
o.hasOwnProperty(i) &&
f.call( o[i], i, o[i] );
}
/**
* MAP
* ===
* var list = map( [1,2,3], function(item) { return item + 1 } )
*/
function map( list, fun ) {
var fin = [];
each( list || [], function( k, v ) { fin.push(fun( k, v )) } );
return fin;
}
/**
* ENCODE
* ======
* var encoded_data = encode('path');
*/
function encode(path) { return encodeURIComponent(path) }
/**
* Generate Subscription Channel List
* ==================================
* generate_channel_list(channels_object);
*/
function generate_channel_list(channels, nopresence) {
var list = [];
each( channels, function( channel, status ) {
if (nopresence) {
if(channel.search('-pnpres') < 0) {
if (status.subscribed) list.push(channel);
}
} else {
if (status.subscribed) list.push(channel);
}
});
return list.sort();
}
/**
* Generate Subscription Channel Groups List
* ==================================
* generate_channel_groups_list(channels_groups object);
*/
function generate_channel_groups_list(channel_groups, nopresence) {
var list = [];
each(channel_groups, function( channel_group, status ) {
if (nopresence) {
if(channel_group.search('-pnpres') < 0) {
if (status.subscribed) list.push(channel_group);
}
} else {
if (status.subscribed) list.push(channel_group);
}
});
return list.sort();
}
// PUBNUB READY TO CONNECT
function ready() { timeout( function() {
if (READY) return;
READY = 1;
each( READY_BUFFER, function(connect) { connect() } );
}, SECOND ); }
function PNmessage(args) {
msg = args || {'apns' : {}},
msg['getPubnubMessage'] = function() {
var m = {};
if (Object.keys(msg['apns']).length) {
m['pn_apns'] = {
'aps' : {
'alert' : msg['apns']['alert'] ,
'badge' : msg['apns']['badge']
}
}
for (var k in msg['apns']) {
m['pn_apns'][k] = msg['apns'][k];
}
var exclude1 = ['badge','alert'];
for (var k in exclude1) {
//console.log(exclude[k]);
delete m['pn_apns'][exclude1[k]];
}
}
if (msg['gcm']) {
m['pn_gcm'] = {
'data' : msg['gcm']
}
}
for (var k in msg) {
m[k] = msg[k];
}
var exclude = ['apns','gcm','publish', 'channel','callback','error'];
for (var k in exclude) {
delete m[exclude[k]];
}
return m;
};
msg['publish'] = function() {
var m = msg.getPubnubMessage();
if (msg['pubnub'] && msg['channel']) {
msg['pubnub'].publish({
'message' : m,
'channel' : msg['channel'],
'callback' : msg['callback'],
'error' : msg['error']
})
}
};
return msg;
}
function PN_API(setup) {
var SUB_WINDOWING = +setup['windowing'] || DEF_WINDOWING
, SUB_TIMEOUT = (+setup['timeout'] || DEF_SUB_TIMEOUT) * SECOND
, KEEPALIVE = (+setup['keepalive'] || DEF_KEEPALIVE) * SECOND
, NOLEAVE = setup['noleave'] || 0
, PUBLISH_KEY = setup['publish_key'] || 'demo'
, SUBSCRIBE_KEY = setup['subscribe_key'] || 'demo'
, AUTH_KEY = setup['auth_key'] || ''
, SECRET_KEY = setup['secret_key'] || ''
, hmac_SHA256 = setup['hmac_SHA256']
, SSL = setup['ssl'] ? 's' : ''
, ORIGIN = 'http'+SSL+'://'+(setup['origin']||'pubsub.pubnub.com')
, STD_ORIGIN = nextorigin(ORIGIN)
, SUB_ORIGIN = nextorigin(ORIGIN)
, CONNECT = function(){}
, PUB_QUEUE = []
, CLOAK = true
, TIME_DRIFT = 0
, SUB_CALLBACK = 0
, SUB_CHANNEL = 0
, SUB_RECEIVER = 0
, SUB_RESTORE = setup['restore'] || 0
, SUB_BUFF_WAIT = 0
, TIMETOKEN = 0
, RESUMED = false
, CHANNELS = {}
, CHANNEL_GROUPS = {}
, STATE = {}
, PRESENCE_HB_TIMEOUT = null
, PRESENCE_HB = validate_presence_heartbeat(setup['heartbeat'] || setup['pnexpires'] || 0, setup['error'])
, PRESENCE_HB_INTERVAL = setup['heartbeat_interval'] || PRESENCE_HB - 3
, PRESENCE_HB_RUNNING = false
, NO_WAIT_FOR_PENDING = setup['no_wait_for_pending']
, COMPATIBLE_35 = setup['compatible_3.5'] || false
, xdr = setup['xdr']
, params = setup['params'] || {}
, error = setup['error'] || function() {}
, _is_online = setup['_is_online'] || function() { return 1 }
, jsonp_cb = setup['jsonp_cb'] || function() { return 0 }
, db = setup['db'] || {'get': function(){}, 'set': function(){}}
, CIPHER_KEY = setup['cipher_key']
, UUID = setup['uuid'] || ( db && db['get'](SUBSCRIBE_KEY+'uuid') || '')
, _poll_timer
, _poll_timer2;
var crypto_obj = setup['crypto_obj'] ||
{
'encrypt' : function(a,key){ return a},
'decrypt' : function(b,key){return b}
};
function _get_url_params(data) {
if (!data) data = {};
each( params , function( key, value ) {
if (!(key in data)) data[key] = value;
});
return data;
}
function _object_to_key_list(o) {
var l = []
each( o , function( key, value ) {
l.push(key);
});
return l;
}
function _object_to_key_list_sorted(o) {
return _object_to_key_list(o).sort();
}
function _get_pam_sign_input_from_params(params) {
var si = "";
var l = _object_to_key_list_sorted(params);
for (var i in l) {
var k = l[i]
si += k + "=" + encode(params[k]) ;
if (i != l.length - 1) si += "&"
}
return si;
}
function validate_presence_heartbeat(heartbeat, cur_heartbeat, error) {
var err = false;
if (typeof heartbeat === 'number') {
if (heartbeat > PRESENCE_HB_THRESHOLD || heartbeat == 0)
err = false;
else
err = true;
} else if(typeof heartbeat === 'boolean'){
if (!heartbeat) {
return 0;
} else {
return PRESENCE_HB_DEFAULT;
}
} else {
err = true;
}
if (err) {
error && error("Presence Heartbeat value invalid. Valid range ( x > " + PRESENCE_HB_THRESHOLD + " or x = 0). Current Value : " + (cur_heartbeat || PRESENCE_HB_THRESHOLD));
return cur_heartbeat || PRESENCE_HB_THRESHOLD;
} else return heartbeat;
}
function encrypt(input, key) {
return crypto_obj['encrypt'](input, key || CIPHER_KEY) || input;
}
function decrypt(input, key) {
return crypto_obj['decrypt'](input, key || CIPHER_KEY) ||
crypto_obj['decrypt'](input, CIPHER_KEY) ||
input;
}
function error_common(message, callback) {
callback && callback({ 'error' : message || "error occurred"});
error && error(message);
}
function _presence_heartbeat() {
clearTimeout(PRESENCE_HB_TIMEOUT);
if (!PRESENCE_HB_INTERVAL || PRESENCE_HB_INTERVAL >= 500 ||
PRESENCE_HB_INTERVAL < 1 ||
(!generate_channel_list(CHANNELS,true).length && !generate_channel_groups_list(CHANNEL_GROUPS, true).length ) )
{
PRESENCE_HB_RUNNING = false;
return;
}
PRESENCE_HB_RUNNING = true;
SELF['presence_heartbeat']({
'callback' : function(r) {
PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
},
'error' : function(e) {
error && error("Presence Heartbeat unable to reach Pubnub servers." + JSON.stringify(e));
PRESENCE_HB_TIMEOUT = timeout( _presence_heartbeat, (PRESENCE_HB_INTERVAL) * SECOND );
}
});
}
function start_presence_heartbeat() {
!PRESENCE_HB_RUNNING && _presence_heartbeat();
}
function publish(next) {
if (NO_WAIT_FOR_PENDING) {
if (!PUB_QUEUE.length) return;
} else {
if (next) PUB_QUEUE.sending = 0;
if ( PUB_QUEUE.sending || !PUB_QUEUE.length ) return;
PUB_QUEUE.sending = 1;
}
xdr(PUB_QUEUE.shift());
}
function each_channel(callback) {
var count = 0;
each( generate_channel_list(CHANNELS), function(channel) {
var chan = CHANNELS[channel];
if (!chan) return;
count++;
(callback||function(){})(chan);
} );
return count;
}
function _invoke_callback(response, callback, err) {
if (typeof response == 'object') {
if (response['error'] && response['message'] && response['payload']) {
err({'message' : response['message'], 'payload' : response['payload']});
return;
}
if (response['payload']) {
callback(response['payload']);
return;
}
}
callback(response);
}
function _invoke_error(response,err) {
if (typeof response == 'object' && response['error'] &&
response['message'] && response['payload']) {
err({'message' : response['message'], 'payload' : response['payload']});
} else err(response);
}
function CR(args, callback, url1, data) {
var callback = args['callback'] || callback
, err = args['error'] || error
, jsonp = jsonp_cb();
if (!data['auth']) {
data['auth'] = args['auth_key'] || AUTH_KEY;
}
var url = [
STD_ORIGIN, 'v1', 'channel-registration',
'sub-key', SUBSCRIBE_KEY
];
url.push.apply(url,url1);
xdr({
callback : jsonp,
data : _get_url_params(data),
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : url
});
}
// Announce Leave Event
var SELF = {
'LEAVE' : function( channel, blocking, callback, error ) {
var data = { 'uuid' : UUID, 'auth' : AUTH_KEY }
, origin = nextorigin(ORIGIN)
, callback = callback || function(){}
, err = error || function(){}
, jsonp = jsonp_cb();
// Prevent Leaving a Presence Channel
if (channel.indexOf(PRESENCE_SUFFIX) > 0) return true;
if (COMPATIBLE_35) {
if (!SSL) return false;
if (jsonp == '0') return false;
}
if (NOLEAVE) return false;
if (jsonp != '0') data['callback'] = jsonp;
xdr({
blocking : blocking || SSL,
timeout : 2000,
callback : jsonp,
data : _get_url_params(data),
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : [
origin, 'v2', 'presence', 'sub_key',
SUBSCRIBE_KEY, 'channel', encode(channel), 'leave'
]
});
return true;
},
'set_resumed' : function(resumed) {
RESUMED = resumed;
},
'get_cipher_key' : function() {
return CIPHER_KEY;
},
'set_cipher_key' : function(key) {
CIPHER_KEY = key;
},
'raw_encrypt' : function(input, key) {
return encrypt(input, key);
},
'raw_decrypt' : function(input, key) {
return decrypt(input, key);
},
'get_heartbeat' : function() {
return PRESENCE_HB;
},
'set_heartbeat' : function(heartbeat) {
PRESENCE_HB = validate_presence_heartbeat(heartbeat, PRESENCE_HB_INTERVAL, error);
PRESENCE_HB_INTERVAL = (PRESENCE_HB - 3 >= 1)?PRESENCE_HB - 3:1;
CONNECT();
_presence_heartbeat();
},
'get_heartbeat_interval' : function() {
return PRESENCE_HB_INTERVAL;
},
'set_heartbeat_interval' : function(heartbeat_interval) {
PRESENCE_HB_INTERVAL = heartbeat_interval;
_presence_heartbeat();
},
'get_version' : function() {
return SDK_VER;
},
'getGcmMessageObject' : function(obj) {
return {
'data' : obj
}
},
'getApnsMessageObject' : function(obj) {
var x = {
'aps' : { 'badge' : 1, 'alert' : ''}
}
for (k in obj) {
k[x] = obj[k];
}
return x;
},
'newPnMessage' : function() {
var x = {};
if (gcm) x['pn_gcm'] = gcm;
if (apns) x['pn_apns'] = apns;
for ( k in n ) {
x[k] = n[k];
}
return x;
},
'_add_param' : function(key,val) {
params[key] = val;
},
'channel_group' : function(args, callback) {
var ns_ch = args['channel_group']
, channels = args['channels'] || args['channel']
, cloak = args['cloak']
, namespace
, channel_group
, url = []
, data = {}
, mode = args['mode'] || 'add';
if (ns_ch) {
var ns_ch_a = ns_ch.split(':');
if (ns_ch_a.length > 1) {
namespace = (ns_ch_a[0] === '*')?null:ns_ch_a[0];
channel_group = ns_ch_a[1];
} else {
channel_group = ns_ch_a[0];
}
}
namespace && url.push('namespace') && url.push(encode(namespace));
url.push('channel-group');
if (channel_group && channel_group !== '*') {
url.push(channel_group);
}
if (channels ) {
if (isArray(channels)) {
channels = channels.join(',');
}
data[mode] = channels;
data['cloak'] = (CLOAK)?'true':'false';
} else {
if (mode === 'remove') url.push('remove');
}
if (typeof cloak != 'undefined') data['cloak'] = (cloak)?'true':'false';
CR(args, callback, url, data);
},
'channel_group_list_groups' : function(args, callback) {
var namespace;
namespace = args['namespace'] || args['ns'] || args['channel_group'] || null;
if (namespace) {
args["channel_group"] = namespace + ":*";
}
SELF['channel_group'](args, callback);
},
'channel_group_list_channels' : function(args, callback) {
if (!args['channel_group']) return error('Missing Channel Group');
SELF['channel_group'](args, callback);
},
'channel_group_remove_channel' : function(args, callback) {
if (!args['channel_group']) return error('Missing Channel Group');
if (!args['channel'] && !args['channels'] ) return error('Missing Channel');
args['mode'] = 'remove';
SELF['channel_group'](args,callback);
},
'channel_group_remove_group' : function(args, callback) {
if (!args['channel_group']) return error('Missing Channel Group');
if (args['channel']) return error('Use channel_group_remove_channel if you want to remove a channel from a group.');
args['mode'] = 'remove';
SELF['channel_group'](args,callback);
},
'channel_group_add_channel' : function(args, callback) {
if (!args['channel_group']) return error('Missing Channel Group');
if (!args['channel'] && !args['channels'] ) return error('Missing Channel');
SELF['channel_group'](args,callback);
},
'channel_group_cloak' : function(args, callback) {
if (typeof args['cloak'] == 'undefined') {
callback(CLOAK);
return;
}
CLOAK = args['cloak'];
SELF['channel_group'](args,callback);
},
'channel_group_list_namespaces' : function(args, callback) {
var url = ['namespace'];
CR(args, callback, url);
},
'channel_group_remove_namespace' : function(args, callback) {
var url = ['namespace',args['namespace'],'remove'];
CR(args, callback, url);
},
/*
PUBNUB.history({
channel : 'my_chat_channel',
limit : 100,
callback : function(history) { }
});
*/
'history' : function( args, callback ) {
var callback = args['callback'] || callback
, count = args['count'] || args['limit'] || 100
, reverse = args['reverse'] || "false"
, err = args['error'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, cipher_key = args['cipher_key']
, channel = args['channel']
, channel_group = args['channel_group']
, start = args['start']
, end = args['end']
, include_token = args['include_token']
, params = {}
, jsonp = jsonp_cb();
// Make sure we have a Channel
if (!channel && !channel_group) return error('Missing Channel');
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
params['stringtoken'] = 'true';
params['count'] = count;
params['reverse'] = reverse;
params['auth'] = auth_key;
if (channel_group) {
params['channel-group'] = channel_group;
if (!channel) {
channel = ',';
}
}
if (jsonp) params['callback'] = jsonp;
if (start) params['start'] = start;
if (end) params['end'] = end;
if (include_token) params['include_token'] = 'true';
// Send Message
xdr({
callback : jsonp,
data : _get_url_params(params),
success : function(response) {
if (typeof response == 'object' && response['error']) {
err({'message' : response['message'], 'payload' : response['payload']});
return;
}
var messages = response[0];
var decrypted_messages = [];
for (var a = 0; a < messages.length; a++) {
var new_message = decrypt(messages[a],cipher_key);
try {
decrypted_messages['push'](JSON['parse'](new_message));
} catch (e) {
decrypted_messages['push']((new_message));
}
}
callback([decrypted_messages, response[1], response[2]]);
},
fail : function(response) {
_invoke_error(response, err);
},
url : [
STD_ORIGIN, 'v2', 'history', 'sub-key',
SUBSCRIBE_KEY, 'channel', encode(channel)
]
});
},
/*
PUBNUB.replay({
source : 'my_channel',
destination : 'new_channel'
});
*/
'replay' : function(args, callback) {
var callback = callback || args['callback'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, source = args['source']
, destination = args['destination']
, stop = args['stop']
, start = args['start']
, end = args['end']
, reverse = args['reverse']
, limit = args['limit']
, jsonp = jsonp_cb()
, data = {}
, url;
// Check User Input
if (!source) return error('Missing Source Channel');
if (!destination) return error('Missing Destination Channel');
if (!PUBLISH_KEY) return error('Missing Publish Key');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
// Setup URL Params
if (jsonp != '0') data['callback'] = jsonp;
if (stop) data['stop'] = 'all';
if (reverse) data['reverse'] = 'true';
if (start) data['start'] = start;
if (end) data['end'] = end;
if (limit) data['count'] = limit;
data['auth'] = auth_key;
// Compose URL Parts
url = [
STD_ORIGIN, 'v1', 'replay',
PUBLISH_KEY, SUBSCRIBE_KEY,
source, destination
];
// Start (or Stop) Replay!
xdr({
callback : jsonp,
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function() { callback([ 0, 'Disconnected' ]) },
url : url,
data : _get_url_params(data)
});
},
/*
PUBNUB.auth('AJFLKAJSDKLA');
*/
'auth' : function(auth) {
AUTH_KEY = auth;
CONNECT();
},
/*
PUBNUB.time(function(time){ });
*/
'time' : function(callback) {
var jsonp = jsonp_cb();
xdr({
callback : jsonp,
data : _get_url_params({ 'uuid' : UUID, 'auth' : AUTH_KEY }),
timeout : SECOND * 5,
url : [STD_ORIGIN, 'time', jsonp],
success : function(response) { callback(response[0]) },
fail : function() { callback(0) }
});
},
/*
PUBNUB.publish({
channel : 'my_chat_channel',
message : 'hello!'
});
*/
'publish' : function( args, callback ) {
var msg = args['message'];
if (!msg) return error('Missing Message');
var callback = callback || args['callback'] || msg['callback'] || function(){}
, channel = args['channel'] || msg['channel']
, auth_key = args['auth_key'] || AUTH_KEY
, cipher_key = args['cipher_key']
, err = args['error'] || msg['error'] || function() {}
, post = args['post'] || false
, store = ('store_in_history' in args) ? args['store_in_history']: true
, jsonp = jsonp_cb()
, add_msg = 'push'
, url;
if (args['prepend']) add_msg = 'unshift'
if (!channel) return error('Missing Channel');
if (!PUBLISH_KEY) return error('Missing Publish Key');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (msg['getPubnubMessage']) {
msg = msg['getPubnubMessage']();
}
// If trying to send Object
msg = JSON['stringify'](encrypt(msg, cipher_key));
// Create URL
url = [
STD_ORIGIN, 'publish',
PUBLISH_KEY, SUBSCRIBE_KEY,
0, encode(channel),
jsonp, encode(msg)
];
params = { 'uuid' : UUID, 'auth' : auth_key }
if (!store) params['store'] ="0"
// Queue Message Send
PUB_QUEUE[add_msg]({
callback : jsonp,
timeout : SECOND * 5,
url : url,
data : _get_url_params(params),
fail : function(response){
_invoke_error(response, err);
publish(1);
},
success : function(response) {
_invoke_callback(response, callback, err);
publish(1);
},
mode : (post)?'POST':'GET'
});
// Send Message
publish();
},
/*
PUBNUB.unsubscribe({ channel : 'my_chat' });
*/
'unsubscribe' : function(args, callback) {
var channel = args['channel']
, channel_group = args['channel_group']
, callback = callback || args['callback'] || function(){}
, err = args['error'] || function(){};
TIMETOKEN = 0;
//SUB_RESTORE = 1; REVISIT !!!!
if (channel) {
// Prepare Channel(s)
channel = map( (
channel.join ? channel.join(',') : ''+channel
).split(','), function(channel) {
if (!CHANNELS[channel]) return;
return channel + ',' + channel + PRESENCE_SUFFIX;
} ).join(',');
// Iterate over Channels
each( channel.split(','), function(channel) {
var CB_CALLED = true;
if (!channel) return;
if (READY) {
CB_CALLED = SELF['LEAVE']( channel, 0 , callback, err);
}
if (!CB_CALLED) callback({action : "leave"});
CHANNELS[channel] = 0;
if (channel in STATE) delete STATE[channel];
} );
}
if (channel_group) {
// Prepare channel group(s)
channel_group = map( (
channel_group.join ? channel_group.join(',') : ''+channel_group
).split(','), function(channel_group) {
if (!CHANNEL_GROUPS[channel_group]) return;
return channel_group + ',' + channel_group + PRESENCE_SUFFIX;
} ).join(',');
// Iterate over channel groups
each( channel_group.split(','), function(channel) {
var CB_CALLED = true;
if (!channel_group) return;
if (READY) {
CB_CALLED = SELF['LEAVE']( channel_group, 0 , callback, err);
}
if (!CB_CALLED) callback({action : "leave"});
CHANNEL_GROUPS[channel_group] = 0;
if (channel_group in STATE) delete STATE[channel_group];
} );
}
// Reset Connection if Count Less
CONNECT();
},
/*
PUBNUB.subscribe({
channel : 'my_chat'
callback : function(message) { }
});
*/
'subscribe' : function( args, callback ) {
var channel = args['channel']
, channel_group = args['channel_group']
, callback = callback || args['callback']
, callback = callback || args['message']
, auth_key = args['auth_key'] || AUTH_KEY
, connect = args['connect'] || function(){}
, reconnect = args['reconnect'] || function(){}
, disconnect = args['disconnect'] || function(){}
, errcb = args['error'] || function(){}
, idlecb = args['idle'] || function(){}
, presence = args['presence'] || 0
, noheresync = args['noheresync'] || 0
, backfill = args['backfill'] || 0
, timetoken = args['timetoken'] || 0
, sub_timeout = args['timeout'] || SUB_TIMEOUT
, windowing = args['windowing'] || SUB_WINDOWING
, state = args['state']
, heartbeat = args['heartbeat'] || args['pnexpires']
, restore = args['restore'] || SUB_RESTORE;
// Restore Enabled?
SUB_RESTORE = restore;
// Always Reset the TT
TIMETOKEN = timetoken;
// Make sure we have a Channel
if (!channel && !channel_group) {
return error('Missing Channel');
}
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (heartbeat || heartbeat === 0) {
SELF['set_heartbeat'](heartbeat);
}
// Setup Channel(s)
if (channel) {
each( (channel.join ? channel.join(',') : ''+channel).split(','),
function(channel) {
var settings = CHANNELS[channel] || {};
// Store Channel State
CHANNELS[SUB_CHANNEL = channel] = {
name : channel,
connected : settings.connected,
disconnected : settings.disconnected,
subscribed : 1,
callback : SUB_CALLBACK = callback,
'cipher_key' : args['cipher_key'],
connect : connect,
disconnect : disconnect,
reconnect : reconnect
};
if (state) {
if (channel in state) {
STATE[channel] = state[channel];
} else {
STATE[channel] = state;
}
}
// Presence Enabled?
if (!presence) return;
// Subscribe Presence Channel
SELF['subscribe']({
'channel' : channel + PRESENCE_SUFFIX,
'callback' : presence,
'restore' : restore
});
// Presence Subscribed?
if (settings.subscribed) return;
// See Who's Here Now?
if (noheresync) return;
SELF['here_now']({
'channel' : channel,
'callback' : function(here) {
each( 'uuids' in here ? here['uuids'] : [],
function(uid) { presence( {
'action' : 'join',
'uuid' : uid,
'timestamp' : Math.floor(rnow() / 1000),
'occupancy' : here['occupancy'] || 1
}, here, channel ); } );
}
});
} );
}
// Setup Channel Groups
if (channel_group) {
each( (channel_group.join ? channel_group.join(',') : ''+channel_group).split(','),
function(channel_group) {
var settings = CHANNEL_GROUPS[channel_group] || {};
CHANNEL_GROUPS[channel_group] = {
name : channel_group,
connected : settings.connected,
disconnected : settings.disconnected,
subscribed : 1,
callback : SUB_CALLBACK = callback,
'cipher_key' : args['cipher_key'],
connect : connect,
disconnect : disconnect,
reconnect : reconnect
};
// Presence Enabled?
if (!presence) return;
// Subscribe Presence Channel
SELF['subscribe']({
'channel_group' : channel_group + PRESENCE_SUFFIX,
'callback' : presence,
'restore' : restore
});
// Presence Subscribed?
if (settings.subscribed) return;
// See Who's Here Now?
if (noheresync) return;
SELF['here_now']({
'channel_group' : channel_group,
'callback' : function(here) {
each( 'uuids' in here ? here['uuids'] : [],
function(uid) { presence( {
'action' : 'join',
'uuid' : uid,
'timestamp' : Math.floor(rnow() / 1000),
'occupancy' : here['occupancy'] || 1
}, here, channel_group ); } );
}
});
} );
}
// Test Network Connection
function _test_connection(success) {
if (success) {
// Begin Next Socket Connection
timeout( CONNECT, SECOND );
}
else {
// New Origin on Failed Connection
STD_ORIGIN = nextorigin( ORIGIN, 1 );
SUB_ORIGIN = nextorigin( ORIGIN, 1 );
// Re-test Connection
timeout( function() {
SELF['time'](_test_connection);
}, SECOND );
}
// Disconnect & Reconnect
each_channel(function(channel){
// Reconnect
if (success && channel.disconnected) {
channel.disconnected = 0;
return channel.reconnect(channel.name);
}
// Disconnect
if (!success && !channel.disconnected) {
channel.disconnected = 1;
channel.disconnect(channel.name);
}
});
}
// Evented Subscribe
function _connect() {
var jsonp = jsonp_cb()
, channels = generate_channel_list(CHANNELS).join(',')
, channel_groups = generate_channel_groups_list(CHANNEL_GROUPS).join(',');
// Stop Connection
if (!channels && !channel_groups) return;
if (!channels) channels = ',';
// Connect to PubNub Subscribe Servers
_reset_offline();
var data = _get_url_params({ 'uuid' : UUID, 'auth' : auth_key });
if (channel_groups) {
data['channel-group'] = channel_groups;
}
var st = JSON.stringify(STATE);
if (st.length > 2) data['state'] = JSON.stringify(STATE);
if (PRESENCE_HB) data['heartbeat'] = PRESENCE_HB;
start_presence_heartbeat();
SUB_RECEIVER = xdr({
timeout : sub_timeout,
callback : jsonp,
fail : function(response) {
//SUB_RECEIVER = null;
SELF['time'](function(success){
!success && ( _invoke_error(response, errcb));
_test_connection(success);
});
},
data : _get_url_params(data),
url : [
SUB_ORIGIN, 'subscribe',
SUBSCRIBE_KEY, encode(channels),
jsonp, TIMETOKEN
],
success : function(messages) {
//SUB_RECEIVER = null;
// Check for Errors
if (!messages || (
typeof messages == 'object' &&
'error' in messages &&
messages['error']
)) {
errcb(messages['error']);
return timeout( CONNECT, SECOND );
}
// User Idle Callback
idlecb(messages[1]);
// Restore Previous Connection Point if Needed
TIMETOKEN = !TIMETOKEN &&
SUB_RESTORE &&
db['get'](SUBSCRIBE_KEY) || messages[1];
/*
// Connect
each_channel_registry(function(registry){
if (registry.connected) return;
registry.connected = 1;
registry.connect(channel.name);
});
*/
// Connect
each_channel(function(channel){
if (channel.connected) return;
channel.connected = 1;
channel.connect(channel.name);
});
if (RESUMED && !SUB_RESTORE) {
TIMETOKEN = 0;
RESUMED = false;
// Update Saved Timetoken
db['set']( SUBSCRIBE_KEY, 0 );
timeout( _connect, windowing );
return;
}
// Invoke Memory Catchup and Receive Up to 100
// Previous Messages from the Queue.
if (backfill) {
TIMETOKEN = 10000;
backfill = 0;
}
// Update Saved Timetoken
db['set']( SUBSCRIBE_KEY, messages[1] );
// Route Channel <---> Callback for Message
var next_callback = (function() {
var channels = '';
if (messages.length > 3) {
channels = messages[3];
} else if (messages.length > 2) {
channels = messages[2];
} else {
channels = map(
generate_channel_list(CHANNELS), function(chan) { return map(
Array(messages[0].length)
.join(',').split(','),
function() { return chan; }
) }).join(',')
}
var list = channels.split(',');
return function() {
var channel = list.shift()||SUB_CHANNEL;
return [
(CHANNELS[channel]||{})
.callback||SUB_CALLBACK,
channel.split(PRESENCE_SUFFIX)[0]
];
};
})();
var latency = detect_latency(+messages[1]);
each( messages[0], function(msg) {
var next = next_callback();
var decrypted_msg = decrypt(msg,
(CHANNELS[next[1]])?CHANNELS[next[1]]['cipher_key']:null);
next[0]( decrypted_msg, messages, next[2] || next[1], latency);
});
timeout( _connect, windowing );
}
});
}
CONNECT = function() {
_reset_offline();
timeout( _connect, windowing );
};
// Reduce Status Flicker
if (!READY) return READY_BUFFER.push(CONNECT);
// Connect Now
CONNECT();
},
/*
PUBNUB.here_now({ channel : 'my_chat', callback : fun });
*/
'here_now' : function( args, callback ) {
var callback = args['callback'] || callback
, err = args['error'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, channel = args['channel']
, channel_group = args['channel_group']
, jsonp = jsonp_cb()
, uuids = ('uuids' in args) ? args['uuids'] : true
, state = args['state']
, data = { 'uuid' : UUID, 'auth' : auth_key };
if (!uuids) data['disable_uuids'] = 1;
if (state) data['state'] = 1;
// Make sure we have a Channel
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
var url = [
STD_ORIGIN, 'v2', 'presence',
'sub_key', SUBSCRIBE_KEY
];
channel && url.push('channel') && url.push(encode(channel));
if (jsonp != '0') { data['callback'] = jsonp; }
if (channel_group) {
data['channel-group'] = channel_group;
!channel && url.push('channel') && url.push(',');
}
xdr({
callback : jsonp,
data : _get_url_params(data),
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : url
});
},
/*
PUBNUB.current_channels_by_uuid({ channel : 'my_chat', callback : fun });
*/
'where_now' : function( args, callback ) {
var callback = args['callback'] || callback
, err = args['error'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, jsonp = jsonp_cb()
, uuid = args['uuid'] || UUID
, data = { 'auth' : auth_key };
// Make sure we have a Channel
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (jsonp != '0') { data['callback'] = jsonp; }
xdr({
callback : jsonp,
data : _get_url_params(data),
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : [
STD_ORIGIN, 'v2', 'presence',
'sub_key', SUBSCRIBE_KEY,
'uuid', encode(uuid)
]
});
},
'state' : function(args, callback) {
var callback = args['callback'] || callback || function(r) {}
, err = args['error'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, jsonp = jsonp_cb()
, state = args['state']
, uuid = args['uuid'] || UUID
, channel = args['channel']
, channel_group = args['channel_group']
, url
, data = _get_url_params({ 'auth' : auth_key });
// Make sure we have a Channel
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (!uuid) return error('Missing UUID');
if (!channel && !channel_group) return error('Missing Channel');
if (jsonp != '0') { data['callback'] = jsonp; }
if (typeof channel != 'undefined'
&& CHANNELS[channel] && CHANNELS[channel].subscribed ) {
if (state) STATE[channel] = state;
}
if (typeof channel_group != 'undefined'
&& CHANNEL_GROUPS[channel_group]
&& CHANNEL_GROUPS[channel_group].subscribed
) {
if (state) STATE[channel_group] = state;
data['channel-group'] = channel_group;
if (!channel) {
channel = ',';
}
}
data['state'] = JSON.stringify(state);
if (state) {
url = [
STD_ORIGIN, 'v2', 'presence',
'sub-key', SUBSCRIBE_KEY,
'channel', channel,
'uuid', uuid, 'data'
]
} else {
url = [
STD_ORIGIN, 'v2', 'presence',
'sub-key', SUBSCRIBE_KEY,
'channel', channel,
'uuid', encode(uuid)
]
}
xdr({
callback : jsonp,
data : _get_url_params(data),
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : url
});
},
/*
PUBNUB.grant({
channel : 'my_chat',
callback : fun,
error : fun,
ttl : 24 * 60, // Minutes
read : true,
write : true,
auth_key : '3y8uiajdklytowsj'
});
*/
'grant' : function( args, callback ) {
var callback = args['callback'] || callback
, err = args['error'] || function(){}
, channel = args['channel']
, channel_group = args['channel_group']
, jsonp = jsonp_cb()
, ttl = args['ttl']
, r = (args['read'] )?"1":"0"
, w = (args['write'])?"1":"0"
, m = (args['manage'])?"1":"0"
, auth_key = args['auth_key'];
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (!PUBLISH_KEY) return error('Missing Publish Key');
if (!SECRET_KEY) return error('Missing Secret Key');
var timestamp = Math.floor(new Date().getTime() / 1000)
, sign_input = SUBSCRIBE_KEY + "\n" + PUBLISH_KEY + "\n"
+ "grant" + "\n";
var data = {
'w' : w,
'r' : r,
'timestamp' : timestamp
};
if (args['manage']) {
data['m'] = m;
}
if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) {
data['channel-group'] = channel_group;
}
if (jsonp != '0') { data['callback'] = jsonp; }
if (ttl || ttl === 0) data['ttl'] = ttl;
if (auth_key) data['auth'] = auth_key;
data = _get_url_params(data)
if (!auth_key) delete data['auth'];
sign_input += _get_pam_sign_input_from_params(data);
var signature = hmac_SHA256( sign_input, SECRET_KEY );
signature = signature.replace( /\+/g, "-" );
signature = signature.replace( /\//g, "_" );
data['signature'] = signature;
xdr({
callback : jsonp,
data : data,
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : [
STD_ORIGIN, 'v1', 'auth', 'grant' ,
'sub-key', SUBSCRIBE_KEY
]
});
},
/*
PUBNUB.mobile_gw_provision ({
device_id: 'A655FBA9931AB',
op : 'add' | 'remove',
gw_type : 'apns' | 'gcm',
channel : 'my_chat',
callback : fun,
error : fun,
});
*/
'mobile_gw_provision' : function( args ) {
var callback = args['callback'] || function(){}
, auth_key = args['auth_key'] || AUTH_KEY
, err = args['error'] || function() {}
, jsonp = jsonp_cb()
, channel = args['channel']
, op = args['op']
, gw_type = args['gw_type']
, device_id = args['device_id']
, url;
if (!device_id) return error('Missing Device ID (device_id)');
if (!gw_type) return error('Missing GW Type (gw_type: gcm or apns)');
if (!op) return error('Missing GW Operation (op: add or remove)');
if (!channel) return error('Missing gw destination Channel (channel)');
if (!PUBLISH_KEY) return error('Missing Publish Key');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
// Create URL
url = [
STD_ORIGIN, 'v1/push/sub-key',
SUBSCRIBE_KEY, 'devices', device_id
];
params = { 'uuid' : UUID, 'auth' : auth_key, 'type': gw_type};
if (op == "add") {
params['add'] = channel;
} else if (op == "remove") {
params['remove'] = channel;
}
xdr({
callback : jsonp,
data : params,
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : url
});
},
/*
PUBNUB.audit({
channel : 'my_chat',
callback : fun,
error : fun,
read : true,
write : true,
auth_key : '3y8uiajdklytowsj'
});
*/
'audit' : function( args, callback ) {
var callback = args['callback'] || callback
, err = args['error'] || function(){}
, channel = args['channel']
, channel_group = args['channel_group']
, auth_key = args['auth_key']
, jsonp = jsonp_cb();
// Make sure we have a Channel
if (!callback) return error('Missing Callback');
if (!SUBSCRIBE_KEY) return error('Missing Subscribe Key');
if (!PUBLISH_KEY) return error('Missing Publish Key');
if (!SECRET_KEY) return error('Missing Secret Key');
var timestamp = Math.floor(new Date().getTime() / 1000)
, sign_input = SUBSCRIBE_KEY + "\n"
+ PUBLISH_KEY + "\n"
+ "audit" + "\n";
var data = {'timestamp' : timestamp };
if (jsonp != '0') { data['callback'] = jsonp; }
if (typeof channel != 'undefined' && channel != null && channel.length > 0) data['channel'] = channel;
if (typeof channel_group != 'undefined' && channel_group != null && channel_group.length > 0) {
data['channel-group'] = channel_group;
}
if (auth_key) data['auth'] = auth_key;
data = _get_url_params(data);
if (!auth_key) delete data['auth'];
sign_input += _get_pam_sign_input_from_params(data);
var signature = hmac_SHA256( sign_input, SECRET_KEY );
signature = signature.replace( /\+/g, "-" );
signature = signature.replace( /\//g, "_" );
data['signature'] = signature;
xdr({
callback : jsonp,
data : data,
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) {
_invoke_error(response, err);
},
url : [
STD_ORIGIN, 'v1', 'auth', 'audit' ,
'sub-key', SUBSCRIBE_KEY
]
});
},
/*
PUBNUB.revoke({
channel : 'my_chat',
callback : fun,
error : fun,
auth_key : '3y8uiajdklytowsj'
});
*/
'revoke' : function( args, callback ) {
args['read'] = false;
args['write'] = false;
SELF['grant']( args, callback );
},
'set_uuid' : function(uuid) {
UUID = uuid;
CONNECT();
},
'get_uuid' : function() {
return UUID;
},
'isArray' : function(arg) {
return isArray(arg);
},
'get_subscibed_channels' : function() {
return generate_channel_list(CHANNELS, true);
},
'presence_heartbeat' : function(args) {
var callback = args['callback'] || function() {}
var err = args['error'] || function() {}
var jsonp = jsonp_cb();
var data = { 'uuid' : UUID, 'auth' : AUTH_KEY };
var st = JSON['stringify'](STATE);
if (st.length > 2) data['state'] = JSON['stringify'](STATE);
if (PRESENCE_HB > 0 && PRESENCE_HB < 320) data['heartbeat'] = PRESENCE_HB;
if (jsonp != '0') { data['callback'] = jsonp; }
var channels = encode(generate_channel_list(CHANNELS, true)['join'](','));
var channel_groups = generate_channel_groups_list(CHANNEL_GROUPS, true)['join'](',');
if (!channels) channels = ',';
if (channel_groups) data['channel-group'] = channel_groups;
xdr({
callback : jsonp,
data : _get_url_params(data),
timeout : SECOND * 5,
url : [
STD_ORIGIN, 'v2', 'presence',
'sub-key', SUBSCRIBE_KEY,
'channel' , channels,
'heartbeat'
],
success : function(response) {
_invoke_callback(response, callback, err);
},
fail : function(response) { _invoke_error(response, err); }
});
},
'stop_timers': function () {
clearTimeout(_poll_timer);
clearTimeout(_poll_timer2);
},
// Expose PUBNUB Functions
'xdr' : xdr,
'ready' : ready,
'db' : db,
'uuid' : uuid,
'map' : map,
'each' : each,
'each-channel' : each_channel,
'grep' : grep,
'offline' : function(){_reset_offline(1, { "message":"Offline. Please check your network settings." })},
'supplant' : supplant,
'now' : rnow,
'unique' : unique,
'updater' : updater
};
function _poll_online() {
_is_online() || _reset_offline( 1, {
"error" : "Offline. Please check your network settings. "
});
_poll_timer && clearTimeout(_poll_timer);
_poll_timer = timeout( _poll_online, SECOND );
}
function _poll_online2() {
SELF['time'](function(success){
detect_time_detla( function(){}, success );
success || _reset_offline( 1, {
"error" : "Heartbeat failed to connect to Pubnub Servers." +
"Please check your network settings."
});
_poll_timer2 && clearTimeout(_poll_timer2);
_poll_timer2 = timeout( _poll_online2, KEEPALIVE );
});
}
function _reset_offline(err, msg) {
SUB_RECEIVER && SUB_RECEIVER(err, msg);
SUB_RECEIVER = null;
clearTimeout(_poll_timer);
clearTimeout(_poll_timer2);
}
if (!UUID) UUID = SELF['uuid']();
db['set']( SUBSCRIBE_KEY + 'uuid', UUID );
_poll_timer = timeout( _poll_online, SECOND );
_poll_timer2 = timeout( _poll_online2, KEEPALIVE );
PRESENCE_HB_TIMEOUT = timeout( start_presence_heartbeat, ( PRESENCE_HB_INTERVAL - 3 ) * SECOND ) ;
// Detect Age of Message
function detect_latency(tt) {
var adjusted_time = rnow() - TIME_DRIFT;
return adjusted_time - tt / 10000;
}
detect_time_detla();
function detect_time_detla( cb, time ) {
var stime = rnow();
time && calculate(time) || SELF['time'](calculate);
function calculate(time) {
if (!time) return;
var ptime = time / 10000
, latency = (rnow() - stime) / 2;
TIME_DRIFT = rnow() - (ptime + latency);
cb && cb(TIME_DRIFT);
}
}
return SELF;
}
| pubnub/kinoma | src/unassembled/pubnub-common.js | JavaScript | mit | 63,498 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<TITLE>
Uses of Class org.apache.poi.hssf.util.HSSFColor.INDIGO (POI API Documentation)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.poi.hssf.util.HSSFColor.INDIGO (POI API Documentation)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/util/HSSFColor.INDIGO.html" title="class in org.apache.poi.hssf.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/util/\class-useHSSFColor.INDIGO.html" target="_top"><B>FRAMES</B></A>
<A HREF="HSSFColor.INDIGO.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.poi.hssf.util.HSSFColor.INDIGO</B></H2>
</CENTER>
No usage of org.apache.poi.hssf.util.HSSFColor.INDIGO
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/poi/hssf/util/HSSFColor.INDIGO.html" title="class in org.apache.poi.hssf.util"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?org/apache/poi/hssf/util/\class-useHSSFColor.INDIGO.html" target="_top"><B>FRAMES</B></A>
<A HREF="HSSFColor.INDIGO.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright 2016 The Apache Software Foundation or
its licensors, as applicable.</i>
</BODY>
</HTML>
| Sebaxtian/KDD | poi-3.14/docs/apidocs/org/apache/poi/hssf/util/class-use/HSSFColor.INDIGO.html | HTML | mit | 6,179 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>http::make_chunk</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Beast">
<link rel="up" href="../ref.html" title="This Page Intentionally Left Blank 2/2">
<link rel="prev" href="boost__beast__http__is_mutable_body_writer.html" title="http::is_mutable_body_writer">
<link rel="next" href="boost__beast__http__make_chunk_last.html" title="http::make_chunk_last">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost__beast__http__is_mutable_body_writer.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ref.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost__beast__http__make_chunk_last.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="beast.ref.boost__beast__http__make_chunk"></a><a class="link" href="boost__beast__http__make_chunk.html" title="http::make_chunk">http::make_chunk</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp121098752"></a>
Returns a <a class="link" href="boost__beast__http__chunk_body.html" title="http::chunk_body"><code class="computeroutput"><span class="identifier">http</span><span class="special">::</span><span class="identifier">chunk_body</span></code></a>.
</p>
<h5>
<a name="beast.ref.boost__beast__http__make_chunk.h0"></a>
<span class="phrase"><a name="beast.ref.boost__beast__http__make_chunk.synopsis"></a></span><a class="link" href="boost__beast__http__make_chunk.html#beast.ref.boost__beast__http__make_chunk.synopsis">Synopsis</a>
</h5>
<p>
Defined in header <code class="literal"><<a href="../../../../../../boost/beast/http/chunk_encode.hpp" target="_top">boost/beast/http/chunk_encode.hpp</a>></code>
</p>
<pre class="programlisting"><span class="keyword">template</span><span class="special"><</span>
<span class="keyword">class</span> <a href="../../../../../../doc/html/boost_asio/reference/ConstBufferSequence.html" target="_top"><span class="bold"><strong>ConstBufferSequence</strong></span></a><span class="special">,</span>
<span class="keyword">class</span><span class="special">...</span> <span class="identifier">Args</span><span class="special">></span>
<span class="keyword">auto</span>
<span class="identifier">make_chunk</span><span class="special">(</span>
<span class="identifier">ConstBufferSequence</span> <span class="keyword">const</span><span class="special">&</span> <span class="identifier">buffers</span><span class="special">,</span>
<span class="identifier">Args</span><span class="special">&&...</span> <span class="identifier">args</span><span class="special">);</span>
</pre>
<h5>
<a name="beast.ref.boost__beast__http__make_chunk.h1"></a>
<span class="phrase"><a name="beast.ref.boost__beast__http__make_chunk.description"></a></span><a class="link" href="boost__beast__http__make_chunk.html#beast.ref.boost__beast__http__make_chunk.description">Description</a>
</h5>
<p>
This functions constructs and returns a complete <a class="link" href="boost__beast__http__chunk_body.html" title="http::chunk_body"><code class="computeroutput"><span class="identifier">http</span><span class="special">::</span><span class="identifier">chunk_body</span></code></a> for a chunk body represented
by the specified buffer sequence.
</p>
<h5>
<a name="beast.ref.boost__beast__http__make_chunk.h2"></a>
<span class="phrase"><a name="beast.ref.boost__beast__http__make_chunk.parameters"></a></span><a class="link" href="boost__beast__http__make_chunk.html#beast.ref.boost__beast__http__make_chunk.parameters">Parameters</a>
</h5>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">buffers</span></code>
</p>
</td>
<td>
<p>
The buffers representing the chunk body.
</p>
</td>
</tr>
<tr>
<td>
<p>
<code class="computeroutput"><span class="identifier">args</span></code>
</p>
</td>
<td>
<p>
Optional arguments passed to the <span class="red">chunk_body</span>
constructor.
</p>
</td>
</tr>
</tbody>
</table></div>
<h5>
<a name="beast.ref.boost__beast__http__make_chunk.h3"></a>
<span class="phrase"><a name="beast.ref.boost__beast__http__make_chunk.remarks"></a></span><a class="link" href="boost__beast__http__make_chunk.html#beast.ref.boost__beast__http__make_chunk.remarks">Remarks</a>
</h5>
<p>
This function is provided as a notational convenience to omit specification
of the class template arguments.
</p>
<p>
Convenience header <code class="literal"><<a href="../../../../../../boost/beast/http.hpp" target="_top">boost/beast/http.hpp</a>></code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2016, 2017 Vinnie Falco<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost__beast__http__is_mutable_body_writer.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ref.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost__beast__http__make_chunk_last.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| nawawi/poedit | deps/boost/libs/beast/doc/html/beast/ref/boost__beast__http__make_chunk.html | HTML | mit | 7,389 |
package com.segment.analytics.internal.integrations;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import com.moe.pushlibrary.MoEHelper;
import com.moe.pushlibrary.utils.MoEHelperConstants;
import com.segment.analytics.Analytics;
import com.segment.analytics.AnalyticsContext;
import com.segment.analytics.Traits;
import com.segment.analytics.ValueMap;
import com.segment.analytics.internal.AbstractIntegration;
import com.segment.analytics.internal.model.payloads.IdentifyPayload;
import com.segment.analytics.internal.model.payloads.TrackPayload;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Set;
import static com.segment.analytics.internal.Utils.hasPermission;
/**
* MoEngage is an advanced mobile marketing and engagement tool which has a wide range of
* features. It helps user retention and increases churn.
*
* @see <a href="http://www.moengage.com/">MoEngage</a>
* @see <a href="https://segment.com/docs/integrations/moengage/">MoEngage Integration</a>
* @see <a href="http://docs.moengage.com/en/latest/android.html">MoEngage Android SDK</a>
*/
public class MoEngageIntegration extends AbstractIntegration<MoEHelper> {
private static final String KEY_MOENGAGE = "MoEngage";
MoEHelper helper;
private static final String ANONYMOUS_ID_KEY = "anonymousId";
private static final String EMAIL_KEY = "email";
private static final String USER_ID_KEY = "userId";
private static final String NAME_KEY = "name";
private static final String PHONE_KEY = "phone";
private static final String BIRTHDAY_KEY = "birthday";
private static final String FIRST_NAME_KEY = "firstName";
private static final String GENDER_KEY = "gender";
private static final String LAST_NAME_KEY = "lastName";
private static final String USER_ATTR_SEGMENT_AID = "USER_ATTRIBUTE_SEGMENT_ID";
@Override public void initialize(Analytics analytics, ValueMap settings)
throws IllegalStateException {
Context context = analytics.getApplication();
if (!hasPermission(context, "com.google.android.c2dm.permission.RECEIVE")) {
throw new IllegalStateException(
"MoEngage requires com.google.android.c2dm.permission.RECEIVE permission");
}
Analytics.LogLevel logLevel = analytics.getLogLevel();
if (logLevel == Analytics.LogLevel.VERBOSE || logLevel == Analytics.LogLevel.INFO) {
MoEHelper.APP_DEBUG = true;
}
}
@Override public String key() {
return KEY_MOENGAGE;
}
@Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
super.onActivityCreated(activity, savedInstanceState);
helper = new MoEHelper(activity);
if (null != savedInstanceState) {
helper.onRestoreInstanceState(savedInstanceState);
}
}
@Override public void onActivityStarted(Activity activity) {
super.onActivityStarted(activity);
helper.onStart(activity);
}
@Override public void onActivityResumed(Activity activity) {
super.onActivityResumed(activity);
helper.onResume(activity);
}
@Override public void onActivityPaused(Activity activity) {
super.onActivityPaused(activity);
helper.onPause(activity);
}
@Override public void onActivityStopped(Activity activity) {
super.onActivityStopped(activity);
helper.onStop(activity);
}
@Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
super.onActivitySaveInstanceState(activity, outState);
helper.onSaveInstanceState(outState);
}
@Override public void identify(IdentifyPayload identify) {
super.identify(identify);
Traits tr = identify.traits();
if (null != tr && !tr.isEmpty()) {
HashMap<String, Object> processedAttrs = new HashMap<String, Object>();
Set<String> keys = tr.keySet();
for (String key : keys) {
if (null != key) {
if (ANONYMOUS_ID_KEY.equals(key)) {
processedAttrs.put(USER_ATTR_SEGMENT_AID, tr.get(key));
} else if (EMAIL_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_EMAIL, tr.get(key));
} else if (USER_ID_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_UNIQUE_ID, tr.get(key));
} else if (NAME_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_NAME, tr.get(key));
} else if (PHONE_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_MOBILE, tr.get(key));
} else if (FIRST_NAME_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_FIRST_NAME, tr.get(key));
} else if (LAST_NAME_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_LAST_NAME, tr.get(key));
} else if (GENDER_KEY.equals(key)) {
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_GENDER, tr.get(key));
} else if (BIRTHDAY_KEY.equals(key)) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String birthDate = df.format(tr.birthday());
processedAttrs.put(MoEHelperConstants.USER_ATTRIBUTE_USER_BDAY, birthDate);
} else {
processedAttrs.put(key, tr.get(key));
}
} else if (MoEHelper.APP_DEBUG) {
Log.e(MoEHelper.TAG, "TRAIT KEY CANNOT BE NULL");
}
}
helper.setUserAttribute(processedAttrs);
}
AnalyticsContext.Location location = identify.context().location();
if (location != null) {
helper.setUserLocation(location.latitude(), location.longitude());
}
}
@Override public void track(TrackPayload track) {
super.track(track);
helper.trackEvent(track.event(), track.properties().toStringMap());
}
@Override public void reset() {
super.reset();
helper.logoutUser();
}
@Override public MoEHelper getUnderlyingInstance() {
return helper;
}
}
| happysir/analytics-android | analytics-integrations/moengage/src/main/java/com/segment/analytics/internal/integrations/MoEngageIntegration.java | Java | mit | 6,039 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Code Viewer</title>
<link id="codestyle" rel="stylesheet" type="text/css" href="../../../css/theme.css" media="all" />
<script type="text/javascript" src="../../../js/syntaxhighlighter.js"></script>
<style>
.syntaxhighlighter {
overflow-y: hidden !important;
}
</style>
</head>
<body>
<pre id="code" class="brush: csharp">import * as React from "react";
import { Component } from "react";
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import getMuiTheme from "material-ui/styles/getMuiTheme";
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import * as injectTapEventPlugin from "react-tap-event-plugin";
import { SelectableList } from "./SelectableList";
import Subheader from 'material-ui/Subheader';
import { ListItem } from "material-ui/List";
import * as objectAssign from 'object-assign';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import Paper from 'material-ui/Paper';
import AppBar from 'material-ui/AppBar';
import Badge from 'material-ui/Badge';
import { BootstrapTable, TableHeaderColumn, Options,SelectRow,SelectRowMode } from "react-bootstrap-table";
import "jquery";
import WarningIcon from 'material-ui/svg-icons/alert/warning';
import ErrorIcon from 'material-ui/svg-icons/alert/error';
import InfoIcon from 'material-ui/svg-icons/action/info';
import SettingsIcon from 'material-ui/svg-icons/action/settings';
import FilterListIcon from 'material-ui/svg-icons/content/filter-list';
import ArrowUpIcon from 'material-ui/svg-icons/navigation/arrow-drop-up';
import ArrowDownIcon from 'material-ui/svg-icons/navigation/arrow-drop-down';
import muiThemeable from 'material-ui/styles/muiThemeable';
import {MuiTheme} from 'material-ui/styles';
import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar';
import IconButton from 'material-ui/IconButton';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Popover from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import DropDownMenu from 'material-ui/DropDownMenu';
import {blue500, red500, green500, lime500} from 'material-ui/styles/colors';
import {IssueGroupByTypes, IInspectResultsSummary,IIssue,IIssueType,IOriginalData,IssueSeverity} from './CommonData';
import { IIssueBrowserState,IssueIconType,IGroup,IItem,IssueBrowserActionDispatcher,DiffMode} from './IssueBrowserReducer';
import {RouteComponentProps} from 'react-router-dom';
import * as querystring from 'query-string';
import {LocationDescriptorObject} from 'history';
export interface IIssueBrowserProps extends IIssueBrowserState,RouteComponentProps<any>
{
actions:IssueBrowserActionDispatcher;
hostWidth?:number;
hostHeight?:number;
selectedThermaId?:number;
muiThema?: MuiTheme;
}
class IssueBrowser extends Component<IIssueBrowserProps> {
constructor(props: IIssueBrowserProps) {
super(props);
this.expandComponent = this.expandComponent.bind(this);
this.formatIssuGroup = this.formatIssuGroup.bind(this);
this.createIssueTreeElement = this.createIssueTreeElement.bind(this);
this.createIssueGroupElement = this.createIssueGroupElement.bind(this);
this.createIssueElement = this.createIssueElement.bind(this);
this.createExpandComponent = this.createExpandComponent.bind(this);
var queyparameters = this.props.location.search
var revisionId = this.props.match.params.revid;
var issueId = this.props.match.params.issueid;
var parsed = querystring.parse(queyparameters);
var hideStr:string = "";
if(parsed.hidefilter !== undefined)
{
hideStr = parsed.hidefilter;
}
var diffMode:DiffMode = DiffMode.Normal;
if(parsed.diff !== undefined)
{
var diffStr:string = parsed.diff;
if(diffStr === "incresedFromPrevious")
{
diffMode = DiffMode.IncresedFromPrevious;
}
else if(diffStr === 'fixedFromPrevious')
{
diffMode = DiffMode.FixedFromPrevious;
}
else if(diffStr === 'incresedFromFirst')
{
diffMode = DiffMode.IncresedFromFirst;
}
else if(diffStr === 'fixedFromFirst')
{
diffMode = DiffMode.FixedFromFirst;
}
}
this.props.actions.getInitialData2(revisionId, diffMode, issueId, hideStr);
}
getCodePageUri():string
{
if(this.props.selectedRevision.id === "" || this.props.selectedIssue.file === "")
{
return "./empty.html"
}
var revisionDataToShow = this.props.selectedRevision;
if(this.props.diffMode === DiffMode.FixedFromFirst || this.props.diffMode === DiffMode.FixedFromPrevious)
{
revisionDataToShow = this.props.selectedDiffBaseRevision;
}
var result = `./revisions/${revisionDataToShow.id}/codes/`;
result += `${this.props.selectedIssue.file.replace(/\\/g, "_")}.html`;
result += `?line=${this.props.selectedIssue.line}`;
if(this.props.selectedThermaId === 1)
{
result += "&therma=dark";
}
return result;
}
toIconElement(icon: IssueIconType):any{
if(icon === IssueIconType.error)
{
return (<ErrorIcon color={red500}/>);
}
if(icon === IssueIconType.warning)
{
return (<WarningIcon color={lime500}/>);
}
if(icon === IssueIconType.suggestion)
{
return (<InfoIcon color={green500}/>);
}
if(icon === IssueIconType.hint)
{
return (<InfoIcon color={blue500}/>);
}
return (<span/>);
}
formatIssuGroup(cell:any, row:any):any {
var group = row as IGroup
return (<div>
<div style={{textAlign:"left" ,float:"left"}}>{this.toIconElement(group.icon)}{cell}</div>
<div style={{textAlign:"right"}}>
<Badge
badgeContent={group.badge}
style={{
marginRight:"12px" ,
paddingBottom: "0px"
}}
primary={true}/></div>
</div>);
}
expandComponent(row:any):any{
var isLargeData = row.items.length > 10;
return (
<BootstrapTable
data={ row.items }
striped
pagination={isLargeData}
selectRow={{
mode: 'radio',
bgColor: darkBaseTheme.palette.primary2Color,
hideSelectColumn: true,
clickToSelect: true,
onSelect: (row: any, isSelected: boolean, e: any)=>{
this.props.history.push(
this.createUri(this.props.selectedRevision.id,
row.id.replace("ISSUE_",""),
this.props.diffMode,
this.props.showErrorIssues,
this.props.showWarningIssues,
this.props.showSuggestionIssues,
this.props.showHintIssues));
this.props.actions.onSelectedIssue(row.id as string);
return false;
},
selected: [this.props.selectedIssueId]
}}
options={{
paginationPosition: 'top',
hideSizePerPage: true,
withFirstAndLast: false,
paginationPanel: this.createNavigationFactory(row.id, row.items.length),
page:row.pageNo,
pageStartIndex:1
} as Options}
>
<TableHeaderColumn isKey dataField='id' hidden>ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'></TableHeaderColumn>
</BootstrapTable>
);
}
createIssueElement(root:IGroup):any
{
var isLargeData = root.items.length > 10;
return (
<BootstrapTable
data={ root.items }
striped
pagination={isLargeData}
selectRow={{
mode: 'radio',
bgColor: darkBaseTheme.palette.primary2Color,
hideSelectColumn: true,
clickToSelect: true,
onSelect: (row: any, isSelected: boolean, e: any)=>{
this.props.history.push(
this.createUri(this.props.selectedRevision.id,
row.id.replace("ISSUE_",""),
this.props.diffMode,
this.props.showErrorIssues,
this.props.showWarningIssues,
this.props.showSuggestionIssues,
this.props.showHintIssues));
this.props.actions.onSelectedIssue(row.id as string);
return false;
},
selected: [this.props.selectedIssueId]
}}
options={{
paginationPosition: 'top',
hideSizePerPage: true,
withFirstAndLast: false,
paginationPanel: this.createNavigationFactory(root.id, root.items.length),
page:root.pageNo,
pageStartIndex:1
} as Options}
>
<TableHeaderColumn isKey dataField='id' hidden>ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'></TableHeaderColumn>
</BootstrapTable>
);
}
createIssueGroupElement(root: IGroup):any{
var isLargeData = root.subGroups.length > 10;
return (
<BootstrapTable
data={root.subGroups}
striped
expandableRow={ (row)=>true }
expandComponent={ this.createExpandComponent }
pagination={isLargeData}
options={{
paginationPosition: 'top',
paginationPanel: this.createNavigationFactory(root.id, root.subGroups.length),
page:root.pageNo,
pageStartIndex:1,
expanding: root.expandedChildren
} as Options}
selectRow={{
mode:'radio',
clickToSelect: true,
clickToExpand: true,
hideSelectColumn: true,
onSelect:(row: any, isSelected: boolean, e: any)=>{
this.props.actions.onSelectedIssueGroup(root, row);
return false;
}
} as SelectRow}
>
<TableHeaderColumn isKey dataField='id' hidden>ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' dataFormat={this.formatIssuGroup}></TableHeaderColumn>
</BootstrapTable>
);
}
createExpandComponent(target: IGroup)
{
if(target.subGroups.length > 0)
{
return this.createIssueGroupElement(target);
}
else
{
return this.createIssueElement(target);
}
}
createNavigationFactory(parentId:any, totalCount:number) : (props:any)=>any
{
let renderPaginationPanel = (props:any) => {
let curPageNo = props.currPage;
let pageStartIndex = props.pageStartIndex;
let sizePerPage = props.sizePerPage;
let totalPageCount = Math.ceil(totalCount / sizePerPage);
let navigationButtonStyle:any = {width:"36px", minWidth:"36px", margin:"4px"};
return (
<div>
<div>
<FlatButton
key={`${parentId}_page_0`}
style={navigationButtonStyle}
onTouchTap={ () => {
//props.changePage(1);
this.props.actions.onChangePage(parentId, 1);
} }>|&lt;</FlatButton>
{
Array.apply(null, {length: 5}).map((val:any,index:number)=>{
let pageNo = curPageNo + index-2;
let disabled = pageNo <= 0 || totalPageCount < pageNo;
return (
<FlatButton
backgroundColor={pageNo === curPageNo ? this.muiTheme.palette.primary1Color : "transparent"}
key={`${parentId}_page_${pageNo}`}
disabled={disabled }
style={navigationButtonStyle}
onTouchTap={ () => {
//props.changePage(pageNo);
this.props.actions.onChangePage(parentId, pageNo);
} }>{disabled?"-":pageNo}</FlatButton>);
})
}
<FlatButton
style={navigationButtonStyle}
onTouchTap={ () => {
//props.changePage(totalPageCount);
this.props.actions.onChangePage(parentId, totalPageCount);
} }>&gt;|</FlatButton>
</div>
</div>
);
}
return renderPaginationPanel;
}
createIssueTreeElement(root: IGroup):any{
return (
<BootstrapTable
data={root.subGroups}
striped
expandableRow={ (row)=>true }
expandComponent={ this.createExpandComponent }
maxHeight={(this.props.hostHeight-64-72-72-32) + "px"}
pagination
options={{
paginationPosition: 'top',
sizePerPage:10,
expanding: root.expandedChildren,
paginationPanel: this.createNavigationFactory(root.id, root.subGroups.length),
page:root.pageNo,
pageStartIndex:1
} as Options}
selectRow={{
mode:'radio',
clickToSelect: true,
clickToExpand: true,
hideSelectColumn: true,
onSelect:(row: any, isSelected: boolean, e: any)=>{
this.props.actions.onSelectedIssueGroup(root, row);
return false;
}
} as SelectRow}
>
<TableHeaderColumn isKey dataField='id' hidden>ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' dataFormat={this.formatIssuGroup}></TableHeaderColumn>
</BootstrapTable>
);
}
createUri(selectedRevisionId:string, issueId:string, diffMode:number, showError:boolean,showWarning:boolean,showSuggestion:boolean,showHint:boolean):LocationDescriptorObject{
var search="";
if(!showError){ search += 'error,'; }
if(!showWarning){ search += 'warning,'; }
if(!showSuggestion){ search += 'suggestion,'; }
if(!showHint){ search += 'hint,'; }
if(search !== "")
{
search = "?hidefilter="+search;
}
console.log(issueId);
return {
pathname:`/issues/${selectedRevisionId}/${issueId}`,
search:search
};
}
muiTheme:MuiTheme;
render() {
this.muiTheme = darkBaseTheme;
if(this.props.selectedThermaId === 0)
{
this.muiTheme = lightBaseTheme;
}
let activeToggleButtonStyle:any = {width:"36px", minWidth:"36px", margin:"4px",backgroundColor:this.muiTheme.palette.clockCircleColor};
let inactiveToggleButtonStyle:any = {width:"36px", minWidth:"36px", margin:"4px"};
return (
<div>
<div style={{float: "left", width: "40%", height: "100%"}}>
<Toolbar style={{backgroundColor:darkBaseTheme.palette.clockCircleColor}} >
<ToolbarGroup firstChild={true}>
<SelectField
floatingLabelText="Revisions"
value={this.props.selectedRevision.id}
onChange={(event:any, index:number, value:string)=>this.props.actions.onChangedRevision(index)}
style={{height:"72px"}}>
{this.props.revisions.revisionInfos.map(revision=>{
return (<MenuItem
key={"Revision_" + revision.id}
value={revision.id}
primaryText={revision.id}
rightAvatar={<Badge badgeContent={revision.issueCount} primary={true}/>} />)
})}
</SelectField>
</ToolbarGroup>
<ToolbarGroup>
<SelectField
floatingLabelText="Issues filter"
value={this.props.diffMode}
onChange={(event:any, index:number, value:number)=>this.props.actions.onChangeDiffMode(value)}
style={{height:"72px"}}
>
<MenuItem value={0} primaryText="All issues" />
<MenuItem value={1} primaryText="Incresed issues from previous revision" />
<MenuItem value={2} primaryText="Incresed issues from first revision" />
<MenuItem value={3} primaryText="Fixed issues from previous revision" />
<MenuItem value={4} primaryText="Fixed issues from first revision" />
</SelectField>
</ToolbarGroup>
</Toolbar>
<Toolbar style={{backgroundColor:darkBaseTheme.palette.clockCircleColor}}>
<ToolbarGroup firstChild={true}>
<SelectField
floatingLabelText="Issues Group By"
value={this.props.issuesGroupBy}
onChange={(event:any, index:number, value:number)=>{
this.props.actions.onChangeIssuesGroupBy(value);
}}
style={{height:"72px"}}
>
<MenuItem value={1} primaryText="Directory and File" />
<MenuItem value={2} primaryText="Issue Type" />
<MenuItem value={3} primaryText="Issue Category" />
</SelectField>
<FlatButton
style={this.props.showErrorIssues?activeToggleButtonStyle:inactiveToggleButtonStyle}
icon={<ErrorIcon color={red500}/>}
onTouchTap={()=>{
this.props.history.replace(
this.createUri(this.props.selectedRevision.id,
this.props.selectedIssue.id,
this.props.diffMode,
!this.props.showErrorIssues,
this.props.showWarningIssues,
this.props.showSuggestionIssues,
this.props.showHintIssues));
this.props.actions.onToggleShowErrorIssues();
}}/>
<FlatButton
style={this.props.showWarningIssues?activeToggleButtonStyle:inactiveToggleButtonStyle}
icon={<WarningIcon color={lime500}/>}
onTouchTap={()=>{
this.props.history.replace(
this.createUri(this.props.selectedRevision.id,
this.props.selectedIssue.id,
this.props.diffMode,
this.props.showErrorIssues,
!this.props.showWarningIssues,
this.props.showSuggestionIssues,
this.props.showHintIssues));
this.props.actions.onToggleShowWarningIssues();
}}/>
<FlatButton
style={this.props.showSuggestionIssues?activeToggleButtonStyle:inactiveToggleButtonStyle}
icon={<InfoIcon color={green500}/>}
onTouchTap={()=>{
this.props.history.replace(
this.createUri(this.props.selectedRevision.id,
this.props.selectedIssue.id,
this.props.diffMode,
this.props.showErrorIssues,
this.props.showWarningIssues,
!this.props.showSuggestionIssues,
this.props.showHintIssues));
this.props.actions.onToggleShowSuggestionIssues();
}}/>
<FlatButton
style={this.props.showHintIssues?activeToggleButtonStyle:inactiveToggleButtonStyle}
icon={<InfoIcon color={blue500}/>}
onTouchTap={()=>{
this.props.history.replace(
this.createUri(this.props.selectedRevision.id,
this.props.selectedIssue.id,
this.props.diffMode,
this.props.showErrorIssues,
this.props.showWarningIssues,
this.props.showSuggestionIssues,
!this.props.showHintIssues));
this.props.actions.onToggleShowHintIssues();
}}/>
</ToolbarGroup>
<ToolbarGroup>
<IconButton onTouchTap={()=>{this.props.actions.onMovePreviousIssue();}}>
<ArrowUpIcon />
</IconButton>
<IconButton onTouchTap={()=>{this.props.actions.onMoveNextIssue();}}>
<ArrowDownIcon />
</IconButton>
</ToolbarGroup>
</Toolbar>
{/*<SelectField
floatingLabelText="Diff Base Rev"
value={this.props.selectedDiffBaseRevision.id}
onChange={(event:any, index:number, value:string)=>this.props.actions.onChangedDiffBaseRevision(index)}
fullWidth
style={{height:"72px"}}>
{this.props.revisions.revisionInfos.map(revision=>{
return (<MenuItem
key={"Revision_" + revision.id}
value={revision.id}
primaryText={revision.caption}
rightAvatar={<Badge badgeContent={revision.issueCount} primary={true}/>} />)
})}
</SelectField>*/}
<div style={{height:(this.props.hostHeight-64-72-72) + "px"}}>
{this.createIssueTreeElement(this.props.tree)}
</div>
</div>
<div style={{float: "none", width: "auto", marginLeft: "40%",height:`${this.props.hostHeight - 64}px`}}>
<iframe src={this.getCodePageUri()} // ReSharper ignore TsResolvedFromInaccessibleModule
width="100%"
//height={this.props.hostHeight - 64 - 100}
style={{
height:`calc(${this.props.hostHeight - 64}px - 12em)`,
display:"initial",
position:"relative"
}}
allowFullScreen />
<div style={{height:"12em", float:"bottom"}}>
<Paper>
Id:{this.props.selectedIssue.id}<br/>
Message:{this.props.selectedIssue.message}<br/>
Project:{this.props.selectedIssue.project}<br/>
File:{this.props.selectedIssue.file} ({this.props.selectedIssue.line}:{this.props.selectedIssue.column})<br/>
Url:<a target="_blank" href={this.props.selectedIssueType.wikiUrl}>{this.props.selectedIssueType.wikiUrl}</a><br/>
</Paper>
</div>
</div>
</div>
);
}
mode:number = 0;
}
export default muiThemeable()(IssueBrowser);
</pre>
<script type="text/javascript" src="../../../js/code.js">
</script>
</body>
</html> | banban525/InspectCodeViewer | demo/revisions/00035/codes/src_js_IssueBrowser.tsx.html | HTML | mit | 24,752 |
#ifndef ISL_LIST_PRIVATE_H
#define ISL_LIST_PRIVATE_H
#include <isl/list.h>
#undef EL
#define EL isl_constraint
#include <isl_list_templ.h>
#undef EL
#define EL isl_basic_set
#include <isl_list_templ.h>
#undef EL
#define EL isl_set
#include <isl_list_templ.h>
#undef EL
#define EL isl_aff
#include <isl_list_templ.h>
#undef EL
#define EL isl_pw_aff
#include <isl_list_templ.h>
#undef EL
#define EL isl_band
#include <isl_list_templ.h>
#undef EL
#define EL isl_id
#include <isl_list_templ.h>
#endif
| pierrotdelalune/isl | isl_list_private.h | C | mit | 514 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class DiagnosticAnalyzerService : IDiagnosticUpdateSource
{
public event EventHandler<DiagnosticsUpdatedArgs> DiagnosticsUpdated
{
add
{
_eventMap.AddEventHandler(DiagnosticsUpdatedEventName, value);
}
remove
{
_eventMap.RemoveEventHandler(DiagnosticsUpdatedEventName, value);
}
}
public event EventHandler DiagnosticsCleared
{
add
{
// don't do anything. this update source doesn't use cleared event
}
remove
{
// don't do anything. this update source doesn't use cleared event
}
}
internal void RaiseDiagnosticsUpdated(DiagnosticsUpdatedArgs args)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => ev.RaiseEvent(handler => handler(this, args)), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Action<Action<DiagnosticsUpdatedArgs>> eventAction)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventAction(raiseEvents), CancellationToken.None);
}
}
internal void RaiseBulkDiagnosticsUpdated(Func<Action<DiagnosticsUpdatedArgs>, Task> eventActionAsync)
{
// all diagnostics events are serialized.
var ev = _eventMap.GetEventHandlers<EventHandler<DiagnosticsUpdatedArgs>>(DiagnosticsUpdatedEventName);
if (ev.HasHandlers)
{
// we do this bulk update to reduce number of tasks (with captured data) enqueued.
// we saw some "out of memory" due to us having long list of pending tasks in memory.
// this is to reduce for such case to happen.
void raiseEvents(DiagnosticsUpdatedArgs args) => ev.RaiseEvent(handler => handler(this, args));
_eventQueue.ScheduleTask(nameof(RaiseDiagnosticsUpdated), () => eventActionAsync(raiseEvents), CancellationToken.None);
}
}
bool IDiagnosticUpdateSource.SupportGetDiagnostics => true;
ImmutableArray<DiagnosticData> IDiagnosticUpdateSource.GetDiagnostics(Workspace workspace, ProjectId projectId, DocumentId documentId, object id, bool includeSuppressedDiagnostics, CancellationToken cancellationToken)
{
if (id != null)
{
return GetSpecificCachedDiagnosticsAsync(workspace, id, includeSuppressedDiagnostics, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
return GetCachedDiagnosticsAsync(workspace, projectId, documentId, includeSuppressedDiagnostics, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken);
}
}
}
| genlu/roslyn | src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_UpdateSource.cs | C# | mit | 4,108 |
Tag {autotrim}
==============
Force enable or disable `auto_trim` option for block area:
```smarty
{autotrim true}
...
Text: {$text} {* value of the variable $text will be escaped *}
...
{/autotrim}
```
Also see :trim, :rtrim and :ltrim tag options | morfy-cms/morfy.org | vendor/fenom/fenom/docs/en/tags/autotrim.md | Markdown | mit | 263 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.Network;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Outbound NAT pool of the load balancer.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class OutboundNatRule : SubResource
{
/// <summary>
/// Initializes a new instance of the OutboundNatRule class.
/// </summary>
public OutboundNatRule()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the OutboundNatRule class.
/// </summary>
/// <param name="backendAddressPool">A reference to a pool of DIPs.
/// Outbound traffic is randomly load balanced across IPs in the
/// backend IPs.</param>
/// <param name="id">Resource ID.</param>
/// <param name="allocatedOutboundPorts">The number of outbound ports
/// to be used for NAT.</param>
/// <param name="frontendIPConfigurations">The Frontend IP addresses of
/// the load balancer.</param>
/// <param name="provisioningState">Gets the provisioning state of the
/// PublicIP resource. Possible values are: 'Updating', 'Deleting', and
/// 'Failed'.</param>
/// <param name="name">The name of the resource that is unique within a
/// resource group. This name can be used to access the
/// resource.</param>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
public OutboundNatRule(SubResource backendAddressPool, string id = default(string), int? allocatedOutboundPorts = default(int?), IList<SubResource> frontendIPConfigurations = default(IList<SubResource>), string provisioningState = default(string), string name = default(string), string etag = default(string))
: base(id)
{
AllocatedOutboundPorts = allocatedOutboundPorts;
FrontendIPConfigurations = frontendIPConfigurations;
BackendAddressPool = backendAddressPool;
ProvisioningState = provisioningState;
Name = name;
Etag = etag;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the number of outbound ports to be used for NAT.
/// </summary>
[JsonProperty(PropertyName = "properties.allocatedOutboundPorts")]
public int? AllocatedOutboundPorts { get; set; }
/// <summary>
/// Gets or sets the Frontend IP addresses of the load balancer.
/// </summary>
[JsonProperty(PropertyName = "properties.frontendIPConfigurations")]
public IList<SubResource> FrontendIPConfigurations { get; set; }
/// <summary>
/// Gets or sets a reference to a pool of DIPs. Outbound traffic is
/// randomly load balanced across IPs in the backend IPs.
/// </summary>
[JsonProperty(PropertyName = "properties.backendAddressPool")]
public SubResource BackendAddressPool { get; set; }
/// <summary>
/// Gets the provisioning state of the PublicIP resource. Possible
/// values are: 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public string ProvisioningState { get; set; }
/// <summary>
/// Gets or sets the name of the resource that is unique within a
/// resource group. This name can be used to access the resource.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets a unique read-only string that changes whenever the
/// resource is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (BackendAddressPool == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "BackendAddressPool");
}
}
}
}
| nathannfan/azure-sdk-for-net | src/SDKs/Network/Management.Network/Generated/Models/OutboundNatRule.cs | C# | mit | 5,056 |
/* mdb_dump.c - memory-mapped database dump tool */
/*
* Copyright 2011-2017 Howard Chu, Symas Corp.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted only as authorized by the OpenLDAP
* Public License.
*
* A copy of this license is available in the file LICENSE in the
* top-level directory of the distribution or, alternatively, at
* <http://www.OpenLDAP.org/license.html>.
*/
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <signal.h>
#include "lmdb.h"
#define Yu MDB_PRIy(u)
#define PRINT 1
static int mode;
typedef struct flagbit {
int bit;
char *name;
} flagbit;
flagbit dbflags[] = {
{ MDB_REVERSEKEY, "reversekey" },
{ MDB_DUPSORT, "dupsort" },
{ MDB_INTEGERKEY, "integerkey" },
{ MDB_DUPFIXED, "dupfixed" },
{ MDB_INTEGERDUP, "integerdup" },
{ MDB_REVERSEDUP, "reversedup" },
{ 0, NULL }
};
static volatile sig_atomic_t gotsig;
static void dumpsig( int sig )
{
gotsig=1;
}
static const char hexc[] = "0123456789abcdef";
static void hex(unsigned char c)
{
putchar(hexc[c >> 4]);
putchar(hexc[c & 0xf]);
}
static void text(MDB_val *v)
{
unsigned char *c, *end;
putchar(' ');
c = v->mv_data;
end = c + v->mv_size;
while (c < end) {
if (isprint(*c)) {
putchar(*c);
} else {
putchar('\\');
hex(*c);
}
c++;
}
putchar('\n');
}
static void byte(MDB_val *v)
{
unsigned char *c, *end;
putchar(' ');
c = v->mv_data;
end = c + v->mv_size;
while (c < end) {
hex(*c++);
}
putchar('\n');
}
/* Dump in BDB-compatible format */
static int dumpit(MDB_txn *txn, MDB_dbi dbi, char *name)
{
MDB_cursor *mc;
MDB_stat ms;
MDB_val key, data;
MDB_envinfo info;
unsigned int flags;
int rc, i;
rc = mdb_dbi_flags(txn, dbi, &flags);
if (rc) return rc;
rc = mdb_stat(txn, dbi, &ms);
if (rc) return rc;
rc = mdb_env_info(mdb_txn_env(txn), &info);
if (rc) return rc;
printf("VERSION=3\n");
printf("format=%s\n", mode & PRINT ? "print" : "bytevalue");
if (name)
printf("database=%s\n", name);
printf("type=btree\n");
printf("mapsize=%"Yu"\n", info.me_mapsize);
if (info.me_mapaddr)
printf("mapaddr=%p\n", info.me_mapaddr);
printf("maxreaders=%u\n", info.me_maxreaders);
if (flags & MDB_DUPSORT)
printf("duplicates=1\n");
for (i=0; dbflags[i].bit; i++)
if (flags & dbflags[i].bit)
printf("%s=1\n", dbflags[i].name);
printf("db_pagesize=%d\n", ms.ms_psize);
printf("HEADER=END\n");
rc = mdb_cursor_open(txn, dbi, &mc);
if (rc) return rc;
while ((rc = mdb_cursor_get(mc, &key, &data, MDB_NEXT) == MDB_SUCCESS)) {
if (gotsig) {
rc = EINTR;
break;
}
if (mode & PRINT) {
text(&key);
text(&data);
} else {
byte(&key);
byte(&data);
}
}
printf("DATA=END\n");
if (rc == MDB_NOTFOUND)
rc = MDB_SUCCESS;
return rc;
}
static void usage(char *prog)
{
fprintf(stderr, "usage: %s [-V] [-f output] [-l] [-n] [-p] [-a|-s subdb] dbpath\n", prog);
exit(EXIT_FAILURE);
}
int main(int argc, char *argv[])
{
int i, rc;
MDB_env *env;
MDB_txn *txn;
MDB_dbi dbi;
char *prog = argv[0];
char *envname;
char *subname = NULL;
int alldbs = 0, envflags = 0, list = 0;
if (argc < 2) {
usage(prog);
}
/* -a: dump main DB and all subDBs
* -s: dump only the named subDB
* -n: use NOSUBDIR flag on env_open
* -p: use printable characters
* -f: write to file instead of stdout
* -V: print version and exit
* (default) dump only the main DB
*/
while ((i = getopt(argc, argv, "af:lnps:V")) != EOF) {
switch(i) {
case 'V':
printf("%s\n", MDB_VERSION_STRING);
exit(0);
break;
case 'l':
list = 1;
/*FALLTHROUGH*/;
case 'a':
if (subname)
usage(prog);
alldbs++;
break;
case 'f':
if (freopen(optarg, "w", stdout) == NULL) {
fprintf(stderr, "%s: %s: reopen: %s\n",
prog, optarg, strerror(errno));
exit(EXIT_FAILURE);
}
break;
case 'n':
envflags |= MDB_NOSUBDIR;
break;
case 'p':
mode |= PRINT;
break;
case 's':
if (alldbs)
usage(prog);
subname = optarg;
break;
default:
usage(prog);
}
}
if (optind != argc - 1)
usage(prog);
#ifdef SIGPIPE
signal(SIGPIPE, dumpsig);
#endif
#ifdef SIGHUP
signal(SIGHUP, dumpsig);
#endif
signal(SIGINT, dumpsig);
signal(SIGTERM, dumpsig);
envname = argv[optind];
rc = mdb_env_create(&env);
if (rc) {
fprintf(stderr, "mdb_env_create failed, error %d %s\n", rc, mdb_strerror(rc));
return EXIT_FAILURE;
}
if (alldbs || subname) {
mdb_env_set_maxdbs(env, 2);
}
rc = mdb_env_open(env, envname, envflags | MDB_RDONLY, 0664);
if (rc) {
fprintf(stderr, "mdb_env_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_txn_begin(env, NULL, MDB_RDONLY, &txn);
if (rc) {
fprintf(stderr, "mdb_txn_begin failed, error %d %s\n", rc, mdb_strerror(rc));
goto env_close;
}
rc = mdb_open(txn, subname, 0, &dbi);
if (rc) {
fprintf(stderr, "mdb_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
if (alldbs) {
MDB_cursor *cursor;
MDB_val key;
int count = 0;
rc = mdb_cursor_open(txn, dbi, &cursor);
if (rc) {
fprintf(stderr, "mdb_cursor_open failed, error %d %s\n", rc, mdb_strerror(rc));
goto txn_abort;
}
while ((rc = mdb_cursor_get(cursor, &key, NULL, MDB_NEXT_NODUP)) == 0) {
char *str;
MDB_dbi db2;
if (memchr(key.mv_data, '\0', key.mv_size))
continue;
count++;
str = malloc(key.mv_size+1);
memcpy(str, key.mv_data, key.mv_size);
str[key.mv_size] = '\0';
rc = mdb_open(txn, str, 0, &db2);
if (rc == MDB_SUCCESS) {
if (list) {
printf("%s\n", str);
list++;
} else {
rc = dumpit(txn, db2, str);
if (rc)
break;
}
mdb_close(env, db2);
}
free(str);
if (rc) continue;
}
mdb_cursor_close(cursor);
if (!count) {
fprintf(stderr, "%s: %s does not contain multiple databases\n", prog, envname);
rc = MDB_NOTFOUND;
} else if (rc == MDB_NOTFOUND) {
rc = MDB_SUCCESS;
}
} else {
rc = dumpit(txn, dbi, subname);
}
if (rc && rc != MDB_NOTFOUND)
fprintf(stderr, "%s: %s: %s\n", prog, envname, mdb_strerror(rc));
mdb_close(env, dbi);
txn_abort:
mdb_txn_abort(txn);
env_close:
mdb_env_close(env);
return rc ? EXIT_FAILURE : EXIT_SUCCESS;
}
| bobek-balinek/BlueJet | vendor/lmdb/libraries/liblmdb/mdb_dump.c | C | mit | 6,327 |
// Copyright (c) 2012 DotNetAnywhere
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if !defined(__GENERICS_H)
#define __GENERICS_H
typedef struct tGenericInstance_ tGenericInstance;
typedef struct tGenericMethodInstance_ tGenericMethodInstance;
#include "Types.h"
#include "MetaData.h"
struct tGenericInstance_ {
// The tMD_TypeDef for this instance of this generic type
tMD_TypeDef *pInstanceTypeDef;
// The next instantiation of this generic type
tGenericInstance *pNext;
// The number of type arguments for this instance
U32 numTypeArgs;
// The type arguments for this instantiation
tMD_TypeDef *pTypeArgs[0];
};
struct tGenericMethodInstance_ {
// This instance method.
tMD_MethodDef *pInstanceMethodDef;
// The next instantiation of this generic method
tGenericMethodInstance *pNext;
// The number of type arguments for this instance
U32 numTypeArgs;
// The method type arguments for this instance
tMD_TypeDef *pTypeArgs[0];
};
void Generic_GetHeapRoots(tHeapRoots *pHeapRoots, tMD_TypeDef *pTypeDef);
tMD_TypeDef* Generics_GetGenericTypeFromSig(tMetaData *pMetaData, SIG *pSig, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppCallingMethodTypeArgs);
tMD_TypeDef* Generics_GetGenericTypeFromCoreType(tMD_TypeDef *pCoreType, U32 numArgs, tMD_TypeDef **ppTypeArgs);//, tMD_TypeDef **ppClassTypeArgs, tMD_TypeDef **ppMethodTypeArgs);
tMD_MethodDef* Generics_GetMethodDefFromSpec(tMD_MethodSpec *pMethodSpec, tMD_TypeDef **ppCallingClassTypeArgs, tMD_TypeDef **ppCallingMethodTypeArgs);
tMD_MethodDef* Generics_GetMethodDefFromCoreMethod(tMD_MethodDef *pCoreMethod, tMD_TypeDef *pParentType, U32 numMethodTypeArgs, tMD_TypeDef **ppMethodTypeArgs);
#endif | ncave/dotnet-js | src/DNA/native/src/Generics.h | C | mit | 2,713 |
/* global module:false */
module.exports = function(grunt) {
var port = grunt.option('port') || 8000;
// Project configuration
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner:
'/*!\n' +
' * reveal.js <%= pkg.version %> (<%= grunt.template.today("yyyy-mm-dd, HH:MM") %>)\n' +
' * http://lab.hakim.se/reveal-js\n' +
' * MIT licensed\n' +
' *\n' +
' * Copyright (C) 2014 Hakim El Hattab, http://hakim.se\n' +
' */'
},
qunit: {
files: [ 'test/*.html' ]
},
uglify: {
options: {
banner: '<%= meta.banner %>\n'
},
build: {
src: 'src/js/reveal.js',
dest: 'dist/js/reveal.min.js'
}
},
sass: {
main: {
files: {
'dist/css/reveal.css': 'src/css/theme/reveal.scss',
'dist/css/default.css': 'src/css/theme/source/default.scss',
'dist/css/gdicool.css': 'src/css/theme/source/gdicool.scss',
'dist/css/gdilight.css': 'src/css/theme/source/gdilight.scss',
'dist/css/gdisunny.css': 'src/css/theme/source/gdisunny.scss'
}
}
},
postcss: {
options: {
map: true,
processors: [
require('autoprefixer')({browsers: 'last 2 versions'}),
require('cssnano')()
]
},
dist: {
src: 'dist/css/*.css'
}
},
jshint: {
options: {
curly: false,
eqeqeq: true,
immed: true,
latedef: true,
newcap: true,
node: true,
noarg: true,
sub: true,
undef: true,
eqnull: true,
browser: true,
expr: true,
globals: {
head: false,
module: false,
console: false,
unescape: false
}
},
files: [ 'Gruntfile.js' ]
},
connect: {
server: {
options: {
port: port,
base: '.'
}
}
},
zip: {
'reveal-js-presentation.zip': [
'index.html',
'src/css/**',
'js/**',
'dist/**',
'images/**',
'plugin/**'
]
},
watch: {
main: {
files: [ 'Gruntfile.js', 'src/js/reveal.js', 'src/css/theme/reveal.scss' ],
tasks: 'default'
},
theme: {
files: [ 'src/css/theme/source/*.scss', 'src/css/theme/template/*.scss' ],
tasks: 'themes'
}
},
browserSync: {
bsFiles: {
src : [
'dist/css/**/*.css',
'*.html'
]
},
options: {
watchTask: true,
server: './'
}
}
});
// Dependencies
grunt.loadNpmTasks( 'grunt-contrib-qunit' );
grunt.loadNpmTasks( 'grunt-contrib-jshint' );
grunt.loadNpmTasks( 'grunt-contrib-uglify' );
grunt.loadNpmTasks( 'grunt-contrib-watch' );
grunt.loadNpmTasks( 'grunt-contrib-sass' );
grunt.loadNpmTasks( 'grunt-browser-sync' );
grunt.loadNpmTasks( 'grunt-postcss' );
grunt.loadNpmTasks( 'grunt-zip' );
// Default task
grunt.registerTask( 'default', [ 'jshint', 'sass', 'postcss', 'uglify', 'qunit', 'browserSync', 'watch' ] );
// Theme task
grunt.registerTask( 'themes', [ 'sass' ] );
// Package presentation to archive
grunt.registerTask( 'package', [ 'default', 'zip' ] );
// Run tests
grunt.registerTask( 'test', [ 'jshint', 'qunit' ] );
};
| mbura/intro_to_salesforce | Gruntfile.js | JavaScript | mit | 4,201 |
<?php
/*
* This file is part of the Symfony framework.
*
* (c) Fabien Potencier <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Symfony\Tests\Component\Security\Http;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\HttpUtils;
class HttpUtilsTest extends \PHPUnit_Framework_TestCase
{
public function testCreateRedirectResponse()
{
$utils = new HttpUtils($this->getRouter());
// absolute path
$response = $utils->createRedirectResponse($this->getRequest(), '/foobar');
$this->assertTrue($response->isRedirect('http://localhost/foobar'));
$this->assertEquals(302, $response->getStatusCode());
// absolute URL
$response = $utils->createRedirectResponse($this->getRequest(), 'http://symfony.com/');
$this->assertTrue($response->isRedirect('http://symfony.com/'));
// route name
$utils = new HttpUtils($router = $this->getMockBuilder('Symfony\Component\Routing\Router')->disableOriginalConstructor()->getMock());
$router
->expects($this->any())
->method('generate')
->with('foobar', array(), true)
->will($this->returnValue('http://localhost/foo/bar'))
;
$router
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMock('Symfony\Component\Routing\RequestContext')))
;
$response = $utils->createRedirectResponse($this->getRequest(), 'foobar');
$this->assertTrue($response->isRedirect('http://localhost/foo/bar'));
}
public function testCreateRequest()
{
$utils = new HttpUtils($this->getRouter());
// absolute path
$request = $this->getRequest();
$request->server->set('Foo', 'bar');
$subRequest = $utils->createRequest($request, '/foobar');
$this->assertEquals('GET', $subRequest->getMethod());
$this->assertEquals('/foobar', $subRequest->getPathInfo());
$this->assertEquals('bar', $subRequest->server->get('Foo'));
// route name
$utils = new HttpUtils($router = $this->getMockBuilder('Symfony\Component\Routing\Router')->disableOriginalConstructor()->getMock());
$router
->expects($this->once())
->method('generate')
->will($this->returnValue('/foo/bar'))
;
$router
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMock('Symfony\Component\Routing\RequestContext')))
;
$subRequest = $utils->createRequest($this->getRequest(), 'foobar');
$this->assertEquals('/foo/bar', $subRequest->getPathInfo());
// absolute URL
$subRequest = $utils->createRequest($this->getRequest(), 'http://symfony.com/');
$this->assertEquals('/', $subRequest->getPathInfo());
}
public function testCheckRequestPath()
{
$utils = new HttpUtils($this->getRouter());
$this->assertTrue($utils->checkRequestPath($this->getRequest(), '/'));
$this->assertFalse($utils->checkRequestPath($this->getRequest(), '/foo'));
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->any())
->method('match')
->will($this->returnValue(array()))
;
$utils = new HttpUtils($router);
$this->assertFalse($utils->checkRequestPath($this->getRequest(), 'foobar'));
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->any())
->method('match')
->will($this->returnValue(array('_route' => 'foobar')))
;
$utils = new HttpUtils($router);
$this->assertTrue($utils->checkRequestPath($this->getRequest('/foo/bar'), 'foobar'));
}
private function getRouter()
{
$router = $this->getMock('Symfony\Component\Routing\RouterInterface');
$router
->expects($this->any())
->method('generate')
->will($this->returnValue('/foo/bar'))
;
return $router;
}
private function getRequest($path = '/')
{
return Request::create($path, 'get');
}
}
| VelvetMirror/padel | vendor/symfony/tests/Symfony/Tests/Component/Security/Http/HttpUtilsTest.php | PHP | mit | 4,463 |
class Fry < Coder
def initialize
@name = 'Fry'
@salary = 1000
end
def work(remain_difficulty)
state = rand(10)
if state > 3 && state < 9
forward = rand(100...500)
puts "#{name}完全不会Ruby,照猫画虎,侥幸将项目推进#{forward}"
remain_difficulty - forward
elsif state >= 9
surprise = rand(10)
if surprise >= 9
forward = rand(800...1000)
puts "#{name}完全不会Ruby,照猫画猫出现暴击,风一般的将项目推进#{forward}, 并且用Ruby重写了喵歌搜索"
elsif
forward = rand(500...600)
puts "#{name}完全不会Ruby,照猫画猫,非常走运的将项目推进#{forward}"
end
remain_difficulty - forward
else
bugs = rand(1...5)
fallback = bugs * rand(0...50)
puts "#{name}完全不会Ruby, 照虎画猫,引入了#{bugs}个BUG, 项目难度增加#{fallback}"
remain_difficulty + fallback
end
end
def pay(company_money)
puts "#{name}领取了#{salary}元薪水, 然而买了一本Ruby入门指南。"
company_money - salary
end
end | gupenghu/Startup-Game | coders/fry.rb | Ruby | mit | 1,121 |
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) keys.push(key);
return keys;
}
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method])
Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex))
return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false)
this.readable = false;
if (options && options.writable === false)
this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false)
this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended)
return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
| Hokua/Overture.Views | node_modules/less/node_modules/request/node_modules/bl/node_modules/readable-stream/lib/_stream_duplex.js | JavaScript | mit | 1,955 |
package seedu.address.commons.events.model;
import seedu.address.commons.events.BaseEvent;
import seedu.address.model.ReadOnlyAddressBook;
/** Indicates the AddressBook in the model has changed*/
public class AddressBookChangedEvent extends BaseEvent {
public final ReadOnlyAddressBook data;
public AddressBookChangedEvent(ReadOnlyAddressBook data) {
this.data = data;
}
@Override
public String toString() {
return "number of persons " + data.getPersonList().size() + ", number of tags " + data.getTagList().size();
}
}
| edmundmok/addressbook-level4 | src/main/java/seedu/address/commons/events/model/AddressBookChangedEvent.java | Java | mit | 565 |
#!/bin/bash
FN="pd.2006.10.31.rn34.refseq.promoter_0.99.3.tar.gz"
URLS=(
"https://bioconductor.org/packages/3.13/data/annotation/src/contrib/pd.2006.10.31.rn34.refseq.promoter_0.99.3.tar.gz"
"https://bioarchive.galaxyproject.org/pd.2006.10.31.rn34.refseq.promoter_0.99.3.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-pd.2006.10.31.rn34.refseq.promoter/bioconductor-pd.2006.10.31.rn34.refseq.promoter_0.99.3_src_all.tar.gz"
"https://depot.galaxyproject.org/software/bioconductor-pd.2006.10.31.rn34.refseq.promoter/bioconductor-pd.2006.10.31.rn34.refseq.promoter_0.99.3_src_all.tar.gz"
)
MD5="ab5bb767ad29b213e5a969a5fc51ee7d"
# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN
SUCCESS=0
for URL in ${URLS[@]}; do
curl $URL > $TARBALL
[[ $? == 0 ]] || continue
# Platform-specific md5sum checks.
if [[ $(uname -s) == "Linux" ]]; then
if md5sum -c <<<"$MD5 $TARBALL"; then
SUCCESS=1
break
fi
else if [[ $(uname -s) == "Darwin" ]]; then
if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
SUCCESS=1
break
fi
fi
fi
done
if [[ $SUCCESS != 1 ]]; then
echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
printf '%s\n' "${URLS[@]}"
exit 1
fi
# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING
| phac-nml/bioconda-recipes | recipes/bioconductor-pd.2006.10.31.rn34.refseq.promoter/post-link.sh | Shell | mit | 1,585 |
/**
* https://github.com/facebook/react-native/blob/master/Libraries/Animated/src/SpringConfig.js
*/
function tensionFromOrigamiValue(oValue) {
return (oValue - 30) * 3.62 + 194;
}
function frictionFromOrigamiValue(oValue) {
return (oValue - 8) * 3 + 25;
}
function fromOrigamiTensionAndFriction(tension, friction) {
return {
tension: tensionFromOrigamiValue(tension),
friction: frictionFromOrigamiValue(friction)
};
}
function fromBouncinessAndSpeed(bounciness, speed) {
function normalize(value, startValue, endValue) {
return (value - startValue) / (endValue - startValue);
}
function projectNormal(n, start, end) {
return start + (n * (end - start));
}
function linearInterpolation(t, start, end) {
return t * end + (1 - t) * start;
}
function quadraticOutInterpolation(t, start, end) {
return linearInterpolation(2 * t - t * t, start, end);
}
function b3Friction1(x) {
return (0.0007 * Math.pow(x, 3)) -
(0.031 * Math.pow(x, 2)) + 0.64 * x + 1.28;
}
function b3Friction2(x) {
return (0.000044 * Math.pow(x, 3)) -
(0.006 * Math.pow(x, 2)) + 0.36 * x + 2;
}
function b3Friction3(x) {
return (0.00000045 * Math.pow(x, 3)) -
(0.000332 * Math.pow(x, 2)) + 0.1078 * x + 5.84;
}
function b3Nobounce(tension) {
if (tension <= 18) {
return b3Friction1(tension);
} else if (tension > 18 && tension <= 44) {
return b3Friction2(tension);
}
return b3Friction3(tension);
}
let b = normalize(bounciness / 1.7, 0, 20);
b = projectNormal(b, 0, 0.8);
const s = normalize(speed / 1.7, 0, 20);
const bouncyTension = projectNormal(s, 0.5, 200);
const bouncyFriction = quadraticOutInterpolation(
b,
b3Nobounce(bouncyTension),
0.01
);
return {
tension: tensionFromOrigamiValue(bouncyTension),
friction: frictionFromOrigamiValue(bouncyFriction)
};
}
module.exports = {
fromOrigamiTensionAndFriction,
fromBouncinessAndSpeed,
};
| Root-App/react-native-mock-render | src/api/Animated/SpringConfig.js | JavaScript | mit | 1,986 |
<!DOCTYPE html>
<html>
<title>{{ code }} {{ name|e }}</title>
<h1>{{ name|e }}</h1>
{{ description }}
</html>
| yosukesuzuki/kay-template | project/kay/_internal/templates/defaulterror.html | HTML | mit | 115 |
/*
* rational numbers
* Copyright (c) 2003 Michael Niedermayer <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file libavutil/rational.h
* rational numbers
* @author Michael Niedermayer <[email protected]>
*/
#ifndef AVUTIL_RATIONAL_H
#define AVUTIL_RATIONAL_H
#include <stdint.h>
#include "common.h"
/**
* rational number numerator/denominator
*/
typedef struct AVRational{
int num; ///< numerator
int den; ///< denominator
} AVRational;
/**
* Compares two rationals.
* @param a first rational
* @param b second rational
* @return 0 if a==b, 1 if a>b and -1 if a<b
*/
static inline int av_cmp_q(AVRational a, AVRational b){
const int64_t tmp= a.num * (int64_t)b.den - b.num * (int64_t)a.den;
if (tmp) return (int) ((tmp>>63)|1);
else return 0;
}
/**
* Converts rational to double.
* @param a rational to convert
* @return (double) a
*/
static inline double av_q2d(AVRational a){
return a.num / (double) a.den;
}
/**
* Reduces a fraction.
* This is useful for framerate calculations.
* @param dst_num destination numerator
* @param dst_den destination denominator
* @param num source numerator
* @param den source denominator
* @param max the maximum allowed for dst_num & dst_den
* @return 1 if exact, 0 otherwise
*/
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max);
/**
* Multiplies two rationals.
* @param b first rational
* @param c second rational
* @return b*c
*/
AVRational av_mul_q(AVRational b, AVRational c) av_const;
/**
* Divides one rational by another.
* @param b first rational
* @param c second rational
* @return b/c
*/
AVRational av_div_q(AVRational b, AVRational c) av_const;
/**
* Adds two rationals.
* @param b first rational
* @param c second rational
* @return b+c
*/
AVRational av_add_q(AVRational b, AVRational c) av_const;
/**
* Subtracts one rational from another.
* @param b first rational
* @param c second rational
* @return b-c
*/
AVRational av_sub_q(AVRational b, AVRational c) av_const;
/**
* Converts a double precision floating point number to a rational.
* @param d double to convert
* @param max the maximum allowed numerator and denominator
* @return (AVRational) d
*/
AVRational av_d2q(double d, int max) av_const;
/**
* @return 1 if \q1 is nearer to \p q than \p q2, -1 if \p q2 is nearer
* than \p q1, 0 if they have the same distance.
*/
int av_nearer_q(AVRational q, AVRational q1, AVRational q2);
/**
* Finds the nearest value in \p q_list to \p q.
* @param q_list an array of rationals terminated by {0, 0}
* @return the index of the nearest value found in the array
*/
int av_find_nearest_q_idx(AVRational q, const AVRational* q_list);
#endif /* AVUTIL_RATIONAL_H */
| century-arcade/src | c64/vice-2.4/src/lib/libffmpeg/libavutil/rational.h | C | mit | 3,486 |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template make_avl_set_member_hook</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../intrusive/reference.html#header.boost.intrusive.avl_set_hook_hpp" title="Header <boost/intrusive/avl_set_hook.hpp>">
<link rel="prev" href="make_avl_set_base_hook.html" title="Struct template make_avl_set_base_hook">
<link rel="next" href="avltree.html" title="Class template avltree">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_avl_set_base_hook.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.avl_set_hook_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="avltree.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.intrusive.make_avl_set_member_hook"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template make_avl_set_member_hook</span></h2>
<p>boost::intrusive::make_avl_set_member_hook</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../intrusive/reference.html#header.boost.intrusive.avl_set_hook_hpp" title="Header <boost/intrusive/avl_set_hook.hpp>">boost/intrusive/avl_set_hook.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">class</span><span class="special">...</span> Options<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="make_avl_set_member_hook.html" title="Struct template make_avl_set_member_hook">make_avl_set_member_hook</a> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">implementation_defined</span> <a name="boost.intrusive.make_avl_set_member_hook.type"></a><span class="identifier">type</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp270015696"></a><h2>Description</h2>
<p>Helper metafunction to define a <code class="computeroutput"><a class="link" href="avl_set_member_hook.html" title="Class template avl_set_member_hook">avl_set_member_hook</a></code> that yields to the same type when the same options (either explicitly or implicitly) are used. </p>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2005 Olaf Krzikalla<br>Copyright © 2006-2015 Ion Gaztanaga<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="make_avl_set_base_hook.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../intrusive/reference.html#header.boost.intrusive.avl_set_hook_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="avltree.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| TyRoXx/cdm | original_sources/boost_1_59_0/doc/html/boost/intrusive/make_avl_set_member_hook.html | HTML | mit | 4,813 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[ExportLspMethod(LSP.Methods.TextDocumentRenameName, mutatesSolutionState: false), Shared]
internal class RenameHandler : IRequestHandler<LSP.RenameParams, WorkspaceEdit?>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RenameHandler()
{
}
public TextDocumentIdentifier? GetTextDocumentIdentifier(RenameParams request) => request.TextDocument;
public async Task<WorkspaceEdit?> HandleRequestAsync(RenameParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document != null)
{
var oldSolution = document.Project.Solution;
var renameService = document.Project.LanguageServices.GetRequiredService<IEditorInlineRenameService>();
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var renameInfo = await renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false);
if (!renameInfo.CanRename)
{
return null;
}
var renameLocationSet = await renameInfo.FindRenameLocationsAsync(oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false);
var renameReplacementInfo = await renameLocationSet.GetReplacementsAsync(request.NewName, oldSolution.Workspace.Options, cancellationToken).ConfigureAwait(false);
var renamedSolution = renameReplacementInfo.NewSolution;
var solutionChanges = renamedSolution.GetChanges(oldSolution);
// Linked files can correspond to multiple roslyn documents each with changes. Merge the changes in the linked files so that all linked documents have the same text.
// Then we can just take the text changes from the first document to avoid returning duplicate edits.
renamedSolution = await renamedSolution.WithMergedLinkedFileChangesAsync(oldSolution, solutionChanges, cancellationToken: cancellationToken).ConfigureAwait(false);
solutionChanges = renamedSolution.GetChanges(oldSolution);
var changedDocuments = solutionChanges
.GetProjectChanges()
.SelectMany(p => p.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true))
.GroupBy(docId => renamedSolution.GetRequiredDocument(docId).FilePath, StringComparer.OrdinalIgnoreCase).Select(group => group.First());
var textDiffService = renamedSolution.Workspace.Services.GetRequiredService<IDocumentTextDifferencingService>();
var documentEdits = await ProtocolConversions.ChangedDocumentsToTextDocumentEditsAsync(changedDocuments, renamedSolution.GetRequiredDocument, oldSolution.GetRequiredDocument,
textDiffService, cancellationToken).ConfigureAwait(false);
return new WorkspaceEdit { DocumentChanges = documentEdits };
}
return null;
}
}
}
| panopticoncentral/roslyn | src/Features/LanguageServer/Protocol/Handler/Rename/RenameHandler.cs | C# | mit | 4,008 |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MinWpfApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MinWpfApp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| FilipRychnavsky/automatic-graph-layout | GraphLayout/Samples/MinWpfApp/Properties/AssemblyInfo.cs | C# | mit | 2,227 |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CommandLine.NativeMethods;
namespace Microsoft.CodeAnalysis.CommandLine
{
internal sealed class BuildServerConnection
{
// Spend up to 1s connecting to existing process (existing processes should be always responsive).
internal const int TimeOutMsExistingProcess = 1000;
// Spend up to 20s connecting to a new process, to allow time for it to start.
internal const int TimeOutMsNewProcess = 20000;
/// <summary>
/// Determines if the compiler server is supported in this environment.
/// </summary>
internal static bool IsCompilerServerSupported => GetPipeName("") is object;
internal static BuildRequest CreateBuildRequest(
Guid requestId,
RequestLanguage language,
List<string> arguments,
string workingDirectory,
string tempDirectory,
string? keepAlive,
string? libDirectory)
{
Debug.Assert(workingDirectory is object);
Debug.Assert(tempDirectory is object);
return BuildRequest.Create(
language,
arguments,
workingDirectory: workingDirectory,
tempDirectory: tempDirectory,
compilerHash: BuildProtocolConstants.GetCommitHash() ?? "",
requestId: requestId,
keepAlive: keepAlive,
libDirectory: libDirectory);
}
/// <summary>
/// Shutting down the server is an inherently racy operation. The server can be started or stopped by
/// external parties at any time.
///
/// This function will return success if at any time in the function the server is determined to no longer
/// be running.
/// </summary>
internal static async Task<bool> RunServerShutdownRequestAsync(
string pipeName,
int? timeoutOverride,
bool waitForProcess,
ICompilerServerLogger logger,
CancellationToken cancellationToken)
{
if (wasServerRunning(pipeName) == false)
{
// The server holds the mutex whenever it is running, if it's not open then the
// server simply isn't running.
return true;
}
try
{
var request = BuildRequest.CreateShutdown();
// Don't create the server when sending a shutdown request. That would defeat the
// purpose a bit.
var response = await RunServerBuildRequestAsync(
request,
pipeName,
timeoutOverride,
tryCreateServerFunc: (_, _) => false,
logger,
cancellationToken).ConfigureAwait(false);
if (response is ShutdownBuildResponse shutdownBuildResponse)
{
if (waitForProcess)
{
try
{
var process = Process.GetProcessById(shutdownBuildResponse.ServerProcessId);
#if NET50_OR_GREATER
await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
#else
process.WaitForExit();
#endif
}
catch (Exception)
{
// There is an inherent race here with the server process. If it has already shutdown
// by the time we try to access it then the operation has succeed.
}
}
return true;
}
return wasServerRunning(pipeName) == false;
}
catch (Exception)
{
// If the server was in the process of shutting down when we connected then it's reasonable
// for an exception to happen. If the mutex has shutdown at this point then the server
// is shut down.
return wasServerRunning(pipeName) == false;
}
// Was a server running with the specified session key during the execution of this call?
static bool? wasServerRunning(string pipeName)
{
string mutexName = GetServerMutexName(pipeName);
return WasServerMutexOpen(mutexName);
}
}
internal static Task<BuildResponse> RunServerBuildRequestAsync(
BuildRequest buildRequest,
string pipeName,
string clientDirectory,
ICompilerServerLogger logger,
CancellationToken cancellationToken)
=> RunServerBuildRequestAsync(
buildRequest,
pipeName,
timeoutOverride: null,
tryCreateServerFunc: (pipeName, logger) => TryCreateServer(clientDirectory, pipeName, logger),
logger,
cancellationToken);
internal static async Task<BuildResponse> RunServerBuildRequestAsync(
BuildRequest buildRequest,
string pipeName,
int? timeoutOverride,
Func<string, ICompilerServerLogger, bool> tryCreateServerFunc,
ICompilerServerLogger logger,
CancellationToken cancellationToken)
{
Debug.Assert(pipeName is object);
// early check for the build hash. If we can't find it something is wrong; no point even trying to go to the server
if (string.IsNullOrWhiteSpace(BuildProtocolConstants.GetCommitHash()))
{
return new IncorrectHashBuildResponse();
}
using var pipe = await tryConnectToServer(pipeName, timeoutOverride, logger, tryCreateServerFunc, cancellationToken).ConfigureAwait(false);
if (pipe is null)
{
return new RejectedBuildResponse("Failed to connect to server");
}
else
{
return await tryRunRequestAsync(pipe, buildRequest, logger, cancellationToken).ConfigureAwait(false);
}
// This code uses a Mutex.WaitOne / ReleaseMutex pairing. Both of these calls must occur on the same thread
// or an exception will be thrown. This code lives in a separate non-async function to help ensure this
// invariant doesn't get invalidated in the future by an `await` being inserted.
static Task<NamedPipeClientStream?> tryConnectToServer(
string pipeName,
int? timeoutOverride,
ICompilerServerLogger logger,
Func<string, ICompilerServerLogger, bool> tryCreateServerFunc,
CancellationToken cancellationToken)
{
var originalThreadId = Environment.CurrentManagedThreadId;
var timeoutNewProcess = timeoutOverride ?? TimeOutMsNewProcess;
var timeoutExistingProcess = timeoutOverride ?? TimeOutMsExistingProcess;
IServerMutex? clientMutex = null;
try
{
var holdsMutex = false;
try
{
var clientMutexName = GetClientMutexName(pipeName);
clientMutex = OpenOrCreateMutex(clientMutexName, out holdsMutex);
}
catch
{
// The Mutex constructor can throw in certain cases. One specific example is docker containers
// where the /tmp directory is restricted. In those cases there is no reliable way to execute
// the server and we need to fall back to the command line.
//
// Example: https://github.com/dotnet/roslyn/issues/24124
return Task.FromResult<NamedPipeClientStream?>(null);
}
if (!holdsMutex)
{
try
{
holdsMutex = clientMutex.TryLock(timeoutNewProcess);
if (!holdsMutex)
{
return Task.FromResult<NamedPipeClientStream?>(null);
}
}
catch (AbandonedMutexException)
{
holdsMutex = true;
}
}
// Check for an already running server
var serverMutexName = GetServerMutexName(pipeName);
bool wasServerRunning = WasServerMutexOpen(serverMutexName);
var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess;
if (wasServerRunning || tryCreateServerFunc(pipeName, logger))
{
return TryConnectToServerAsync(pipeName, timeout, logger, cancellationToken);
}
else
{
return Task.FromResult<NamedPipeClientStream?>(null);
}
}
finally
{
try
{
clientMutex?.Dispose();
}
catch (ApplicationException e)
{
var releaseThreadId = Environment.CurrentManagedThreadId;
var message = $"ReleaseMutex failed. WaitOne Id: {originalThreadId} Release Id: {releaseThreadId}";
throw new Exception(message, e);
}
}
}
// Try and run the given BuildRequest on the server. If the request cannot be run then
// an appropriate error response will be returned.
static async Task<BuildResponse> tryRunRequestAsync(
NamedPipeClientStream pipeStream,
BuildRequest request,
ICompilerServerLogger logger,
CancellationToken cancellationToken)
{
try
{
logger.Log($"Begin writing request for {request.RequestId}");
await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false);
logger.Log($"End writing request for {request.RequestId}");
}
catch (Exception e)
{
logger.LogException(e, $"Error writing build request for {request.RequestId}");
return new RejectedBuildResponse($"Error writing build request: {e.Message}");
}
// Wait for the compilation and a monitor to detect if the server disconnects
var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
logger.Log($"Begin reading response for {request.RequestId}");
var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token);
var monitorTask = MonitorDisconnectAsync(pipeStream, request.RequestId, logger, serverCts.Token);
await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false);
logger.Log($"End reading response for {request.RequestId}");
BuildResponse response;
if (responseTask.IsCompleted)
{
// await the task to log any exceptions
try
{
response = await responseTask.ConfigureAwait(false);
}
catch (Exception e)
{
logger.LogException(e, $"Reading response for {request.RequestId}");
response = new RejectedBuildResponse($"Error reading response: {e.Message}");
}
}
else
{
logger.LogError($"Client disconnect for {request.RequestId}");
response = new RejectedBuildResponse($"Client disconnected");
}
// Cancel whatever task is still around
serverCts.Cancel();
RoslynDebug.Assert(response != null);
return response;
}
}
/// <summary>
/// The IsConnected property on named pipes does not detect when the client has disconnected
/// if we don't attempt any new I/O after the client disconnects. We start an async I/O here
/// which serves to check the pipe for disconnection.
/// </summary>
internal static async Task MonitorDisconnectAsync(
PipeStream pipeStream,
Guid requestId,
ICompilerServerLogger logger,
CancellationToken cancellationToken = default)
{
var buffer = Array.Empty<byte>();
while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected)
{
try
{
// Wait a tenth of a second before trying again
await Task.Delay(millisecondsDelay: 100, cancellationToken).ConfigureAwait(false);
await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (Exception e)
{
// It is okay for this call to fail. Errors will be reflected in the
// IsConnected property which will be read on the next iteration of the
logger.LogException(e, $"Error poking pipe {requestId}.");
}
}
}
/// <summary>
/// Attempt to connect to the server and return a null <see cref="NamedPipeClientStream"/> if connection
/// failed. This method will throw on cancellation.
/// </summary>
internal static async Task<NamedPipeClientStream?> TryConnectToServerAsync(
string pipeName,
int timeoutMs,
ICompilerServerLogger logger,
CancellationToken cancellationToken)
{
NamedPipeClientStream? pipeStream = null;
try
{
// Machine-local named pipes are named "\\.\pipe\<pipename>".
// We use the SHA1 of the directory the compiler exes live in as the pipe name.
// The NamedPipeClientStream class handles the "\\.\pipe\" part for us.
logger.Log("Attempt to open named pipe '{0}'", pipeName);
pipeStream = NamedPipeUtil.CreateClient(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
cancellationToken.ThrowIfCancellationRequested();
logger.Log("Attempt to connect named pipe '{0}'", pipeName);
try
{
// NamedPipeClientStream.ConnectAsync on the "full" framework has a bug where it
// tries to move potentially expensive work (actually connecting to the pipe) to
// a background thread with Task.Factory.StartNew. However, that call will merely
// queue the work onto the TaskScheduler associated with the "current" Task which
// does not guarantee it will be processed on a background thread and this could
// lead to a hang.
// To avoid this, we first force ourselves to a background thread using Task.Run.
// This ensures that the Task created by ConnectAsync will run on the default
// TaskScheduler (i.e., on a threadpool thread) which was the intent all along.
await Task.Run(() => pipeStream.ConnectAsync(timeoutMs, cancellationToken), cancellationToken).ConfigureAwait(false);
}
catch (Exception e) when (e is IOException || e is TimeoutException)
{
// Note: IOException can also indicate timeout. From docs:
// TimeoutException: Could not connect to the server within the
// specified timeout period.
// IOException: The server is connected to another client and the
// time-out period has expired.
logger.LogException(e, $"Connecting to server timed out after {timeoutMs} ms");
pipeStream.Dispose();
return null;
}
logger.Log("Named pipe '{0}' connected", pipeName);
cancellationToken.ThrowIfCancellationRequested();
// Verify that we own the pipe.
if (!NamedPipeUtil.CheckPipeConnectionOwnership(pipeStream))
{
pipeStream.Dispose();
logger.LogError("Owner of named pipe is incorrect");
return null;
}
return pipeStream;
}
catch (Exception e) when (!(e is TaskCanceledException || e is OperationCanceledException))
{
logger.LogException(e, "Exception while connecting to process");
pipeStream?.Dispose();
return null;
}
}
internal static (string processFilePath, string commandLineArguments, string toolFilePath) GetServerProcessInfo(string clientDir, string pipeName)
{
var serverPathWithoutExtension = Path.Combine(clientDir, "VBCSCompiler");
var commandLineArgs = $@"""-pipename:{pipeName}""";
return RuntimeHostInfo.GetProcessInfo(serverPathWithoutExtension, commandLineArgs);
}
/// <summary>
/// This will attempt to start a compiler server process using the executable inside the
/// directory <paramref name="clientDirectory"/>. This returns "true" if starting the
/// compiler server process was successful, it does not state whether the server successfully
/// started or not (it could crash on startup).
/// </summary>
private static bool TryCreateServer(string clientDirectory, string pipeName, ICompilerServerLogger logger)
{
var serverInfo = GetServerProcessInfo(clientDirectory, pipeName);
if (!File.Exists(serverInfo.toolFilePath))
{
return false;
}
if (PlatformInformation.IsWindows)
{
// As far as I can tell, there isn't a way to use the Process class to
// create a process with no stdin/stdout/stderr, so we use P/Invoke.
// This code was taken from MSBuild task starting code.
STARTUPINFO startInfo = new STARTUPINFO();
startInfo.cb = Marshal.SizeOf(startInfo);
startInfo.hStdError = InvalidIntPtr;
startInfo.hStdInput = InvalidIntPtr;
startInfo.hStdOutput = InvalidIntPtr;
startInfo.dwFlags = STARTF_USESTDHANDLES;
uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW;
PROCESS_INFORMATION processInfo;
logger.Log("Attempting to create process '{0}'", serverInfo.processFilePath);
var builder = new StringBuilder($@"""{serverInfo.processFilePath}"" {serverInfo.commandLineArguments}");
bool success = CreateProcess(
lpApplicationName: null,
lpCommandLine: builder,
lpProcessAttributes: NullPtr,
lpThreadAttributes: NullPtr,
bInheritHandles: false,
dwCreationFlags: dwCreationFlags,
lpEnvironment: NullPtr, // Inherit environment
lpCurrentDirectory: clientDirectory,
lpStartupInfo: ref startInfo,
lpProcessInformation: out processInfo);
if (success)
{
logger.Log("Successfully created process with process id {0}", processInfo.dwProcessId);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
}
else
{
logger.LogError("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error());
}
return success;
}
else
{
try
{
var startInfo = new ProcessStartInfo()
{
FileName = serverInfo.processFilePath,
Arguments = serverInfo.commandLineArguments,
UseShellExecute = false,
WorkingDirectory = clientDirectory,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
Process.Start(startInfo);
return true;
}
catch
{
return false;
}
}
}
/// <returns>
/// Null if not enough information was found to create a valid pipe name.
/// </returns>
internal static string GetPipeName(string clientDirectory)
{
// Prefix with username and elevation
bool isAdmin = false;
if (PlatformInformation.IsWindows)
{
#pragma warning disable CA1416 // Validate platform compatibility
var currentIdentity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(currentIdentity);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
#pragma warning restore CA1416
}
var userName = Environment.UserName;
return GetPipeName(userName, isAdmin, clientDirectory);
}
internal static string GetPipeName(
string userName,
bool isAdmin,
string clientDirectory)
{
// Normalize away trailing slashes. File APIs include / exclude this with no
// discernable pattern. Easiest to normalize it here vs. auditing every caller
// of this method.
clientDirectory = clientDirectory.TrimEnd(Path.DirectorySeparatorChar);
var pipeNameInput = $"{userName}.{isAdmin}.{clientDirectory}";
using (var sha = SHA256.Create())
{
var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(pipeNameInput));
return Convert.ToBase64String(bytes)
.Replace("/", "_")
.Replace("=", string.Empty);
}
}
internal static bool WasServerMutexOpen(string mutexName)
{
try
{
if (PlatformInformation.IsUsingMonoRuntime)
{
using var mutex = new ServerFileMutex(mutexName);
return !mutex.CouldLock();
}
else
{
return ServerNamedMutex.WasOpen(mutexName);
}
}
catch
{
// In the case an exception occurred trying to open the Mutex then
// the assumption is that it's not open.
return false;
}
}
internal static IServerMutex OpenOrCreateMutex(string name, out bool createdNew)
{
if (PlatformInformation.IsUsingMonoRuntime)
{
var mutex = new ServerFileMutex(name);
createdNew = mutex.TryLock(0);
return mutex;
}
else
{
return new ServerNamedMutex(name, out createdNew);
}
}
internal static string GetServerMutexName(string pipeName)
{
return $"{pipeName}.server";
}
internal static string GetClientMutexName(string pipeName)
{
return $"{pipeName}.client";
}
/// <summary>
/// Gets the value of the temporary path for the current environment assuming the working directory
/// is <paramref name="workingDir"/>. This function must emulate <see cref="Path.GetTempPath"/> as
/// closely as possible.
/// </summary>
internal static string? GetTempPath(string? workingDir)
{
if (PlatformInformation.IsUnix)
{
// Unix temp path is fine: it does not use the working directory
// (it uses ${TMPDIR} if set, otherwise, it returns /tmp)
return Path.GetTempPath();
}
var tmp = Environment.GetEnvironmentVariable("TMP");
if (Path.IsPathRooted(tmp))
{
return tmp;
}
var temp = Environment.GetEnvironmentVariable("TEMP");
if (Path.IsPathRooted(temp))
{
return temp;
}
if (!string.IsNullOrEmpty(workingDir))
{
if (!string.IsNullOrEmpty(tmp))
{
return Path.Combine(workingDir, tmp);
}
if (!string.IsNullOrEmpty(temp))
{
return Path.Combine(workingDir, temp);
}
}
var userProfile = Environment.GetEnvironmentVariable("USERPROFILE");
if (Path.IsPathRooted(userProfile))
{
return userProfile;
}
return Environment.GetEnvironmentVariable("SYSTEMROOT");
}
}
internal interface IServerMutex : IDisposable
{
bool TryLock(int timeoutMs);
bool IsDisposed { get; }
}
/// <summary>
/// An interprocess mutex abstraction based on file sharing permission (FileShare.None).
/// If multiple processes running as the same user create FileMutex instances with the same name,
/// those instances will all point to the same file somewhere in a selected temporary directory.
/// The TryLock method can be used to attempt to acquire the mutex, with Dispose used to release.
/// The CouldLock method can be used to check whether an attempt to acquire the mutex would have
/// succeeded at the current time, without actually acquiring it.
/// Unlike Win32 named mutexes, there is no mechanism for detecting an abandoned mutex. The file
/// will simply revert to being unlocked but remain where it is.
/// </summary>
internal sealed class ServerFileMutex : IServerMutex
{
public FileStream? Stream;
public readonly string FilePath;
public readonly string GuardPath;
public bool IsDisposed { get; private set; }
internal static string GetMutexDirectory()
{
var tempPath = BuildServerConnection.GetTempPath(null);
var result = Path.Combine(tempPath!, ".roslyn");
Directory.CreateDirectory(result);
return result;
}
public ServerFileMutex(string name)
{
var mutexDirectory = GetMutexDirectory();
FilePath = Path.Combine(mutexDirectory, name);
GuardPath = Path.Combine(mutexDirectory, ".guard");
}
/// <summary>
/// Acquire the guard by opening the guard file with FileShare.None. The guard must only ever
/// be held for very brief amounts of time, so we can simply spin until it is acquired. The
/// guard must be released by disposing the FileStream returned from this routine. Note the
/// guard file is never deleted; this is a leak, but only of a single file.
/// </summary>
internal FileStream LockGuard()
{
// We should be able to acquire the guard quickly. Limit the number of retries anyway
// by some arbitrary bound to avoid getting hung up in a possibly infinite loop.
for (var i = 0; i < 100; i++)
{
try
{
return new FileStream(GuardPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
// Guard currently held by someone else.
// We want to sleep for a short period of time to ensure that other processes
// have an opportunity to finish their work and relinquish the lock.
// Spinning here (via Yield) would work but risks creating a priority
// inversion if the lock is held by a lower-priority process.
Thread.Sleep(1);
}
}
// Handle unexpected failure to acquire guard as error.
throw new InvalidOperationException("Unable to acquire guard");
}
/// <summary>
/// Attempt to acquire the lock by opening the lock file with FileShare.None. Sets "Stream"
/// and returns true if successful, returns false if the lock is already held by another
/// thread or process. Guard must be held when calling this routine.
/// </summary>
internal bool TryLockFile()
{
Debug.Assert(Stream is null);
FileStream? stream = null;
try
{
stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
// On some targets, the file locking used to implement FileShare.None may not be
// atomic with opening/creating the file. This creates a race window when another
// thread holds the lock and is just about to unlock: we may be able to open the
// file here, then the other thread unlocks and deletes the file, and then we
// acquire the lock on our file handle - but the actual file is already deleted.
// To close this race, we verify that the file does in fact still exist now that
// we have successfully acquired the locked FileStream. (Note that this check is
// safe because we cannot race with an other attempt to create the file since we
// hold the guard, and after the FileStream constructor returned we can no race
// with file deletion because we hold the lock.)
if (!File.Exists(FilePath))
{
// To simplify the logic, we treat this case as "unable to acquire the lock"
// because it we caught another process while it owned the lock and was just
// giving it up. If the caller retries, we'll likely acquire the lock then.
stream.Dispose();
return false;
}
}
catch (Exception)
{
stream?.Dispose();
return false;
}
Stream = stream;
return true;
}
/// <summary>
/// Release the lock by deleting the lock file and disposing "Stream".
/// </summary>
internal void UnlockFile()
{
Debug.Assert(Stream is not null);
try
{
// Delete the lock file while the stream is not yet disposed
// and we therefore still hold the FileShare.None exclusion.
// There may still be a race with another thread attempting a
// TryLockFile in parallel, but that is safely handled there.
File.Delete(FilePath);
}
finally
{
Stream.Dispose();
Stream = null;
}
}
public bool TryLock(int timeoutMs)
{
if (IsDisposed)
throw new ObjectDisposedException("Mutex");
if (Stream is not null)
throw new InvalidOperationException("Lock already held");
var sw = Stopwatch.StartNew();
do
{
try
{
// Attempt to acquire lock while holding guard.
using var guard = LockGuard();
if (TryLockFile())
return true;
}
catch (Exception)
{
return false;
}
// See comment in LockGuard.
Thread.Sleep(1);
} while (sw.ElapsedMilliseconds < timeoutMs);
return false;
}
public bool CouldLock()
{
if (IsDisposed)
return false;
if (Stream is not null)
return false;
try
{
// Attempt to acquire lock while holding guard, and if successful
// immediately unlock again while still holding guard. This ensures
// no other thread will spuriously observe the lock as held due to
// the lock attempt here.
using var guard = LockGuard();
if (TryLockFile())
{
UnlockFile();
return true;
}
}
catch (Exception)
{
return false;
}
return false;
}
public void Dispose()
{
if (IsDisposed)
return;
IsDisposed = true;
if (Stream is not null)
{
try
{
UnlockFile();
}
catch (Exception)
{
}
}
}
}
internal sealed class ServerNamedMutex : IServerMutex
{
public readonly Mutex Mutex;
public bool IsDisposed { get; private set; }
public bool IsLocked { get; private set; }
public ServerNamedMutex(string mutexName, out bool createdNew)
{
Mutex = new Mutex(
initiallyOwned: true,
name: mutexName,
createdNew: out createdNew
);
if (createdNew)
IsLocked = true;
}
public static bool WasOpen(string mutexName)
{
Mutex? m = null;
try
{
return Mutex.TryOpenExisting(mutexName, out m);
}
catch
{
// In the case an exception occurred trying to open the Mutex then
// the assumption is that it's not open.
return false;
}
finally
{
m?.Dispose();
}
}
public bool TryLock(int timeoutMs)
{
if (IsDisposed)
throw new ObjectDisposedException("Mutex");
if (IsLocked)
throw new InvalidOperationException("Lock already held");
return IsLocked = Mutex.WaitOne(timeoutMs);
}
public void Dispose()
{
if (IsDisposed)
return;
IsDisposed = true;
try
{
if (IsLocked)
Mutex.ReleaseMutex();
}
finally
{
Mutex.Dispose();
IsLocked = false;
}
}
}
}
| mavasani/roslyn | src/Compilers/Shared/BuildServerConnection.cs | C# | mit | 36,937 |
'use strict';
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtml
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
* ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
* is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
* core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlDirective = ['$sce', function($sce) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function ngBindHtmlWatchAction(value) {
element.html(value || '');
});
};
}];
| jwagner/angular.js | src/ng/directive/ngBind.js | JavaScript | mit | 5,431 |
var title = "Winter Walk";
var desc = "part 2";
var offer = "Ready for another Winter Walk?";
var completion = "Hope it was a breath of fresh air.";
var auto_complete = 0;
var familiar_turnin = 0;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var is_repeatable = 1;
var hide_questlog = 1;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = ["winter_walk"];
var prerequisites = [];
var end_npcs = ["street_spirit","street_spirit_firebog","street_spirit_zutto","street_spirit_groddle","street_spirit_ix"];
var locations = {
"level_quest_winter_walk_part2" : {
"dev_tsid" : "",
"prod_tsid" : "LIFNBTGUQJ739MC"
},
"level_quest_winter_haven_part2" : {
"dev_tsid" : "",
"prod_tsid" : "LIFNEN3QHC73UO9"
}
};
var requirements = {
"r513" : {
"type" : "flag",
"name" : "leave",
"desc" : "Toggle flag leave"
}
};
function onComplete(pc){ // generated from rewards
var xp=0;
var currants=0;
var mood=0;
var energy=0;
var favor=0;
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_quest_modifier();
apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
}
var rewards = {};
function callback_winter_walk_part2_finish(details){
var pc = details.pc;
if (!pc) pc = this.owner;
if (!pc) return;
this.set_flag(pc, 'leave');
pc.instances_exit(pc.location.instance_id);
}
function canOffer(pc){
// We don't want to offer this immediately after part 1 finishes
var part1 = pc.getQuestInstance('winter_walk');
if (!part1) return false;
if (!part1.ts_done) return false;
if (time() - part1.ts_done < 60*60) return false;
// Also repeatable only once every hour
if (this.ts_done && time() - this.ts_done < 60*60) return false;
if (this.fail_time && time() - this.fail_time < 60*60) return false;
return true;
}
function onEnterLocation(location){
if (location == 'level_quest_winter_haven_part2'){
var pc = this.owner;
if (!pc) return;
//pc.instances_exit('level_quest_winter_walk_part2');
return;
}
}
function onExitLocation(previous_location){
var pc = this.owner;
if (!pc) return;
if (pc.location.instance_id == 'level_quest_winter_walk_part2' || pc.location.instance_id == 'level_quest_winter_haven_part2') return;
if (!this.is_complete){
this.fail_time = time();
pc.failQuest(this.class_tsid);
pc.instances_exit(previous_location);
}
}
function onStarted(pc){
this.questInstanceLocation(pc, 'level_quest_winter_walk_part2', -2875, -81, 5*60);
return {ok: 1};
}
// generated ok (NO DATE)
| Mexiswow/eleven-gsjs | quests/winter_walk_part2.js | JavaScript | mit | 2,753 |
from sklearn_pmml.convert import * | kod3r/sklearn-pmml | sklearn_pmml/__init__.py | Python | mit | 34 |
<?php
return [
'name' => 'Name',
'sync-roles' => 'Sync Roles',
'enable-timezone' => 'Enable Timezone',
'roles' => [
'configuration' => 'Role Configuration',
'admin' => 'Administrator Role',
'member' => 'Member Role',
],
'themes' => [
'activate' => 'Activate Theme',
'current' => 'Current Theme',
],
];
| m4ch1n3/management | resources/lang/en/label.php | PHP | mit | 405 |
require 'cr_cas_future'
FutureImplementation = CRCasFuture
require 'bench_fulfill'
| MadBomber/concurrent-ruby | benchmarks/futures-rubyconf2015/benchmarks/cr-cas-fulfill.rb | Ruby | mit | 83 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Global btrt_detect_fp_except</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../../../header/boost/test/unit_test_parameters_hpp.html" title="Header <boost/test/unit_test_parameters.hpp>">
<link rel="prev" href="btrt_color_output.html" title="Global btrt_color_output">
<link rel="next" href="btrt_detect_mem_leaks.html" title="Global btrt_detect_mem_leaks">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="btrt_color_output.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../header/boost/test/unit_test_parameters_hpp.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="btrt_detect_mem_leaks.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.unit_test.runtime_config.btrt_detect_fp_except"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Global btrt_detect_fp_except</span></h2>
<p>boost::unit_test::runtime_config::btrt_detect_fp_except</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../header/boost/test/unit_test_parameters_hpp.html" title="Header <boost/test/unit_test_parameters.hpp>">boost/test/unit_test_parameters.hpp</a>>
</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">string</span> btrt_detect_fp_except<span class="special">;</span></pre></div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2001-2018 Boost.Test contributors<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="btrt_color_output.html"><img src="../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../header/boost/test/unit_test_parameters_hpp.html"><img src="../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="btrt_detect_mem_leaks.html"><img src="../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| nawawi/poedit | deps/boost/libs/test/doc/html/boost/unit_test/runtime_config/btrt_detect_fp_except.html | HTML | mit | 3,809 |
//
// Persist.h
// Persist
//
// Created by Daniel Tomlinson on 13/09/2015.
// Copyright © 2015 Daniel Tomlinson. All rights reserved.
//
#import <Foundation/Foundation.h>
//! Project version number for Persist.
FOUNDATION_EXPORT double PersistVersionNumber;
//! Project version string for Persist.
FOUNDATION_EXPORT const unsigned char PersistVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <Persist/PublicHeader.h>
| alvinvarghese/Persist | Persist/Persist.h | C | mit | 505 |
<!-- HTML header for doxygen 1.8.13-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Generic Image Library: Member List</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="doxygen.css" rel="stylesheet" type="text/css" />
<link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="boost-header">
<table border="0" cellpadding="7" cellspacing="0" width="100%" summary="header">
<tr>
<td valign="top" width="300">
<h3><a href="../index.html"><img alt="Boost GIL" src="../_static/gil.png" border="0"></a></h3>
</td>
<td ><h1 align="center"><a href="../index.html"></a></h1></td>
<td></td>
</tr>
</table>
</div>
<hr/>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<!-- Generated by Doxygen 1.8.6 -->
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>boost</b></li><li class="navelem"><b>gil</b></li><li class="navelem"><a class="el" href="structboost_1_1gil_1_1_mutable_random_access2_d_image_view_concept.html">MutableRandomAccess2DImageViewConcept</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">MutableRandomAccess2DImageViewConcept< View > Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="structboost_1_1gil_1_1_mutable_random_access2_d_image_view_concept.html">MutableRandomAccess2DImageViewConcept< View ></a>, including all inherited members.</p>
<table class="directory">
<tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>constraints</b>() (defined in <a class="el" href="structboost_1_1gil_1_1_mutable_random_access2_d_image_view_concept.html">MutableRandomAccess2DImageViewConcept< View ></a>)</td><td class="entry"><a class="el" href="structboost_1_1gil_1_1_mutable_random_access2_d_image_view_concept.html">MutableRandomAccess2DImageViewConcept< View ></a></td><td class="entry"><span class="mlabel">inline</span></td></tr>
</table></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.13-->
<!-- start footer part -->
<hr class="footer"/>
<address class="footer">
<small>
Generated on Wed Dec 5 2018 20:05:50 for Generic Image Library by  <a href="http://www.doxygen.org/index.html">doxygen</a> 1.8.6
</small>
</address>
</body>
</html>
| nawawi/poedit | deps/boost/libs/gil/doc/html/reference/structboost_1_1gil_1_1_mutable_random_access2_d_image_view_concept-members.html | HTML | mit | 3,699 |
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information, see
* <http://www.doctrine-project.org>.
*/
namespace Doctrine\ODM\MongoDB\Hydrator;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\Types\Type;
use Doctrine\ODM\MongoDB\UnitOfWork;
use Doctrine\ODM\MongoDB\Events;
use Doctrine\Common\EventManager;
use Doctrine\ODM\MongoDB\Event\LifecycleEventArgs;
use Doctrine\ODM\MongoDB\Event\PreLoadEventArgs;
use Doctrine\ODM\MongoDB\PersistentCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Proxy\Proxy;
/**
* The HydratorFactory class is responsible for instantiating a correct hydrator
* type based on document's ClassMetadata
*
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
* @link www.doctrine-project.com
* @since 1.0
* @author Jonathan H. Wage <[email protected]>
*/
class HydratorFactory
{
/**
* The DocumentManager this factory is bound to.
*
* @var Doctrine\ODM\MongoDB\DocumentManager
*/
private $dm;
/**
* The UnitOfWork used to coordinate object-level transactions.
*
* @var Doctrine\ODM\MongoDB\UnitOfWork
*/
private $unitOfWork;
/**
* The EventManager associated with this Hydrator
*
* @var Doctrine\Common\EventManager
*/
private $evm;
/**
* Whether to automatically (re)generate hydrator classes.
*
* @var boolean
*/
private $autoGenerate;
/**
* The namespace that contains all hydrator classes.
*
* @var string
*/
private $hydratorNamespace;
/**
* The directory that contains all hydrator classes.
*
* @var string
*/
private $hydratorDir;
/**
* Array of instantiated document hydrators.
*
* @var array
*/
private $hydrators = array();
/**
* Mongo command prefix
* @var string
*/
private $cmd;
public function __construct(DocumentManager $dm, EventManager $evm, $hydratorDir, $hydratorNs, $autoGenerate, $cmd)
{
if ( ! $hydratorDir) {
throw HydratorException::hydratorDirectoryRequired();
}
if ( ! $hydratorNs) {
throw HydratorException::hydratorNamespaceRequired();
}
$this->dm = $dm;
$this->evm = $evm;
$this->hydratorDir = $hydratorDir;
$this->hydratorNamespace = $hydratorNs;
$this->autoGenerate = $autoGenerate;
$this->cmd = $cmd;
}
/**
* Sets the UnitOfWork instance.
*
* @param UnitOfWork $uow
*/
public function setUnitOfWork(UnitOfWork $uow)
{
$this->unitOfWork = $uow;
}
/**
* Gets the hydrator object for the given document class.
*
* @param string $className
* @return Doctrine\ODM\MongoDB\Hydrator\HydratorInterface $hydrator
*/
public function getHydratorFor($className)
{
if (isset($this->hydrators[$className])) {
return $this->hydrators[$className];
}
$hydratorClassName = str_replace('\\', '', $className) . 'Hydrator';
$fqn = $this->hydratorNamespace . '\\' . $hydratorClassName;
$class = $this->dm->getClassMetadata($className);
if (! class_exists($fqn, false)) {
$fileName = $this->hydratorDir . DIRECTORY_SEPARATOR . $hydratorClassName . '.php';
if ($this->autoGenerate) {
$this->generateHydratorClass($class, $hydratorClassName, $fileName);
}
require $fileName;
}
$this->hydrators[$className] = new $fqn($this->dm, $this->unitOfWork, $class);
return $this->hydrators[$className];
}
/**
* Generates hydrator classes for all given classes.
*
* @param array $classes The classes (ClassMetadata instances) for which to generate hydrators.
* @param string $toDir The target directory of the hydrator classes. If not specified, the
* directory configured on the Configuration of the DocumentManager used
* by this factory is used.
*/
public function generateHydratorClasses(array $classes, $toDir = null)
{
$hydratorDir = $toDir ?: $this->hydratorDir;
$hydratorDir = rtrim($hydratorDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
foreach ($classes as $class) {
$hydratorClassName = str_replace('\\', '', $class->name) . 'Hydrator';
$hydratorFileName = $hydratorDir . $hydratorClassName . '.php';
$this->generateHydratorClass($class, $hydratorClassName, $hydratorFileName);
}
}
private function generateHydratorClass(ClassMetadata $class, $hydratorClassName, $fileName)
{
$code = '';
foreach ($class->fieldMappings as $fieldName => $mapping) {
if (isset($mapping['alsoLoadFields'])) {
foreach ($mapping['alsoLoadFields'] as $name) {
$code .= sprintf(<<<EOF
/** @AlsoLoad("$name") */
if (isset(\$data['$name'])) {
\$data['$fieldName'] = \$data['$name'];
}
EOF
);
}
}
if ($mapping['type'] === 'date') {
$code .= sprintf(<<<EOF
/** @Field(type="date") */
if (isset(\$data['%1\$s'])) {
\$value = \$data['%1\$s'];
%3\$s
\$this->class->reflFields['%2\$s']->setValue(\$document, clone \$return);
\$hydratedData['%2\$s'] = \$return;
}
EOF
,
$mapping['name'],
$mapping['fieldName'],
Type::getType($mapping['type'])->closureToPHP()
);
} elseif ( ! isset($mapping['association'])) {
$code .= sprintf(<<<EOF
/** @Field(type="{$mapping['type']}") */
if (isset(\$data['%1\$s'])) {
\$value = \$data['%1\$s'];
%3\$s
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
}
EOF
,
$mapping['name'],
$mapping['fieldName'],
Type::getType($mapping['type'])->closureToPHP()
);
} elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isOwningSide']) {
$code .= sprintf(<<<EOF
/** @ReferenceOne */
if (isset(\$data['%1\$s'])) {
\$reference = \$data['%1\$s'];
if (isset(\$this->class->fieldMappings['%2\$s']['simple']) && \$this->class->fieldMappings['%2\$s']['simple']) {
\$className = \$this->class->fieldMappings['%2\$s']['targetDocument'];
\$mongoId = \$reference;
} else {
\$className = \$this->dm->getClassNameFromDiscriminatorValue(\$this->class->fieldMappings['%2\$s'], \$reference);
\$mongoId = \$reference['\$id'];
}
\$targetMetadata = \$this->dm->getClassMetadata(\$className);
\$id = \$targetMetadata->getPHPIdentifierValue(\$mongoId);
\$return = \$this->dm->getReference(\$className, \$id);
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
}
EOF
,
$mapping['name'],
$mapping['fieldName']
);
} elseif ($mapping['association'] === ClassMetadata::REFERENCE_ONE && $mapping['isInverseSide']) {
if (isset($mapping['repositoryMethod']) && $mapping['repositoryMethod']) {
$code .= sprintf(<<<EOF
\$className = \$this->class->fieldMappings['%2\$s']['targetDocument'];
\$return = \$this->dm->getRepository(\$className)->%3\$s(\$document);
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
EOF
,
$mapping['name'],
$mapping['fieldName'],
$mapping['repositoryMethod']
);
} else {
$code .= sprintf(<<<EOF
\$mapping = \$this->class->fieldMappings['%2\$s'];
\$className = \$mapping['targetDocument'];
\$targetClass = \$this->dm->getClassMetadata(\$mapping['targetDocument']);
\$mappedByMapping = \$targetClass->fieldMappings[\$mapping['mappedBy']];
\$mappedByFieldName = isset(\$mappedByMapping['simple']) && \$mappedByMapping['simple'] ? \$mapping['mappedBy'] : \$mapping['mappedBy'].'.id';
\$criteria = array_merge(
array(\$mappedByFieldName => \$data['_id']),
isset(\$this->class->fieldMappings['%2\$s']['criteria']) ? \$this->class->fieldMappings['%2\$s']['criteria'] : array()
);
\$sort = isset(\$this->class->fieldMappings['%2\$s']['sort']) ? \$this->class->fieldMappings['%2\$s']['sort'] : array();
\$return = \$this->unitOfWork->getDocumentPersister(\$className)->load(\$criteria, null, array(), 0, \$sort);
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
EOF
,
$mapping['name'],
$mapping['fieldName']
);
}
} elseif ($mapping['association'] === ClassMetadata::REFERENCE_MANY || $mapping['association'] === ClassMetadata::EMBED_MANY) {
$code .= sprintf(<<<EOF
/** @Many */
\$mongoData = isset(\$data['%1\$s']) ? \$data['%1\$s'] : null;
\$return = new \Doctrine\ODM\MongoDB\PersistentCollection(new \Doctrine\Common\Collections\ArrayCollection(), \$this->dm, \$this->unitOfWork, '$');
\$return->setHints(\$hints);
\$return->setOwner(\$document, \$this->class->fieldMappings['%2\$s']);
\$return->setInitialized(false);
if (\$mongoData) {
\$return->setMongoData(\$mongoData);
}
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
EOF
,
$mapping['name'],
$mapping['fieldName']
);
} elseif ($mapping['association'] === ClassMetadata::EMBED_ONE) {
$code .= sprintf(<<<EOF
/** @EmbedOne */
if (isset(\$data['%1\$s'])) {
\$embeddedDocument = \$data['%1\$s'];
\$className = \$this->dm->getClassNameFromDiscriminatorValue(\$this->class->fieldMappings['%2\$s'], \$embeddedDocument);
\$embeddedMetadata = \$this->dm->getClassMetadata(\$className);
\$return = \$embeddedMetadata->newInstance();
\$embeddedData = \$this->dm->getHydratorFactory()->hydrate(\$return, \$embeddedDocument, \$hints);
\$this->unitOfWork->registerManaged(\$return, null, \$embeddedData);
\$this->unitOfWork->setParentAssociation(\$return, \$this->class->fieldMappings['%2\$s'], \$document, '%1\$s');
\$this->class->reflFields['%2\$s']->setValue(\$document, \$return);
\$hydratedData['%2\$s'] = \$return;
}
EOF
,
$mapping['name'],
$mapping['fieldName']
);
}
}
$className = $class->name;
$namespace = $this->hydratorNamespace;
$code = sprintf(<<<EOF
<?php
namespace $namespace;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
use Doctrine\ODM\MongoDB\Hydrator\HydratorInterface;
use Doctrine\ODM\MongoDB\UnitOfWork;
/**
* THIS CLASS WAS GENERATED BY THE DOCTRINE ODM. DO NOT EDIT THIS FILE.
*/
class $hydratorClassName implements HydratorInterface
{
private \$dm;
private \$unitOfWork;
private \$class;
public function __construct(DocumentManager \$dm, UnitOfWork \$uow, ClassMetadata \$class)
{
\$this->dm = \$dm;
\$this->unitOfWork = \$uow;
\$this->class = \$class;
}
public function hydrate(\$document, \$data, array \$hints = array())
{
\$hydratedData = array();
%s return \$hydratedData;
}
}
EOF
,
$code
);
file_put_contents($fileName, $code);
}
/**
* Hydrate array of MongoDB document data into the given document object.
*
* @param object $document The document object to hydrate the data into.
* @param array $data The array of document data.
* @param array $hints Any hints to account for during reconstitution/lookup of the document.
* @return array $values The array of hydrated values.
*/
public function hydrate($document, $data, array $hints = array())
{
$metadata = $this->dm->getClassMetadata(get_class($document));
// Invoke preLoad lifecycle events and listeners
if (isset($metadata->lifecycleCallbacks[Events::preLoad])) {
$args = array(&$data);
$metadata->invokeLifecycleCallbacks(Events::preLoad, $document, $args);
}
if ($this->evm->hasListeners(Events::preLoad)) {
$this->evm->dispatchEvent(Events::preLoad, new PreLoadEventArgs($document, $this->dm, $data));
}
// Use the alsoLoadMethods on the document object to transform the data before hydration
if (isset($metadata->alsoLoadMethods)) {
foreach ($metadata->alsoLoadMethods as $fieldName => $method) {
if (isset($data[$fieldName])) {
$document->$method($data[$fieldName]);
}
}
}
$data = $this->getHydratorFor($metadata->name)->hydrate($document, $data, $hints);
if ($document instanceof Proxy) {
$document->__isInitialized__ = true;
}
// Invoke the postLoad lifecycle callbacks and listeners
if (isset($metadata->lifecycleCallbacks[Events::postLoad])) {
$metadata->invokeLifecycleCallbacks(Events::postLoad, $document);
}
if ($this->evm->hasListeners(Events::postLoad)) {
$this->evm->dispatchEvent(Events::postLoad, new LifecycleEventArgs($document, $this->dm));
}
return $data;
}
} | tomat/symfony-standard-bootstrap-mongodb | vendor/doctrine-mongodb-odm/lib/Doctrine/ODM/MongoDB/Hydrator/HydratorFactory.php | PHP | mit | 15,430 |
<?php
if(!defined('INITIALIZED'))
exit;
class Database extends PDO
{
public $connectionError = '';
private $connected = false;
const DB_MYSQL = 1;
const DB_SQLITE = 2;
const DB_PGSQL = 3;
private $db_driver;
private $db_host = 'localhost';
private $db_port = '3306';
private $db_name;
private $db_username;
private $db_password;
private $db_file;
public $queriesCount = 0;
public $printQueries = false;
public function connect()
{
return false;
}
public function isConnected()
{
return $this->connected;
}
public function setPrintQueries($value)
{
return $this->printQueries = $value;
}
public function setConnected($value)
{
$this->connected = $value;
}
public function getDatabaseDriver()
{
return $this->db_driver;
}
public function getDatabaseHost()
{
return $this->db_host;
}
public function getDatabasePort()
{
return $this->db_port;
}
public function getDatabaseName()
{
return $this->db_name;
}
public function getDatabaseUsername()
{
return $this->db_username;
}
public function getDatabasePassword()
{
return $this->db_password;
}
public function getDatabaseFile()
{
return $this->db_file;
}
public function setDatabaseDriver($value)
{
$this->db_driver = $value;
}
public function setDatabaseHost($value)
{
$this->db_host = $value;
}
public function setDatabasePort($value)
{
$this->db_port = $value;
}
public function setDatabaseName($value)
{
$this->db_name = $value;
}
public function setDatabaseUsername($value)
{
$this->db_username = $value;
}
public function setDatabasePassword($value)
{
$this->db_password = $value;
}
public function setDatabaseFile($value)
{
$this->db_file = $value;
}
public function beginTransaction()
{
if($this->isConnected() || $this->connect())
return parent::beginTransaction();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute "beginTransaction()"');
}
public function commit()
{
if($this->isConnected() || $this->connect())
return parent::commit();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute "commit()"');
}
public function errorCode()
{
if($this->isConnected() || $this->connect())
return parent::errorCode();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute "errorCode()"');
}
public function errorInfo()
{
if($this->isConnected() || $this->connect())
return parent::errorInfo();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute errorInfo()');
}
public function exec($statement)
{
if($this->isConnected() || $this->connect())
return parent::exec($statement);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute exec($statement)');
}
public function getAttribute($attribute)
{
if($this->isConnected() || $this->connect())
return parent::getAttribute($attribute);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute getAttribute($attribute)');
}
public static function getAvailableDrivers()
{
if($this->isConnected() || $this->connect())
return parent::getAvailableDrivers();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute getAvailableDrivers()');
}
public function inTransaction()
{
if($this->isConnected() || $this->connect())
return parent::inTransaction();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute inTransaction()');
}
public function lastInsertId($name = NULL)
{
if($this->isConnected() || $this->connect())
return parent::lastInsertId($name);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute ');
}
public function prepare($statement, $driver_options = array())
{
if($this->isConnected() || $this->connect())
return parent::prepare($statement, $driver_options);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute lastInsertId($name)');
}
public function query($statement)
{
$this->queriesCount++;
// BETA TESTS - uncomment line below to print all queries on website before execution
//echo'<br />' . $statement . '<br />';
if($this->isConnected() || $this->connect())
{
$ret = parent::query($statement);
if($this->printQueries)
{
$_errorInfo = $this->errorInfo();
echo '<table>';
echo '<tr><td>Query: </td><td>' . $statement . '</td></tr>';
echo '<tr><td>SQLSTATE: </td><td>' . $_errorInfo[0] . '</td></tr>';
echo '<tr><td>Driver code: </td><td>' . $_errorInfo[1] . '</td></tr>';
echo '<tr><td>Error message: </td><td>' . $_errorInfo[2] . '</td></tr>';
echo '</table>';
}
return $ret;
}
else
new Error_Critic('', 'Website is not connected to database. Cannot execute query($statement)');
}
public function quote($string, $parameter_type = PDO::PARAM_STR)
{
if($this->isConnected() || $this->connect())
return parent::quote($string, $parameter_type);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute quote($string, $parameter_type)');
}
public function rollBack()
{
if($this->isConnected() || $this->connect())
return parent::rollBack();
else
new Error_Critic('', 'Website is not connected to database. Cannot execute rollBack()');
}
public function setAttribute($attribute, $value)
{
if($this->isConnected() || $this->connect())
return parent::setAttribute($attribute, $value);
else
new Error_Critic('', 'Website is not connected to database. Cannot execute setAttribute($attribute, $value)');
}
public function setConnectionError($string)
{
$this->connectionError = $string;
}
} | Leo32onGIT/Flash-Bootstrap | game/classes/database.php | PHP | mit | 5,756 |
set(CMAKE_Fortran_VERBOSE_FLAG "-v")
set(CMAKE_Fortran_FORMAT_FIXED_FLAG "-fixedform")
set(CMAKE_Fortran_FORMAT_FREE_FLAG "-freeform")
| htfy96/htscheme | cmake/share/cmake-3.3/Modules/Compiler/MIPSpro-Fortran.cmake | CMake | mit | 138 |
class Gws::Qna::TopicsController < ApplicationController
include Gws::BaseFilter
include Gws::CrudFilter
include Gws::Qna::BaseFilter
include Gws::Memo::NotificationFilter
model Gws::Qna::Topic
navi_view "gws/qna/main/navi"
private
def fix_params
{ cur_user: @cur_user, cur_site: @cur_site }
end
def pre_params
p = super
p[:category_ids] = [@category.id] if @category.present?
p
end
def items
if @mode == 'editable'
@model.site(@cur_site).topic.allow(:read, @cur_user, site: @cur_site).without_deleted
elsif @mode == 'trash'
@model.site(@cur_site).topic.allow(:trash, @cur_user, site: @cur_site).only_deleted
else
@model.site(@cur_site).topic.and_public.readable(@cur_user, site: @cur_site).without_deleted
end
end
def readable?
if @mode == 'editable'
@item.allowed?(:read, @cur_user, site: @cur_site) && @item.deleted.blank?
elsif @mode == 'trash'
@item.allowed?(:trash, @cur_user, site: @cur_site) && @item.deleted.present?
else
(@item.allowed?(:read, @cur_user, site: @cur_site) || @item.readable?(@cur_user)) && @item.deleted.blank?
end
end
public
def index
if @category.present?
params[:s] ||= {}
params[:s][:site] = @cur_site
params[:s][:category] = @category.name
end
@items = items.search(params[:s]).
custom_order(params.dig(:s, :sort) || 'updated_desc').
page(params[:page]).per(50)
end
def show
raise '403' unless readable?
render file: "show_#{@item.mode}"
end
def read
set_item
raise '403' unless readable?
result = true
if [email protected]?(@cur_user)
@item.set_browsed!(@cur_user)
result = true
@item.reload
end
if result
respond_to do |format|
format.html { redirect_to({ action: :show }, { notice: t('ss.notice.saved') }) }
format.json { render json: { _id: @item.id, browsed_at: @item.browsed_at(@cur_user) }, content_type: json_content_type }
end
else
respond_to do |format|
format.html { render({ file: :edit }) }
format.json { render(json: @item.errors.full_messages, status: :unprocessable_entity, content_type: json_content_type) }
end
end
end
def resolve
set_item
raise '403' unless @item.allowed?(:edit, @cur_user, site: @cur_site)
@item.update_attributes(question_state: 'resolved')
redirect_to action: :show
end
def unresolve
set_item
raise '403' unless @item.allowed?(:edit, @cur_user, site: @cur_site)
@item.update_attributes(question_state: 'open')
redirect_to action: :show
end
end
| mizoki/shirasagi | app/controllers/gws/qna/topics_controller.rb | Ruby | mit | 2,653 |
<?php
/**
* PHPMailer - PHP email creation and transport class.
* PHP Version 5.5.
*
* @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
*
* @author Marcus Bointon (Synchro/coolbru) <[email protected]>
* @author Jim Jagielski (jimjag) <[email protected]>
* @author Andy Prevost (codeworxtech) <[email protected]>
* @author Brent R. Matzelle (original founder)
* @copyright 2012 - 2017 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
namespace PHPMailer\PHPMailer;
/**
* PHPMailer - PHP email creation and transport class.
*
* @author Marcus Bointon (Synchro/coolbru) <[email protected]>
* @author Jim Jagielski (jimjag) <[email protected]>
* @author Andy Prevost (codeworxtech) <[email protected]>
* @author Brent R. Matzelle (original founder)
*/
class PHPMailer
{
const CHARSET_ISO88591 = 'iso-8859-1';
const CHARSET_UTF8 = 'utf-8';
const CONTENT_TYPE_PLAINTEXT = 'text/plain';
const CONTENT_TYPE_TEXT_CALENDAR = 'text/calendar';
const CONTENT_TYPE_TEXT_HTML = 'text/html';
const CONTENT_TYPE_MULTIPART_ALTERNATIVE = 'multipart/alternative';
const CONTENT_TYPE_MULTIPART_MIXED = 'multipart/mixed';
const CONTENT_TYPE_MULTIPART_RELATED = 'multipart/related';
const ENCODING_7BIT = '7bit';
const ENCODING_8BIT = '8bit';
const ENCODING_BASE64 = 'base64';
const ENCODING_BINARY = 'binary';
const ENCODING_QUOTED_PRINTABLE = 'quoted-printable';
/**
* Email priority.
* Options: null (default), 1 = High, 3 = Normal, 5 = low.
* When null, the header is not set at all.
*
* @var int
*/
public $Priority;
/**
* The character set of the message.
*
* @var string
*/
public $CharSet = self::CHARSET_ISO88591;
/**
* The MIME Content-type of the message.
*
* @var string
*/
public $ContentType = self::CONTENT_TYPE_PLAINTEXT;
/**
* The message encoding.
* Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
*
* @var string
*/
public $Encoding = self::ENCODING_8BIT;
/**
* Holds the most recent mailer error message.
*
* @var string
*/
public $ErrorInfo = '';
/**
* The From email address for the message.
*
* @var string
*/
public $From = 'root@localhost';
/**
* The From name of the message.
*
* @var string
*/
public $FromName = 'Root User';
/**
* The envelope sender of the message.
* This will usually be turned into a Return-Path header by the receiver,
* and is the address that bounces will be sent to.
* If not empty, will be passed via `-f` to sendmail or as the 'MAIL FROM' value over SMTP.
*
* @var string
*/
public $Sender = '';
/**
* The Subject of the message.
*
* @var string
*/
public $Subject = '';
/**
* An HTML or plain text message body.
* If HTML then call isHTML(true).
*
* @var string
*/
public $Body = '';
/**
* The plain-text message body.
* This body can be read by mail clients that do not have HTML email
* capability such as mutt & Eudora.
* Clients that can read HTML will view the normal Body.
*
* @var string
*/
public $AltBody = '';
/**
* An iCal message part body.
* Only supported in simple alt or alt_inline message types
* To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
*
* @see http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
* @see http://kigkonsult.se/iCalcreator/
*
* @var string
*/
public $Ical = '';
/**
* The complete compiled MIME message body.
*
* @var string
*/
protected $MIMEBody = '';
/**
* The complete compiled MIME message headers.
*
* @var string
*/
protected $MIMEHeader = '';
/**
* Extra headers that createHeader() doesn't fold in.
*
* @var string
*/
protected $mailHeader = '';
/**
* Word-wrap the message body to this number of chars.
* Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
*
* @see static::STD_LINE_LENGTH
*
* @var int
*/
public $WordWrap = 0;
/**
* Which method to use to send mail.
* Options: "mail", "sendmail", or "smtp".
*
* @var string
*/
public $Mailer = 'mail';
/**
* The path to the sendmail program.
*
* @var string
*/
public $Sendmail = '/usr/sbin/sendmail';
/**
* Whether mail() uses a fully sendmail-compatible MTA.
* One which supports sendmail's "-oi -f" options.
*
* @var bool
*/
public $UseSendmailOptions = true;
/**
* The email address that a reading confirmation should be sent to, also known as read receipt.
*
* @var string
*/
public $ConfirmReadingTo = '';
/**
* The hostname to use in the Message-ID header and as default HELO string.
* If empty, PHPMailer attempts to find one with, in order,
* $_SERVER['SERVER_NAME'], gethostname(), php_uname('n'), or the value
* 'localhost.localdomain'.
*
* @var string
*/
public $Hostname = '';
/**
* An ID to be used in the Message-ID header.
* If empty, a unique id will be generated.
* You can set your own, but it must be in the format "<id@domain>",
* as defined in RFC5322 section 3.6.4 or it will be ignored.
*
* @see https://tools.ietf.org/html/rfc5322#section-3.6.4
*
* @var string
*/
public $MessageID = '';
/**
* The message Date to be used in the Date header.
* If empty, the current date will be added.
*
* @var string
*/
public $MessageDate = '';
/**
* SMTP hosts.
* Either a single hostname or multiple semicolon-delimited hostnames.
* You can also specify a different port
* for each host by using this format: [hostname:port]
* (e.g. "smtp1.example.com:25;smtp2.example.com").
* You can also specify encryption type, for example:
* (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
* Hosts will be tried in order.
*
* @var string
*/
public $Host = 'localhost';
/**
* The default SMTP server port.
*
* @var int
*/
public $Port = 25;
/**
* The SMTP HELO of the message.
* Default is $Hostname. If $Hostname is empty, PHPMailer attempts to find
* one with the same method described above for $Hostname.
*
* @see PHPMailer::$Hostname
*
* @var string
*/
public $Helo = '';
/**
* What kind of encryption to use on the SMTP connection.
* Options: '', 'ssl' or 'tls'.
*
* @var string
*/
public $SMTPSecure = '';
/**
* Whether to enable TLS encryption automatically if a server supports it,
* even if `SMTPSecure` is not set to 'tls'.
* Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
*
* @var bool
*/
public $SMTPAutoTLS = true;
/**
* Whether to use SMTP authentication.
* Uses the Username and Password properties.
*
* @see PHPMailer::$Username
* @see PHPMailer::$Password
*
* @var bool
*/
public $SMTPAuth = false;
/**
* Options array passed to stream_context_create when connecting via SMTP.
*
* @var array
*/
public $SMTPOptions = [];
/**
* SMTP username.
*
* @var string
*/
public $Username = '';
/**
* SMTP password.
*
* @var string
*/
public $Password = '';
/**
* SMTP auth type.
* Options are CRAM-MD5, LOGIN, PLAIN, XOAUTH2, attempted in that order if not specified.
*
* @var string
*/
public $AuthType = '';
/**
* An instance of the PHPMailer OAuth class.
*
* @var OAuth
*/
protected $oauth;
/**
* The SMTP server timeout in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2.
*
* @var int
*/
public $Timeout = 300;
/**
* SMTP class debug output mode.
* Debug output level.
* Options:
* * `0` No output
* * `1` Commands
* * `2` Data and commands
* * `3` As 2 plus connection status
* * `4` Low-level data output.
*
* @see SMTP::$do_debug
*
* @var int
*/
public $SMTPDebug = 0;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
* By default PHPMailer will use `echo` if run from a `cli` or `cli-server` SAPI, `html` otherwise.
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
*
* ```php
* $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* ```
*
* Alternatively, you can pass in an instance of a PSR-3 compatible logger, though only `debug`
* level output is used:
*
* ```php
* $mail->Debugoutput = new myPsr3Logger;
* ```
*
* @see SMTP::$Debugoutput
*
* @var string|callable|\Psr\Log\LoggerInterface
*/
public $Debugoutput = 'echo';
/**
* Whether to keep SMTP connection open after each message.
* If this is set to true then to close the connection
* requires an explicit call to smtpClose().
*
* @var bool
*/
public $SMTPKeepAlive = false;
/**
* Whether to split multiple to addresses into multiple messages
* or send them all in one message.
* Only supported in `mail` and `sendmail` transports, not in SMTP.
*
* @var bool
*/
public $SingleTo = false;
/**
* Storage for addresses when SingleTo is enabled.
*
* @var array
*/
protected $SingleToArray = [];
/**
* Whether to generate VERP addresses on send.
* Only applicable when sending via SMTP.
*
* @see https://en.wikipedia.org/wiki/Variable_envelope_return_path
* @see http://www.postfix.org/VERP_README.html Postfix VERP info
*
* @var bool
*/
public $do_verp = false;
/**
* Whether to allow sending messages with an empty body.
*
* @var bool
*/
public $AllowEmpty = false;
/**
* DKIM selector.
*
* @var string
*/
public $DKIM_selector = '';
/**
* DKIM Identity.
* Usually the email address used as the source of the email.
*
* @var string
*/
public $DKIM_identity = '';
/**
* DKIM passphrase.
* Used if your key is encrypted.
*
* @var string
*/
public $DKIM_passphrase = '';
/**
* DKIM signing domain name.
*
* @example 'example.com'
*
* @var string
*/
public $DKIM_domain = '';
/**
* DKIM Copy header field values for diagnostic use.
*
* @var bool
*/
public $DKIM_copyHeaderFields = true;
/**
* DKIM Extra signing headers.
*
* @example ['List-Unsubscribe', 'List-Help']
*
* @var array
*/
public $DKIM_extraHeaders = [];
/**
* DKIM private key file path.
*
* @var string
*/
public $DKIM_private = '';
/**
* DKIM private key string.
*
* If set, takes precedence over `$DKIM_private`.
*
* @var string
*/
public $DKIM_private_string = '';
/**
* Callback Action function name.
*
* The function that handles the result of the send email action.
* It is called out by send() for each email sent.
*
* Value can be any php callable: http://www.php.net/is_callable
*
* Parameters:
* bool $result result of the send action
* array $to email addresses of the recipients
* array $cc cc email addresses
* array $bcc bcc email addresses
* string $subject the subject
* string $body the email body
* string $from email address of sender
* string $extra extra information of possible use
* "smtp_transaction_id' => last smtp transaction id
*
* @var string
*/
public $action_function = '';
/**
* What to put in the X-Mailer header.
* Options: An empty string for PHPMailer default, whitespace for none, or a string to use.
*
* @var string
*/
public $XMailer = '';
/**
* Which validator to use by default when validating email addresses.
* May be a callable to inject your own validator, but there are several built-in validators.
* The default validator uses PHP's FILTER_VALIDATE_EMAIL filter_var option.
*
* @see PHPMailer::validateAddress()
*
* @var string|callable
*/
public static $validator = 'php';
/**
* An instance of the SMTP sender class.
*
* @var SMTP
*/
protected $smtp;
/**
* The array of 'to' names and addresses.
*
* @var array
*/
protected $to = [];
/**
* The array of 'cc' names and addresses.
*
* @var array
*/
protected $cc = [];
/**
* The array of 'bcc' names and addresses.
*
* @var array
*/
protected $bcc = [];
/**
* The array of reply-to names and addresses.
*
* @var array
*/
protected $ReplyTo = [];
/**
* An array of all kinds of addresses.
* Includes all of $to, $cc, $bcc.
*
* @see PHPMailer::$to
* @see PHPMailer::$cc
* @see PHPMailer::$bcc
*
* @var array
*/
protected $all_recipients = [];
/**
* An array of names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $all_recipients
* and one of $to, $cc, or $bcc.
* This array is used only for addresses with IDN.
*
* @see PHPMailer::$to
* @see PHPMailer::$cc
* @see PHPMailer::$bcc
* @see PHPMailer::$all_recipients
*
* @var array
*/
protected $RecipientsQueue = [];
/**
* An array of reply-to names and addresses queued for validation.
* In send(), valid and non duplicate entries are moved to $ReplyTo.
* This array is used only for addresses with IDN.
*
* @see PHPMailer::$ReplyTo
*
* @var array
*/
protected $ReplyToQueue = [];
/**
* The array of attachments.
*
* @var array
*/
protected $attachment = [];
/**
* The array of custom headers.
*
* @var array
*/
protected $CustomHeader = [];
/**
* The most recent Message-ID (including angular brackets).
*
* @var string
*/
protected $lastMessageID = '';
/**
* The message's MIME type.
*
* @var string
*/
protected $message_type = '';
/**
* The array of MIME boundary strings.
*
* @var array
*/
protected $boundary = [];
/**
* The array of available languages.
*
* @var array
*/
protected $language = [];
/**
* The number of errors encountered.
*
* @var int
*/
protected $error_count = 0;
/**
* The S/MIME certificate file path.
*
* @var string
*/
protected $sign_cert_file = '';
/**
* The S/MIME key file path.
*
* @var string
*/
protected $sign_key_file = '';
/**
* The optional S/MIME extra certificates ("CA Chain") file path.
*
* @var string
*/
protected $sign_extracerts_file = '';
/**
* The S/MIME password for the key.
* Used only if the key is encrypted.
*
* @var string
*/
protected $sign_key_pass = '';
/**
* Whether to throw exceptions for errors.
*
* @var bool
*/
protected $exceptions = false;
/**
* Unique ID used for message ID and boundaries.
*
* @var string
*/
protected $uniqueid = '';
/**
* The PHPMailer Version number.
*
* @var string
*/
const VERSION = '6.0.7';
/**
* Error severity: message only, continue processing.
*
* @var int
*/
const STOP_MESSAGE = 0;
/**
* Error severity: message, likely ok to continue processing.
*
* @var int
*/
const STOP_CONTINUE = 1;
/**
* Error severity: message, plus full stop, critical error reached.
*
* @var int
*/
const STOP_CRITICAL = 2;
/**
* SMTP RFC standard line ending.
*
* @var string
*/
protected static $LE = "\r\n";
/**
* The maximum line length allowed by RFC 2822 section 2.1.1.
*
* @var int
*/
const MAX_LINE_LENGTH = 998;
/**
* The lower maximum line length allowed by RFC 2822 section 2.1.1.
* This length does NOT include the line break
* 76 means that lines will be 77 or 78 chars depending on whether
* the line break format is LF or CRLF; both are valid.
*
* @var int
*/
const STD_LINE_LENGTH = 76;
/**
* Constructor.
*
* @param bool $exceptions Should we throw external exceptions?
*/
public function __construct($exceptions = null)
{
if (null !== $exceptions) {
$this->exceptions = (bool) $exceptions;
}
//Pick an appropriate debug output format automatically
$this->Debugoutput = (strpos(PHP_SAPI, 'cli') !== false ? 'echo' : 'html');
}
/**
* Destructor.
*/
public function __destruct()
{
//Close any open SMTP connection nicely
$this->smtpClose();
}
/**
* Call mail() in a safe_mode-aware fashion.
* Also, unless sendmail_path points to sendmail (or something that
* claims to be sendmail), don't pass params (not a perfect fix,
* but it will do).
*
* @param string $to To
* @param string $subject Subject
* @param string $body Message Body
* @param string $header Additional Header(s)
* @param string|null $params Params
*
* @return bool
*/
private function mailPassthru($to, $subject, $body, $header, $params)
{
//Check overloading of mail function to avoid double-encoding
if (ini_get('mbstring.func_overload') & 1) {
$subject = $this->secureHeader($subject);
} else {
$subject = $this->encodeHeader($this->secureHeader($subject));
}
//Calling mail() with null params breaks
if (!$this->UseSendmailOptions or null === $params) {
$result = @mail($to, $subject, $body, $header);
} else {
$result = @mail($to, $subject, $body, $header, $params);
}
return $result;
}
/**
* Output debugging info via user-defined method.
* Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
*
* @see PHPMailer::$Debugoutput
* @see PHPMailer::$SMTPDebug
*
* @param string $str
*/
protected function edebug($str)
{
if ($this->SMTPDebug <= 0) {
return;
}
//Is this a PSR-3 logger?
if ($this->Debugoutput instanceof \Psr\Log\LoggerInterface) {
$this->Debugoutput->debug($str);
return;
}
//Avoid clash with built-in function names
if (!in_array($this->Debugoutput, ['error_log', 'html', 'echo']) and is_callable($this->Debugoutput)) {
call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
return;
}
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
), "<br>\n";
break;
case 'echo':
default:
//Normalize line breaks
$str = preg_replace('/\r\n|\r/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s'),
"\t",
//Trim trailing space
trim(
//Indent for readability, except for trailing break
str_replace(
"\n",
"\n \t ",
trim($str)
)
),
"\n";
}
}
/**
* Sets message type to HTML or plain.
*
* @param bool $isHtml True for HTML mode
*/
public function isHTML($isHtml = true)
{
if ($isHtml) {
$this->ContentType = static::CONTENT_TYPE_TEXT_HTML;
} else {
$this->ContentType = static::CONTENT_TYPE_PLAINTEXT;
}
}
/**
* Send messages using SMTP.
*/
public function isSMTP()
{
$this->Mailer = 'smtp';
}
/**
* Send messages using PHP's mail() function.
*/
public function isMail()
{
$this->Mailer = 'mail';
}
/**
* Send messages using $Sendmail.
*/
public function isSendmail()
{
$ini_sendmail_path = ini_get('sendmail_path');
if (false === stripos($ini_sendmail_path, 'sendmail')) {
$this->Sendmail = '/usr/sbin/sendmail';
} else {
$this->Sendmail = $ini_sendmail_path;
}
$this->Mailer = 'sendmail';
}
/**
* Send messages using qmail.
*/
public function isQmail()
{
$ini_sendmail_path = ini_get('sendmail_path');
if (false === stripos($ini_sendmail_path, 'qmail')) {
$this->Sendmail = '/var/qmail/bin/qmail-inject';
} else {
$this->Sendmail = $ini_sendmail_path;
}
$this->Mailer = 'qmail';
}
/**
* Add a "To" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addAddress($address, $name = '')
{
return $this->addOrEnqueueAnAddress('to', $address, $name);
}
/**
* Add a "CC" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('cc', $address, $name);
}
/**
* Add a "BCC" address.
*
* @param string $address The email address to send to
* @param string $name
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addBCC($address, $name = '')
{
return $this->addOrEnqueueAnAddress('bcc', $address, $name);
}
/**
* Add a "Reply-To" address.
*
* @param string $address The email address to reply to
* @param string $name
*
* @return bool true on success, false if address already used or invalid in some way
*/
public function addReplyTo($address, $name = '')
{
return $this->addOrEnqueueAnAddress('Reply-To', $address, $name);
}
/**
* Add an address to one of the recipient arrays or to the ReplyTo array. Because PHPMailer
* can't validate addresses with an IDN without knowing the PHPMailer::$CharSet (that can still
* be modified after calling this function), addition of such addresses is delayed until send().
* Addresses that have been added already return false, but do not throw exceptions.
*
* @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
* @param string $address The email address to send, resp. to reply to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
protected function addOrEnqueueAnAddress($kind, $address, $name)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
$pos = strrpos($address, '@');
if (false === $pos) {
// At-sign is missing.
$error_message = sprintf('%s (%s): %s',
$this->lang('invalid_address'),
$kind,
$address);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
$params = [$kind, $address, $name];
// Enqueue addresses with IDN until we know the PHPMailer::$CharSet.
if ($this->has8bitChars(substr($address, ++$pos)) and static::idnSupported()) {
if ('Reply-To' != $kind) {
if (!array_key_exists($address, $this->RecipientsQueue)) {
$this->RecipientsQueue[$address] = $params;
return true;
}
} else {
if (!array_key_exists($address, $this->ReplyToQueue)) {
$this->ReplyToQueue[$address] = $params;
return true;
}
}
return false;
}
// Immediately add standard addresses without IDN.
return call_user_func_array([$this, 'addAnAddress'], $params);
}
/**
* Add an address to one of the recipient arrays or to the ReplyTo array.
* Addresses that have been added already return false, but do not throw exceptions.
*
* @param string $kind One of 'to', 'cc', 'bcc', or 'ReplyTo'
* @param string $address The email address to send, resp. to reply to
* @param string $name
*
* @throws Exception
*
* @return bool true on success, false if address already used or invalid in some way
*/
protected function addAnAddress($kind, $address, $name = '')
{
if (!in_array($kind, ['to', 'cc', 'bcc', 'Reply-To'])) {
$error_message = sprintf('%s: %s',
$this->lang('Invalid recipient kind'),
$kind);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
if (!static::validateAddress($address)) {
$error_message = sprintf('%s (%s): %s',
$this->lang('invalid_address'),
$kind,
$address);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
if ('Reply-To' != $kind) {
if (!array_key_exists(strtolower($address), $this->all_recipients)) {
$this->{$kind}[] = [$address, $name];
$this->all_recipients[strtolower($address)] = true;
return true;
}
} else {
if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
$this->ReplyTo[strtolower($address)] = [$address, $name];
return true;
}
}
return false;
}
/**
* Parse and validate a string containing one or more RFC822-style comma-separated email addresses
* of the form "display name <address>" into an array of name/address pairs.
* Uses the imap_rfc822_parse_adrlist function if the IMAP extension is available.
* Note that quotes in the name part are removed.
*
* @see http://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
*
* @param string $addrstr The address list string
* @param bool $useimap Whether to use the IMAP extension to parse the list
*
* @return array
*/
public static function parseAddresses($addrstr, $useimap = true)
{
$addresses = [];
if ($useimap and function_exists('imap_rfc822_parse_adrlist')) {
//Use this built-in parser if it's available
$list = imap_rfc822_parse_adrlist($addrstr, '');
foreach ($list as $address) {
if ('.SYNTAX-ERROR.' != $address->host) {
if (static::validateAddress($address->mailbox . '@' . $address->host)) {
$addresses[] = [
'name' => (property_exists($address, 'personal') ? $address->personal : ''),
'address' => $address->mailbox . '@' . $address->host,
];
}
}
}
} else {
//Use this simpler parser
$list = explode(',', $addrstr);
foreach ($list as $address) {
$address = trim($address);
//Is there a separate name part?
if (strpos($address, '<') === false) {
//No separate name, just use the whole thing
if (static::validateAddress($address)) {
$addresses[] = [
'name' => '',
'address' => $address,
];
}
} else {
list($name, $email) = explode('<', $address);
$email = trim(str_replace('>', '', $email));
if (static::validateAddress($email)) {
$addresses[] = [
'name' => trim(str_replace(['"', "'"], '', $name)),
'address' => $email,
];
}
}
}
}
return $addresses;
}
/**
* Set the From and FromName properties.
*
* @param string $address
* @param string $name
* @param bool $auto Whether to also set the Sender address, defaults to true
*
* @throws Exception
*
* @return bool
*/
public function setFrom($address, $name = '', $auto = true)
{
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
// Don't validate now addresses with IDN. Will be done in send().
$pos = strrpos($address, '@');
if (false === $pos or
(!$this->has8bitChars(substr($address, ++$pos)) or !static::idnSupported()) and
!static::validateAddress($address)) {
$error_message = sprintf('%s (From): %s',
$this->lang('invalid_address'),
$address);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
/**
* Return the Message-ID header of the last email.
* Technically this is the value from the last time the headers were created,
* but it's also the message ID of the last sent message except in
* pathological cases.
*
* @return string
*/
public function getLastMessageID()
{
return $this->lastMessageID;
}
/**
* Check that a string looks like an email address.
* Validation patterns supported:
* * `auto` Pick best pattern automatically;
* * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0;
* * `pcre` Use old PCRE implementation;
* * `php` Use PHP built-in FILTER_VALIDATE_EMAIL;
* * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
* * `noregex` Don't use a regex: super fast, really dumb.
* Alternatively you may pass in a callable to inject your own validator, for example:
*
* ```php
* PHPMailer::validateAddress('[email protected]', function($address) {
* return (strpos($address, '@') !== false);
* });
* ```
*
* You can also set the PHPMailer::$validator static to a callable, allowing built-in methods to use your validator.
*
* @param string $address The email address to check
* @param string|callable $patternselect Which pattern to use
*
* @return bool
*/
public static function validateAddress($address, $patternselect = null)
{
if (null === $patternselect) {
$patternselect = static::$validator;
}
if (is_callable($patternselect)) {
return call_user_func($patternselect, $address);
}
//Reject line breaks in addresses; it's valid RFC5322, but not RFC5321
if (strpos($address, "\n") !== false or strpos($address, "\r") !== false) {
return false;
}
switch ($patternselect) {
case 'pcre': //Kept for BC
case 'pcre8':
/*
* A more complex and more permissive version of the RFC5322 regex on which FILTER_VALIDATE_EMAIL
* is based.
* In addition to the addresses allowed by filter_var, also permits:
* * dotless domains: `a@b`
* * comments: `1234 @ local(blah) .machine .example`
* * quoted elements: `'"test blah"@example.org'`
* * numeric TLDs: `[email protected]`
* * unbracketed IPv4 literals: `[email protected]`
* * IPv6 literals: 'first.last@[IPv6:a1::]'
* Not all of these will necessarily work for sending!
*
* @see http://squiloople.com/2009/12/20/email-address-validation/
* @copyright 2009-2010 Michael Rushton
* Feel free to use and redistribute this code. But please keep this copyright notice.
*/
return (bool) preg_match(
'/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
'((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
'(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
'([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
'(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
'(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
'|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
'|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
'|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
$address
);
case 'html5':
/*
* This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
*
* @see http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
*/
return (bool) preg_match(
'/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
'[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
$address
);
case 'php':
default:
return (bool) filter_var($address, FILTER_VALIDATE_EMAIL);
}
}
/**
* Tells whether IDNs (Internationalized Domain Names) are supported or not. This requires the
* `intl` and `mbstring` PHP extensions.
*
* @return bool `true` if required functions for IDN support are present
*/
public static function idnSupported()
{
return function_exists('idn_to_ascii') and function_exists('mb_convert_encoding');
}
/**
* Converts IDN in given email address to its ASCII form, also known as punycode, if possible.
* Important: Address must be passed in same encoding as currently set in PHPMailer::$CharSet.
* This function silently returns unmodified address if:
* - No conversion is necessary (i.e. domain name is not an IDN, or is already in ASCII form)
* - Conversion to punycode is impossible (e.g. required PHP functions are not available)
* or fails for any reason (e.g. domain contains characters not allowed in an IDN).
*
* @see PHPMailer::$CharSet
*
* @param string $address The email address to convert
*
* @return string The encoded address in ASCII form
*/
public function punyencodeAddress($address)
{
// Verify we have required functions, CharSet, and at-sign.
$pos = strrpos($address, '@');
if (static::idnSupported() and
!empty($this->CharSet) and
false !== $pos
) {
$domain = substr($address, ++$pos);
// Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
if ($this->has8bitChars($domain) and @mb_check_encoding($domain, $this->CharSet)) {
$domain = mb_convert_encoding($domain, 'UTF-8', $this->CharSet);
//Ignore IDE complaints about this line - method signature changed in PHP 5.4
$errorcode = 0;
$punycode = idn_to_ascii($domain, $errorcode, INTL_IDNA_VARIANT_UTS46);
if (false !== $punycode) {
return substr($address, 0, $pos) . $punycode;
}
}
}
return $address;
}
/**
* Create a message and send it.
* Uses the sending method specified by $Mailer.
*
* @throws Exception
*
* @return bool false on error - See the ErrorInfo property for details of the error
*/
public function send()
{
try {
if (!$this->preSend()) {
return false;
}
return $this->postSend();
} catch (Exception $exc) {
$this->mailHeader = '';
$this->setError($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
}
/**
* Prepare a message for sending.
*
* @throws Exception
*
* @return bool
*/
public function preSend()
{
if ('smtp' == $this->Mailer or
('mail' == $this->Mailer and stripos(PHP_OS, 'WIN') === 0)
) {
//SMTP mandates RFC-compliant line endings
//and it's also used with mail() on Windows
static::setLE("\r\n");
} else {
//Maintain backward compatibility with legacy Linux command line mailers
static::setLE(PHP_EOL);
}
//Check for buggy PHP versions that add a header with an incorrect line break
if (ini_get('mail.add_x_header') == 1
and 'mail' == $this->Mailer
and stripos(PHP_OS, 'WIN') === 0
and ((version_compare(PHP_VERSION, '7.0.0', '>=')
and version_compare(PHP_VERSION, '7.0.17', '<'))
or (version_compare(PHP_VERSION, '7.1.0', '>=')
and version_compare(PHP_VERSION, '7.1.3', '<')))
) {
trigger_error(
'Your version of PHP is affected by a bug that may result in corrupted messages.' .
' To fix it, switch to sending using SMTP, disable the mail.add_x_header option in' .
' your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+.',
E_USER_WARNING
);
}
try {
$this->error_count = 0; // Reset errors
$this->mailHeader = '';
// Dequeue recipient and Reply-To addresses with IDN
foreach (array_merge($this->RecipientsQueue, $this->ReplyToQueue) as $params) {
$params[1] = $this->punyencodeAddress($params[1]);
call_user_func_array([$this, 'addAnAddress'], $params);
}
if (count($this->to) + count($this->cc) + count($this->bcc) < 1) {
throw new Exception($this->lang('provide_address'), self::STOP_CRITICAL);
}
// Validate From, Sender, and ConfirmReadingTo addresses
foreach (['From', 'Sender', 'ConfirmReadingTo'] as $address_kind) {
$this->$address_kind = trim($this->$address_kind);
if (empty($this->$address_kind)) {
continue;
}
$this->$address_kind = $this->punyencodeAddress($this->$address_kind);
if (!static::validateAddress($this->$address_kind)) {
$error_message = sprintf('%s (%s): %s',
$this->lang('invalid_address'),
$address_kind,
$this->$address_kind);
$this->setError($error_message);
$this->edebug($error_message);
if ($this->exceptions) {
throw new Exception($error_message);
}
return false;
}
}
// Set whether the message is multipart/alternative
if ($this->alternativeExists()) {
$this->ContentType = static::CONTENT_TYPE_MULTIPART_ALTERNATIVE;
}
$this->setMessageType();
// Refuse to send an empty message unless we are specifically allowing it
if (!$this->AllowEmpty and empty($this->Body)) {
throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
}
//Trim subject consistently
$this->Subject = trim($this->Subject);
// Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
$this->MIMEHeader = '';
$this->MIMEBody = $this->createBody();
// createBody may have added some headers, so retain them
$tempheaders = $this->MIMEHeader;
$this->MIMEHeader = $this->createHeader();
$this->MIMEHeader .= $tempheaders;
// To capture the complete message when using mail(), create
// an extra header list which createHeader() doesn't fold in
if ('mail' == $this->Mailer) {
if (count($this->to) > 0) {
$this->mailHeader .= $this->addrAppend('To', $this->to);
} else {
$this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
}
$this->mailHeader .= $this->headerLine(
'Subject',
$this->encodeHeader($this->secureHeader($this->Subject))
);
}
// Sign with DKIM if enabled
if (!empty($this->DKIM_domain)
and !empty($this->DKIM_selector)
and (!empty($this->DKIM_private_string)
or (!empty($this->DKIM_private)
and static::isPermittedPath($this->DKIM_private)
and file_exists($this->DKIM_private)
)
)
) {
$header_dkim = $this->DKIM_Add(
$this->MIMEHeader . $this->mailHeader,
$this->encodeHeader($this->secureHeader($this->Subject)),
$this->MIMEBody
);
$this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . static::$LE .
static::normalizeBreaks($header_dkim) . static::$LE;
}
return true;
} catch (Exception $exc) {
$this->setError($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
}
/**
* Actually send a message via the selected mechanism.
*
* @throws Exception
*
* @return bool
*/
public function postSend()
{
try {
// Choose the mailer and send through it
switch ($this->Mailer) {
case 'sendmail':
case 'qmail':
return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
case 'smtp':
return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
case 'mail':
return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
default:
$sendMethod = $this->Mailer . 'Send';
if (method_exists($this, $sendMethod)) {
return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
}
return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
}
} catch (Exception $exc) {
$this->setError($exc->getMessage());
$this->edebug($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
}
return false;
}
/**
* Send mail using the $Sendmail program.
*
* @see PHPMailer::$Sendmail
*
* @param string $header The message headers
* @param string $body The message body
*
* @throws Exception
*
* @return bool
*/
protected function sendmailSend($header, $body)
{
// CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
if (!empty($this->Sender) and self::isShellSafe($this->Sender)) {
if ('qmail' == $this->Mailer) {
$sendmailFmt = '%s -f%s';
} else {
$sendmailFmt = '%s -oi -f%s -t';
}
} else {
if ('qmail' == $this->Mailer) {
$sendmailFmt = '%s';
} else {
$sendmailFmt = '%s -oi -t';
}
}
$sendmail = sprintf($sendmailFmt, escapeshellcmd($this->Sendmail), $this->Sender);
if ($this->SingleTo) {
foreach ($this->SingleToArray as $toAddr) {
$mail = @popen($sendmail, 'w');
if (!$mail) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fwrite($mail, 'To: ' . $toAddr . "\n");
fwrite($mail, $header);
fwrite($mail, $body);
$result = pclose($mail);
$this->doCallback(
($result == 0),
[$toAddr],
$this->cc,
$this->bcc,
$this->Subject,
$body,
$this->From,
[]
);
if (0 !== $result) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
} else {
$mail = @popen($sendmail, 'w');
if (!$mail) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
fwrite($mail, $header);
fwrite($mail, $body);
$result = pclose($mail);
$this->doCallback(
($result == 0),
$this->to,
$this->cc,
$this->bcc,
$this->Subject,
$body,
$this->From,
[]
);
if (0 !== $result) {
throw new Exception($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
}
}
return true;
}
/**
* Fix CVE-2016-10033 and CVE-2016-10045 by disallowing potentially unsafe shell characters.
* Note that escapeshellarg and escapeshellcmd are inadequate for our purposes, especially on Windows.
*
* @see https://github.com/PHPMailer/PHPMailer/issues/924 CVE-2016-10045 bug report
*
* @param string $string The string to be validated
*
* @return bool
*/
protected static function isShellSafe($string)
{
// Future-proof
if (escapeshellcmd($string) !== $string
or !in_array(escapeshellarg($string), ["'$string'", "\"$string\""])
) {
return false;
}
$length = strlen($string);
for ($i = 0; $i < $length; ++$i) {
$c = $string[$i];
// All other characters have a special meaning in at least one common shell, including = and +.
// Full stop (.) has a special meaning in cmd.exe, but its impact should be negligible here.
// Note that this does permit non-Latin alphanumeric characters based on the current locale.
if (!ctype_alnum($c) && strpos('@_-.', $c) === false) {
return false;
}
}
return true;
}
/**
* Check whether a file path is of a permitted type.
* Used to reject URLs and phar files from functions that access local file paths,
* such as addAttachment.
*
* @param string $path A relative or absolute path to a file
*
* @return bool
*/
protected static function isPermittedPath($path)
{
return !preg_match('#^[a-z]+://#i', $path);
}
/**
* Send mail using the PHP mail() function.
*
* @see http://www.php.net/manual/en/book.mail.php
*
* @param string $header The message headers
* @param string $body The message body
*
* @throws Exception
*
* @return bool
*/
protected function mailSend($header, $body)
{
$toArr = [];
foreach ($this->to as $toaddr) {
$toArr[] = $this->addrFormat($toaddr);
}
$to = implode(', ', $toArr);
$params = null;
//This sets the SMTP envelope sender which gets turned into a return-path header by the receiver
if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
//A space after `-f` is optional, but there is a long history of its presence
//causing problems, so we don't use one
//Exim docs: http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
//Sendmail docs: http://www.sendmail.org/~ca/email/man/sendmail.html
//Qmail docs: http://www.qmail.org/man/man8/qmail-inject.html
//Example problem: https://www.drupal.org/node/1057954
// CVE-2016-10033, CVE-2016-10045: Don't pass -f if characters will be escaped.
if (self::isShellSafe($this->Sender)) {
$params = sprintf('-f%s', $this->Sender);
}
}
if (!empty($this->Sender) and static::validateAddress($this->Sender)) {
$old_from = ini_get('sendmail_from');
ini_set('sendmail_from', $this->Sender);
}
$result = false;
if ($this->SingleTo and count($toArr) > 1) {
foreach ($toArr as $toAddr) {
$result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
$this->doCallback($result, [$toAddr], $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
}
} else {
$result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
$this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From, []);
}
if (isset($old_from)) {
ini_set('sendmail_from', $old_from);
}
if (!$result) {
throw new Exception($this->lang('instantiate'), self::STOP_CRITICAL);
}
return true;
}
/**
* Get an instance to use for SMTP operations.
* Override this function to load your own SMTP implementation,
* or set one with setSMTPInstance.
*
* @return SMTP
*/
public function getSMTPInstance()
{
if (!is_object($this->smtp)) {
$this->smtp = new SMTP();
}
return $this->smtp;
}
/**
* Provide an instance to use for SMTP operations.
*
* @param SMTP $smtp
*
* @return SMTP
*/
public function setSMTPInstance(SMTP $smtp)
{
$this->smtp = $smtp;
return $this->smtp;
}
/**
* Send mail via SMTP.
* Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
*
* @see PHPMailer::setSMTPInstance() to use a different class.
*
* @uses \PHPMailer\PHPMailer\SMTP
*
* @param string $header The message headers
* @param string $body The message body
*
* @throws Exception
*
* @return bool
*/
protected function smtpSend($header, $body)
{
$bad_rcpt = [];
if (!$this->smtpConnect($this->SMTPOptions)) {
throw new Exception($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
}
//Sender already validated in preSend()
if ('' == $this->Sender) {
$smtp_from = $this->From;
} else {
$smtp_from = $this->Sender;
}
if (!$this->smtp->mail($smtp_from)) {
$this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
throw new Exception($this->ErrorInfo, self::STOP_CRITICAL);
}
$callbacks = [];
// Attempt to send to all recipients
foreach ([$this->to, $this->cc, $this->bcc] as $togroup) {
foreach ($togroup as $to) {
if (!$this->smtp->recipient($to[0])) {
$error = $this->smtp->getError();
$bad_rcpt[] = ['to' => $to[0], 'error' => $error['detail']];
$isSent = false;
} else {
$isSent = true;
}
$callbacks[] = ['issent'=>$isSent, 'to'=>$to[0]];
}
}
// Only send the DATA command if we have viable recipients
if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
throw new Exception($this->lang('data_not_accepted'), self::STOP_CRITICAL);
}
$smtp_transaction_id = $this->smtp->getLastTransactionID();
if ($this->SMTPKeepAlive) {
$this->smtp->reset();
} else {
$this->smtp->quit();
$this->smtp->close();
}
foreach ($callbacks as $cb) {
$this->doCallback(
$cb['issent'],
[$cb['to']],
[],
[],
$this->Subject,
$body,
$this->From,
['smtp_transaction_id' => $smtp_transaction_id]
);
}
//Create error message for any bad addresses
if (count($bad_rcpt) > 0) {
$errstr = '';
foreach ($bad_rcpt as $bad) {
$errstr .= $bad['to'] . ': ' . $bad['error'];
}
throw new Exception(
$this->lang('recipients_failed') . $errstr,
self::STOP_CONTINUE
);
}
return true;
}
/**
* Initiate a connection to an SMTP server.
* Returns false if the operation failed.
*
* @param array $options An array of options compatible with stream_context_create()
*
* @throws Exception
*
* @uses \PHPMailer\PHPMailer\SMTP
*
* @return bool
*/
public function smtpConnect($options = null)
{
if (null === $this->smtp) {
$this->smtp = $this->getSMTPInstance();
}
//If no options are provided, use whatever is set in the instance
if (null === $options) {
$options = $this->SMTPOptions;
}
// Already connected?
if ($this->smtp->connected()) {
return true;
}
$this->smtp->setTimeout($this->Timeout);
$this->smtp->setDebugLevel($this->SMTPDebug);
$this->smtp->setDebugOutput($this->Debugoutput);
$this->smtp->setVerp($this->do_verp);
$hosts = explode(';', $this->Host);
$lastexception = null;
foreach ($hosts as $hostentry) {
$hostinfo = [];
if (!preg_match(
'/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*|\[[a-fA-F0-9:]+\]):?([0-9]*)$/',
trim($hostentry),
$hostinfo
)) {
static::edebug($this->lang('connect_host') . ' ' . $hostentry);
// Not a valid host entry
continue;
}
// $hostinfo[2]: optional ssl or tls prefix
// $hostinfo[3]: the hostname
// $hostinfo[4]: optional port number
// The host string prefix can temporarily override the current setting for SMTPSecure
// If it's not specified, the default value is used
//Check the host name is a valid name or IP address before trying to use it
if (!static::isValidHost($hostinfo[3])) {
static::edebug($this->lang('connect_host') . ' ' . $hostentry);
continue;
}
$prefix = '';
$secure = $this->SMTPSecure;
$tls = ('tls' == $this->SMTPSecure);
if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
$prefix = 'ssl://';
$tls = false; // Can't have SSL and TLS at the same time
$secure = 'ssl';
} elseif ('tls' == $hostinfo[2]) {
$tls = true;
// tls doesn't use a prefix
$secure = 'tls';
}
//Do we need the OpenSSL extension?
$sslext = defined('OPENSSL_ALGO_SHA256');
if ('tls' === $secure or 'ssl' === $secure) {
//Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
if (!$sslext) {
throw new Exception($this->lang('extension_missing') . 'openssl', self::STOP_CRITICAL);
}
}
$host = $hostinfo[3];
$port = $this->Port;
$tport = (int) $hostinfo[4];
if ($tport > 0 and $tport < 65536) {
$port = $tport;
}
if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
try {
if ($this->Helo) {
$hello = $this->Helo;
} else {
$hello = $this->serverHostname();
}
$this->smtp->hello($hello);
//Automatically enable TLS encryption if:
// * it's not disabled
// * we have openssl extension
// * we are not already using SSL
// * the server offers STARTTLS
if ($this->SMTPAutoTLS and $sslext and 'ssl' != $secure and $this->smtp->getServerExt('STARTTLS')) {
$tls = true;
}
if ($tls) {
if (!$this->smtp->startTLS()) {
throw new Exception($this->lang('connect_host'));
}
// We must resend EHLO after TLS negotiation
$this->smtp->hello($hello);
}
if ($this->SMTPAuth) {
if (!$this->smtp->authenticate(
$this->Username,
$this->Password,
$this->AuthType,
$this->oauth
)
) {
throw new Exception($this->lang('authenticate'));
}
}
return true;
} catch (Exception $exc) {
$lastexception = $exc;
$this->edebug($exc->getMessage());
// We must have connected, but then failed TLS or Auth, so close connection nicely
$this->smtp->quit();
}
}
}
// If we get here, all connection attempts have failed, so close connection hard
$this->smtp->close();
// As we've caught all exceptions, just report whatever the last one was
if ($this->exceptions and null !== $lastexception) {
throw $lastexception;
}
return false;
}
/**
* Close the active SMTP session if one exists.
*/
public function smtpClose()
{
if (null !== $this->smtp) {
if ($this->smtp->connected()) {
$this->smtp->quit();
$this->smtp->close();
}
}
}
/**
* Set the language for error messages.
* Returns false if it cannot load the language file.
* The default language is English.
*
* @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
* @param string $lang_path Path to the language file directory, with trailing separator (slash)
*
* @return bool
*/
public function setLanguage($langcode = 'en', $lang_path = '')
{
// Backwards compatibility for renamed language codes
$renamed_langcodes = [
'br' => 'pt_br',
'cz' => 'cs',
'dk' => 'da',
'no' => 'nb',
'se' => 'sv',
'rs' => 'sr',
'tg' => 'tl',
];
if (isset($renamed_langcodes[$langcode])) {
$langcode = $renamed_langcodes[$langcode];
}
// Define full set of translatable strings in English
$PHPMAILER_LANG = [
'authenticate' => 'SMTP Error: Could not authenticate.',
'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
'data_not_accepted' => 'SMTP Error: data not accepted.',
'empty_message' => 'Message body empty',
'encoding' => 'Unknown encoding: ',
'execute' => 'Could not execute: ',
'file_access' => 'Could not access file: ',
'file_open' => 'File Error: Could not open file: ',
'from_failed' => 'The following From address failed: ',
'instantiate' => 'Could not instantiate mail function.',
'invalid_address' => 'Invalid address: ',
'mailer_not_supported' => ' mailer is not supported.',
'provide_address' => 'You must provide at least one recipient email address.',
'recipients_failed' => 'SMTP Error: The following recipients failed: ',
'signing' => 'Signing Error: ',
'smtp_connect_failed' => 'SMTP connect() failed.',
'smtp_error' => 'SMTP server error: ',
'variable_set' => 'Cannot set or reset variable: ',
'extension_missing' => 'Extension missing: ',
];
if (empty($lang_path)) {
// Calculate an absolute path so it can work if CWD is not here
$lang_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'language' . DIRECTORY_SEPARATOR;
}
//Validate $langcode
if (!preg_match('/^[a-z]{2}(?:_[a-zA-Z]{2})?$/', $langcode)) {
$langcode = 'en';
}
$foundlang = true;
$lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
// There is no English translation file
if ('en' != $langcode) {
// Make sure language file path is readable
if (!static::isPermittedPath($lang_file) || !file_exists($lang_file)) {
$foundlang = false;
} else {
// Overwrite language-specific strings.
// This way we'll never have missing translation keys.
$foundlang = include $lang_file;
}
}
$this->language = $PHPMAILER_LANG;
return (bool) $foundlang; // Returns false if language not found
}
/**
* Get the array of strings for the current language.
*
* @return array
*/
public function getTranslations()
{
return $this->language;
}
/**
* Create recipient headers.
*
* @param string $type
* @param array $addr An array of recipients,
* where each recipient is a 2-element indexed array with element 0 containing an address
* and element 1 containing a name, like:
* [['[email protected]', 'Joe User'], ['[email protected]', 'Zoe User']]
*
* @return string
*/
public function addrAppend($type, $addr)
{
$addresses = [];
foreach ($addr as $address) {
$addresses[] = $this->addrFormat($address);
}
return $type . ': ' . implode(', ', $addresses) . static::$LE;
}
/**
* Format an address for use in a message header.
*
* @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name like
* ['[email protected]', 'Joe User']
*
* @return string
*/
public function addrFormat($addr)
{
if (empty($addr[1])) { // No name provided
return $this->secureHeader($addr[0]);
}
return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
$addr[0]
) . '>';
}
/**
* Word-wrap message.
* For use with mailers that do not automatically perform wrapping
* and for quoted-printable encoded messages.
* Original written by philippe.
*
* @param string $message The message to wrap
* @param int $length The line length to wrap to
* @param bool $qp_mode Whether to run in Quoted-Printable mode
*
* @return string
*/
public function wrapText($message, $length, $qp_mode = false)
{
if ($qp_mode) {
$soft_break = sprintf(' =%s', static::$LE);
} else {
$soft_break = static::$LE;
}
// If utf-8 encoding is used, we will need to make sure we don't
// split multibyte characters when we wrap
$is_utf8 = static::CHARSET_UTF8 === strtolower($this->CharSet);
$lelen = strlen(static::$LE);
$crlflen = strlen(static::$LE);
$message = static::normalizeBreaks($message);
//Remove a trailing line break
if (substr($message, -$lelen) == static::$LE) {
$message = substr($message, 0, -$lelen);
}
//Split message into lines
$lines = explode(static::$LE, $message);
//Message will be rebuilt in here
$message = '';
foreach ($lines as $line) {
$words = explode(' ', $line);
$buf = '';
$firstword = true;
foreach ($words as $word) {
if ($qp_mode and (strlen($word) > $length)) {
$space_left = $length - strlen($buf) - $crlflen;
if (!$firstword) {
if ($space_left > 20) {
$len = $space_left;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif ('=' == substr($word, $len - 1, 1)) {
--$len;
} elseif ('=' == substr($word, $len - 2, 1)) {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
$buf .= ' ' . $part;
$message .= $buf . sprintf('=%s', static::$LE);
} else {
$message .= $buf . $soft_break;
}
$buf = '';
}
while (strlen($word) > 0) {
if ($length <= 0) {
break;
}
$len = $length;
if ($is_utf8) {
$len = $this->utf8CharBoundary($word, $len);
} elseif ('=' == substr($word, $len - 1, 1)) {
--$len;
} elseif ('=' == substr($word, $len - 2, 1)) {
$len -= 2;
}
$part = substr($word, 0, $len);
$word = substr($word, $len);
if (strlen($word) > 0) {
$message .= $part . sprintf('=%s', static::$LE);
} else {
$buf = $part;
}
}
} else {
$buf_o = $buf;
if (!$firstword) {
$buf .= ' ';
}
$buf .= $word;
if (strlen($buf) > $length and '' != $buf_o) {
$message .= $buf_o . $soft_break;
$buf = $word;
}
}
$firstword = false;
}
$message .= $buf . static::$LE;
}
return $message;
}
/**
* Find the last character boundary prior to $maxLength in a utf-8
* quoted-printable encoded string.
* Original written by Colin Brown.
*
* @param string $encodedText utf-8 QP text
* @param int $maxLength Find the last character boundary prior to this length
*
* @return int
*/
public function utf8CharBoundary($encodedText, $maxLength)
{
$foundSplitPos = false;
$lookBack = 3;
while (!$foundSplitPos) {
$lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
$encodedCharPos = strpos($lastChunk, '=');
if (false !== $encodedCharPos) {
// Found start of encoded character byte within $lookBack block.
// Check the encoded byte value (the 2 chars after the '=')
$hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
$dec = hexdec($hex);
if ($dec < 128) {
// Single byte character.
// If the encoded char was found at pos 0, it will fit
// otherwise reduce maxLength to start of the encoded char
if ($encodedCharPos > 0) {
$maxLength -= $lookBack - $encodedCharPos;
}
$foundSplitPos = true;
} elseif ($dec >= 192) {
// First byte of a multi byte character
// Reduce maxLength to split at start of character
$maxLength -= $lookBack - $encodedCharPos;
$foundSplitPos = true;
} elseif ($dec < 192) {
// Middle byte of a multi byte character, look further back
$lookBack += 3;
}
} else {
// No encoded character found
$foundSplitPos = true;
}
}
return $maxLength;
}
/**
* Apply word wrapping to the message body.
* Wraps the message body to the number of chars set in the WordWrap property.
* You should only do this to plain-text bodies as wrapping HTML tags may break them.
* This is called automatically by createBody(), so you don't need to call it yourself.
*/
public function setWordWrap()
{
if ($this->WordWrap < 1) {
return;
}
switch ($this->message_type) {
case 'alt':
case 'alt_inline':
case 'alt_attach':
case 'alt_inline_attach':
$this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
break;
default:
$this->Body = $this->wrapText($this->Body, $this->WordWrap);
break;
}
}
/**
* Assemble message headers.
*
* @return string The assembled headers
*/
public function createHeader()
{
$result = '';
$result .= $this->headerLine('Date', '' == $this->MessageDate ? self::rfcDate() : $this->MessageDate);
// To be created automatically by mail()
if ($this->SingleTo) {
if ('mail' != $this->Mailer) {
foreach ($this->to as $toaddr) {
$this->SingleToArray[] = $this->addrFormat($toaddr);
}
}
} else {
if (count($this->to) > 0) {
if ('mail' != $this->Mailer) {
$result .= $this->addrAppend('To', $this->to);
}
} elseif (count($this->cc) == 0) {
$result .= $this->headerLine('To', 'undisclosed-recipients:;');
}
}
$result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
// sendmail and mail() extract Cc from the header before sending
if (count($this->cc) > 0) {
$result .= $this->addrAppend('Cc', $this->cc);
}
// sendmail and mail() extract Bcc from the header before sending
if ((
'sendmail' == $this->Mailer or 'qmail' == $this->Mailer or 'mail' == $this->Mailer
)
and count($this->bcc) > 0
) {
$result .= $this->addrAppend('Bcc', $this->bcc);
}
if (count($this->ReplyTo) > 0) {
$result .= $this->addrAppend('Reply-To', $this->ReplyTo);
}
// mail() sets the subject itself
if ('mail' != $this->Mailer) {
$result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
}
// Only allow a custom message ID if it conforms to RFC 5322 section 3.6.4
// https://tools.ietf.org/html/rfc5322#section-3.6.4
if ('' != $this->MessageID and preg_match('/^<.*@.*>$/', $this->MessageID)) {
$this->lastMessageID = $this->MessageID;
} else {
$this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
}
$result .= $this->headerLine('Message-ID', $this->lastMessageID);
if (null !== $this->Priority) {
$result .= $this->headerLine('X-Priority', $this->Priority);
}
if ('' == $this->XMailer) {
$result .= $this->headerLine(
'X-Mailer',
'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
);
} else {
$myXmailer = trim($this->XMailer);
if ($myXmailer) {
$result .= $this->headerLine('X-Mailer', $myXmailer);
}
}
if ('' != $this->ConfirmReadingTo) {
$result .= $this->headerLine('Disposition-Notification-To', '<' . $this->ConfirmReadingTo . '>');
}
// Add custom headers
foreach ($this->CustomHeader as $header) {
$result .= $this->headerLine(
trim($header[0]),
$this->encodeHeader(trim($header[1]))
);
}
if (!$this->sign_key_file) {
$result .= $this->headerLine('MIME-Version', '1.0');
$result .= $this->getMailMIME();
}
return $result;
}
/**
* Get the message MIME type headers.
*
* @return string
*/
public function getMailMIME()
{
$result = '';
$ismultipart = true;
switch ($this->message_type) {
case 'inline':
$result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'attach':
case 'inline_attach':
case 'alt_attach':
case 'alt_inline_attach':
$result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_MIXED . ';');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
case 'alt':
case 'alt_inline':
$result .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
$result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
break;
default:
// Catches case 'plain': and case '':
$result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
$ismultipart = false;
break;
}
// RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT != $this->Encoding) {
// RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
if ($ismultipart) {
if (static::ENCODING_8BIT == $this->Encoding) {
$result .= $this->headerLine('Content-Transfer-Encoding', static::ENCODING_8BIT);
}
// The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
} else {
$result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
}
}
if ('mail' != $this->Mailer) {
$result .= static::$LE;
}
return $result;
}
/**
* Returns the whole MIME message.
* Includes complete headers and body.
* Only valid post preSend().
*
* @see PHPMailer::preSend()
*
* @return string
*/
public function getSentMIMEMessage()
{
return rtrim($this->MIMEHeader . $this->mailHeader, "\n\r") . static::$LE . static::$LE . $this->MIMEBody;
}
/**
* Create a unique ID to use for boundaries.
*
* @return string
*/
protected function generateId()
{
$len = 32; //32 bytes = 256 bits
if (function_exists('random_bytes')) {
$bytes = random_bytes($len);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes($len);
} else {
//Use a hash to force the length to the same as the other methods
$bytes = hash('sha256', uniqid((string) mt_rand(), true), true);
}
//We don't care about messing up base64 format here, just want a random string
return str_replace(['=', '+', '/'], '', base64_encode(hash('sha256', $bytes, true)));
}
/**
* Assemble the message body.
* Returns an empty string on failure.
*
* @throws Exception
*
* @return string The assembled message body
*/
public function createBody()
{
$body = '';
//Create unique IDs and preset boundaries
$this->uniqueid = $this->generateId();
$this->boundary[1] = 'b1_' . $this->uniqueid;
$this->boundary[2] = 'b2_' . $this->uniqueid;
$this->boundary[3] = 'b3_' . $this->uniqueid;
if ($this->sign_key_file) {
$body .= $this->getMailMIME() . static::$LE;
}
$this->setWordWrap();
$bodyEncoding = $this->Encoding;
$bodyCharSet = $this->CharSet;
//Can we do a 7-bit downgrade?
if (static::ENCODING_8BIT == $bodyEncoding and !$this->has8bitChars($this->Body)) {
$bodyEncoding = static::ENCODING_7BIT;
//All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
$bodyCharSet = 'us-ascii';
}
//If lines are too long, and we're not already using an encoding that will shorten them,
//change to quoted-printable transfer encoding for the body part only
if (static::ENCODING_BASE64 != $this->Encoding and static::hasLineLongerThanMax($this->Body)) {
$bodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
}
$altBodyEncoding = $this->Encoding;
$altBodyCharSet = $this->CharSet;
//Can we do a 7-bit downgrade?
if (static::ENCODING_8BIT == $altBodyEncoding and !$this->has8bitChars($this->AltBody)) {
$altBodyEncoding = static::ENCODING_7BIT;
//All ISO 8859, Windows codepage and UTF-8 charsets are ascii compatible up to 7-bit
$altBodyCharSet = 'us-ascii';
}
//If lines are too long, and we're not already using an encoding that will shorten them,
//change to quoted-printable transfer encoding for the alt body part only
if (static::ENCODING_BASE64 != $altBodyEncoding and static::hasLineLongerThanMax($this->AltBody)) {
$altBodyEncoding = static::ENCODING_QUOTED_PRINTABLE;
}
//Use this as a preamble in all multipart message types
$mimepre = 'This is a multi-part message in MIME format.' . static::$LE;
switch ($this->message_type) {
case 'inline':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
$body .= $this->attachAll('inline', $this->boundary[1]);
break;
case 'attach':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'inline_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
$body .= $this->attachAll('inline', $this->boundary[2]);
$body .= static::$LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'alt':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[1], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
if (!empty($this->Ical)) {
$body .= $this->getBoundary($this->boundary[1], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
$body .= $this->encodeString($this->Ical, $this->Encoding);
$body .= static::$LE;
}
$body .= $this->endBoundary($this->boundary[1]);
break;
case 'alt_inline':
$body .= $mimepre;
$body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= static::$LE;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
$body .= $this->attachAll('inline', $this->boundary[2]);
$body .= static::$LE;
$body .= $this->endBoundary($this->boundary[1]);
break;
case 'alt_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[2], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
if (!empty($this->Ical)) {
$body .= $this->getBoundary($this->boundary[2], '', static::CONTENT_TYPE_TEXT_CALENDAR . '; method=REQUEST', '');
$body .= $this->encodeString($this->Ical, $this->Encoding);
}
$body .= $this->endBoundary($this->boundary[2]);
$body .= static::$LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
case 'alt_inline_attach':
$body .= $mimepre;
$body .= $this->textLine('--' . $this->boundary[1]);
$body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_ALTERNATIVE . ';');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, static::CONTENT_TYPE_PLAINTEXT, $altBodyEncoding);
$body .= $this->encodeString($this->AltBody, $altBodyEncoding);
$body .= static::$LE;
$body .= $this->textLine('--' . $this->boundary[2]);
$body .= $this->headerLine('Content-Type', static::CONTENT_TYPE_MULTIPART_RELATED . ';');
$body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
$body .= static::$LE;
$body .= $this->getBoundary($this->boundary[3], $bodyCharSet, static::CONTENT_TYPE_TEXT_HTML, $bodyEncoding);
$body .= $this->encodeString($this->Body, $bodyEncoding);
$body .= static::$LE;
$body .= $this->attachAll('inline', $this->boundary[3]);
$body .= static::$LE;
$body .= $this->endBoundary($this->boundary[2]);
$body .= static::$LE;
$body .= $this->attachAll('attachment', $this->boundary[1]);
break;
default:
// Catch case 'plain' and case '', applies to simple `text/plain` and `text/html` body content types
//Reset the `Encoding` property in case we changed it for line length reasons
$this->Encoding = $bodyEncoding;
$body .= $this->encodeString($this->Body, $this->Encoding);
break;
}
if ($this->isError()) {
$body = '';
if ($this->exceptions) {
throw new Exception($this->lang('empty_message'), self::STOP_CRITICAL);
}
} elseif ($this->sign_key_file) {
try {
if (!defined('PKCS7_TEXT')) {
throw new Exception($this->lang('extension_missing') . 'openssl');
}
// @TODO would be nice to use php://temp streams here
$file = tempnam(sys_get_temp_dir(), 'mail');
if (false === file_put_contents($file, $body)) {
throw new Exception($this->lang('signing') . ' Could not write temp file');
}
$signed = tempnam(sys_get_temp_dir(), 'signed');
//Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
if (empty($this->sign_extracerts_file)) {
$sign = @openssl_pkcs7_sign(
$file,
$signed,
'file://' . realpath($this->sign_cert_file),
['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
[]
);
} else {
$sign = @openssl_pkcs7_sign(
$file,
$signed,
'file://' . realpath($this->sign_cert_file),
['file://' . realpath($this->sign_key_file), $this->sign_key_pass],
[],
PKCS7_DETACHED,
$this->sign_extracerts_file
);
}
@unlink($file);
if ($sign) {
$body = file_get_contents($signed);
@unlink($signed);
//The message returned by openssl contains both headers and body, so need to split them up
$parts = explode("\n\n", $body, 2);
$this->MIMEHeader .= $parts[0] . static::$LE . static::$LE;
$body = $parts[1];
} else {
@unlink($signed);
throw new Exception($this->lang('signing') . openssl_error_string());
}
} catch (Exception $exc) {
$body = '';
if ($this->exceptions) {
throw $exc;
}
}
}
return $body;
}
/**
* Return the start of a message boundary.
*
* @param string $boundary
* @param string $charSet
* @param string $contentType
* @param string $encoding
*
* @return string
*/
protected function getBoundary($boundary, $charSet, $contentType, $encoding)
{
$result = '';
if ('' == $charSet) {
$charSet = $this->CharSet;
}
if ('' == $contentType) {
$contentType = $this->ContentType;
}
if ('' == $encoding) {
$encoding = $this->Encoding;
}
$result .= $this->textLine('--' . $boundary);
$result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
$result .= static::$LE;
// RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT != $encoding) {
$result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
}
$result .= static::$LE;
return $result;
}
/**
* Return the end of a message boundary.
*
* @param string $boundary
*
* @return string
*/
protected function endBoundary($boundary)
{
return static::$LE . '--' . $boundary . '--' . static::$LE;
}
/**
* Set the message type.
* PHPMailer only supports some preset message types, not arbitrary MIME structures.
*/
protected function setMessageType()
{
$type = [];
if ($this->alternativeExists()) {
$type[] = 'alt';
}
if ($this->inlineImageExists()) {
$type[] = 'inline';
}
if ($this->attachmentExists()) {
$type[] = 'attach';
}
$this->message_type = implode('_', $type);
if ('' == $this->message_type) {
//The 'plain' message_type refers to the message having a single body element, not that it is plain-text
$this->message_type = 'plain';
}
}
/**
* Format a header line.
*
* @param string $name
* @param string|int $value
*
* @return string
*/
public function headerLine($name, $value)
{
return $name . ': ' . $value . static::$LE;
}
/**
* Return a formatted mail line.
*
* @param string $value
*
* @return string
*/
public function textLine($value)
{
return $value . static::$LE;
}
/**
* Add an attachment from a path on the filesystem.
* Never use a user-supplied path to a file!
* Returns false if the file could not be found or read.
* Explicitly *does not* support passing URLs; PHPMailer is not an HTTP client.
* If you need to do that, fetch the resource yourself and pass it in via a local file or string.
*
* @param string $path Path to the attachment
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
* @param string $type File extension (MIME) type
* @param string $disposition Disposition to use
*
* @throws Exception
*
* @return bool
*/
public function addAttachment($path, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'attachment')
{
try {
if (!static::isPermittedPath($path) || !@is_file($path)) {
throw new Exception($this->lang('file_access') . $path, self::STOP_CONTINUE);
}
// If a MIME type is not specified, try to work it out from the file name
if ('' == $type) {
$type = static::filenameToType($path);
}
$filename = basename($path);
if ('' == $name) {
$name = $filename;
}
$this->attachment[] = [
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => $disposition,
7 => $name,
];
} catch (Exception $exc) {
$this->setError($exc->getMessage());
$this->edebug($exc->getMessage());
if ($this->exceptions) {
throw $exc;
}
return false;
}
return true;
}
/**
* Return the array of attachments.
*
* @return array
*/
public function getAttachments()
{
return $this->attachment;
}
/**
* Attach all file, string, and binary attachments to the message.
* Returns an empty string on failure.
*
* @param string $disposition_type
* @param string $boundary
*
* @return string
*/
protected function attachAll($disposition_type, $boundary)
{
// Return text of body
$mime = [];
$cidUniq = [];
$incl = [];
// Add all attachments
foreach ($this->attachment as $attachment) {
// Check if it is a valid disposition_filter
if ($attachment[6] == $disposition_type) {
// Check for string attachment
$string = '';
$path = '';
$bString = $attachment[5];
if ($bString) {
$string = $attachment[0];
} else {
$path = $attachment[0];
}
$inclhash = hash('sha256', serialize($attachment));
if (in_array($inclhash, $incl)) {
continue;
}
$incl[] = $inclhash;
$name = $attachment[2];
$encoding = $attachment[3];
$type = $attachment[4];
$disposition = $attachment[6];
$cid = $attachment[7];
if ('inline' == $disposition and array_key_exists($cid, $cidUniq)) {
continue;
}
$cidUniq[$cid] = true;
$mime[] = sprintf('--%s%s', $boundary, static::$LE);
//Only include a filename property if we have one
if (!empty($name)) {
$mime[] = sprintf(
'Content-Type: %s; name="%s"%s',
$type,
$this->encodeHeader($this->secureHeader($name)),
static::$LE
);
} else {
$mime[] = sprintf(
'Content-Type: %s%s',
$type,
static::$LE
);
}
// RFC1341 part 5 says 7bit is assumed if not specified
if (static::ENCODING_7BIT != $encoding) {
$mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, static::$LE);
}
if (!empty($cid)) {
$mime[] = sprintf('Content-ID: <%s>%s', $cid, static::$LE);
}
// If a filename contains any of these chars, it should be quoted,
// but not otherwise: RFC2183 & RFC2045 5.1
// Fixes a warning in IETF's msglint MIME checker
// Allow for bypassing the Content-Disposition header totally
if (!(empty($disposition))) {
$encoded_name = $this->encodeHeader($this->secureHeader($name));
if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
$mime[] = sprintf(
'Content-Disposition: %s; filename="%s"%s',
$disposition,
$encoded_name,
static::$LE . static::$LE
);
} else {
if (!empty($encoded_name)) {
$mime[] = sprintf(
'Content-Disposition: %s; filename=%s%s',
$disposition,
$encoded_name,
static::$LE . static::$LE
);
} else {
$mime[] = sprintf(
'Content-Disposition: %s%s',
$disposition,
static::$LE . static::$LE
);
}
}
} else {
$mime[] = static::$LE;
}
// Encode as string attachment
if ($bString) {
$mime[] = $this->encodeString($string, $encoding);
} else {
$mime[] = $this->encodeFile($path, $encoding);
}
if ($this->isError()) {
return '';
}
$mime[] = static::$LE;
}
}
$mime[] = sprintf('--%s--%s', $boundary, static::$LE);
return implode('', $mime);
}
/**
* Encode a file attachment in requested format.
* Returns an empty string on failure.
*
* @param string $path The full path to the file
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
*
* @throws Exception
*
* @return string
*/
protected function encodeFile($path, $encoding = self::ENCODING_BASE64)
{
try {
if (!static::isPermittedPath($path) || !file_exists($path)) {
throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
}
$file_buffer = file_get_contents($path);
if (false === $file_buffer) {
throw new Exception($this->lang('file_open') . $path, self::STOP_CONTINUE);
}
$file_buffer = $this->encodeString($file_buffer, $encoding);
return $file_buffer;
} catch (Exception $exc) {
$this->setError($exc->getMessage());
return '';
}
}
/**
* Encode a string in requested format.
* Returns an empty string on failure.
*
* @param string $str The text to encode
* @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
*
* @return string
*/
public function encodeString($str, $encoding = self::ENCODING_BASE64)
{
$encoded = '';
switch (strtolower($encoding)) {
case static::ENCODING_BASE64:
$encoded = chunk_split(
base64_encode($str),
static::STD_LINE_LENGTH,
static::$LE
);
break;
case static::ENCODING_7BIT:
case static::ENCODING_8BIT:
$encoded = static::normalizeBreaks($str);
// Make sure it ends with a line break
if (substr($encoded, -(strlen(static::$LE))) != static::$LE) {
$encoded .= static::$LE;
}
break;
case static::ENCODING_BINARY:
$encoded = $str;
break;
case static::ENCODING_QUOTED_PRINTABLE:
$encoded = $this->encodeQP($str);
break;
default:
$this->setError($this->lang('encoding') . $encoding);
break;
}
return $encoded;
}
/**
* Encode a header value (not including its label) optimally.
* Picks shortest of Q, B, or none. Result includes folding if needed.
* See RFC822 definitions for phrase, comment and text positions.
*
* @param string $str The header value to encode
* @param string $position What context the string will be used in
*
* @return string
*/
public function encodeHeader($str, $position = 'text')
{
$matchcount = 0;
switch (strtolower($position)) {
case 'phrase':
if (!preg_match('/[\200-\377]/', $str)) {
// Can't use addslashes as we don't know the value of magic_quotes_sybase
$encoded = addcslashes($str, "\0..\37\177\\\"");
if (($str == $encoded) and !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
return $encoded;
}
return "\"$encoded\"";
}
$matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
break;
/* @noinspection PhpMissingBreakStatementInspection */
case 'comment':
$matchcount = preg_match_all('/[()"]/', $str, $matches);
//fallthrough
case 'text':
default:
$matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
break;
}
//RFCs specify a maximum line length of 78 chars, however mail() will sometimes
//corrupt messages with headers longer than 65 chars. See #818
$lengthsub = 'mail' == $this->Mailer ? 13 : 0;
$maxlen = static::STD_LINE_LENGTH - $lengthsub;
// Try to select the encoding which should produce the shortest output
if ($matchcount > strlen($str) / 3) {
// More than a third of the content will need encoding, so B encoding will be most efficient
$encoding = 'B';
//This calculation is:
// max line length
// - shorten to avoid mail() corruption
// - Q/B encoding char overhead ("` =?<charset>?[QB]?<content>?=`")
// - charset name length
$maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
if ($this->hasMultiBytes($str)) {
// Use a custom function which correctly encodes and wraps long
// multibyte strings without breaking lines within a character
$encoded = $this->base64EncodeWrapMB($str, "\n");
} else {
$encoded = base64_encode($str);
$maxlen -= $maxlen % 4;
$encoded = trim(chunk_split($encoded, $maxlen, "\n"));
}
$encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
} elseif ($matchcount > 0) {
//1 or more chars need encoding, use Q-encode
$encoding = 'Q';
//Recalc max line length for Q encoding - see comments on B encode
$maxlen = static::STD_LINE_LENGTH - $lengthsub - 8 - strlen($this->CharSet);
$encoded = $this->encodeQ($str, $position);
$encoded = $this->wrapText($encoded, $maxlen, true);
$encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
$encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
} elseif (strlen($str) > $maxlen) {
//No chars need encoding, but line is too long, so fold it
$encoded = trim($this->wrapText($str, $maxlen, false));
if ($str == $encoded) {
//Wrapping nicely didn't work, wrap hard instead
$encoded = trim(chunk_split($str, static::STD_LINE_LENGTH, static::$LE));
}
$encoded = str_replace(static::$LE, "\n", trim($encoded));
$encoded = preg_replace('/^(.*)$/m', ' \\1', $encoded);
} else {
//No reformatting needed
return $str;
}
return trim(static::normalizeBreaks($encoded));
}
/**
* Check if a string contains multi-byte characters.
*
* @param string $str multi-byte text to wrap encode
*
* @return bool
*/
public function hasMultiBytes($str)
{
if (function_exists('mb_strlen')) {
return strlen($str) > mb_strlen($str, $this->CharSet);
}
// Assume no multibytes (we can't handle without mbstring functions anyway)
return false;
}
/**
* Does a string contain any 8-bit chars (in any charset)?
*
* @param string $text
*
* @return bool
*/
public function has8bitChars($text)
{
return (bool) preg_match('/[\x80-\xFF]/', $text);
}
/**
* Encode and wrap long multibyte strings for mail headers
* without breaking lines within a character.
* Adapted from a function by paravoid.
*
* @see http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
*
* @param string $str multi-byte text to wrap encode
* @param string $linebreak string to use as linefeed/end-of-line
*
* @return string
*/
public function base64EncodeWrapMB($str, $linebreak = null)
{
$start = '=?' . $this->CharSet . '?B?';
$end = '?=';
$encoded = '';
if (null === $linebreak) {
$linebreak = static::$LE;
}
$mb_length = mb_strlen($str, $this->CharSet);
// Each line must have length <= 75, including $start and $end
$length = 75 - strlen($start) - strlen($end);
// Average multi-byte ratio
$ratio = $mb_length / strlen($str);
// Base64 has a 4:3 ratio
$avgLength = floor($length * $ratio * .75);
for ($i = 0; $i < $mb_length; $i += $offset) {
$lookBack = 0;
do {
$offset = $avgLength - $lookBack;
$chunk = mb_substr($str, $i, $offset, $this->CharSet);
$chunk = base64_encode($chunk);
++$lookBack;
} while (strlen($chunk) > $length);
$encoded .= $chunk . $linebreak;
}
// Chomp the last linefeed
return substr($encoded, 0, -strlen($linebreak));
}
/**
* Encode a string in quoted-printable format.
* According to RFC2045 section 6.7.
*
* @param string $string The text to encode
*
* @return string
*/
public function encodeQP($string)
{
return static::normalizeBreaks(quoted_printable_encode($string));
}
/**
* Encode a string using Q encoding.
*
* @see http://tools.ietf.org/html/rfc2047#section-4.2
*
* @param string $str the text to encode
* @param string $position Where the text is going to be used, see the RFC for what that means
*
* @return string
*/
public function encodeQ($str, $position = 'text')
{
// There should not be any EOL in the string
$pattern = '';
$encoded = str_replace(["\r", "\n"], '', $str);
switch (strtolower($position)) {
case 'phrase':
// RFC 2047 section 5.3
$pattern = '^A-Za-z0-9!*+\/ -';
break;
/*
* RFC 2047 section 5.2.
* Build $pattern without including delimiters and []
*/
/* @noinspection PhpMissingBreakStatementInspection */
case 'comment':
$pattern = '\(\)"';
/* Intentional fall through */
case 'text':
default:
// RFC 2047 section 5.1
// Replace every high ascii, control, =, ? and _ characters
/** @noinspection SuspiciousAssignmentsInspection */
$pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
break;
}
$matches = [];
if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
// If the string contains an '=', make sure it's the first thing we replace
// so as to avoid double-encoding
$eqkey = array_search('=', $matches[0]);
if (false !== $eqkey) {
unset($matches[0][$eqkey]);
array_unshift($matches[0], '=');
}
foreach (array_unique($matches[0]) as $char) {
$encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
}
}
// Replace spaces with _ (more readable than =20)
// RFC 2047 section 4.2(2)
return str_replace(' ', '_', $encoded);
}
/**
* Add a string or binary attachment (non-filesystem).
* This method can be used to attach ascii or binary data,
* such as a BLOB record from a database.
*
* @param string $string String attachment data
* @param string $filename Name of the attachment
* @param string $encoding File encoding (see $Encoding)
* @param string $type File extension (MIME) type
* @param string $disposition Disposition to use
*/
public function addStringAttachment(
$string,
$filename,
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'attachment'
) {
// If a MIME type is not specified, try to work it out from the file name
if ('' == $type) {
$type = static::filenameToType($filename);
}
// Append to $attachment array
$this->attachment[] = [
0 => $string,
1 => $filename,
2 => basename($filename),
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => $disposition,
7 => 0,
];
}
/**
* Add an embedded (inline) attachment from a file.
* This can include images, sounds, and just about any other document type.
* These differ from 'regular' attachments in that they are intended to be
* displayed inline with the message, not just attached for download.
* This is used in HTML messages that embed the images
* the HTML refers to using the $cid value.
* Never use a user-supplied path to a file!
*
* @param string $path Path to the attachment
* @param string $cid Content ID of the attachment; Use this to reference
* the content when using an embedded image in HTML
* @param string $name Overrides the attachment name
* @param string $encoding File encoding (see $Encoding)
* @param string $type File MIME type
* @param string $disposition Disposition to use
*
* @return bool True on successfully adding an attachment
*/
public function addEmbeddedImage($path, $cid, $name = '', $encoding = self::ENCODING_BASE64, $type = '', $disposition = 'inline')
{
if (!static::isPermittedPath($path) || !@is_file($path)) {
$this->setError($this->lang('file_access') . $path);
return false;
}
// If a MIME type is not specified, try to work it out from the file name
if ('' == $type) {
$type = static::filenameToType($path);
}
$filename = basename($path);
if ('' == $name) {
$name = $filename;
}
// Append to $attachment array
$this->attachment[] = [
0 => $path,
1 => $filename,
2 => $name,
3 => $encoding,
4 => $type,
5 => false, // isStringAttachment
6 => $disposition,
7 => $cid,
];
return true;
}
/**
* Add an embedded stringified attachment.
* This can include images, sounds, and just about any other document type.
* If your filename doesn't contain an extension, be sure to set the $type to an appropriate MIME type.
*
* @param string $string The attachment binary data
* @param string $cid Content ID of the attachment; Use this to reference
* the content when using an embedded image in HTML
* @param string $name A filename for the attachment. If this contains an extension,
* PHPMailer will attempt to set a MIME type for the attachment.
* For example 'file.jpg' would get an 'image/jpeg' MIME type.
* @param string $encoding File encoding (see $Encoding), defaults to 'base64'
* @param string $type MIME type - will be used in preference to any automatically derived type
* @param string $disposition Disposition to use
*
* @return bool True on successfully adding an attachment
*/
public function addStringEmbeddedImage(
$string,
$cid,
$name = '',
$encoding = self::ENCODING_BASE64,
$type = '',
$disposition = 'inline'
) {
// If a MIME type is not specified, try to work it out from the name
if ('' == $type and !empty($name)) {
$type = static::filenameToType($name);
}
// Append to $attachment array
$this->attachment[] = [
0 => $string,
1 => $name,
2 => $name,
3 => $encoding,
4 => $type,
5 => true, // isStringAttachment
6 => $disposition,
7 => $cid,
];
return true;
}
/**
* Check if an embedded attachment is present with this cid.
*
* @param string $cid
*
* @return bool
*/
protected function cidExists($cid)
{
foreach ($this->attachment as $attachment) {
if ('inline' == $attachment[6] and $cid == $attachment[7]) {
return true;
}
}
return false;
}
/**
* Check if an inline attachment is present.
*
* @return bool
*/
public function inlineImageExists()
{
foreach ($this->attachment as $attachment) {
if ('inline' == $attachment[6]) {
return true;
}
}
return false;
}
/**
* Check if an attachment (non-inline) is present.
*
* @return bool
*/
public function attachmentExists()
{
foreach ($this->attachment as $attachment) {
if ('attachment' == $attachment[6]) {
return true;
}
}
return false;
}
/**
* Check if this message has an alternative body set.
*
* @return bool
*/
public function alternativeExists()
{
return !empty($this->AltBody);
}
/**
* Clear queued addresses of given kind.
*
* @param string $kind 'to', 'cc', or 'bcc'
*/
public function clearQueuedAddresses($kind)
{
$this->RecipientsQueue = array_filter(
$this->RecipientsQueue,
function ($params) use ($kind) {
return $params[0] != $kind;
}
);
}
/**
* Clear all To recipients.
*/
public function clearAddresses()
{
foreach ($this->to as $to) {
unset($this->all_recipients[strtolower($to[0])]);
}
$this->to = [];
$this->clearQueuedAddresses('to');
}
/**
* Clear all CC recipients.
*/
public function clearCCs()
{
foreach ($this->cc as $cc) {
unset($this->all_recipients[strtolower($cc[0])]);
}
$this->cc = [];
$this->clearQueuedAddresses('cc');
}
/**
* Clear all BCC recipients.
*/
public function clearBCCs()
{
foreach ($this->bcc as $bcc) {
unset($this->all_recipients[strtolower($bcc[0])]);
}
$this->bcc = [];
$this->clearQueuedAddresses('bcc');
}
/**
* Clear all ReplyTo recipients.
*/
public function clearReplyTos()
{
$this->ReplyTo = [];
$this->ReplyToQueue = [];
}
/**
* Clear all recipient types.
*/
public function clearAllRecipients()
{
$this->to = [];
$this->cc = [];
$this->bcc = [];
$this->all_recipients = [];
$this->RecipientsQueue = [];
}
/**
* Clear all filesystem, string, and binary attachments.
*/
public function clearAttachments()
{
$this->attachment = [];
}
/**
* Clear all custom headers.
*/
public function clearCustomHeaders()
{
$this->CustomHeader = [];
}
/**
* Add an error message to the error container.
*
* @param string $msg
*/
protected function setError($msg)
{
++$this->error_count;
if ('smtp' == $this->Mailer and null !== $this->smtp) {
$lasterror = $this->smtp->getError();
if (!empty($lasterror['error'])) {
$msg .= $this->lang('smtp_error') . $lasterror['error'];
if (!empty($lasterror['detail'])) {
$msg .= ' Detail: ' . $lasterror['detail'];
}
if (!empty($lasterror['smtp_code'])) {
$msg .= ' SMTP code: ' . $lasterror['smtp_code'];
}
if (!empty($lasterror['smtp_code_ex'])) {
$msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
}
}
}
$this->ErrorInfo = $msg;
}
/**
* Return an RFC 822 formatted date.
*
* @return string
*/
public static function rfcDate()
{
// Set the time zone to whatever the default is to avoid 500 errors
// Will default to UTC if it's not set properly in php.ini
date_default_timezone_set(@date_default_timezone_get());
return date('D, j M Y H:i:s O');
}
/**
* Get the server hostname.
* Returns 'localhost.localdomain' if unknown.
*
* @return string
*/
protected function serverHostname()
{
$result = '';
if (!empty($this->Hostname)) {
$result = $this->Hostname;
} elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER)) {
$result = $_SERVER['SERVER_NAME'];
} elseif (function_exists('gethostname') and gethostname() !== false) {
$result = gethostname();
} elseif (php_uname('n') !== false) {
$result = php_uname('n');
}
if (!static::isValidHost($result)) {
return 'localhost.localdomain';
}
return $result;
}
/**
* Validate whether a string contains a valid value to use as a hostname or IP address.
* IPv6 addresses must include [], e.g. `[::1]`, not just `::1`.
*
* @param string $host The host name or IP address to check
*
* @return bool
*/
public static function isValidHost($host)
{
//Simple syntax limits
if (empty($host)
or !is_string($host)
or strlen($host) > 256
) {
return false;
}
//Looks like a bracketed IPv6 address
if (trim($host, '[]') != $host) {
return (bool) filter_var(trim($host, '[]'), FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
}
//If removing all the dots results in a numeric string, it must be an IPv4 address.
//Need to check this first because otherwise things like `999.0.0.0` are considered valid host names
if (is_numeric(str_replace('.', '', $host))) {
//Is it a valid IPv4 address?
return (bool) filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
}
if (filter_var('http://' . $host, FILTER_VALIDATE_URL)) {
//Is it a syntactically valid hostname?
return true;
}
return false;
}
/**
* Get an error message in the current language.
*
* @param string $key
*
* @return string
*/
protected function lang($key)
{
if (count($this->language) < 1) {
$this->setLanguage('en'); // set the default language
}
if (array_key_exists($key, $this->language)) {
if ('smtp_connect_failed' == $key) {
//Include a link to troubleshooting docs on SMTP connection failure
//this is by far the biggest cause of support questions
//but it's usually not PHPMailer's fault.
return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
}
return $this->language[$key];
}
//Return the key as a fallback
return $key;
}
/**
* Check if an error occurred.
*
* @return bool True if an error did occur
*/
public function isError()
{
return $this->error_count > 0;
}
/**
* Add a custom header.
* $name value can be overloaded to contain
* both header name and value (name:value).
*
* @param string $name Custom header name
* @param string|null $value Header value
*/
public function addCustomHeader($name, $value = null)
{
if (null === $value) {
// Value passed in as name:value
$this->CustomHeader[] = explode(':', $name, 2);
} else {
$this->CustomHeader[] = [$name, $value];
}
}
/**
* Returns all custom headers.
*
* @return array
*/
public function getCustomHeaders()
{
return $this->CustomHeader;
}
/**
* Create a message body from an HTML string.
* Automatically inlines images and creates a plain-text version by converting the HTML,
* overwriting any existing values in Body and AltBody.
* Do not source $message content from user input!
* $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
* will look for an image file in $basedir/images/a.png and convert it to inline.
* If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
* Converts data-uri images into embedded attachments.
* If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
*
* @param string $message HTML message string
* @param string $basedir Absolute path to a base directory to prepend to relative paths to images
* @param bool|callable $advanced Whether to use the internal HTML to text converter
* or your own custom converter @see PHPMailer::html2text()
*
* @return string $message The transformed message Body
*/
public function msgHTML($message, $basedir = '', $advanced = false)
{
preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
if (array_key_exists(2, $images)) {
if (strlen($basedir) > 1 && '/' != substr($basedir, -1)) {
// Ensure $basedir has a trailing /
$basedir .= '/';
}
foreach ($images[2] as $imgindex => $url) {
// Convert data URIs into embedded images
//e.g. "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
if (preg_match('#^data:(image/(?:jpe?g|gif|png));?(base64)?,(.+)#', $url, $match)) {
if (count($match) == 4 and static::ENCODING_BASE64 == $match[2]) {
$data = base64_decode($match[3]);
} elseif ('' == $match[2]) {
$data = rawurldecode($match[3]);
} else {
//Not recognised so leave it alone
continue;
}
//Hash the decoded data, not the URL so that the same data-URI image used in multiple places
//will only be embedded once, even if it used a different encoding
$cid = hash('sha256', $data) . '@phpmailer.0'; // RFC2392 S 2
if (!$this->cidExists($cid)) {
$this->addStringEmbeddedImage($data, $cid, 'embed' . $imgindex, static::ENCODING_BASE64, $match[1]);
}
$message = str_replace(
$images[0][$imgindex],
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
continue;
}
if (// Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
!empty($basedir)
// Ignore URLs containing parent dir traversal (..)
and (strpos($url, '..') === false)
// Do not change urls that are already inline images
and 0 !== strpos($url, 'cid:')
// Do not change absolute URLs, including anonymous protocol
and !preg_match('#^[a-z][a-z0-9+.-]*:?//#i', $url)
) {
$filename = basename($url);
$directory = dirname($url);
if ('.' == $directory) {
$directory = '';
}
$cid = hash('sha256', $url) . '@phpmailer.0'; // RFC2392 S 2
if (strlen($basedir) > 1 and '/' != substr($basedir, -1)) {
$basedir .= '/';
}
if (strlen($directory) > 1 and '/' != substr($directory, -1)) {
$directory .= '/';
}
if ($this->addEmbeddedImage(
$basedir . $directory . $filename,
$cid,
$filename,
static::ENCODING_BASE64,
static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
)
) {
$message = preg_replace(
'/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
$images[1][$imgindex] . '="cid:' . $cid . '"',
$message
);
}
}
}
}
$this->isHTML(true);
// Convert all message body line breaks to LE, makes quoted-printable encoding work much better
$this->Body = static::normalizeBreaks($message);
$this->AltBody = static::normalizeBreaks($this->html2text($message, $advanced));
if (!$this->alternativeExists()) {
$this->AltBody = 'This is an HTML-only message. To view it, activate HTML in your email application.'
. static::$LE;
}
return $this->Body;
}
/**
* Convert an HTML string into plain text.
* This is used by msgHTML().
* Note - older versions of this function used a bundled advanced converter
* which was removed for license reasons in #232.
* Example usage:
*
* ```php
* // Use default conversion
* $plain = $mail->html2text($html);
* // Use your own custom converter
* $plain = $mail->html2text($html, function($html) {
* $converter = new MyHtml2text($html);
* return $converter->get_text();
* });
* ```
*
* @param string $html The HTML text to convert
* @param bool|callable $advanced Any boolean value to use the internal converter,
* or provide your own callable for custom conversion
*
* @return string
*/
public function html2text($html, $advanced = false)
{
if (is_callable($advanced)) {
return call_user_func($advanced, $html);
}
return html_entity_decode(
trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
ENT_QUOTES,
$this->CharSet
);
}
/**
* Get the MIME type for a file extension.
*
* @param string $ext File extension
*
* @return string MIME type of file
*/
public static function _mime_types($ext = '')
{
$mimes = [
'xl' => 'application/excel',
'js' => 'application/javascript',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'bin' => 'application/macbinary',
'doc' => 'application/msword',
'word' => 'application/msword',
'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'class' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'psd' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'so' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'php3' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => 'application/x-tar',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'zip' => 'application/zip',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'm4a' => 'audio/mp4',
'mpga' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'mka' => 'audio/x-matroska',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'jpeg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'jpg' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'webp' => 'image/webp',
'heif' => 'image/heif',
'heifs' => 'image/heif-sequence',
'heic' => 'image/heic',
'heics' => 'image/heic-sequence',
'eml' => 'message/rfc822',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'log' => 'text/plain',
'text' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'vcf' => 'text/vcard',
'vcard' => 'text/vcard',
'ics' => 'text/calendar',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'wmv' => 'video/x-ms-wmv',
'mpeg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mp4' => 'video/mp4',
'm4v' => 'video/mp4',
'mov' => 'video/quicktime',
'qt' => 'video/quicktime',
'rv' => 'video/vnd.rn-realvideo',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'webm' => 'video/webm',
'mkv' => 'video/x-matroska',
];
$ext = strtolower($ext);
if (array_key_exists($ext, $mimes)) {
return $mimes[$ext];
}
return 'application/octet-stream';
}
/**
* Map a file name to a MIME type.
* Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
*
* @param string $filename A file name or full path, does not need to exist as a file
*
* @return string
*/
public static function filenameToType($filename)
{
// In case the path is a URL, strip any query string before getting extension
$qpos = strpos($filename, '?');
if (false !== $qpos) {
$filename = substr($filename, 0, $qpos);
}
$ext = static::mb_pathinfo($filename, PATHINFO_EXTENSION);
return static::_mime_types($ext);
}
/**
* Multi-byte-safe pathinfo replacement.
* Drop-in replacement for pathinfo(), but multibyte- and cross-platform-safe.
*
* @see http://www.php.net/manual/en/function.pathinfo.php#107461
*
* @param string $path A filename or path, does not need to exist as a file
* @param int|string $options Either a PATHINFO_* constant,
* or a string name to return only the specified piece
*
* @return string|array
*/
public static function mb_pathinfo($path, $options = null)
{
$ret = ['dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''];
$pathinfo = [];
if (preg_match('#^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$#im', $path, $pathinfo)) {
if (array_key_exists(1, $pathinfo)) {
$ret['dirname'] = $pathinfo[1];
}
if (array_key_exists(2, $pathinfo)) {
$ret['basename'] = $pathinfo[2];
}
if (array_key_exists(5, $pathinfo)) {
$ret['extension'] = $pathinfo[5];
}
if (array_key_exists(3, $pathinfo)) {
$ret['filename'] = $pathinfo[3];
}
}
switch ($options) {
case PATHINFO_DIRNAME:
case 'dirname':
return $ret['dirname'];
case PATHINFO_BASENAME:
case 'basename':
return $ret['basename'];
case PATHINFO_EXTENSION:
case 'extension':
return $ret['extension'];
case PATHINFO_FILENAME:
case 'filename':
return $ret['filename'];
default:
return $ret;
}
}
/**
* Set or reset instance properties.
* You should avoid this function - it's more verbose, less efficient, more error-prone and
* harder to debug than setting properties directly.
* Usage Example:
* `$mail->set('SMTPSecure', 'tls');`
* is the same as:
* `$mail->SMTPSecure = 'tls';`.
*
* @param string $name The property name to set
* @param mixed $value The value to set the property to
*
* @return bool
*/
public function set($name, $value = '')
{
if (property_exists($this, $name)) {
$this->$name = $value;
return true;
}
$this->setError($this->lang('variable_set') . $name);
return false;
}
/**
* Strip newlines to prevent header injection.
*
* @param string $str
*
* @return string
*/
public function secureHeader($str)
{
return trim(str_replace(["\r", "\n"], '', $str));
}
/**
* Normalize line breaks in a string.
* Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
* Defaults to CRLF (for message bodies) and preserves consecutive breaks.
*
* @param string $text
* @param string $breaktype What kind of line break to use; defaults to static::$LE
*
* @return string
*/
public static function normalizeBreaks($text, $breaktype = null)
{
if (null === $breaktype) {
$breaktype = static::$LE;
}
// Normalise to \n
$text = str_replace(["\r\n", "\r"], "\n", $text);
// Now convert LE as needed
if ("\n" !== $breaktype) {
$text = str_replace("\n", $breaktype, $text);
}
return $text;
}
/**
* Return the current line break format string.
*
* @return string
*/
public static function getLE()
{
return static::$LE;
}
/**
* Set the line break format string, e.g. "\r\n".
*
* @param string $le
*/
protected static function setLE($le)
{
static::$LE = $le;
}
/**
* Set the public and private key files and password for S/MIME signing.
*
* @param string $cert_filename
* @param string $key_filename
* @param string $key_pass Password for private key
* @param string $extracerts_filename Optional path to chain certificate
*/
public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
{
$this->sign_cert_file = $cert_filename;
$this->sign_key_file = $key_filename;
$this->sign_key_pass = $key_pass;
$this->sign_extracerts_file = $extracerts_filename;
}
/**
* Quoted-Printable-encode a DKIM header.
*
* @param string $txt
*
* @return string
*/
public function DKIM_QP($txt)
{
$line = '';
$len = strlen($txt);
for ($i = 0; $i < $len; ++$i) {
$ord = ord($txt[$i]);
if (((0x21 <= $ord) and ($ord <= 0x3A)) or $ord == 0x3C or ((0x3E <= $ord) and ($ord <= 0x7E))) {
$line .= $txt[$i];
} else {
$line .= '=' . sprintf('%02X', $ord);
}
}
return $line;
}
/**
* Generate a DKIM signature.
*
* @param string $signHeader
*
* @throws Exception
*
* @return string The DKIM signature value
*/
public function DKIM_Sign($signHeader)
{
if (!defined('PKCS7_TEXT')) {
if ($this->exceptions) {
throw new Exception($this->lang('extension_missing') . 'openssl');
}
return '';
}
$privKeyStr = !empty($this->DKIM_private_string) ?
$this->DKIM_private_string :
file_get_contents($this->DKIM_private);
if ('' != $this->DKIM_passphrase) {
$privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
} else {
$privKey = openssl_pkey_get_private($privKeyStr);
}
if (openssl_sign($signHeader, $signature, $privKey, 'sha256WithRSAEncryption')) {
openssl_pkey_free($privKey);
return base64_encode($signature);
}
openssl_pkey_free($privKey);
return '';
}
/**
* Generate a DKIM canonicalization header.
* Uses the 'relaxed' algorithm from RFC6376 section 3.4.2.
* Canonicalized headers should *always* use CRLF, regardless of mailer setting.
*
* @see https://tools.ietf.org/html/rfc6376#section-3.4.2
*
* @param string $signHeader Header
*
* @return string
*/
public function DKIM_HeaderC($signHeader)
{
//Unfold all header continuation lines
//Also collapses folded whitespace.
//Note PCRE \s is too broad a definition of whitespace; RFC5322 defines it as `[ \t]`
//@see https://tools.ietf.org/html/rfc5322#section-2.2
//That means this may break if you do something daft like put vertical tabs in your headers.
$signHeader = preg_replace('/\r\n[ \t]+/', ' ', $signHeader);
$lines = explode("\r\n", $signHeader);
foreach ($lines as $key => $line) {
//If the header is missing a :, skip it as it's invalid
//This is likely to happen because the explode() above will also split
//on the trailing LE, leaving an empty line
if (strpos($line, ':') === false) {
continue;
}
list($heading, $value) = explode(':', $line, 2);
//Lower-case header name
$heading = strtolower($heading);
//Collapse white space within the value
$value = preg_replace('/[ \t]{2,}/', ' ', $value);
//RFC6376 is slightly unclear here - it says to delete space at the *end* of each value
//But then says to delete space before and after the colon.
//Net result is the same as trimming both ends of the value.
//by elimination, the same applies to the field name
$lines[$key] = trim($heading, " \t") . ':' . trim($value, " \t");
}
return implode("\r\n", $lines);
}
/**
* Generate a DKIM canonicalization body.
* Uses the 'simple' algorithm from RFC6376 section 3.4.3.
* Canonicalized bodies should *always* use CRLF, regardless of mailer setting.
*
* @see https://tools.ietf.org/html/rfc6376#section-3.4.3
*
* @param string $body Message Body
*
* @return string
*/
public function DKIM_BodyC($body)
{
if (empty($body)) {
return "\r\n";
}
// Normalize line endings to CRLF
$body = static::normalizeBreaks($body, "\r\n");
//Reduce multiple trailing line breaks to a single one
return rtrim($body, "\r\n") . "\r\n";
}
/**
* Create the DKIM header and body in a new message header.
*
* @param string $headers_line Header lines
* @param string $subject Subject
* @param string $body Body
*
* @return string
*/
public function DKIM_Add($headers_line, $subject, $body)
{
$DKIMsignatureType = 'rsa-sha256'; // Signature & hash algorithms
$DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
$DKIMquery = 'dns/txt'; // Query method
$DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
$subject_header = "Subject: $subject";
$headers = explode(static::$LE, $headers_line);
$from_header = '';
$to_header = '';
$date_header = '';
$current = '';
$copiedHeaderFields = '';
$foundExtraHeaders = [];
$extraHeaderKeys = '';
$extraHeaderValues = '';
$extraCopyHeaderFields = '';
foreach ($headers as $header) {
if (strpos($header, 'From:') === 0) {
$from_header = $header;
$current = 'from_header';
} elseif (strpos($header, 'To:') === 0) {
$to_header = $header;
$current = 'to_header';
} elseif (strpos($header, 'Date:') === 0) {
$date_header = $header;
$current = 'date_header';
} elseif (!empty($this->DKIM_extraHeaders)) {
foreach ($this->DKIM_extraHeaders as $extraHeader) {
if (strpos($header, $extraHeader . ':') === 0) {
$headerValue = $header;
foreach ($this->CustomHeader as $customHeader) {
if ($customHeader[0] === $extraHeader) {
$headerValue = trim($customHeader[0]) .
': ' .
$this->encodeHeader(trim($customHeader[1]));
break;
}
}
$foundExtraHeaders[$extraHeader] = $headerValue;
$current = '';
break;
}
}
} else {
if (!empty($$current) and strpos($header, ' =?') === 0) {
$$current .= $header;
} else {
$current = '';
}
}
}
foreach ($foundExtraHeaders as $key => $value) {
$extraHeaderKeys .= ':' . $key;
$extraHeaderValues .= $value . "\r\n";
if ($this->DKIM_copyHeaderFields) {
$extraCopyHeaderFields .= "\t|" . str_replace('|', '=7C', $this->DKIM_QP($value)) . ";\r\n";
}
}
if ($this->DKIM_copyHeaderFields) {
$from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
$to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
$date = str_replace('|', '=7C', $this->DKIM_QP($date_header));
$subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header));
$copiedHeaderFields = "\tz=$from\r\n" .
"\t|$to\r\n" .
"\t|$date\r\n" .
"\t|$subject;\r\n" .
$extraCopyHeaderFields;
}
$body = $this->DKIM_BodyC($body);
$DKIMlen = strlen($body); // Length of body
$DKIMb64 = base64_encode(pack('H*', hash('sha256', $body))); // Base64 of packed binary SHA-256 hash of body
if ('' == $this->DKIM_identity) {
$ident = '';
} else {
$ident = ' i=' . $this->DKIM_identity . ';';
}
$dkimhdrs = 'DKIM-Signature: v=1; a=' .
$DKIMsignatureType . '; q=' .
$DKIMquery . '; l=' .
$DKIMlen . '; s=' .
$this->DKIM_selector .
";\r\n" .
"\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
"\th=From:To:Date:Subject" . $extraHeaderKeys . ";\r\n" .
"\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
$copiedHeaderFields .
"\tbh=" . $DKIMb64 . ";\r\n" .
"\tb=";
$toSign = $this->DKIM_HeaderC(
$from_header . "\r\n" .
$to_header . "\r\n" .
$date_header . "\r\n" .
$subject_header . "\r\n" .
$extraHeaderValues .
$dkimhdrs
);
$signed = $this->DKIM_Sign($toSign);
return static::normalizeBreaks($dkimhdrs . $signed) . static::$LE;
}
/**
* Detect if a string contains a line longer than the maximum line length
* allowed by RFC 2822 section 2.1.1.
*
* @param string $str
*
* @return bool
*/
public static function hasLineLongerThanMax($str)
{
return (bool) preg_match('/^(.{' . (self::MAX_LINE_LENGTH + strlen(static::$LE)) . ',})/m', $str);
}
/**
* Allows for public read access to 'to' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
*
* @return array
*/
public function getToAddresses()
{
return $this->to;
}
/**
* Allows for public read access to 'cc' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
*
* @return array
*/
public function getCcAddresses()
{
return $this->cc;
}
/**
* Allows for public read access to 'bcc' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
*
* @return array
*/
public function getBccAddresses()
{
return $this->bcc;
}
/**
* Allows for public read access to 'ReplyTo' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
*
* @return array
*/
public function getReplyToAddresses()
{
return $this->ReplyTo;
}
/**
* Allows for public read access to 'all_recipients' property.
* Before the send() call, queued addresses (i.e. with IDN) are not yet included.
*
* @return array
*/
public function getAllRecipientAddresses()
{
return $this->all_recipients;
}
/**
* Perform a callback.
*
* @param bool $isSent
* @param array $to
* @param array $cc
* @param array $bcc
* @param string $subject
* @param string $body
* @param string $from
* @param array $extra
*/
protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from, $extra)
{
if (!empty($this->action_function) and is_callable($this->action_function)) {
call_user_func($this->action_function, $isSent, $to, $cc, $bcc, $subject, $body, $from, $extra);
}
}
/**
* Get the OAuth instance.
*
* @return OAuth
*/
public function getOAuth()
{
return $this->oauth;
}
/**
* Set an OAuth instance.
*
* @param OAuth $oauth
*/
public function setOAuth(OAuth $oauth)
{
$this->oauth = $oauth;
}
}
| unaio/una | upgrade/files/9.0.1-10.0.0.B1/files/plugins/phpmailer/PHPMailer.php | PHP | mit | 155,283 |
/*
* Copyright (c) 2012 - present Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets */
define(function (require, exports, module) {
"use strict";
var EditorManager = brackets.getModule("editor/EditorManager"),
QuickOpen = brackets.getModule("search/QuickOpen"),
QuickOpenHelper = brackets.getModule("search/QuickOpenHelper"),
CSSUtils = brackets.getModule("language/CSSUtils"),
DocumentManager = brackets.getModule("document/DocumentManager"),
StringMatch = brackets.getModule("utils/StringMatch");
/**
* Returns a list of information about selectors for a single document. This array is populated
* by createSelectorList()
* @return {?Array.<FileLocation>}
*/
function createSelectorList() {
var doc = DocumentManager.getCurrentDocument();
if (!doc) {
return;
}
var docText = doc.getText();
return CSSUtils.extractAllSelectors(docText, doc.getLanguage().getMode());
}
/**
* @param {string} query what the user is searching for
* @return {Array.<SearchResult>} sorted and filtered results that match the query
*/
function search(query, matcher) {
var selectorList = matcher.selectorList;
if (!selectorList) {
selectorList = createSelectorList();
matcher.selectorList = selectorList;
}
query = query.slice(query.indexOf("@") + 1, query.length);
// Filter and rank how good each match is
var filteredList = $.map(selectorList, function (itemInfo) {
var searchResult = matcher.match(CSSUtils.getCompleteSelectors(itemInfo), query);
if (searchResult) {
searchResult.selectorInfo = itemInfo;
}
return searchResult;
});
// Sort based on ranking & basic alphabetical order
StringMatch.basicMatchSort(filteredList);
return filteredList;
}
/**
* Scroll to the selected item in the current document (unless no query string entered yet,
* in which case the topmost list item is irrelevant)
* @param {?SearchResult} selectedItem
* @param {string} query
* @param {boolean} explicit False if this is only highlighted due to being at top of list after search()
*/
function itemFocus(selectedItem, query, explicit) {
if (!selectedItem || (query.length < 2 && !explicit)) {
return;
}
var selectorInfo = selectedItem.selectorInfo;
var from = {line: selectorInfo.selectorStartLine, ch: selectorInfo.selectorStartChar};
var to = {line: selectorInfo.selectorStartLine, ch: selectorInfo.selectorEndChar};
EditorManager.getCurrentFullEditor().setSelection(from, to, true);
}
function itemSelect(selectedItem, query) {
itemFocus(selectedItem, query, true);
}
QuickOpen.addQuickOpenPlugin(
{
name: "CSS Selectors",
languageIds: ["css", "less", "scss"],
search: search,
match: QuickOpenHelper.match,
itemFocus: itemFocus,
itemSelect: itemSelect
}
);
});
| kolipka/brackets | src/extensions/default/QuickOpenCSS/main.js | JavaScript | mit | 4,432 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.