text
stringlengths 2
1.04M
| meta
dict |
---|---|
#source `brew --prefix`/etc/grc.bashrc
#fi
| {
"content_hash": "f7e9d6f3e22eb706706aa67916b661f4",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 40,
"avg_line_length": 22.5,
"alnum_prop": 0.6666666666666666,
"repo_name": "clintkelly/dotfiles",
"id": "4a20d72533fbb535d0a13feffe40a5f4a90184c7",
"size": "155",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/grc.zsh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AppleScript",
"bytes": "2048"
},
{
"name": "Ruby",
"bytes": "16269"
},
{
"name": "Shell",
"bytes": "21394"
},
{
"name": "Vim script",
"bytes": "14331"
}
],
"symlink_target": ""
} |
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("NetflixBrowser")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NetflixBrowser")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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")]
| {
"content_hash": "5ad8ace92dd953bd1599054ac2fe93da",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 96,
"avg_line_length": 40.61818181818182,
"alnum_prop": 0.7551477170993733,
"repo_name": "goofwear/Kodi-Netflix-Utilities",
"id": "b8b206b72d2bea1ccb98b98a3a9901b4faf0f974",
"size": "2237",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NetflixBrowser/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "56115"
}
],
"symlink_target": ""
} |
var renderer;
var canvas;
function Renderer(width, height, canvas)
{
this.canvas = canvas;
if (!this.canvas.getContext)
{
alert ("Requires a browser that supports HTML5 Canvas");
throw "Canvas fail";
}
this.context = this.canvas.getContext("2d");
if (!this.context)
{
alert ("Error getting canvas 2d context");
throw "Context fail";
}
this.width = this.canvas.width = width;
this.height = this.canvas.height = height;
this.GetContext = function () {
return this.context;
};
// Sets smooth or pixelated image rendering. Should work for all browsers.
this.SetSmooth = function(val)
{
if (this.context.imageSmoothingEnabled != undefined)
{
//Hooray, you win the internet
this.context.imageSmoothingEnabled = val;
}
else
{
//Boo, I hate prefix tags
this.context.mozImageSmoothingEnabled = val;
this.context.webkitImageSmoothingEnabled = val;
this.context.msImageSmoothingEnabled = val;
}
}
this.SetFill = function(fillstyle) {
this.context.fillStyle = fillstyle;
};
this.SetStroke = function(strokestyle) {
this.context.strokeStyle = strokestyle;
};
// Fills canvas with current fill colour
this.Fill = function() {
this.context.fillRect(0, 0, this.width, this.height);
};
// Clears canvas to transparent
this.Clear = function() {
this.context.clearRect(0, 0, this.width, this.height);
};
this.SetAlpha = function(a) {
this.context.globalAlpha = a;
}
// Draws line segment
this.Line = function(x1, y1, x2, y2) {
this.context.moveTo(x1, y1);
this.context.lineTo(x2, y2);
}
// Draws circle
this.Circle = function(x, y, r) {
this.context.beginPath();
this.context.arc(x, y, r, 0, Math.PI * 2, false);
this.context.stroke();
}
this.CircleFill = function(x, y, r) {
this.context.beginPath();
this.context.arc(x, y, r, 0, Math.PI * 2, false);
this.context.fill();
}
this.DrawTile = function(img, srcx, srcy, srcw, srch, x, y, w, h) {
this.context.drawImage(img, srcx, srcy, srcw, srch, x, y, w, h);
}
this.DrawSprite = function(img, srcx, srcy, srcw, srch, x, y, zoom, rot) {
this.context.save();
this.context.translate(x, y);
this.context.rotate(rot*Math.PI/180);
this.context.drawImage(img, srcx, srcy, srcw, srch, -1*zoom, -1*zoom, 2*zoom, 2*zoom);
this.context.restore();
}
};
| {
"content_hash": "06f398d1431c61365520032e12f6d374",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 88,
"avg_line_length": 22.066666666666666,
"alnum_prop": 0.6702632714717307,
"repo_name": "lasty/ld31_onescreen",
"id": "4bb15bb51c8d54eeb7c14f7ed612eef778896f17",
"size": "2318",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "renderer.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1683"
},
{
"name": "JavaScript",
"bytes": "547439"
}
],
"symlink_target": ""
} |
package me.mtrupkin.control
import java.lang.Math._
import javafx.scene.control.Label
import javafx.scene.layout.{Pane, StackPane}
import javafx.scene.paint.{Paint, Color}
import javafx.scene.text.{Font, FontWeight}
import me.mtrupkin.console.{RGB, Screen, ScreenChar}
import me.mtrupkin.core.{Matrix, Point, Size}
import scala.Array._
/**
* Created by mtrupkin on 12/13/2014.
*/
class ConsoleFx(val size: Size) extends Pane {
setStyle("-fx-background-color: black;")
val offsetX, offsetY = 1
val font = Font.font("Consolas", FontWeight.NORMAL, 21)
val charBounds = ConsoleFx.charBounds(font)
val stacks = new Matrix[StackPane](size)
val labels = new Matrix[Label](size)
val (conWidth, conHeight) = toPixel(Point(size.width, size.height))
val (sizeX, sizeY) = (conWidth + offsetX * 2, conHeight + offsetY * 2)
setPrefSize(sizeX, sizeY)
setMinSize(sizeX, sizeY)
size.foreach(init)
def init(p: Point): Unit = {
val s = new StackPane()
val l = new Label()
l.setTextFill(Color.WHITE)
l.setFont(font)
s.getChildren.addAll(l)
stacks(p) = s
labels(p) = l
val (px, py) = toPixel(p.x, p.y)
s.relocate(px, py)
getChildren.add(s)
}
def apply(p: Point): Label = labels(p)
// draw screen to window
def draw(screen: Screen): Unit = screen.foreach(draw)
def draw(p: Point, s: ScreenChar): Unit = {
val l = this(p)
l.setText(s)
l.setTextFill(color(s.fg))
}
def color(c: RGB): Color = new Color(c.r/255f, c.g/255f, c.b/255f, 1)
def toPixel(p: Point): (Double, Double) = {
val (width, height) = charBounds
(p.x * width + offsetX, p.y * height + offsetY)
}
def floor(d: Double): Int = Math.floor(d).toInt
def toScreen(x: Double, y: Double): Option[Point] = {
val (width, height) = charBounds
val c = Point(floor((x-offsetX) / width), floor((y-offsetY) / height))
if (size.in(c)) Some(c) else None
}
// def pixelSize(): Size = toPixel(size)
}
object ConsoleFx {
def charBounds(f: Font): (Double, Double) = {
val fl = com.sun.javafx.tk.Toolkit.getToolkit.getFontLoader
val metrics = fl.getFontMetrics(f)
val fontWidth = fl.computeStringWidth(" ", f)
(floor(fontWidth), floor(metrics.getLineHeight))
}
}
| {
"content_hash": "9e2c965f1634d3e719308f9d4a531327",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 74,
"avg_line_length": 26,
"alnum_prop": 0.6333333333333333,
"repo_name": "mtrupkin/omicron",
"id": "890e2d2939fab6477fb254fb9864a20ab3c15e81",
"size": "2340",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/control/ConsoleFx.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9404"
},
{
"name": "Scala",
"bytes": "59905"
}
],
"symlink_target": ""
} |
"""
Base and utility classes for pandas objects.
"""
from collections import OrderedDict
import textwrap
import warnings
import numpy as np
import pandas._libs.lib as lib
import pandas.compat as compat
from pandas.compat import PYPY, builtins, map, range
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import Appender, Substitution, cache_readonly
from pandas.util._validators import validate_bool_kwarg
from pandas.core.dtypes.common import (
is_datetime64_ns_dtype, is_datetime64tz_dtype, is_datetimelike,
is_extension_array_dtype, is_extension_type, is_list_like, is_object_dtype,
is_scalar, is_timedelta64_ns_dtype)
from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries
from pandas.core.dtypes.missing import isna
from pandas.core import algorithms, common as com
from pandas.core.accessor import DirNamesMixin
import pandas.core.nanops as nanops
_shared_docs = dict()
_indexops_doc_kwargs = dict(klass='IndexOpsMixin', inplace='',
unique='IndexOpsMixin', duplicated='IndexOpsMixin')
class StringMixin(object):
"""implements string methods so long as object defines a `__unicode__`
method.
Handles Python2/3 compatibility transparently.
"""
# side note - this could be made into a metaclass if more than one
# object needs
# ----------------------------------------------------------------------
# Formatting
def __unicode__(self):
raise AbstractMethodError(self)
def __str__(self):
"""
Return a string representation for a particular Object
Invoked by str(df) in both py2/py3.
Yields Bytestring in Py2, Unicode String in py3.
"""
if compat.PY3:
return self.__unicode__()
return self.__bytes__()
def __bytes__(self):
"""
Return a string representation for a particular object.
Invoked by bytes(obj) in py3 only.
Yields a bytestring in both py2/py3.
"""
from pandas.core.config import get_option
encoding = get_option("display.encoding")
return self.__unicode__().encode(encoding, 'replace')
def __repr__(self):
"""
Return a string representation for a particular object.
Yields Bytestring in Py2, Unicode String in py3.
"""
return str(self)
class PandasObject(StringMixin, DirNamesMixin):
"""baseclass for various pandas objects"""
@property
def _constructor(self):
"""class constructor (for this class it's just `__class__`"""
return self.__class__
def __unicode__(self):
"""
Return a string representation for a particular object.
Invoked by unicode(obj) in py2 only. Yields a Unicode String in both
py2/py3.
"""
# Should be overwritten by base classes
return object.__repr__(self)
def _reset_cache(self, key=None):
"""
Reset cached properties. If ``key`` is passed, only clears that key.
"""
if getattr(self, '_cache', None) is None:
return
if key is None:
self._cache.clear()
else:
self._cache.pop(key, None)
def __sizeof__(self):
"""
Generates the total memory usage for an object that returns
either a value or Series of values
"""
if hasattr(self, 'memory_usage'):
mem = self.memory_usage(deep=True)
if not is_scalar(mem):
mem = mem.sum()
return int(mem)
# no memory_usage attribute, so fall back to
# object's 'sizeof'
return super(PandasObject, self).__sizeof__()
class NoNewAttributesMixin(object):
"""Mixin which prevents adding new attributes.
Prevents additional attributes via xxx.attribute = "something" after a
call to `self.__freeze()`. Mainly used to prevent the user from using
wrong attributes on a accessor (`Series.cat/.str/.dt`).
If you really want to add a new attribute at a later time, you need to use
`object.__setattr__(self, key, value)`.
"""
def _freeze(self):
"""Prevents setting additional attributes"""
object.__setattr__(self, "__frozen", True)
# prevent adding any attribute via s.xxx.new_attribute = ...
def __setattr__(self, key, value):
# _cache is used by a decorator
# We need to check both 1.) cls.__dict__ and 2.) getattr(self, key)
# because
# 1.) getattr is false for attributes that raise errors
# 2.) cls.__dict__ doesn't traverse into base classes
if (getattr(self, "__frozen", False) and not
(key == "_cache" or
key in type(self).__dict__ or
getattr(self, key, None) is not None)):
raise AttributeError("You cannot add any new attribute '{key}'".
format(key=key))
object.__setattr__(self, key, value)
class GroupByError(Exception):
pass
class DataError(GroupByError):
pass
class SpecificationError(GroupByError):
pass
class SelectionMixin(object):
"""
mixin implementing the selection & aggregation interface on a group-like
object sub-classes need to define: obj, exclusions
"""
_selection = None
_internal_names = ['_cache', '__setstate__']
_internal_names_set = set(_internal_names)
_builtin_table = OrderedDict((
(builtins.sum, np.sum),
(builtins.max, np.max),
(builtins.min, np.min),
))
_cython_table = OrderedDict((
(builtins.sum, 'sum'),
(builtins.max, 'max'),
(builtins.min, 'min'),
(np.all, 'all'),
(np.any, 'any'),
(np.sum, 'sum'),
(np.nansum, 'sum'),
(np.mean, 'mean'),
(np.nanmean, 'mean'),
(np.prod, 'prod'),
(np.nanprod, 'prod'),
(np.std, 'std'),
(np.nanstd, 'std'),
(np.var, 'var'),
(np.nanvar, 'var'),
(np.median, 'median'),
(np.nanmedian, 'median'),
(np.max, 'max'),
(np.nanmax, 'max'),
(np.min, 'min'),
(np.nanmin, 'min'),
(np.cumprod, 'cumprod'),
(np.nancumprod, 'cumprod'),
(np.cumsum, 'cumsum'),
(np.nancumsum, 'cumsum'),
))
@property
def _selection_name(self):
"""
return a name for myself; this would ideally be called
the 'name' property, but we cannot conflict with the
Series.name property which can be set
"""
if self._selection is None:
return None # 'result'
else:
return self._selection
@property
def _selection_list(self):
if not isinstance(self._selection, (list, tuple, ABCSeries,
ABCIndexClass, np.ndarray)):
return [self._selection]
return self._selection
@cache_readonly
def _selected_obj(self):
if self._selection is None or isinstance(self.obj, ABCSeries):
return self.obj
else:
return self.obj[self._selection]
@cache_readonly
def ndim(self):
return self._selected_obj.ndim
@cache_readonly
def _obj_with_exclusions(self):
if self._selection is not None and isinstance(self.obj,
ABCDataFrame):
return self.obj.reindex(columns=self._selection_list)
if len(self.exclusions) > 0:
return self.obj.drop(self.exclusions, axis=1)
else:
return self.obj
def __getitem__(self, key):
if self._selection is not None:
raise IndexError('Column(s) {selection} already selected'
.format(selection=self._selection))
if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass,
np.ndarray)):
if len(self.obj.columns.intersection(key)) != len(key):
bad_keys = list(set(key).difference(self.obj.columns))
raise KeyError("Columns not found: {missing}"
.format(missing=str(bad_keys)[1:-1]))
return self._gotitem(list(key), ndim=2)
elif not getattr(self, 'as_index', False):
if key not in self.obj.columns:
raise KeyError("Column not found: {key}".format(key=key))
return self._gotitem(key, ndim=2)
else:
if key not in self.obj:
raise KeyError("Column not found: {key}".format(key=key))
return self._gotitem(key, ndim=1)
def _gotitem(self, key, ndim, subset=None):
"""
sub-classes to define
return a sliced object
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on
"""
raise AbstractMethodError(self)
def aggregate(self, func, *args, **kwargs):
raise AbstractMethodError(self)
agg = aggregate
def _try_aggregate_string_function(self, arg, *args, **kwargs):
"""
if arg is a string, then try to operate on it:
- try to find a function (or attribute) on ourselves
- try to find a numpy function
- raise
"""
assert isinstance(arg, compat.string_types)
f = getattr(self, arg, None)
if f is not None:
if callable(f):
return f(*args, **kwargs)
# people may try to aggregate on a non-callable attribute
# but don't let them think they can pass args to it
assert len(args) == 0
assert len([kwarg for kwarg in kwargs
if kwarg not in ['axis', '_level']]) == 0
return f
f = getattr(np, arg, None)
if f is not None:
return f(self, *args, **kwargs)
raise ValueError("{arg} is an unknown string function".format(arg=arg))
def _aggregate(self, arg, *args, **kwargs):
"""
provide an implementation for the aggregators
Parameters
----------
arg : string, dict, function
*args : args to pass on to the function
**kwargs : kwargs to pass on to the function
Returns
-------
tuple of result, how
Notes
-----
how can be a string describe the required post-processing, or
None if not required
"""
is_aggregator = lambda x: isinstance(x, (list, tuple, dict))
is_nested_renamer = False
_axis = kwargs.pop('_axis', None)
if _axis is None:
_axis = getattr(self, 'axis', 0)
_level = kwargs.pop('_level', None)
if isinstance(arg, compat.string_types):
return self._try_aggregate_string_function(arg, *args,
**kwargs), None
if isinstance(arg, dict):
# aggregate based on the passed dict
if _axis != 0: # pragma: no cover
raise ValueError('Can only pass dict with axis=0')
obj = self._selected_obj
def nested_renaming_depr(level=4):
# deprecation of nested renaming
# GH 15931
warnings.warn(
("using a dict with renaming "
"is deprecated and will be removed in a future "
"version"),
FutureWarning, stacklevel=level)
# if we have a dict of any non-scalars
# eg. {'A' : ['mean']}, normalize all to
# be list-likes
if any(is_aggregator(x) for x in compat.itervalues(arg)):
new_arg = OrderedDict()
for k, v in compat.iteritems(arg):
if not isinstance(v, (tuple, list, dict)):
new_arg[k] = [v]
else:
new_arg[k] = v
# the keys must be in the columns
# for ndim=2, or renamers for ndim=1
# ok for now, but deprecated
# {'A': { 'ra': 'mean' }}
# {'A': { 'ra': ['mean'] }}
# {'ra': ['mean']}
# not ok
# {'ra' : { 'A' : 'mean' }}
if isinstance(v, dict):
is_nested_renamer = True
if k not in obj.columns:
msg = ('cannot perform renaming for {key} with a '
'nested dictionary').format(key=k)
raise SpecificationError(msg)
nested_renaming_depr(4 + (_level or 0))
elif isinstance(obj, ABCSeries):
nested_renaming_depr()
elif (isinstance(obj, ABCDataFrame) and
k not in obj.columns):
raise KeyError(
"Column '{col}' does not exist!".format(col=k))
arg = new_arg
else:
# deprecation of renaming keys
# GH 15931
keys = list(compat.iterkeys(arg))
if (isinstance(obj, ABCDataFrame) and
len(obj.columns.intersection(keys)) != len(keys)):
nested_renaming_depr()
from pandas.core.reshape.concat import concat
def _agg_1dim(name, how, subset=None):
"""
aggregate a 1-dim with how
"""
colg = self._gotitem(name, ndim=1, subset=subset)
if colg.ndim != 1:
raise SpecificationError("nested dictionary is ambiguous "
"in aggregation")
return colg.aggregate(how, _level=(_level or 0) + 1)
def _agg_2dim(name, how):
"""
aggregate a 2-dim with how
"""
colg = self._gotitem(self._selection, ndim=2,
subset=obj)
return colg.aggregate(how, _level=None)
def _agg(arg, func):
"""
run the aggregations over the arg with func
return an OrderedDict
"""
result = OrderedDict()
for fname, agg_how in compat.iteritems(arg):
result[fname] = func(fname, agg_how)
return result
# set the final keys
keys = list(compat.iterkeys(arg))
result = OrderedDict()
# nested renamer
if is_nested_renamer:
result = list(_agg(arg, _agg_1dim).values())
if all(isinstance(r, dict) for r in result):
result, results = OrderedDict(), result
for r in results:
result.update(r)
keys = list(compat.iterkeys(result))
else:
if self._selection is not None:
keys = None
# some selection on the object
elif self._selection is not None:
sl = set(self._selection_list)
# we are a Series like object,
# but may have multiple aggregations
if len(sl) == 1:
result = _agg(arg, lambda fname,
agg_how: _agg_1dim(self._selection, agg_how))
# we are selecting the same set as we are aggregating
elif not len(sl - set(keys)):
result = _agg(arg, _agg_1dim)
# we are a DataFrame, with possibly multiple aggregations
else:
result = _agg(arg, _agg_2dim)
# no selection
else:
try:
result = _agg(arg, _agg_1dim)
except SpecificationError:
# we are aggregating expecting all 1d-returns
# but we have 2d
result = _agg(arg, _agg_2dim)
# combine results
def is_any_series():
# return a boolean if we have *any* nested series
return any(isinstance(r, ABCSeries)
for r in compat.itervalues(result))
def is_any_frame():
# return a boolean if we have *any* nested series
return any(isinstance(r, ABCDataFrame)
for r in compat.itervalues(result))
if isinstance(result, list):
return concat(result, keys=keys, axis=1, sort=True), True
elif is_any_frame():
# we have a dict of DataFrames
# return a MI DataFrame
return concat([result[k] for k in keys],
keys=keys, axis=1), True
elif isinstance(self, ABCSeries) and is_any_series():
# we have a dict of Series
# return a MI Series
try:
result = concat(result)
except TypeError:
# we want to give a nice error here if
# we have non-same sized objects, so
# we don't automatically broadcast
raise ValueError("cannot perform both aggregation "
"and transformation operations "
"simultaneously")
return result, True
# fall thru
from pandas import DataFrame, Series
try:
result = DataFrame(result)
except ValueError:
# we have a dict of scalars
result = Series(result,
name=getattr(self, 'name', None))
return result, True
elif is_list_like(arg) and arg not in compat.string_types:
# we require a list, but not an 'str'
return self._aggregate_multiple_funcs(arg,
_level=_level,
_axis=_axis), None
else:
result = None
f = self._is_cython_func(arg)
if f and not args and not kwargs:
return getattr(self, f)(), None
# caller can react
return result, True
def _aggregate_multiple_funcs(self, arg, _level, _axis):
from pandas.core.reshape.concat import concat
if _axis != 0:
raise NotImplementedError("axis other than 0 is not supported")
if self._selected_obj.ndim == 1:
obj = self._selected_obj
else:
obj = self._obj_with_exclusions
results = []
keys = []
# degenerate case
if obj.ndim == 1:
for a in arg:
try:
colg = self._gotitem(obj.name, ndim=1, subset=obj)
results.append(colg.aggregate(a))
# make sure we find a good name
name = com.get_callable_name(a) or a
keys.append(name)
except (TypeError, DataError):
pass
except SpecificationError:
raise
# multiples
else:
for index, col in enumerate(obj):
try:
colg = self._gotitem(col, ndim=1,
subset=obj.iloc[:, index])
results.append(colg.aggregate(arg))
keys.append(col)
except (TypeError, DataError):
pass
except ValueError:
# cannot aggregate
continue
except SpecificationError:
raise
# if we are empty
if not len(results):
raise ValueError("no results")
try:
return concat(results, keys=keys, axis=1, sort=False)
except TypeError:
# we are concatting non-NDFrame objects,
# e.g. a list of scalars
from pandas.core.dtypes.cast import is_nested_object
from pandas import Series
result = Series(results, index=keys, name=self.name)
if is_nested_object(result):
raise ValueError("cannot combine transform and "
"aggregation operations")
return result
def _shallow_copy(self, obj=None, obj_type=None, **kwargs):
"""
return a new object with the replacement attributes
"""
if obj is None:
obj = self._selected_obj.copy()
if obj_type is None:
obj_type = self._constructor
if isinstance(obj, obj_type):
obj = obj.obj
for attr in self._attributes:
if attr not in kwargs:
kwargs[attr] = getattr(self, attr)
return obj_type(obj, **kwargs)
def _is_cython_func(self, arg):
"""
if we define an internal function for this argument, return it
"""
return self._cython_table.get(arg)
def _is_builtin_func(self, arg):
"""
if we define an builtin function for this argument, return it,
otherwise return the arg
"""
return self._builtin_table.get(arg, arg)
class IndexOpsMixin(object):
""" common ops mixin to support a unified interface / docs for Series /
Index
"""
# ndarray compatibility
__array_priority__ = 1000
def transpose(self, *args, **kwargs):
"""
Return the transpose, which is by definition self.
"""
nv.validate_transpose(args, kwargs)
return self
T = property(transpose, doc="Return the transpose, which is by "
"definition self.")
@property
def _is_homogeneous_type(self):
"""
Whether the object has a single dtype.
By definition, Series and Index are always considered homogeneous.
A MultiIndex may or may not be homogeneous, depending on the
dtypes of the levels.
See Also
--------
DataFrame._is_homogeneous_type
MultiIndex._is_homogeneous_type
"""
return True
@property
def shape(self):
"""
Return a tuple of the shape of the underlying data.
"""
return self._values.shape
@property
def ndim(self):
"""
Number of dimensions of the underlying data, by definition 1.
"""
return 1
def item(self):
"""
Return the first element of the underlying data as a python scalar.
"""
try:
return self.values.item()
except IndexError:
# copy numpy's message here because Py26 raises an IndexError
raise ValueError('can only convert an array of size 1 to a '
'Python scalar')
@property
def data(self):
"""
Return the data pointer of the underlying data.
"""
warnings.warn("{obj}.data is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self.values.data
@property
def itemsize(self):
"""
Return the size of the dtype of the item of the underlying data.
"""
warnings.warn("{obj}.itemsize is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self._ndarray_values.itemsize
@property
def nbytes(self):
"""
Return the number of bytes in the underlying data.
"""
return self._values.nbytes
@property
def strides(self):
"""
Return the strides of the underlying data.
"""
warnings.warn("{obj}.strides is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self._ndarray_values.strides
@property
def size(self):
"""
Return the number of elements in the underlying data.
"""
return self._values.size
@property
def flags(self):
"""
Return the ndarray.flags for the underlying data.
"""
warnings.warn("{obj}.flags is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self.values.flags
@property
def base(self):
"""
Return the base object if the memory of the underlying data is shared.
"""
warnings.warn("{obj}.base is deprecated and will be removed "
"in a future version".format(obj=type(self).__name__),
FutureWarning, stacklevel=2)
return self.values.base
@property
def array(self):
# type: () -> ExtensionArray
"""
The ExtensionArray of the data backing this Series or Index.
.. versionadded:: 0.24.0
Returns
-------
ExtensionArray
An ExtensionArray of the values stored within. For extension
types, this is the actual array. For NumPy native types, this
is a thin (no copy) wrapper around :class:`numpy.ndarray`.
``.array`` differs ``.values`` which may require converting the
data to a different form.
See Also
--------
Index.to_numpy : Similar method that always returns a NumPy array.
Series.to_numpy : Similar method that always returns a NumPy array.
Notes
-----
This table lays out the different array types for each extension
dtype within pandas.
================== =============================
dtype array type
================== =============================
category Categorical
period PeriodArray
interval IntervalArray
IntegerNA IntegerArray
datetime64[ns, tz] DatetimeArray
================== =============================
For any 3rd-party extension types, the array type will be an
ExtensionArray.
For all remaining dtypes ``.array`` will be a
:class:`arrays.NumpyExtensionArray` wrapping the actual ndarray
stored within. If you absolutely need a NumPy array (possibly with
copying / coercing data), then use :meth:`Series.to_numpy` instead.
Examples
--------
For regular NumPy types like int, and float, a PandasArray
is returned.
>>> pd.Series([1, 2, 3]).array
<PandasArray>
[1, 2, 3]
Length: 3, dtype: int64
For extension types, like Categorical, the actual ExtensionArray
is returned
>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.array
[a, b, a]
Categories (2, object): [a, b]
"""
result = self._values
if is_datetime64_ns_dtype(result.dtype):
from pandas.arrays import DatetimeArray
result = DatetimeArray(result)
elif is_timedelta64_ns_dtype(result.dtype):
from pandas.arrays import TimedeltaArray
result = TimedeltaArray(result)
elif not is_extension_array_dtype(result.dtype):
from pandas.core.arrays.numpy_ import PandasArray
result = PandasArray(result)
return result
def to_numpy(self, dtype=None, copy=False):
"""
A NumPy ndarray representing the values in this Series or Index.
.. versionadded:: 0.24.0
Parameters
----------
dtype : str or numpy.dtype, optional
The dtype to pass to :meth:`numpy.asarray`
copy : bool, default False
Whether to ensure that the returned value is a not a view on
another array. Note that ``copy=False`` does not *ensure* that
``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that
a copy is made, even if not strictly necessary.
Returns
-------
numpy.ndarray
See Also
--------
Series.array : Get the actual data stored within.
Index.array : Get the actual data stored within.
DataFrame.to_numpy : Similar method for DataFrame.
Notes
-----
The returned array will be the same up to equality (values equal
in `self` will be equal in the returned array; likewise for values
that are not equal). When `self` contains an ExtensionArray, the
dtype may be different. For example, for a category-dtype Series,
``to_numpy()`` will return a NumPy array and the categorical dtype
will be lost.
For NumPy dtypes, this will be a reference to the actual data stored
in this Series or Index (assuming ``copy=False``). Modifying the result
in place will modify the data stored in the Series or Index (not that
we recommend doing that).
For extension types, ``to_numpy()`` *may* require copying data and
coercing the result to a NumPy type (possibly object), which may be
expensive. When you need a no-copy reference to the underlying data,
:attr:`Series.array` should be used instead.
This table lays out the different dtypes and default return types of
``to_numpy()`` for various dtypes within pandas.
================== ================================
dtype array type
================== ================================
category[T] ndarray[T] (same dtype as input)
period ndarray[object] (Periods)
interval ndarray[object] (Intervals)
IntegerNA ndarray[object]
datetime64[ns] datetime64[ns]
datetime64[ns, tz] ndarray[object] (Timestamps)
================== ================================
Examples
--------
>>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))
>>> ser.to_numpy()
array(['a', 'b', 'a'], dtype=object)
Specify the `dtype` to control how datetime-aware data is represented.
Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp`
objects, each with the correct ``tz``.
>>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET"))
>>> ser.to_numpy(dtype=object)
array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),
Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],
dtype=object)
Or ``dtype='datetime64[ns]'`` to return an ndarray of native
datetime64 values. The values are converted to UTC and the timezone
info is dropped.
>>> ser.to_numpy(dtype="datetime64[ns]")
... # doctest: +ELLIPSIS
array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],
dtype='datetime64[ns]')
"""
if is_datetime64tz_dtype(self.dtype) and dtype is None:
# note: this is going to change very soon.
# I have a WIP PR making this unnecessary, but it's
# a bit out of scope for the DatetimeArray PR.
dtype = "object"
result = np.asarray(self._values, dtype=dtype)
# TODO(GH-24345): Avoid potential double copy
if copy:
result = result.copy()
return result
@property
def _ndarray_values(self):
# type: () -> np.ndarray
"""
The data as an ndarray, possibly losing information.
The expectation is that this is cheap to compute, and is primarily
used for interacting with our indexers.
- categorical -> codes
"""
if is_extension_array_dtype(self):
return self.array._ndarray_values
return self.values
@property
def empty(self):
return not self.size
def max(self, axis=None, skipna=True):
"""
Return the maximum value of the Index.
Parameters
----------
axis : int, optional
For compatibility with NumPy. Only 0 or None are allowed.
skipna : bool, default True
Returns
-------
scalar
Maximum value.
See Also
--------
Index.min : Return the minimum value in an Index.
Series.max : Return the maximum value in a Series.
DataFrame.max : Return the maximum values in a DataFrame.
Examples
--------
>>> idx = pd.Index([3, 2, 1])
>>> idx.max()
3
>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.max()
'c'
For a MultiIndex, the maximum is determined lexicographically.
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.max()
('b', 2)
"""
nv.validate_minmax_axis(axis)
return nanops.nanmax(self._values, skipna=skipna)
def argmax(self, axis=None, skipna=True):
"""
Return an ndarray of the maximum argument indexer.
Parameters
----------
axis : {None}
Dummy argument for consistency with Series
skipna : bool, default True
See Also
--------
numpy.ndarray.argmax
"""
nv.validate_minmax_axis(axis)
return nanops.nanargmax(self._values, skipna=skipna)
def min(self, axis=None, skipna=True):
"""
Return the minimum value of the Index.
Parameters
----------
axis : {None}
Dummy argument for consistency with Series
skipna : bool, default True
Returns
-------
scalar
Minimum value.
See Also
--------
Index.max : Return the maximum value of the object.
Series.min : Return the minimum value in a Series.
DataFrame.min : Return the minimum values in a DataFrame.
Examples
--------
>>> idx = pd.Index([3, 2, 1])
>>> idx.min()
1
>>> idx = pd.Index(['c', 'b', 'a'])
>>> idx.min()
'a'
For a MultiIndex, the minimum is determined lexicographically.
>>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])
>>> idx.min()
('a', 1)
"""
nv.validate_minmax_axis(axis)
return nanops.nanmin(self._values, skipna=skipna)
def argmin(self, axis=None, skipna=True):
"""
Return a ndarray of the minimum argument indexer.
Parameters
----------
axis : {None}
Dummy argument for consistency with Series
skipna : bool, default True
Returns
-------
numpy.ndarray
See Also
--------
numpy.ndarray.argmin
"""
nv.validate_minmax_axis(axis)
return nanops.nanargmin(self._values, skipna=skipna)
def tolist(self):
"""
Return a list of the values.
These are each a scalar type, which is a Python scalar
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
Returns
-------
list
See Also
--------
numpy.ndarray.tolist
"""
if is_datetimelike(self._values):
return [com.maybe_box_datetimelike(x) for x in self._values]
elif is_extension_array_dtype(self._values):
return list(self._values)
else:
return self._values.tolist()
to_list = tolist
def __iter__(self):
"""
Return an iterator of the values.
These are each a scalar type, which is a Python scalar
(for str, int, float) or a pandas scalar
(for Timestamp/Timedelta/Interval/Period)
"""
# We are explicity making element iterators.
if is_datetimelike(self._values):
return map(com.maybe_box_datetimelike, self._values)
elif is_extension_array_dtype(self._values):
return iter(self._values)
else:
return map(self._values.item, range(self._values.size))
@cache_readonly
def hasnans(self):
"""
Return if I have any nans; enables various perf speedups.
"""
return bool(isna(self).any())
def _reduce(self, op, name, axis=0, skipna=True, numeric_only=None,
filter_type=None, **kwds):
""" perform the reduction type operation if we can """
func = getattr(self, name, None)
if func is None:
raise TypeError("{klass} cannot perform the operation {op}".format(
klass=self.__class__.__name__, op=name))
return func(skipna=skipna, **kwds)
def _map_values(self, mapper, na_action=None):
"""
An internal function that maps values using the input
correspondence (which can be a dict, Series, or function).
Parameters
----------
mapper : function, dict, or Series
The input correspondence object
na_action : {None, 'ignore'}
If 'ignore', propagate NA values, without passing them to the
mapping function
Returns
-------
Union[Index, MultiIndex], inferred
The output of the mapping function applied to the index.
If the function returns a tuple with more than one element
a MultiIndex will be returned.
"""
# we can fastpath dict/Series to an efficient map
# as we know that we are not going to have to yield
# python types
if isinstance(mapper, dict):
if hasattr(mapper, '__missing__'):
# If a dictionary subclass defines a default value method,
# convert mapper to a lookup function (GH #15999).
dict_with_default = mapper
mapper = lambda x: dict_with_default[x]
else:
# Dictionary does not have a default. Thus it's safe to
# convert to an Series for efficiency.
# we specify the keys here to handle the
# possibility that they are tuples
from pandas import Series
mapper = Series(mapper)
if isinstance(mapper, ABCSeries):
# Since values were input this means we came from either
# a dict or a series and mapper should be an index
if is_extension_type(self.dtype):
values = self._values
else:
values = self.values
indexer = mapper.index.get_indexer(values)
new_values = algorithms.take_1d(mapper._values, indexer)
return new_values
# we must convert to python types
if is_extension_type(self.dtype):
values = self._values
if na_action is not None:
raise NotImplementedError
map_f = lambda values, f: values.map(f)
else:
values = self.astype(object)
values = getattr(values, 'values', values)
if na_action == 'ignore':
def map_f(values, f):
return lib.map_infer_mask(values, f,
isna(values).view(np.uint8))
else:
map_f = lib.map_infer
# mapper is a function
new_values = map_f(values, mapper)
return new_values
def value_counts(self, normalize=False, sort=True, ascending=False,
bins=None, dropna=True):
"""
Return a Series containing counts of unique values.
The resulting object will be in descending order so that the
first element is the most frequently-occurring element.
Excludes NA values by default.
Parameters
----------
normalize : boolean, default False
If True then the object returned will contain the relative
frequencies of the unique values.
sort : boolean, default True
Sort by frequencies.
ascending : boolean, default False
Sort in ascending order.
bins : integer, optional
Rather than count values, group them into half-open bins,
a convenience for ``pd.cut``, only works with numeric data.
dropna : boolean, default True
Don't include counts of NaN.
Returns
-------
Series
See Also
--------
Series.count: Number of non-NA elements in a Series.
DataFrame.count: Number of non-NA elements in a DataFrame.
Examples
--------
>>> index = pd.Index([3, 1, 2, 3, 4, np.nan])
>>> index.value_counts()
3.0 2
4.0 1
2.0 1
1.0 1
dtype: int64
With `normalize` set to `True`, returns the relative frequency by
dividing all values by the sum of values.
>>> s = pd.Series([3, 1, 2, 3, 4, np.nan])
>>> s.value_counts(normalize=True)
3.0 0.4
4.0 0.2
2.0 0.2
1.0 0.2
dtype: float64
**bins**
Bins can be useful for going from a continuous variable to a
categorical variable; instead of counting unique
apparitions of values, divide the index in the specified
number of half-open bins.
>>> s.value_counts(bins=3)
(2.0, 3.0] 2
(0.996, 2.0] 2
(3.0, 4.0] 1
dtype: int64
**dropna**
With `dropna` set to `False` we can also see NaN index values.
>>> s.value_counts(dropna=False)
3.0 2
NaN 1
4.0 1
2.0 1
1.0 1
dtype: int64
"""
from pandas.core.algorithms import value_counts
result = value_counts(self, sort=sort, ascending=ascending,
normalize=normalize, bins=bins, dropna=dropna)
return result
def unique(self):
values = self._values
if hasattr(values, 'unique'):
result = values.unique()
else:
from pandas.core.algorithms import unique1d
result = unique1d(values)
return result
def nunique(self, dropna=True):
"""
Return number of unique elements in the object.
Excludes NA values by default.
Parameters
----------
dropna : bool, default True
Don't include NaN in the count.
Returns
-------
int
See Also
--------
DataFrame.nunique: Method nunique for DataFrame.
Series.count: Count non-NA/null observations in the Series.
Examples
--------
>>> s = pd.Series([1, 3, 5, 7, 7])
>>> s
0 1
1 3
2 5
3 7
4 7
dtype: int64
>>> s.nunique()
4
"""
uniqs = self.unique()
n = len(uniqs)
if dropna and isna(uniqs).any():
n -= 1
return n
@property
def is_unique(self):
"""
Return boolean if values in the object are unique.
Returns
-------
bool
"""
return self.nunique(dropna=False) == len(self)
@property
def is_monotonic(self):
"""
Return boolean if values in the object are
monotonic_increasing.
.. versionadded:: 0.19.0
Returns
-------
bool
"""
from pandas import Index
return Index(self).is_monotonic
is_monotonic_increasing = is_monotonic
@property
def is_monotonic_decreasing(self):
"""
Return boolean if values in the object are
monotonic_decreasing.
.. versionadded:: 0.19.0
Returns
-------
bool
"""
from pandas import Index
return Index(self).is_monotonic_decreasing
def memory_usage(self, deep=False):
"""
Memory usage of the values
Parameters
----------
deep : bool
Introspect the data deeply, interrogate
`object` dtypes for system-level memory consumption
Returns
-------
bytes used
See Also
--------
numpy.ndarray.nbytes
Notes
-----
Memory usage does not include memory consumed by elements that
are not components of the array if deep=False or if used on PyPy
"""
if hasattr(self.array, 'memory_usage'):
return self.array.memory_usage(deep=deep)
v = self.array.nbytes
if deep and is_object_dtype(self) and not PYPY:
v += lib.memory_usage_of_objects(self.array)
return v
@Substitution(
values='', order='', size_hint='',
sort=textwrap.dedent("""\
sort : boolean, default False
Sort `uniques` and shuffle `labels` to maintain the
relationship.
"""))
@Appender(algorithms._shared_docs['factorize'])
def factorize(self, sort=False, na_sentinel=-1):
return algorithms.factorize(self, sort=sort, na_sentinel=na_sentinel)
_shared_docs['searchsorted'] = (
"""
Find indices where elements should be inserted to maintain order.
Find the indices into a sorted %(klass)s `self` such that, if the
corresponding elements in `value` were inserted before the indices,
the order of `self` would be preserved.
Parameters
----------
value : array_like
Values to insert into `self`.
side : {'left', 'right'}, optional
If 'left', the index of the first suitable location found is given.
If 'right', return the last such index. If there is no suitable
index, return either 0 or N (where N is the length of `self`).
sorter : 1-D array_like, optional
Optional array of integer indices that sort `self` into ascending
order. They are typically the result of ``np.argsort``.
Returns
-------
int or array of int
A scalar or array of insertion points with the
same shape as `value`.
.. versionchanged :: 0.24.0
If `value` is a scalar, an int is now always returned.
Previously, scalar inputs returned an 1-item array for
:class:`Series` and :class:`Categorical`.
See Also
--------
numpy.searchsorted
Notes
-----
Binary search is used to find the required insertion points.
Examples
--------
>>> x = pd.Series([1, 2, 3])
>>> x
0 1
1 2
2 3
dtype: int64
>>> x.searchsorted(4)
3
>>> x.searchsorted([0, 4])
array([0, 3])
>>> x.searchsorted([1, 3], side='left')
array([0, 2])
>>> x.searchsorted([1, 3], side='right')
array([1, 3])
>>> x = pd.Categorical(['apple', 'bread', 'bread',
'cheese', 'milk'], ordered=True)
[apple, bread, bread, cheese, milk]
Categories (4, object): [apple < bread < cheese < milk]
>>> x.searchsorted('bread')
1
>>> x.searchsorted(['bread'], side='right')
array([3])
""")
@Substitution(klass='Index')
@Appender(_shared_docs['searchsorted'])
def searchsorted(self, value, side='left', sorter=None):
return algorithms.searchsorted(self._values, value,
side=side, sorter=sorter)
def drop_duplicates(self, keep='first', inplace=False):
inplace = validate_bool_kwarg(inplace, 'inplace')
if isinstance(self, ABCIndexClass):
if self.is_unique:
return self._shallow_copy()
duplicated = self.duplicated(keep=keep)
result = self[np.logical_not(duplicated)]
if inplace:
return self._update_inplace(result)
else:
return result
def duplicated(self, keep='first'):
from pandas.core.algorithms import duplicated
if isinstance(self, ABCIndexClass):
if self.is_unique:
return np.zeros(len(self), dtype=np.bool)
return duplicated(self, keep=keep)
else:
return self._constructor(duplicated(self, keep=keep),
index=self.index).__finalize__(self)
# ----------------------------------------------------------------------
# abstracts
def _update_inplace(self, result, **kwargs):
raise AbstractMethodError(self)
| {
"content_hash": "1c65f9ce8c668202efa90cb5972382ca",
"timestamp": "",
"source": "github",
"line_count": 1558,
"max_line_length": 79,
"avg_line_length": 31.86007702182285,
"alnum_prop": 0.5278012812764414,
"repo_name": "MJuddBooth/pandas",
"id": "f896596dd5216cf0a33371940682a734f02e0485",
"size": "49638",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pandas/core/base.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4879"
},
{
"name": "C",
"bytes": "406766"
},
{
"name": "C++",
"bytes": "17248"
},
{
"name": "HTML",
"bytes": "606963"
},
{
"name": "Makefile",
"bytes": "529"
},
{
"name": "Python",
"bytes": "14858932"
},
{
"name": "Shell",
"bytes": "29575"
},
{
"name": "Smarty",
"bytes": "2040"
}
],
"symlink_target": ""
} |
Bastion: Default instance type: f1-micro (can be changed in terraform.tfvars). All SSH connectivity and tunnels go through this host.
Jenkins & Spinnaker host: Default instance type: n1-highmem-8 (can be changed in terraform.tfvars but this is the smallest recommended size due to Spinnakers memory requirements). Access to this host is tunneled/port forwarded through the bastion because Spinnaker currently has no authorization or authentication available.
Other things the terraform does:
* Creates the necessary firewall rules.
* Creates the test application and pipeline in Spinnaker
## To use:
* Install Pre-Requisites. The scripts will happily complain if the pre-reqs aren't there, but who wants to hear complaining?
* git
* Terraform >= 0.8.2
* Download from https://terraform.io/downloads.html and put it in your $PATH
* Python Modules:
* boto >= 2.38.0
* requests >= 2.8.1
* json >= 2.0.9
* docopt >= 0.6.2
* You may need to install pip. Please consult pip install instructions specific to your OS.
* Look at ./gcp/terraform.tfvars and change anything you think might need changing (region, zone, network_cidr, credentials_file, project, etc.). If these variables are not set you will be prompted for them when you run terraform. These can also be set via the install_spinnaker.sh command line.
* Required:
* Set ssh_private_key_location to the filesystem location of the ssh private key associated with your GCP account.
* Set jenkins_admin_password. Due to a bug in terraform this value must be set here or via the install_spinnaker.sh command line.
* Optional:
* Set adm_bastion_incoming_cidrs to a comma separated list of CIDRS that need to access these services. These are only necessary if you will be accessing the services from locations other than the host that is running terraform.
* Change the value for jenkins_admin_username.
* run the script:
This one is good if you have set all the variables in terraform.tfvars:
```
./install_spinnaker.sh -a apply -c gcp
```
An example of passing variables to terraform via the command line:
```
/install_spinnaker.sh -c gcp -a apply -t "-var jenkins_admin_password=somethingorother -var credentials_file=gcp_credentials_file.json -var project=your-gcp-spinnaker-project-id"
```
-a is the terraform action to run (apply, plan, or destroy)
-c is the cloud provider you're using
There are two optional flags you can pass to the install_spinnaker.sh script
```
-l Tells the script to log the terraform output to a file. Location of file will be printed.
-i <path where to store tf state files>. If you don't want the tfstate files to be stored in the default location ('./')
```
You can also put 'plan' in place of 'apply', and 'terraform plan' will be run, which will show you what terraform would do if you ran apply. It's a good way to test changes to any of the .tf files as most syntax errors will be caught.
... wait 15 minutes or so ...
Pay careful attention to the output at the end, example:
```
Outputs:
=
Bastion Public IP (for DNS): 104.197.192.50
Region: us-central1
Zone: a
Network: spinnaker-network
STATEPATH: /Users/tempuser/Stuff/code/Work/kenzan/internal/temploc/gcp/terraform.tfstate
Execute the following steps, in this order, to create a tunnel to the spinnaker instance and an example pipeline:
1. Start up the Spinnaker tunnel:
--- cut ---
cd support ; ./tunnel.sh -a start -s /Users/tempuser/Stuff/code/Work/kenzan/internal/temploc/gcp/terraform.tfstate
--- end cut ---
2. Go to http://localhost:9090/ (This is Jenkins) in your browser and login with the credentials you set in terraform.tfvars.
3. Go to http://localhost:9000/ (This is Spinnaker) in a separate tab in your browser. This is the tunnel to the new Spinnaker instance.
4. On Jenkins, choose the job "TestJob2" and "build now"
NOTE: sometimes the build fails with gradle errors about being unable to download dependencies. If that happens try building again.
5. When the Jenkins build is done, go to the spinnaker instance in your browser, select 'appname', and then 'Pipelines'. The pipeline should automatically start after the jenkins job is complete.
It will bake an image, then deploy that image.
6. Run the following command and it will give you a URL where you can access the example app that was launched in the previous step (if it was deployed successfully):
--- cut ---
cd support ; ./get_lb_url.py gcp testappname-test 7070
--- end cut ---
NOTE: it may take a few minutes before the instance is available in the load balancer.
```
To create the Spinnaker tunnel, you need to do run the following command (from the example output above)
```
cd support ; ./tunnel.sh -a start -s /Users/tempuser/Stuff/code/Work/kenzan/internal/temploc/gcp/terraform.tfstate
```
* With the tunnel running you can go to http://localhost:9000/ to access Spinnaker and http://localhost:9090/ to access Jenkins.
With a working pipeline, all you should have to do is go to the 'Package_example_app' job on jenkins and build it. The Spinnaker pipeline will be triggered, an Image baked, and a Server Group deployed with a Load Balancer.
After the pipeline successfully completes run the following from the output above:
```
cd support ; ./get_lb_url.py gcp testappname-test 7070
```
And it will tell you where to point your browser to view the example application you just deployed. It will wait until the Load Balancer is up and accepting traffic so it might take a bit of time.
# Destroying the Spinnaker network
Run this command:
```
./install_spinnaker.sh -a destroy -c gcp
```
Congratulations, your Spinnaker network is now gone!
# If you need to destroy the network manually:
* Terminate all instances in the network that was created.
* Delete any Load Balancers that were created
* Delete the network that was created
## TODO
* Remove unnecessary packages and services from the Bastion host. | {
"content_hash": "a8ee42f73dc84043409a7479f7bdcf0b",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 324,
"avg_line_length": 52.9375,
"alnum_prop": 0.7564513408669253,
"repo_name": "jpancoast-kenzan/spinnaker-terraform",
"id": "9f3b093494497278a5d6796a48ac2e096e76a89e",
"size": "5970",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/GCP.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HCL",
"bytes": "32476"
},
{
"name": "JavaScript",
"bytes": "3583"
},
{
"name": "Nginx",
"bytes": "2213"
},
{
"name": "Python",
"bytes": "36210"
},
{
"name": "Shell",
"bytes": "21168"
},
{
"name": "Smarty",
"bytes": "2888"
}
],
"symlink_target": ""
} |
title: Bokningar
inshort: Kunden själv reservationer
translator: Microsoft Cognitive Services
---
Kunden själv reservationer
| {
"content_hash": "b98ce839765969eb1dc1a98134c2c24e",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 40,
"avg_line_length": 16,
"alnum_prop": 0.8203125,
"repo_name": "Hexatown/docs",
"id": "1d993b9bed310e073399d6d058a843aa1ee013da",
"size": "134",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "microsoft/office365/bookings/sv.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "58"
},
{
"name": "CSS",
"bytes": "62970"
},
{
"name": "HTML",
"bytes": "50886"
},
{
"name": "PowerShell",
"bytes": "104690"
},
{
"name": "Ruby",
"bytes": "72"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "834f61c67051c8375e89f4ea8ce471c9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "c2d60ed8e1fbef747fe75e162213bf992152b9ec",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Protozoa/Ciliophora/Hypotrichea/Oxytrichida/Oxytrichidae/Oxytricha/Oxytricha erethisticus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0"?>
<cd:ProductDefinition xmlns:cd="http://www.stcorp.nl/coda/definition/2008/07" id="OMTO3" format="hdf5" last-modified="2016-09-19">
</cd:ProductDefinition>
| {
"content_hash": "13727e508bf8a88b54ce9c1bbb030591",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 130,
"avg_line_length": 59,
"alnum_prop": 0.7288135593220338,
"repo_name": "stcorp/harp",
"id": "a7df4f434bb13dd9d4762ac07f8d704e33a36d9e",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "definitions/AURA_OMI/products/OMTO3.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8034482"
},
{
"name": "C++",
"bytes": "49077"
},
{
"name": "CMake",
"bytes": "98451"
},
{
"name": "Lex",
"bytes": "17675"
},
{
"name": "M4",
"bytes": "26316"
},
{
"name": "MATLAB",
"bytes": "2379"
},
{
"name": "Makefile",
"bytes": "86352"
},
{
"name": "Python",
"bytes": "89089"
},
{
"name": "R",
"bytes": "520"
},
{
"name": "Shell",
"bytes": "2555"
},
{
"name": "Yacc",
"bytes": "77754"
}
],
"symlink_target": ""
} |
require "keg"
require "language/python"
require "formula"
require "version"
require "development_tools"
require "utils/shell"
module Homebrew
module Diagnostic
def self.missing_deps(ff, hide = nil)
missing = {}
ff.each do |f|
missing_dependencies = f.missing_dependencies(hide: hide)
next if missing_dependencies.empty?
yield f.full_name, missing_dependencies if block_given?
missing[f.full_name] = missing_dependencies
end
missing
end
class Volumes
def initialize
@volumes = get_mounts
end
def which(path)
vols = get_mounts path
# no volume found
return -1 if vols.empty?
vol_index = @volumes.index(vols[0])
# volume not found in volume list
return -1 if vol_index.nil?
vol_index
end
def get_mounts(path = nil)
vols = []
# get the volume of path, if path is nil returns all volumes
args = %w[/bin/df -P]
args << path if path
Utils.popen_read(*args) do |io|
io.each_line do |line|
case line.chomp
# regex matches: /dev/disk0s2 489562928 440803616 48247312 91% /
when /^.+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]{1,3}%\s+(.+)/
vols << Regexp.last_match(1)
end
end
end
vols
end
end
class Checks
############# HELPERS
# Finds files in HOMEBREW_PREFIX *and* /usr/local.
# Specify paths relative to a prefix eg. "include/foo.h".
# Sets @found for your convenience.
def find_relative_paths(*relative_paths)
@found = [HOMEBREW_PREFIX, "/usr/local"].uniq.reduce([]) do |found, prefix|
found + relative_paths.map { |f| File.join(prefix, f) }.select { |f| File.exist? f }
end
end
def inject_file_list(list, string)
list.reduce(string) { |acc, elem| acc << " #{elem}\n" }
end
############# END HELPERS
def fatal_install_checks
%w[
check_access_directories
].freeze
end
def development_tools_checks
%w[
check_for_installed_developer_tools
].freeze
end
def fatal_development_tools_checks
%w[
].freeze
end
def build_error_checks
(development_tools_checks + %w[
]).freeze
end
def check_for_installed_developer_tools
return if DevelopmentTools.installed?
<<~EOS
No developer tools installed.
#{DevelopmentTools.installation_instructions}
EOS
end
def check_build_from_source
return unless ENV["HOMEBREW_BUILD_FROM_SOURCE"]
<<~EOS
You have HOMEBREW_BUILD_FROM_SOURCE set. This environment variable is
intended for use by Homebrew developers. If you are encountering errors,
please try unsetting this. Please do not file issues if you encounter
errors when using this environment variable.
EOS
end
# Anaconda installs multiple system & brew dupes, including OpenSSL, Python,
# sqlite, libpng, Qt, etc. Regularly breaks compile on Vim, MacVim and others.
# Is flagged as part of the *-config script checks below, but people seem
# to ignore those as warnings rather than extremely likely breakage.
def check_for_anaconda
return unless which("anaconda")
return unless which("python")
anaconda_directory = which("anaconda").realpath.dirname
python_binary = Utils.popen_read(which("python"), "-c", "import sys; sys.stdout.write(sys.executable)")
python_directory = Pathname.new(python_binary).realpath.dirname
# Only warn if Python lives with Anaconda, since is most problematic case.
return unless python_directory == anaconda_directory
<<~EOS
Anaconda is known to frequently break Homebrew builds, including Vim and
MacVim, due to bundling many duplicates of system and Homebrew-available
tools.
If you encounter a build failure please temporarily remove Anaconda
from your $PATH and attempt the build again prior to reporting the
failure to us. Thanks!
EOS
end
def __check_stray_files(dir, pattern, white_list, message)
return unless File.directory?(dir)
files = Dir.chdir(dir) do
(Dir.glob(pattern) - Dir.glob(white_list))
.select { |f| File.file?(f) && !File.symlink?(f) }
.map { |f| File.join(dir, f) }
end
return if files.empty?
inject_file_list(files.sort, message)
end
def check_for_stray_dylibs
# Dylibs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libfuse.2.dylib", # MacFuse
"libfuse_ino64.2.dylib", # MacFuse
"libmacfuse_i32.2.dylib", # OSXFuse MacFuse compatibility layer
"libmacfuse_i64.2.dylib", # OSXFuse MacFuse compatibility layer
"libosxfuse_i32.2.dylib", # OSXFuse
"libosxfuse_i64.2.dylib", # OSXFuse
"libosxfuse.2.dylib", # OSXFuse
"libTrAPI.dylib", # TrAPI/Endpoint Security VPN
"libntfs-3g.*.dylib", # NTFS-3G
"libntfs.*.dylib", # NTFS-3G
"libublio.*.dylib", # NTFS-3G
"libUFSDNTFS.dylib", # Paragon NTFS
"libUFSDExtFS.dylib", # Paragon ExtFS
"libecomlodr.dylib", # Symantec Endpoint Protection
"libsymsea*.dylib", # Symantec Endpoint Protection
"sentinel.dylib", # SentinelOne
"sentinel-*.dylib", # SentinelOne
]
__check_stray_files "/usr/local/lib", "*.dylib", white_list, <<~EOS
Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected dylibs:
EOS
end
def check_for_stray_static_libs
# Static libs which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"libsecurity_agent_client.a", # OS X 10.8.2 Supplemental Update
"libsecurity_agent_server.a", # OS X 10.8.2 Supplemental Update
"libntfs-3g.a", # NTFS-3G
"libntfs.a", # NTFS-3G
"libublio.a", # NTFS-3G
"libappfirewall.a", # Symantec Endpoint Protection
"libautoblock.a", # Symantec Endpoint Protection
"libautosetup.a", # Symantec Endpoint Protection
"libconnectionsclient.a", # Symantec Endpoint Protection
"liblocationawareness.a", # Symantec Endpoint Protection
"libpersonalfirewall.a", # Symantec Endpoint Protection
"libtrustedcomponents.a", # Symantec Endpoint Protection
]
__check_stray_files "/usr/local/lib", "*.a", white_list, <<~EOS
Unbrewed static libraries were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected static libraries:
EOS
end
def check_for_stray_pcs
# Package-config files which are generally OK should be added to this list,
# with a short description of the software they come with.
white_list = [
"fuse.pc", # OSXFuse/MacFuse
"macfuse.pc", # OSXFuse MacFuse compatibility layer
"osxfuse.pc", # OSXFuse
"libntfs-3g.pc", # NTFS-3G
"libublio.pc", # NTFS-3G
]
__check_stray_files "/usr/local/lib/pkgconfig", "*.pc", white_list, <<~EOS
Unbrewed .pc files were found in /usr/local/lib/pkgconfig.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .pc files:
EOS
end
def check_for_stray_las
white_list = [
"libfuse.la", # MacFuse
"libfuse_ino64.la", # MacFuse
"libosxfuse_i32.la", # OSXFuse
"libosxfuse_i64.la", # OSXFuse
"libosxfuse.la", # OSXFuse
"libntfs-3g.la", # NTFS-3G
"libntfs.la", # NTFS-3G
"libublio.la", # NTFS-3G
]
__check_stray_files "/usr/local/lib", "*.la", white_list, <<~EOS
Unbrewed .la files were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected .la files:
EOS
end
def check_for_stray_headers
white_list = [
"fuse.h", # MacFuse
"fuse/**/*.h", # MacFuse
"macfuse/**/*.h", # OSXFuse MacFuse compatibility layer
"osxfuse/**/*.h", # OSXFuse
"ntfs/**/*.h", # NTFS-3G
"ntfs-3g/**/*.h", # NTFS-3G
]
__check_stray_files "/usr/local/include", "**/*.h", white_list, <<~EOS
Unbrewed header files were found in /usr/local/include.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.
Unexpected header files:
EOS
end
def check_for_broken_symlinks
broken_symlinks = []
Keg::PRUNEABLE_DIRECTORIES.each do |d|
next unless d.directory?
d.find do |path|
if path.symlink? && !path.resolved_path_exists?
broken_symlinks << path
end
end
end
return if broken_symlinks.empty?
inject_file_list broken_symlinks, <<~EOS
Broken symlinks were found. Remove them with `brew prune`:
EOS
end
def check_tmpdir_sticky_bit
world_writable = HOMEBREW_TEMP.stat.mode & 0777 == 0777
return if !world_writable || HOMEBREW_TEMP.sticky?
<<~EOS
#{HOMEBREW_TEMP} is world-writable but does not have the sticky bit set.
Please execute `sudo chmod +t #{HOMEBREW_TEMP}` in your Terminal.
EOS
end
def check_exist_directories
not_exist_dirs = Keg::MUST_EXIST_DIRECTORIES.reject(&:exist?)
return if not_exist_dirs.empty?
<<~EOS
The following directories do not exist:
#{not_exist_dirs.join("\n")}
You should create these directories and change their ownership to your account.
sudo mkdir -p #{not_exist_dirs.join(" ")}
sudo chown -R $(whoami) #{not_exist_dirs.join(" ")}
EOS
end
def check_access_directories
not_writable_dirs =
Keg::MUST_BE_WRITABLE_DIRECTORIES.select(&:exist?)
.reject(&:writable_real?)
return if not_writable_dirs.empty?
<<~EOS
The following directories are not writable by your user:
#{not_writable_dirs.join("\n")}
You should change the ownership of these directories to your user.
sudo chown -R $(whoami) #{not_writable_dirs.join(" ")}
EOS
end
def check_multiple_cellars
return if HOMEBREW_PREFIX.to_s == HOMEBREW_REPOSITORY.to_s
return unless (HOMEBREW_REPOSITORY/"Cellar").exist?
return unless (HOMEBREW_PREFIX/"Cellar").exist?
<<~EOS
You have multiple Cellars.
You should delete #{HOMEBREW_REPOSITORY}/Cellar:
rm -rf #{HOMEBREW_REPOSITORY}/Cellar
EOS
end
def check_user_path_1
@seen_prefix_bin = false
@seen_prefix_sbin = false
message = ""
paths.each do |p|
case p
when "/usr/bin"
unless @seen_prefix_bin
# only show the doctor message if there are any conflicts
# rationale: a default install should not trigger any brew doctor messages
conflicts = Dir["#{HOMEBREW_PREFIX}/bin/*"]
.map { |fn| File.basename fn }
.select { |bn| File.exist? "/usr/bin/#{bn}" }
unless conflicts.empty?
message = inject_file_list conflicts, <<~EOS
/usr/bin occurs before #{HOMEBREW_PREFIX}/bin
This means that system-provided programs will be used instead of those
provided by Homebrew. The following tools exist at both paths:
EOS
message += <<~EOS
Consider setting your PATH so that #{HOMEBREW_PREFIX}/bin
occurs before /usr/bin. Here is a one-liner:
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/bin")}
EOS
end
end
when "#{HOMEBREW_PREFIX}/bin"
@seen_prefix_bin = true
when "#{HOMEBREW_PREFIX}/sbin"
@seen_prefix_sbin = true
end
end
message unless message.empty?
end
def check_user_path_2
return if @seen_prefix_bin
<<~EOS
Homebrew's bin was not found in your PATH.
Consider setting the PATH for example like so
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/bin")}
EOS
end
def check_user_path_3
return if @seen_prefix_sbin
# Don't complain about sbin not being in the path if it doesn't exist
sbin = HOMEBREW_PREFIX/"sbin"
return unless sbin.directory? && !sbin.children.empty?
<<~EOS
Homebrew's sbin was not found in your PATH but you have installed
formulae that put executables in #{HOMEBREW_PREFIX}/sbin.
Consider setting the PATH for example like so
#{Utils::Shell.prepend_path_in_profile("#{HOMEBREW_PREFIX}/sbin")}
EOS
end
def check_for_config_scripts
return unless HOMEBREW_CELLAR.exist?
real_cellar = HOMEBREW_CELLAR.realpath
scripts = []
whitelist = %W[
/usr/bin /usr/sbin
/usr/X11/bin /usr/X11R6/bin /opt/X11/bin
#{HOMEBREW_PREFIX}/bin #{HOMEBREW_PREFIX}/sbin
/Applications/Server.app/Contents/ServerRoot/usr/bin
/Applications/Server.app/Contents/ServerRoot/usr/sbin
].map(&:downcase)
paths.each do |p|
next if whitelist.include?(p.downcase) || !File.directory?(p)
realpath = Pathname.new(p).realpath.to_s
next if realpath.start_with?(real_cellar.to_s, HOMEBREW_CELLAR.to_s)
scripts += Dir.chdir(p) { Dir["*-config"] }.map { |c| File.join(p, c) }
end
return if scripts.empty?
inject_file_list scripts, <<~EOS
"config" scripts exist outside your system or Homebrew directories.
`./configure` scripts often look for *-config scripts to determine if
software packages are installed, and what additional flags to use when
compiling and linking.
Having additional scripts in your path can confuse software installed via
Homebrew if the config script overrides a system or Homebrew provided
script of the same name. We found the following "config" scripts:
EOS
end
def check_ld_vars
ld_vars = ENV.keys.grep(/^(|DY)LD_/)
return if ld_vars.empty?
values = ld_vars.map { |var| "#{var}: #{ENV.fetch(var)}" }
message = inject_file_list values, <<~EOS
Setting DYLD_* or LD_* variables can break dynamic linking.
Set variables:
EOS
if ld_vars.include? "DYLD_INSERT_LIBRARIES"
message += <<~EOS
Setting DYLD_INSERT_LIBRARIES can cause Go builds to fail.
Having this set is common if you use this software:
#{Formatter.url("https://asepsis.binaryage.com/")}
EOS
end
message
end
def check_for_symlinked_cellar
return unless HOMEBREW_CELLAR.exist?
return unless HOMEBREW_CELLAR.symlink?
<<~EOS
Symlinked Cellars can cause problems.
Your Homebrew Cellar is a symlink: #{HOMEBREW_CELLAR}
which resolves to: #{HOMEBREW_CELLAR.realpath}
The recommended Homebrew installations are either:
(A) Have Cellar be a real directory inside of your HOMEBREW_PREFIX
(B) Symlink "bin/brew" into your prefix, but don't symlink "Cellar".
Older installations of Homebrew may have created a symlinked Cellar, but this can
cause problems when two formula install to locations that are mapped on top of each
other during the linking step.
EOS
end
def check_git_version
# System Git version on macOS Sierra.
minimum_version = "2.14.3".freeze
return unless Utils.git_available?
return if Version.create(Utils.git_version) >= Version.create(minimum_version)
git = Formula["git"]
git_upgrade_cmd = git.any_version_installed? ? "upgrade" : "install"
<<~EOS
An outdated version (#{Utils.git_version}) of Git was detected in your PATH.
Git #{minimum_version} or newer is required for Homebrew.
Please upgrade:
brew #{git_upgrade_cmd} git
EOS
end
def check_for_git
return if Utils.git_available?
<<~EOS
Git could not be found in your PATH.
Homebrew uses Git for several internal functions, and some formulae use Git
checkouts instead of stable tarballs. You may want to install Git:
brew install git
EOS
end
def check_git_newline_settings
return unless Utils.git_available?
autocrlf = HOMEBREW_REPOSITORY.cd { `git config --get core.autocrlf`.chomp }
return unless autocrlf == "true"
<<~EOS
Suspicious Git newline settings found.
The detected Git newline settings will cause checkout problems:
core.autocrlf = #{autocrlf}
If you are not routinely dealing with Windows-based projects,
consider removing these by running:
git config --global core.autocrlf input
EOS
end
def check_brew_git_origin
return if !Utils.git_available? || !(HOMEBREW_REPOSITORY/".git").exist?
origin = HOMEBREW_REPOSITORY.git_origin
if origin.nil?
<<~EOS
Missing Homebrew/brew git origin remote.
Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the Homebrew remote:
git -C "#{HOMEBREW_REPOSITORY}" remote add origin #{Formatter.url("https://github.com/Homebrew/brew.git")}
EOS
elsif origin !~ %r{Homebrew/brew(\.git|/)?$}
<<~EOS
Suspicious Homebrew/brew git origin remote found.
With a non-standard origin, Homebrew won't pull updates from
the main repository. The current git origin is:
#{origin}
Unless you have compelling reasons, consider setting the
origin remote to point at the main repository by running:
git -C "#{HOMEBREW_REPOSITORY}" remote set-url origin #{Formatter.url("https://github.com/Homebrew/brew.git")}
EOS
end
end
def check_coretap_git_origin
coretap_path = CoreTap.instance.path
return if !Utils.git_available? || !(coretap_path/".git").exist?
origin = coretap_path.git_origin
if origin.nil?
<<~EOS
Missing #{CoreTap.instance} git origin remote.
Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the Homebrew remote:
git -C "#{coretap_path}" remote add origin #{Formatter.url("https://github.com/Homebrew/homebrew-core.git")}
EOS
elsif origin !~ %r{Homebrew/homebrew-core(\.git|/)?$}
return if ENV["CI"] && origin.include?("Homebrew/homebrew-test-bot")
<<~EOS
Suspicious #{CoreTap.instance} git origin remote found.
With a non-standard origin, Homebrew won't pull updates from
the main repository. The current git origin is:
#{origin}
Unless you have compelling reasons, consider setting the
origin remote to point at the main repository by running:
git -C "#{coretap_path}" remote set-url origin #{Formatter.url("https://github.com/Homebrew/homebrew-core.git")}
EOS
end
return if ENV["CI"]
branch = coretap_path.git_branch
return if branch.nil? || branch =~ /master/
<<~EOS
Homebrew/homebrew-core is not on the master branch
Check out the master branch by running:
git -C "$(brew --repo homebrew/core)" checkout master
EOS
end
def __check_linked_brew(f)
f.installed_prefixes.each do |prefix|
prefix.find do |src|
next if src == prefix
dst = HOMEBREW_PREFIX + src.relative_path_from(prefix)
return true if dst.symlink? && src == dst.resolved_path
end
end
false
end
def check_for_other_frameworks
# Other frameworks that are known to cause problems when present
frameworks_to_check = %w[
expat.framework
libexpat.framework
libcurl.framework
]
frameworks_found = frameworks_to_check
.map { |framework| "/Library/Frameworks/#{framework}" }
.select { |framework| File.exist? framework }
return if frameworks_found.empty?
inject_file_list frameworks_found, <<~EOS
Some frameworks can be picked up by CMake's build system and likely
cause the build to fail. To compile CMake, you may wish to move these
out of the way:
EOS
end
def check_tmpdir
tmpdir = ENV["TMPDIR"]
return if tmpdir.nil? || File.directory?(tmpdir)
<<~EOS
TMPDIR #{tmpdir.inspect} doesn't exist.
EOS
end
def check_missing_deps
return unless HOMEBREW_CELLAR.exist?
missing = Set.new
Homebrew::Diagnostic.missing_deps(Formula.installed).each_value do |deps|
missing.merge(deps)
end
return if missing.empty?
<<~EOS
Some installed formulae are missing dependencies.
You should `brew install` the missing dependencies:
brew install #{missing.sort_by(&:full_name) * " "}
Run `brew missing` for more details.
EOS
end
def check_git_status
return unless Utils.git_available?
HOMEBREW_REPOSITORY.cd do
return if `git status --untracked-files=all --porcelain -- Library/Homebrew/ 2>/dev/null`.chomp.empty?
end
<<~EOS
You have uncommitted modifications to Homebrew
If this is a surprise to you, then you should stash these modifications.
Stashing returns Homebrew to a pristine state but can be undone
should you later need to do so for some reason.
cd #{HOMEBREW_LIBRARY} && git stash && git clean -d -f
EOS
end
def check_for_bad_python_symlink
return unless which "python"
`python -V 2>&1` =~ /Python (\d+)\./
# This won't be the right warning if we matched nothing at all
return if Regexp.last_match(1).nil?
return if Regexp.last_match(1) == "2"
<<~EOS
python is symlinked to python#{Regexp.last_match(1)}
This will confuse build scripts and in general lead to subtle breakage.
EOS
end
def check_for_non_prefixed_coreutils
coreutils = Formula["coreutils"]
return unless coreutils.any_version_installed?
gnubin = %W[#{coreutils.opt_libexec}/gnubin #{coreutils.libexec}/gnubin]
return if (paths & gnubin).empty?
<<~EOS
Putting non-prefixed coreutils in your path can cause gmp builds to fail.
EOS
rescue FormulaUnavailableError
nil
end
def check_for_pydistutils_cfg_in_home
return unless File.exist? "#{ENV["HOME"]}/.pydistutils.cfg"
<<~EOS
A .pydistutils.cfg file was found in $HOME, which may cause Python
builds to fail. See:
#{Formatter.url("https://bugs.python.org/issue6138")}
#{Formatter.url("https://bugs.python.org/issue4655")}
EOS
end
def check_for_unlinked_but_not_keg_only
unlinked = Formula.racks.reject do |rack|
if !(HOMEBREW_LINKED_KEGS/rack.basename).directory?
begin
Formulary.from_rack(rack).keg_only?
rescue FormulaUnavailableError, TapFormulaAmbiguityError, TapFormulaWithOldnameAmbiguityError
false
end
else
true
end
end.map(&:basename)
return if unlinked.empty?
inject_file_list unlinked, <<~EOS
You have unlinked kegs in your Cellar
Leaving kegs unlinked can lead to build-trouble and cause brews that depend on
those kegs to fail to run properly once built. Run `brew link` on these:
EOS
end
def check_for_external_cmd_name_conflict
cmds = Tap.cmd_directories.flat_map { |p| Dir["#{p}/brew-*"] }.uniq
cmds = cmds.select { |cmd| File.file?(cmd) && File.executable?(cmd) }
cmd_map = {}
cmds.each do |cmd|
cmd_name = File.basename(cmd, ".rb")
cmd_map[cmd_name] ||= []
cmd_map[cmd_name] << cmd
end
cmd_map.reject! { |_cmd_name, cmd_paths| cmd_paths.size == 1 }
return if cmd_map.empty?
if ENV["CI"] && cmd_map.keys.length == 1 &&
cmd_map.keys.first == "brew-test-bot"
return
end
message = "You have external commands with conflicting names.\n"
cmd_map.each do |cmd_name, cmd_paths|
message += inject_file_list cmd_paths, <<~EOS
Found command `#{cmd_name}` in following places:
EOS
end
message
end
def check_for_tap_ruby_files_locations
bad_tap_files = {}
Tap.each do |tap|
unused_formula_dirs = tap.potential_formula_dirs - [tap.formula_dir]
unused_formula_dirs.each do |dir|
next unless dir.exist?
dir.children.each do |path|
next unless path.extname == ".rb"
bad_tap_files[tap] ||= []
bad_tap_files[tap] << path
end
end
end
return if bad_tap_files.empty?
bad_tap_files.keys.map do |tap|
<<~EOS
Found Ruby file outside #{tap} tap formula directory
(#{tap.formula_dir}):
#{bad_tap_files[tap].join("\n ")}
EOS
end.join("\n")
end
def all
methods.map(&:to_s).grep(/^check_/)
end
end
end
end
require "extend/os/diagnostic"
| {
"content_hash": "5a4d9b04e711a119f47d9cde9c8bedad",
"timestamp": "",
"source": "github",
"line_count": 791,
"max_line_length": 126,
"avg_line_length": 34.686472819216185,
"alnum_prop": 0.5865072712031199,
"repo_name": "DomT4/brew",
"id": "56eb943260892da9f55b4bc9fdec4e3336e287a6",
"size": "27437",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Library/Homebrew/diagnostic.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "11559"
},
{
"name": "PostScript",
"bytes": "485"
},
{
"name": "Roff",
"bytes": "73410"
},
{
"name": "Ruby",
"bytes": "2041803"
},
{
"name": "Shell",
"bytes": "65057"
},
{
"name": "Swift",
"bytes": "1154"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe Songkick::OAuth2::Provider::Authorization do
let(:resource_owner) { TestApp::User['Bob'] }
let(:authorization) { Songkick::OAuth2::Provider::Authorization.new(resource_owner, params) }
let(:params) { { 'response_type' => 'code',
'client_id' => @client.client_id,
'redirect_uri' => @client.redirect_uri }
}
before do
@client = Factory(:client)
Songkick::OAuth2.stub(:random_string).and_return('s1', 's2', 's3')
end
describe "with valid parameters" do
it "is valid" do
authorization.error.should be_nil
end
end
describe "with the scope parameter" do
before { params['scope'] = 'foo bar qux' }
it "exposes the scope as a list of strings" do
authorization.scopes.should == Set.new(%w[foo bar qux])
end
it "exposes the scopes the client has not yet granted" do
authorization.unauthorized_scopes.should == Set.new(%w[foo bar qux])
end
describe "when the owner has already authorized the client" do
before do
create_authorization(:owner => resource_owner, :client => @client, :scope => 'foo bar')
end
it "exposes the scope as a list of strings" do
authorization.scopes.should == Set.new(%w[foo bar qux])
end
it "exposes the scopes the client has not yet granted" do
authorization.unauthorized_scopes.should == %w[qux]
end
end
end
describe "missing response_type" do
before { params.delete('response_type') }
it "is invalid" do
authorization.error.should == "invalid_request"
authorization.error_description.should == "Missing required parameter response_type"
end
end
describe "with a bad response_type" do
before { params['response_type'] = "no_such_type" }
it "is invalid" do
authorization.error.should == "unsupported_response_type"
authorization.error_description.should == "Response type no_such_type is not supported"
end
it "causes a redirect" do
authorization.should be_redirect
authorization.redirect_uri.should == "https://client.example.com/cb?error=unsupported_response_type&error_description=Response+type+no_such_type+is+not+supported"
end
end
describe "missing client_id" do
before { params.delete('client_id') }
it "is invalid" do
authorization.error.should == "invalid_request"
authorization.error_description.should == "Missing required parameter client_id"
end
it "does not cause a redirect" do
authorization.should_not be_redirect
end
end
describe "with an unknown client_id" do
before { params['client_id'] = "unknown" }
it "is invalid" do
authorization.error.should == "invalid_client"
authorization.error_description.should == "Unknown client ID unknown"
end
it "does not cause a redirect" do
authorization.should_not be_redirect
end
end
describe "missing redirect_uri" do
before { params.delete('redirect_uri') }
it "is invalid" do
authorization.error.should == "invalid_request"
authorization.error_description.should == "Missing required parameter redirect_uri"
end
it "causes a redirect to the client's registered redirect_uri" do
authorization.should be_redirect
authorization.redirect_uri.should == "https://client.example.com/cb?error=invalid_request&error_description=Missing+required+parameter+redirect_uri"
end
end
describe "with a mismatched redirect_uri" do
before { params['redirect_uri'] = "http://songkick.com" }
it "is invalid" do
authorization.error.should == "redirect_uri_mismatch"
authorization.error_description.should == "Parameter redirect_uri does not match registered URI"
end
it "causes a redirect to the client's registered redirect_uri" do
authorization.should be_redirect
authorization.redirect_uri.should == "https://client.example.com/cb?error=redirect_uri_mismatch&error_description=Parameter+redirect_uri+does+not+match+registered+URI"
end
describe "when the client has not registered a redirect_uri" do
before { @client.update_attribute(:redirect_uri, nil) }
it "is valid" do
authorization.error.should be_nil
end
end
end
describe "with a redirect_uri with parameters" do
before do
authorization.client.redirect_uri = "http://songkick.com?some_parameter"
params['redirect_uri'] = "http://songkick.com?some_parameter"
end
it "adds the extra parameters with & instead of ?" do
authorization.redirect_uri.should == "http://songkick.com?some_parameter&"
end
end
# http://en.wikipedia.org/wiki/HTTP_response_splitting
# scope and state values are passed back in the redirect
describe "with an illegal scope" do
before { params['scope'] = "http\r\nsplitter" }
it "is invalid" do
authorization.error.should == "invalid_request"
authorization.error_description.should == "Illegal value for scope parameter"
end
end
describe "with an illegal state" do
before { params['state'] = "http\r\nsplitter" }
it "is invalid" do
authorization.error.should == "invalid_request"
authorization.error_description.should == "Illegal value for state parameter"
end
end
describe "#grant_access!" do
describe "when there is an existing authorization with no code" do
before do
@model = create_authorization(
:owner => resource_owner,
:client => @client,
:code => nil)
end
it "generates and returns a code to the client" do
authorization.grant_access!
@model.reload
@model.code.should == "s1"
authorization.code.should == "s1"
end
end
describe "when there is an existing authorization with scopes" do
before do
@model = create_authorization(
:owner => resource_owner,
:client => @client,
:code => nil,
:scope => 'foo bar')
params['scope'] = 'qux'
end
it "merges the new scopes with the existing ones" do
authorization.grant_access!
@model.reload
@model.scopes.should == Set.new(%w[foo bar qux])
end
end
describe "when there is an existing expired authorization" do
before do
@model = create_authorization(
:owner => resource_owner,
:client => @client,
:expires_at => 2.months.ago,
:code => 'existing_code',
:scope => 'foo bar')
end
it "renews the authorization" do
authorization.grant_access!
@model.reload
@model.expires_at.should be_nil
end
it "returns a code to the client" do
authorization.grant_access!
authorization.code.should == "existing_code"
authorization.access_token.should be_nil
end
it "sets the expiry time if a duration is given" do
authorization.grant_access!(:duration => 1.hour)
@model.reload
@model.expires_in.should == 3600
authorization.expires_in.should == 3600
end
it "augments the scope" do
params['scope'] = 'qux'
authorization.grant_access!
@model.reload
@model.scopes.should == Set.new(%w[foo bar qux])
end
end
describe "for code requests" do
before do
params['response_type'] = 'code'
params['scope'] = 'foo bar'
end
it "makes the authorization redirect" do
authorization.grant_access!
authorization.client.should_not be_nil
authorization.should be_redirect
end
it "creates a code for the authorization" do
authorization.grant_access!
authorization.code.should == "s1"
authorization.access_token.should be_nil
authorization.expires_in.should be_nil
end
it "creates an Authorization in the database" do
authorization.grant_access!
authorization = Songkick::OAuth2::Model::Authorization.first
authorization.owner.should == resource_owner
authorization.client.should == @client
authorization.code.should == "s1"
authorization.scopes.should == Set.new(%w[foo bar])
end
end
describe "for token requests" do
before { params['response_type'] = 'token' }
it "creates a token for the authorization" do
authorization.grant_access!
authorization.code.should be_nil
authorization.access_token.should == "s1"
authorization.refresh_token.should == "s2"
authorization.expires_in.should be_nil
end
it "creates an Authorization in the database" do
authorization.grant_access!
authorization = Songkick::OAuth2::Model::Authorization.first
authorization.owner.should == resource_owner
authorization.client.should == @client
authorization.code.should be_nil
authorization.access_token_hash.should == Songkick::OAuth2.hashify("s1")
authorization.refresh_token_hash.should == Songkick::OAuth2.hashify("s2")
end
end
describe "for code_and_token requests" do
before { params['response_type'] = 'code_and_token' }
it "creates a code and token for the authorization" do
authorization.grant_access!
authorization.code.should == "s1"
authorization.access_token.should == "s2"
authorization.refresh_token.should == "s3"
authorization.expires_in.should be_nil
end
it "creates an Authorization in the database" do
authorization.grant_access!
authorization = Songkick::OAuth2::Model::Authorization.first
authorization.owner.should == resource_owner
authorization.client.should == @client
authorization.code.should == "s1"
authorization.access_token_hash.should == Songkick::OAuth2.hashify("s2")
authorization.refresh_token_hash.should == Songkick::OAuth2.hashify("s3")
end
end
end
describe "#deny_access!" do
it "puts the authorization in an error state" do
authorization.deny_access!
authorization.error.should == "access_denied"
authorization.error_description.should == "The user denied you access"
end
it "does not create an Authorization" do
Songkick::OAuth2::Model::Authorization.should_not_receive(:create)
Songkick::OAuth2::Model::Authorization.should_not_receive(:new)
authorization.deny_access!
end
end
describe "#params" do
before do
params['scope'] = params['state'] = 'valid'
params['controller'] = 'invalid'
end
it "only exposes OAuth-related parameters" do
authorization.params.should == {
'response_type' => 'code',
'client_id' => @client.client_id,
'redirect_uri' => @client.redirect_uri,
'state' => 'valid',
'scope' => 'valid'
}
end
it "does not expose parameters with no value" do
params.delete('scope')
authorization.params.should == {
'response_type' => 'code',
'client_id' => @client.client_id,
'redirect_uri' => @client.redirect_uri,
'state' => 'valid'
}
end
end
end
| {
"content_hash": "f99008b3746184bae9883e8a26365f92",
"timestamp": "",
"source": "github",
"line_count": 357,
"max_line_length": 173,
"avg_line_length": 32.529411764705884,
"alnum_prop": 0.6286919831223629,
"repo_name": "GSA/oauth2-provider",
"id": "e259d87d9039dade05ea214d5e2f954f46752846",
"size": "11613",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/songkick/oauth2/provider/authorization_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1084"
},
{
"name": "Ruby",
"bytes": "109712"
}
],
"symlink_target": ""
} |
using System;
using System.Collections;
using System.Windows.Forms;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Reflection;
using C1.Win.C1Preview;
using PCSComUtils.Common;
using PCSUtils.Utils;
namespace MonthlyReturnGoodsReceipt
{
[Serializable]
public class MonthlyReturnGoodsReceipt : MarshalByRefObject, IDynamicReport
{
public MonthlyReturnGoodsReceipt()
{
}
#region IDynamicReport Members
private bool mUseReportViewerRenderEngine = false;
private string mConnectionString;
private ReportBuilder mReportBuilder;
private C1PrintPreviewControl mReportViewer;
private object mResult;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseReportViewerRenderEngine; }
set { mUseReportViewerRenderEngine = value; }
}
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mstrReportDefinitionFolder; }
set { mstrReportDefinitionFolder = value; }
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get
{
return mstrReportLayoutFile;
}
set
{
mstrReportLayoutFile = value;
}
}
#endregion
#region Processing Data
private const string PRODUCT_CODE = "Code";
private const string PRODUCT_NAME = "Description";
private const string PRODUCT_MODEL = "Revision";
private const string SEMI_COLON = "; ";
private const int MAX_LENGTH = 250;
private const string CODE_FIELD = "Code";
private const string NAME_FIELD = "Name";
private DataTable GetMonthlyReturnGoodsReceiptData(string pstrMonth, string pstrYear, string pstrCustomerIDList)
{
OleDbConnection cn = null;
try
{
cn = new OleDbConnection(mConnectionString);
DataTable dtbBOMData = new DataTable();
//Build WHERE clause
string strWhereClause = " WHERE 1 = 1 ";
//Month
if(pstrMonth != null && pstrMonth != string.Empty)
{
strWhereClause += " AND Month(SO_ReturnedGoodsMaster.TransDate) =" + pstrMonth;
}
//To Date
if(pstrYear != null && pstrYear != string.Empty)
{
strWhereClause += " AND Year(SO_ReturnedGoodsMaster.TransDate) =" + pstrYear;
}
//Customer ID List
if(pstrCustomerIDList != null && pstrCustomerIDList != string.Empty)
{
strWhereClause += " AND MST_Party.PartyID IN (" + pstrCustomerIDList + ") ";
}
//Build SQL string
string strSql = " SELECT DISTINCT SO_ReturnedGoodsDetail.ReturnedGoodsDetailID, ";
strSql += " SO_ReturnedGoodsMaster.TransDate as PostDate, ";
strSql += " SO_ReturnedGoodsMaster.ReturnedGoodsNumber as RGRNo, ";
strSql += " refDetail.CustomerItemCode PartNo, ";
strSql += " ITM_Product.ProductID, ";
strSql += " ITM_Product.Description as PartName, ";
strSql += " ITM_Product.Revision as PartModel, ";
strSql += " SO_ReturnedGoodsDetail.ReceiveQuantity as ReturnQuantity, ";
strSql += " SO_ReturnedGoodsDetail.ReceiveQuantity * ";
strSql += " ISNULL(SO_ReturnedGoodsDetail.UnitPrice, 0) as Amount, ";
strSql += " (SO_ReturnedGoodsDetail.ReceiveQuantity ";
strSql += " * ISNULL(SO_ReturnedGoodsDetail.UnitPrice, 0)) ";
strSql += " * 0.01 ";
strSql += " * ISNULL(ITM_Product.VAT, 0) as VATAmount, ";
strSql += " ISNULL(";
strSql += " ( ";
strSql += " Case ";
strSql += " When ";
strSql += " ( ";
strSql += " SELECT SUM(cost.ActualCost) as ActualCost ";
strSql += " FROM CST_ActualCostHistory cost ";
strSql += " INNER JOIN cst_ActCostAllocationMaster cycle ON cycle.ActCostAllocationMasterID = cost.ActCostAllocationMasterID ";
strSql += " WHERE cost.ProductID = ITM_Product.ProductID ";
strSql += " AND (Year(cycle.FromDate) <= " + pstrYear + " AND Month(cycle.FromDate) <= " + pstrMonth + ") ";
strSql += " AND (Year(cycle.ToDate) >= " + pstrYear + " AND Month(cycle.ToDate) >= " + pstrMonth + ") ";
strSql += " ) ";
strSql += " Is Not Null Then ";
strSql += " (SELECT SUM(cost.ActualCost) as ActualCost ";
strSql += " FROM CST_ActualCostHistory cost ";
strSql += " INNER JOIN cst_ActCostAllocationMaster cycle ON cycle.ActCostAllocationMasterID = cost.ActCostAllocationMasterID ";
strSql += " WHERE cost.ProductID = ITM_Product.ProductID ";
strSql += " AND (Year(cycle.FromDate) <= " + pstrYear + " AND Month(cycle.FromDate) <= " + pstrMonth + ") ";
strSql += " AND (Year(cycle.ToDate) >= " + pstrYear + " AND Month(cycle.ToDate) >= " + pstrMonth + ") ";
strSql += " ) ";
strSql += " Else ";
strSql += " (SELECT SUM(Cost) ";
strSql += " FROM CST_STDItemCost ";
strSql += " WHERE ProductID = ITM_Product.ProductID) ";
strSql += " End) ";
strSql += " , 0) as ItemCost, ";
/*
strSql += " ISNULL((SELECT SUM(ISNULL(DSAmount,0) + ISNULL(OH_DSAmount,0))";
strSql += " FROM CST_DSAndRecycleAllocation charge JOIN CST_ActCostAllocationMaster cycle";
strSql += " ON charge.ActCostAllocationMasterID = cycle.ActCostAllocationMasterID";
strSql += " WHERE charge.ProductID = ITM_Product.ProductID";
strSql += " AND (Year(cycle.FromDate) <= " + pstrYear + " AND Month(cycle.FromDate) <= " + pstrMonth + ") ";
strSql += " AND (Year(cycle.ToDate) >= " + pstrYear + " AND Month(cycle.ToDate) >= " + pstrMonth + ")";
strSql += " ),0) AS DSAmount, ";
strSql += " ISNULL((SELECT SUM(ISNULL(AdjustAmount,0) + ISNULL(OH_AdjustAmount,0))";
strSql += " FROM CST_DSAndRecycleAllocation charge JOIN CST_ActCostAllocationMaster cycle";
strSql += " ON charge.ActCostAllocationMasterID = cycle.ActCostAllocationMasterID";
strSql += " WHERE charge.ProductID = ITM_Product.ProductID";
strSql += " AND (Year(cycle.FromDate) <= " + pstrYear + " AND Month(cycle.FromDate) <= " + pstrMonth + ") ";
strSql += " AND (Year(cycle.ToDate) >= " + pstrYear + " AND Month(cycle.ToDate) >= " + pstrMonth + ")";
strSql += " ),0) AS AdjustAmount, ";
strSql += " ISNULL((SELECT SUM(ISNULL(RecycleAmount,0) + ISNULL(OH_RecycleAmount,0))";
strSql += " FROM CST_DSAndRecycleAllocation charge JOIN CST_ActCostAllocationMaster cycle";
strSql += " ON charge.ActCostAllocationMasterID = cycle.ActCostAllocationMasterID";
strSql += " WHERE charge.ProductID = ITM_Product.ProductID";
strSql += " AND (Year(cycle.FromDate) <= " + pstrYear + " AND Month(cycle.FromDate) <= " + pstrMonth + ") ";
strSql += " AND (Year(cycle.ToDate) >= " + pstrYear + " AND Month(cycle.ToDate) >= " + pstrMonth + ")";
strSql += " ),0) AS RecycleAmount,";*/
strSql += " MST_Party.Code as PartyCode, ";
strSql += " MST_Party.Name as PartyName ";
strSql += " FROM SO_ReturnedGoodsDetail ";
strSql += " INNER JOIN SO_ReturnedGoodsMaster ON SO_ReturnedGoodsMaster.ReturnedGoodsMasterID = SO_ReturnedGoodsDetail.ReturnedGoodsMasterID ";
strSql += " INNER JOIN MST_Party ON SO_ReturnedGoodsMaster.PartyID = MST_Party.PartyID ";
strSql += " INNER JOIN ITM_Product ON SO_ReturnedGoodsDetail.ProductID = ITM_Product.ProductID ";
strSql += " LEFT JOIN SO_CustomerItemRefMaster refMaster ON refMaster.PartyID = MST_Party.PartyID ";
strSql += " LEFT JOIN SO_CustomerItemRefDetail refDetail ON refMaster.CustomerItemRefMasterID = refDetail.CustomerItemRefMasterID ";
strSql += " AND refDetail.ProductID = ITM_Product.ProductID";
//Add WHERE clause
strSql += strWhereClause;
OleDbDataAdapter odad = new OleDbDataAdapter(strSql, cn);
odad.Fill(dtbBOMData);
return dtbBOMData;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (cn != null)
if (cn.State != ConnectionState.Closed)
cn.Close();
}
}
/// <summary>
/// Get Customer Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCustomerInfoByID(string pstrIDList)
{
DataSet dstPCS = new DataSet();
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + CODE_FIELD + ", " + NAME_FIELD
+ " FROM MST_Party"
+ " WHERE MST_Party.PartyID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if(odrPCS != null)
{
while(odrPCS.Read())
{
strResult += odrPCS[CODE_FIELD].ToString().Trim() + SEMI_COLON;
}
}
if(strResult.Length > MAX_LENGTH)
{
int i = strResult.IndexOf(SEMI_COLON, MAX_LENGTH);
if(i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
#endregion Processing Data
#region Public Method
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
public DataTable ExecuteReport(string pstrMonth, string pstrYear, string pstrCustomerIDList)
{
try
{
const string DATE_FORMAT = "MMM-yyyy";
const string REPORT_NAME = "MonthlyReturnGoodsReceipt";
const string REPORT_LAYOUT = "MonthlyReturnGoodsReceipt.xml";
const string RPT_PAGE_HEADER = "PageHeader";
//Report field names
const string RPT_TITLE_FIELD = "fldTitle";
const string RPT_REPORT_MONTH = "Month";
const string RPT_CUSTOMER = "Customer";
DataTable dtbTranHis = GetMonthlyReturnGoodsReceiptData(pstrMonth, pstrYear, pstrCustomerIDList);
//Create builder object
ReportBuilder reportBuilder = new ReportBuilder();
//Set report name
reportBuilder.ReportName = REPORT_NAME;
//Set Datasource
reportBuilder.SourceDataTable = dtbTranHis;
//Set report layout location
reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder;
reportBuilder.ReportLayoutFile = REPORT_LAYOUT;
reportBuilder.UseLayoutFile = true;
reportBuilder.MakeDataTableForRender();
// And show it in preview dialog
PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog printPreview = new PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog();
//Attach report viewer
reportBuilder.ReportViewer = printPreview.ReportViewer;
reportBuilder.RenderReport();
//Draw parameters
System.Collections.Specialized.NameValueCollection arrParamAndValue = new System.Collections.Specialized.NameValueCollection();
//From Date
if(pstrMonth != null && pstrMonth != string.Empty
&& pstrYear != null && pstrYear != string.Empty)
{
DateTime dtmTemp = new DateTime(int.Parse(pstrYear), int.Parse(pstrMonth), 1);
arrParamAndValue.Add(RPT_REPORT_MONTH, dtmTemp.ToString(DATE_FORMAT));
}
//Customer Information
if(pstrCustomerIDList != null && pstrCustomerIDList != string.Empty)
{
arrParamAndValue.Add(RPT_CUSTOMER, GetCustomerInfoByID(pstrCustomerIDList));
}
//Anchor the Parameter drawing canvas cordinate to the fldTitle
C1.C1Report.Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FIELD);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3 * fldTitle.RenderHeight;
reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true;
reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size);
try
{
printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FIELD).Text;
}
catch{}
reportBuilder.RefreshReport();
printPreview.Show();
return dtbTranHis;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion Public Method
}
} | {
"content_hash": "81ce7767b374fd3065bf6c65b21e8175",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 157,
"avg_line_length": 35.39012345679012,
"alnum_prop": 0.6489220679550687,
"repo_name": "dungle/pcs",
"id": "ebf4f1ad96079e71117c8520849afdfa3667bb25",
"size": "14333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MAP2013/PCSTestReport/PCSTestReport/ReportDefinition/MonthlyReturnGoodsReceipt.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "26581423"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>PresentationContextKind Structure Reference</title>
<link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
<link rel="stylesheet" type="text/css" href="../css/highlight.css" />
<meta charset='utf-8'>
<script src="../js/jquery.min.js" defer></script>
<script src="../js/jazzy.js" defer></script>
</head>
<body>
<a name="//apple_ref/swift/Struct/PresentationContextKind" class="dashAnchor"></a>
<a title="PresentationContextKind Structure Reference"></a>
<header>
<div class="content-wrapper">
<p><a href="../index.html">Xcore 1.0.0 Docs</a> (34% documented)</p>
<p class="header-right"><a href="https://github.com/zmian/xcore.swift"><img src="../img/gh.png"/>View on GitHub</a></p>
<p class="header-right"><a href="dash-feed://https%3A%2F%2Fgithub%2Ecom%2Fzmian%2Fdocsets%2FXcore%2Exml"><img src="../img/dash.png"/>Install in Dash</a></p>
</div>
</header>
<div class="content-wrapper">
<p id="breadcrumbs">
<a href="../index.html">Xcore Reference</a>
<img id="carat" src="../img/carat.png" />
PresentationContextKind Structure Reference
</p>
</div>
<div class="content-wrapper">
<nav class="sidebar">
<ul class="nav-groups">
<li class="nav-group-name">
<a href="../Classes.html">Classes</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Classes/Analytics.html">Analytics</a>
</li>
<li class="nav-group-task">
<a href="../Classes/AnalyticsSessionTracker.html">AnalyticsSessionTracker</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html">Anchor</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor/Axis.html">– Axis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor/XAxis.html">– XAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor/YAxis.html">– YAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor/DimensionAxis.html">– DimensionAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC8SizeAxisC">– SizeAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor/EdgesAxis.html">– EdgesAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC10CenterAxisC">– CenterAxis</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC9XAxisTypeO">– XAxisType</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC9YAxisTypeO">– YAxisType</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC17DimensionAxisTypeO">– DimensionAxisType</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC13EdgesAxisTypeO">– EdgesAxisType</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Anchor.html#/s:5Xcore6AnchorC14CenterAxisTypeO">– CenterAxisType</a>
</li>
<li class="nav-group-task">
<a href="../Classes/AnimationRunLoop.html">AnimationRunLoop</a>
</li>
<li class="nav-group-task">
<a href="../Classes/BlurView.html">BlurView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CarouselView.html">CarouselView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CarouselViewModel.html">CarouselViewModel</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Chrome.html">Chrome</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Chrome/Element.html">– Element</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Chrome/BackgroundStyle.html">– BackgroundStyle</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Chrome/Style.html">– Style</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CollectionViewCarouselLayout.html">CollectionViewCarouselLayout</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CollectionViewDequeueCache.html">CollectionViewDequeueCache</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Console.html">Console</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Console/LevelOptions.html">– LevelOptions</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Console/PrefixOptions.html">– PrefixOptions</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ContainerViewController.html">ContainerViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CurrencyFormatter.html">CurrencyFormatter</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CustomCarouselView.html">CustomCarouselView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/CustomCarouselView/Style.html">– Style</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DatePicker.html">DatePicker</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DrawerScreen.html">DrawerScreen</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DrawerScreen/Appearance.html">– Appearance</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DynamicTableView.html">DynamicTableView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DynamicTableViewCell.html">DynamicTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/DynamicTableViewController.html">DynamicTableViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Environment.html">Environment</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Environment/Kind.html">– Kind</a>
</li>
<li class="nav-group-task">
<a href="../Classes/FadeAnimator.html">FadeAnimator</a>
</li>
<li class="nav-group-task">
<a href="../Classes/GradientLayer.html">GradientLayer</a>
</li>
<li class="nav-group-task">
<a href="../Classes/GradientView.html">GradientView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HUD.html">HUD</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HUD/StatusBarAppearance.html">– StatusBarAppearance</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HUD/Duration.html">– Duration</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HUD/Appearance.html">– Appearance</a>
</li>
<li class="nav-group-task">
<a href="../Classes/HapticFeedback.html">HapticFeedback</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IconLabelCollectionView.html">IconLabelCollectionView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IconLabelCollectionView/Cell.html">– Cell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IconLabelCollectionViewController.html">IconLabelCollectionViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IconLabelView.html">IconLabelView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/InputToolbar.html">InputToolbar</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IntrinsicContentSizeImageView.html">IntrinsicContentSizeImageView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/IntrinsicContentSizeView.html">IntrinsicContentSizeView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/KeychainHelpers.html">KeychainHelpers</a>
</li>
<li class="nav-group-task">
<a href="../Classes/LabelTextView.html">LabelTextView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/LinePageControl.html">LinePageControl</a>
</li>
<li class="nav-group-task">
<a href="../Classes/LoadingView.html">LoadingView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MarkupText.html">MarkupText</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MarkupText/Appearance.html">– Appearance</a>
</li>
<li class="nav-group-task">
<a href="../Classes/MulticastDelegate.html">MulticastDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Classes/NavigationController.html">NavigationController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Observers.html">Observers</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PageControl.html">PageControl</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PageNavigationController.html">PageNavigationController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PassthroughStackView.html">PassthroughStackView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PassthroughView.html">PassthroughView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Picker.html">Picker</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Picker/RowModel.html">– RowModel</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Picker/RowView.html">– RowView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/PickerList.html">PickerList</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ProgressView.html">ProgressView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ReorderTableView.html">ReorderTableView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Request.html">Request</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Request/Method.html">– Method</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Request/Body.html">– Body</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Router.html">Router</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Router/Route.html">– Route</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Router/RouteKind.html">– RouteKind</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SearchBarView.html">SearchBarView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SearchBarView/SeparatorPosition.html">– SeparatorPosition</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SeparatorView.html">SeparatorView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SeparatorView/Style.html">– Style</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SiriShortcuts.html">SiriShortcuts</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SiriShortcuts/Domain.html">– Domain</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SiriShortcuts/Suggestions.html">– Suggestions</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SplitScreenViewController.html">SplitScreenViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SwizzleManager.html">SwizzleManager</a>
</li>
<li class="nav-group-task">
<a href="../Classes/SwizzleManager/SwizzleOptions.html">– SwizzleOptions</a>
</li>
<li class="nav-group-task">
<a href="../Classes/TextViewController.html">TextViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/TransitionAnimator.html">TransitionAnimator</a>
</li>
<li class="nav-group-task">
<a href="../Classes/TransitionContext.html">TransitionContext</a>
</li>
<li class="nav-group-task">
<a href="../Classes/UserDefaultStore.html">UserDefaultStore</a>
</li>
<li class="nav-group-task">
<a href="../Classes/UserDefaultsAnalyticsProvider.html">UserDefaultsAnalyticsProvider</a>
</li>
<li class="nav-group-task">
<a href="../Classes/Weak.html">Weak</a>
</li>
<li class="nav-group-task">
<a href="../Classes/WebViewController.html">WebViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/WebViewController/Autofill.html">– Autofill</a>
</li>
<li class="nav-group-task">
<a href="../Classes/WebViewController/Style.html">– Style</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionReusableView.html">XCCollectionReusableView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionView.html">XCCollectionView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewCell.html">XCCollectionViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewComposedDataSource.html">XCCollectionViewComposedDataSource</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewDataSource.html">XCCollectionViewDataSource</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewFlowLayout.html">XCCollectionViewFlowLayout</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewFlowLayout/Attributes.html">– Attributes</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewFlowLayoutAdapter.html">XCCollectionViewFlowLayoutAdapter</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewTileLayout.html">XCCollectionViewTileLayout</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCCollectionViewTileLayoutAdapter.html">XCCollectionViewTileLayoutAdapter</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCComposedCollectionViewController.html">XCComposedCollectionViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCComposedCollectionViewLayoutAdapter.html">XCComposedCollectionViewLayoutAdapter</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCComposedTableViewController.html">XCComposedTableViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCPageViewController.html">XCPageViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCPageViewController/PageControlPosition.html">– PageControlPosition</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCScrollViewController.html">XCScrollViewController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCTabBarController.html">XCTabBarController</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCTableViewCell.html">XCTableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCTableViewComposedDataSource.html">XCTableViewComposedDataSource</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCTableViewDataSource.html">XCTableViewDataSource</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCToolbar.html">XCToolbar</a>
</li>
<li class="nav-group-task">
<a href="../Classes/XCView.html">XCView</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ZoomAnimator.html">ZoomAnimator</a>
</li>
<li class="nav-group-task">
<a href="../Classes/ZoomAnimatorNavigationControllerDelegate.html">ZoomAnimatorNavigationControllerDelegate</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Global%20Variables.html">Global Variables</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Global%20Variables.html#/s:5Xcore18isDebuggerAttachedSbvp">isDebuggerAttached</a>
</li>
<li class="nav-group-task">
<a href="../Global%20Variables.html#/s:5Xcore003Bxa12CoreGraphics7CGFloatVvp">π</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Enums.html">Enumerations</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Enums/AnimationDirection.html">AnimationDirection</a>
</li>
<li class="nav-group-task">
<a href="../Enums/AnimationState.html">AnimationState</a>
</li>
<li class="nav-group-task">
<a href="../Enums/AssociationPolicy.html">AssociationPolicy</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Count.html">Count</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Currency.html">Currency</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Currency/Components.html">– Components</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Currency/SymbolsOptions.html">– SymbolsOptions</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Either.html">Either</a>
</li>
<li class="nav-group-task">
<a href="../Enums/FeatureFlag.html">FeatureFlag</a>
</li>
<li class="nav-group-task">
<a href="../Enums/FeatureFlag/Key.html">– Key</a>
</li>
<li class="nav-group-task">
<a href="../Enums/GradientDirection.html">GradientDirection</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Handler.html">Handler</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Handler/Completion.html">– Completion</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Handler/Lifecycle.html">– Lifecycle</a>
</li>
<li class="nav-group-task">
<a href="../Enums/ImageRepresentableAlignment.html">ImageRepresentableAlignment</a>
</li>
<li class="nav-group-task">
<a href="../Enums/ImageSourceType.html">ImageSourceType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/ImageSourceType/CacheType.html">– CacheType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Interstitial.html">Interstitial</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Interstitial/UserState.html">– UserState</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Interstitial/Controller.html">– Controller</a>
</li>
<li class="nav-group-task">
<a href="../Enums/Interstitial/Item.html">– Item</a>
</li>
<li class="nav-group-task">
<a href="../Enums/LaunchScreen.html">LaunchScreen</a>
</li>
<li class="nav-group-task">
<a href="../Enums/LaunchScreen/View.html">– View</a>
</li>
<li class="nav-group-task">
<a href="../Enums/LaunchScreen/ViewController.html">– ViewController</a>
</li>
<li class="nav-group-task">
<a href="../Enums/ListAccessoryType.html">ListAccessoryType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/MultiplePromisesResolutionStrategy.html">MultiplePromisesResolutionStrategy</a>
</li>
<li class="nav-group-task">
<a href="../Enums/StringSourceType.html">StringSourceType</a>
</li>
<li class="nav-group-task">
<a href="../Enums/SwizzleMethodKind.html">SwizzleMethodKind</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Extensions.html">Extensions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Extensions/AVAsset.html">AVAsset</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/AVPlayer.html">AVPlayer</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/AVPlayerItem.html">AVPlayerItem</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Array.html">Array</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Bundle.html">Bundle</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CALayer.html">CALayer</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CAMediaTimingFunction.html">CAMediaTimingFunction</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CATransaction.html">CATransaction</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CATransitionType.html">CATransitionType</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGAffineTransform.html">CGAffineTransform</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGColor.html">CGColor</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGContext.html">CGContext</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGFloat.html">CGFloat</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGRect.html">CGRect</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CGSize.html">CGSize</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CMTime.html">CMTime</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CaseIterable.html">CaseIterable</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/CharacterSet.html">CharacterSet</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ClosedRange.html">ClosedRange</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Collection.html">Collection</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Comparable.html">Comparable</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Constraint.html">Constraint</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ConstraintMakerEditable.html">ConstraintMakerEditable</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ConstraintMakerPriortizable.html">ConstraintMakerPriortizable</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ConstraintMakerRelatable.html">ConstraintMakerRelatable</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ConstraintPriority.html">ConstraintPriority</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Data.html">Data</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Data/HexEncodingOptions.html">– HexEncodingOptions</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Date.html">Date</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Dictionary.html">Dictionary</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Dictionary/MergingStrategy.html">– MergingStrategy</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/DispatchTime.html">DispatchTime</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Double.html">Double</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/FileManager.html">FileManager</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/FileManager/Options.html">– Options</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/FixedWidthInteger.html">FixedWidthInteger</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/FloatingPoint.html">FloatingPoint</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/HTTPCookieStorage.html">HTTPCookieStorage</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/INBalanceAmount.html">INBalanceAmount</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/INCurrencyAmount.html">INCurrencyAmount</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/INIntent.html">INIntent</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/IndexPath.html">IndexPath</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Int.html">Int</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Locale.html">Locale</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/MFMailComposeViewController.html">MFMailComposeViewController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSAttributedString.html">NSAttributedString</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSAttributedString/CaretDirection.html">– CaretDirection</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSAttributedString/BulletStyle.html">– BulletStyle</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSLayoutConstraint.html">NSLayoutConstraint</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSLayoutConstraint/Edges.html">– Edges</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSLayoutConstraint/Size.html">– Size</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSMutableAttributedString.html">NSMutableAttributedString</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSObject.html">NSObject</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSObject/LookupComparison.html">– LookupComparison</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSObjectProtocol.html">NSObjectProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSPredicate.html">NSPredicate</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NSString.html">NSString</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NotificationCenter.html">NotificationCenter</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/NotificationCenter/Event.html">– Event</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Optional.html">Optional</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ProcessInfo.html">ProcessInfo</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ProcessInfo/Argument.html">– Argument</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/ProcessInfo/Arguments.html">– Arguments</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Promise.html">Promise</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Promise/MultiplePromisesResponse.html">– MultiplePromisesResponse</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/RandomAccessCollection.html">RandomAccessCollection</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/RangeReplaceableCollection.html">RangeReplaceableCollection</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Sequence.html">Sequence</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/SignedInteger.html">SignedInteger</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/String.html">String</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/String/TruncationPosition.html">– TruncationPosition</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/StringProtocol.html">StringProtocol</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/TimeInterval.html">TimeInterval</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/TimeZone.html">TimeZone</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/Timer.html">Timer</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIAlertController.html">UIAlertController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIApplication.html">UIApplication</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIBarButtonItem.html">UIBarButtonItem</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIButton.html">UIButton</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIButton/Configuration.html">– Configuration</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIButton/DefaultAppearance.html">– DefaultAppearance</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionReusableView.html">UICollectionReusableView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionView.html">UICollectionView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionView/SupplementaryViewKind.html">– SupplementaryViewKind</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionViewCell.html">UICollectionViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionViewFlowLayout.html">UICollectionViewFlowLayout</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UICollectionViewLayout.html">UICollectionViewLayout</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIColor.html">UIColor</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIControl.html">UIControl</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIDatePicker.html">UIDatePicker</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIDevice.html">UIDevice</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIDevice/BiometryType.html">– BiometryType</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIDevice/Capability.html">– Capability</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIDevice/ModelType.html">– ModelType</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIEdgeInsets.html">UIEdgeInsets</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIFont.html">UIFont</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIFont/Trait.html">– Trait</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIFont/TextStyle.html">– TextStyle</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIFont/LoaderError.html">– LoaderError</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIFont/Typeface.html">– Typeface</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIGestureRecognizer.html">UIGestureRecognizer</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIImage.html">UIImage</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIImage/Fetcher.html">– Fetcher</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIImageView.html">UIImageView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UILabel.html">UILabel</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UILayoutPriority.html">UILayoutPriority</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UINavigationBar.html">UINavigationBar</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UINavigationController.html">UINavigationController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UINavigationController/AnimationStyle.html">– AnimationStyle</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UINib.html">UINib</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIPopoverPresentationController.html">UIPopoverPresentationController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIRectCorner.html">UIRectCorner</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIRefreshControl.html">UIRefreshControl</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIResponder.html">UIResponder</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIScrollView.html">UIScrollView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIScrollView/ScrollingDirection.html">– ScrollingDirection</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UISearchBar.html">UISearchBar</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIStackView.html">UIStackView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITabBar.html">UITabBar</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITabBarController.html">UITabBarController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITabBarController/TabItem.html">– TabItem</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITableView.html">UITableView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITableViewCell.html">UITableViewCell</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITextField.html">UITextField</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UITextView.html">UITextView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIToolbar.html">UIToolbar</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIView.html">UIView</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIViewController.html">UIViewController</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIViewController/DefaultAppearance.html">– DefaultAppearance</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/UIWindow.html">UIWindow</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/URL.html">URL</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/URL/Scheme.html">– Scheme</a>
</li>
<li class="nav-group-task">
<a href="../Extensions/WKWebView.html">WKWebView</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Functions.html">Functions</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore2neoiySbSDyxq_SgG_ADtSHRzr0_lF">!=(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore1poiySDyxq_GAC_ACSgtSHRzr0_lF">+(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore1poiySDyxq_GAC_ACtSHRzr0_lF">+(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore2peoiyySDyxq_Gz_ACtSHRzr0_lF">+=(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore2eeoiySbSDyxq_SgG_ADtSHRzr0_lF">==(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore2eeoiySbyXlSg_So6UIViewCtF">==(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore5alert5title7messageySS_SStF">alert(title:message:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore13collectionify_10parameters8callbackyyx_yq_Sgctc_SayxGySayq_Gctr0_lF">collectionify(_:parameters:callback:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore13collectionify_10parameters8callbackyyx_yq_ctc_SayxGySayq_Gctr0_lF">collectionify(_:parameters:callback:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore13collectionify_9splitSize10parameters8callbackyySayxG_ySayq_Gctc_SiAFyAGctr0_lF">collectionify(_:splitSize:parameters:callback:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8debounce5delay5queue6actionyx_q_tc8Dispatch0F12TimeIntervalO_So012OS_dispatch_D0Cyx_q_tctr0_lF">debounce(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8debounce5delay5queue6actionyxc8Dispatch0F12TimeIntervalO_So012OS_dispatch_D0CyxctlF">debounce(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8debounce5delay5queue6actionyyc8Dispatch0F12TimeIntervalO_So012OS_dispatch_D0CyyctF">debounce(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore5delay2by_ySd_yyctF">delay(by:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore10fatalError7because8function4file4lines5NeverOAA11FatalReasonV_s12StaticStringVALSutF">fatalError(because:function:file:line:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore4join_8strategy10PromiseKit0D0CyAfAE24MultiplePromisesResponseVyx_GGSayAFySayxGGG_AA0fG18ResolutionStrategyOtlF">join(_:strategy:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore7measure5label5blockySS_yyyXEXEtF">measure(label:block:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore4name2ofSSyp_tF">name(of:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore4open3url4fromy10Foundation3URLV_So16UIViewControllerCtF">open(url:from:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore11orderedJoiny10PromiseKit0D0CySayxGGSayAGycGlF">orderedJoin(_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore12promiseUntil9predicate4body10retryDelay15maxRetrySeconds10PromiseKit0K0CyxGSbxc_AJycSdSitlF">promiseUntil(predicate:body:retryDelay:maxRetrySeconds:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore1ryAA20ImageAssetIdentifierVADF">r(_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore7swizzle_16originalSelector08swizzledD04kindyyXlXp_10ObjectiveC0D0VAhA17SwizzleMethodKindOtF">swizzle(_:originalSelector:swizzledSelector:kind:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore12synchronizedyxyXl_xyKXEtKlF">synchronized(_:_:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8throttle5delay5queue6actionyx_q_tcSd_So012OS_dispatch_D0Cyx_q_tctr0_lF">throttle(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8throttle5delay5queue6actionyxcSd_So012OS_dispatch_D0CyxctlF">throttle(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore8throttle5delay5queue6actionyycSd_So012OS_dispatch_D0CyyctF">throttle(delay:queue:action:)</a>
</li>
<li class="nav-group-task">
<a href="../Functions.html#/s:5Xcore11warnUnknown_4file8function4lineyyp_S2SSitF">warnUnknown(_:file:function:line:)</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Protocols.html">Protocols</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Protocols/AnalyticsEvent.html">AnalyticsEvent</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/AnalyticsProvider.html">AnalyticsProvider</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Appliable.html">Appliable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/CarouselAccessibilitySupport.html">CarouselAccessibilitySupport</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/CarouselViewCellRepresentable.html">CarouselViewCellRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/CarouselViewModelRepresentable.html">CarouselViewModelRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/CollectionViewLayoutRepresentable.html">CollectionViewLayoutRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Colorable.html">Colorable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Configurable.html">Configurable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ConfigurationInitializable.html">ConfigurationInitializable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ControlTargetActionBlockRepresentable.html">ControlTargetActionBlockRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/CurrencySymbolsProvider.html">CurrencySymbolsProvider</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/DimmableLayout.html">DimmableLayout</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/DisplayTimestampPreferenceStorage.html">DisplayTimestampPreferenceStorage</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/DrawerScreenContent.html">DrawerScreenContent</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/EquatableByPointer.html">EquatableByPointer</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ExtensibleByAssociatedObject.html">ExtensibleByAssociatedObject</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FadeAnimatorBounceable.html">FadeAnimatorBounceable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/FeatureFlagProvider.html">FeatureFlagProvider</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ImageFetcher.html">ImageFetcher</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ImageRepresentable.html">ImageRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ImageRepresentablePlugin.html">ImageRepresentablePlugin</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ImageTitleDisplayable.html">ImageTitleDisplayable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ImageTransform.html">ImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/InitializableByEmptyConstructor.html">InitializableByEmptyConstructor</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/InterstitialCompatibleViewController.html">InterstitialCompatibleViewController</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/KeyboardObservable.html">KeyboardObservable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ModallyPresentable.html">ModallyPresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/MutableAppliable.html">MutableAppliable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NibInstantiable.html">NibInstantiable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/NotificationObject.html">NotificationObject</a>
</li>
<li class="nav-group-task">
<a href="../Protocols.html#/s:5Xcore16ObstructableViewP">ObstructableView</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/OptionalType.html">OptionalType</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/OptionsRepresentable.html">OptionsRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PickerListModel.html">PickerListModel</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PickerModel.html">PickerModel</a>
</li>
<li class="nav-group-task">
<a href="../Protocols.html#/s:5Xcore29PopoverPresentationSourceViewP">PopoverPresentationSourceView</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PredicateRepresentable.html">PredicateRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/PresentationContext.html">PresentationContext</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ReorderTableViewDelegate.html">ReorderTableViewDelegate</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/Reusable.html">Reusable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/RouteHandler.html">RouteHandler</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SiriShortcutConvertible.html">SiriShortcutConvertible</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/SortOrderable.html">SortOrderable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/StoryboardInstantiable.html">StoryboardInstantiable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/StringRepresentable.html">StringRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/TargetActionBlockRepresentable.html">TargetActionBlockRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/TextAttributedTextRepresentable.html">TextAttributedTextRepresentable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/UserInfoContainer.html">UserInfoContainer</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ViewMaskable.html">ViewMaskable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/XCCollectionViewDelegateTileLayout.html">XCCollectionViewDelegateTileLayout</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/XCCollectionViewFlowLayoutCustomizable.html">XCCollectionViewFlowLayoutCustomizable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/XCCollectionViewTileLayoutCustomizable.html">XCCollectionViewTileLayoutCustomizable</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/XCComposedCollectionViewLayoutCompatible.html">XCComposedCollectionViewLayoutCompatible</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ZoomAnimatorDestination.html">ZoomAnimatorDestination</a>
</li>
<li class="nav-group-task">
<a href="../Protocols/ZoomAnimatorSource.html">ZoomAnimatorSource</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Structs.html">Structures</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Structs/AdaptiveURL.html">AdaptiveURL</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AlphaImageTransform.html">AlphaImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnyConfigurable.html">AnyConfigurable</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AnyEquatable.html">AnyEquatable</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AppAnalyticsEvent.html">AppAnalyticsEvent</a>
</li>
<li class="nav-group-task">
<a href="../Structs/AppConstants.html">AppConstants</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ArrayIterator.html">ArrayIterator</a>
</li>
<li class="nav-group-task">
<a href="../Structs/BackgroundImageTransform.html">BackgroundImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/BlockImageTransform.html">BlockImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/CellOptions.html">CellOptions</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Clamping.html">Clamping</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ColorizeImageTransform.html">ColorizeImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ColorizeImageTransform/Kind.html">– Kind</a>
</li>
<li class="nav-group-task">
<a href="../Structs/CompositeImageTransform.html">CompositeImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Configuration.html">Configuration</a>
</li>
<li class="nav-group-task">
<a href="../Structs/CornerRadiusImageTransform.html">CornerRadiusImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/DataSource.html">DataSource</a>
</li>
<li class="nav-group-task">
<a href="../Structs/DelayedMutable.html">DelayedMutable</a>
</li>
<li class="nav-group-task">
<a href="../Structs/DynamicTableModel.html">DynamicTableModel</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ElementPosition.html">ElementPosition</a>
</li>
<li class="nav-group-task">
<a href="../Structs/FatalReason.html">FatalReason</a>
</li>
<li class="nav-group-task">
<a href="../Structs/GradientImageTransform.html">GradientImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/HighlightedAnimationOptions.html">HighlightedAnimationOptions</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Identifier.html">Identifier</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ImageAssetIdentifier.html">ImageAssetIdentifier</a>
</li>
<li class="nav-group-task">
<a href="../Structs/IndexPathCache.html">IndexPathCache</a>
</li>
<li class="nav-group-task">
<a href="../Structs/JSONHelpers.html">JSONHelpers</a>
</li>
<li class="nav-group-task">
<a href="../Structs/KeyboardPayload.html">KeyboardPayload</a>
</li>
<li class="nav-group-task">
<a href="../Structs/LazyReset.html">LazyReset</a>
</li>
<li class="nav-group-task">
<a href="../Structs/MetaStaticMember.html">MetaStaticMember</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Percentage.html">Percentage</a>
</li>
<li class="nav-group-task">
<a href="../Structs/PresentationContextKind.html">PresentationContextKind</a>
</li>
<li class="nav-group-task">
<a href="../Structs/PrintAnalyticsProvider.html">PrintAnalyticsProvider</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ResizeImageTransform.html">ResizeImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ResizeImageTransform/ScalingMode.html">– ScalingMode</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Response.html">Response</a>
</li>
<li class="nav-group-task">
<a href="../Structs/SafeAreaLayoutGuideOptions.html">SafeAreaLayoutGuideOptions</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Section.html">Section</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Shadow.html">Shadow</a>
</li>
<li class="nav-group-task">
<a href="../Structs/StringConverter.html">StringConverter</a>
</li>
<li class="nav-group-task">
<a href="../Structs/StringsFile.html">StringsFile</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Theme.html">Theme</a>
</li>
<li class="nav-group-task">
<a href="../Structs/TintColorImageTransform.html">TintColorImageTransform</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Trimmed.html">Trimmed</a>
</li>
<li class="nav-group-task">
<a href="../Structs/UserDefault.html">UserDefault</a>
</li>
<li class="nav-group-task">
<a href="../Structs/UserInfoKey.html">UserInfoKey</a>
</li>
<li class="nav-group-task">
<a href="../Structs/ValidationRule.html">ValidationRule</a>
</li>
<li class="nav-group-task">
<a href="../Structs/Version.html">Version</a>
</li>
<li class="nav-group-task">
<a href="../Structs/WebViewScripts.html">WebViewScripts</a>
</li>
<li class="nav-group-task">
<a href="../Structs/XCComposedCollectionViewLayout.html">XCComposedCollectionViewLayout</a>
</li>
</ul>
</li>
<li class="nav-group-name">
<a href="../Typealiases.html">Type Aliases</a>
<ul class="nav-group-tasks">
<li class="nav-group-task">
<a href="../Typealiases.html#/s:5Xcore25CarouselAccessibilityItema">CarouselAccessibilityItem</a>
</li>
<li class="nav-group-task">
<a href="../Typealiases.html#/s:5Xcore20CarouselViewCellTypea">CarouselViewCellType</a>
</li>
</ul>
</li>
</ul>
</nav>
<article class="main-content">
<section>
<section class="section">
<h1>PresentationContextKind</h1>
<div class="declaration">
<div class="language">
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">struct</span> <span class="kt">PresentationContextKind</span> <span class="p">:</span> <span class="kt">Equatable</span></code></pre>
</div>
</div>
<p>Undocumented</p>
</section>
<section class="section task-group-section">
<div class="task-group">
<ul>
<li class="item">
<div>
<code>
<a name="/s:5Xcore23PresentationContextKindV2idAA10IdentifierVyACGvp"></a>
<a name="//apple_ref/swift/Property/id" class="dashAnchor"></a>
<a class="token" href="#/s:5Xcore23PresentationContextKindV2idAA10IdentifierVyACGvp">id</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="k">let</span> <span class="nv">id</span><span class="p">:</span> <span class="kt"><a href="../Structs/Identifier.html">Identifier</a></span><span class="o"><</span><span class="kt">PresentationContextKind</span><span class="o">></span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/zmian/xcore.swift/blob/master/Sources/Cocoa/Protocols/PresentationContext.swift#L">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:5Xcore23PresentationContextKindV2idAcA10IdentifierVyACG_tcfc"></a>
<a name="//apple_ref/swift/Method/init(id:)" class="dashAnchor"></a>
<a class="token" href="#/s:5Xcore23PresentationContextKindV2idAcA10IdentifierVyACG_tcfc">init(id:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="nv">id</span><span class="p">:</span> <span class="kt"><a href="../Structs/Identifier.html">Identifier</a></span><span class="o"><</span><span class="kt">PresentationContextKind</span><span class="o">></span><span class="p">)</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/zmian/xcore.swift/blob/master/Sources/Cocoa/Protocols/PresentationContext.swift#L47-L49">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<div class="task-name-container">
<a name="/Kind"></a>
<a name="//apple_ref/swift/Section/Kind" class="dashAnchor"></a>
<a href="#/Kind">
<h3 class="section-name">Kind</h3>
</a>
</div>
<ul>
<li class="item">
<div>
<code>
<a name="/s:s26ExpressibleByStringLiteralP06stringD0x0cD4TypeQz_tcfc"></a>
<a name="//apple_ref/swift/Method/init(stringLiteral:)" class="dashAnchor"></a>
<a class="token" href="#/s:s26ExpressibleByStringLiteralP06stringD0x0cD4TypeQz_tcfc">init(stringLiteral:)</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="nf">init</span><span class="p">(</span><span class="n">stringLiteral</span> <span class="nv">value</span><span class="p">:</span> <span class="kt">StringLiteralType</span><span class="p">)</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/zmian/xcore.swift/blob/master/Sources/Cocoa/Protocols/PresentationContext.swift#L53-L55">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
<div class="task-group">
<div class="task-name-container">
<a name="/Kind2"></a>
<a name="//apple_ref/swift/Section/Kind" class="dashAnchor"></a>
<a href="#/Kind2">
<h3 class="section-name">Kind</h3>
</a>
</div>
<ul>
<li class="item">
<div>
<code>
<a name="/s:5Xcore23PresentationContextKindV4feedACvpZ"></a>
<a name="//apple_ref/swift/Variable/feed" class="dashAnchor"></a>
<a class="token" href="#/s:5Xcore23PresentationContextKindV4feedACvpZ">feed</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">var</span> <span class="nv">feed</span><span class="p">:</span> <span class="kt">PresentationContextKind</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/zmian/xcore.swift/blob/master/Sources/Cocoa/Protocols/PresentationContext.swift#L59-L61">Show on GitHub</a>
</div>
</section>
</div>
</li>
<li class="item">
<div>
<code>
<a name="/s:5Xcore23PresentationContextKindV6detailACvpZ"></a>
<a name="//apple_ref/swift/Variable/detail" class="dashAnchor"></a>
<a class="token" href="#/s:5Xcore23PresentationContextKindV6detailACvpZ">detail</a>
</code>
</div>
<div class="height-container">
<div class="pointer-container"></div>
<section class="section">
<div class="pointer"></div>
<div class="abstract">
<p>Undocumented</p>
</div>
<div class="declaration">
<h4>Declaration</h4>
<div class="language">
<p class="aside-title">Swift</p>
<pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">static</span> <span class="k">var</span> <span class="nv">detail</span><span class="p">:</span> <span class="kt">PresentationContextKind</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span></code></pre>
</div>
</div>
<div class="slightly-smaller">
<a href="https://github.com/zmian/xcore.swift/blob/master/Sources/Cocoa/Protocols/PresentationContext.swift#L63-L65">Show on GitHub</a>
</div>
</section>
</div>
</li>
</ul>
</div>
</section>
</section>
<section id="footer">
<p>© 2019 <a class="link" href="https://zmian.me" target="_blank" rel="external">Zeeshan</a>. All rights reserved. (Last updated: 2019-11-28)</p>
<p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.12.0</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p>
</section>
</article>
</div>
</body>
</div>
</html>
| {
"content_hash": "a1ea098a055720f70c2891083e448985",
"timestamp": "",
"source": "github",
"line_count": 1539,
"max_line_length": 408,
"avg_line_length": 49.06432748538012,
"alnum_prop": 0.4978148589590783,
"repo_name": "zmian/xcore.swift",
"id": "7bbf502d6c45b10e0070ee27e2ded8a0b2bb6769",
"size": "75679",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "docs/docsets/Xcore.docset/Contents/Resources/Documents/Structs/PresentationContextKind.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "209"
},
{
"name": "Ruby",
"bytes": "2280"
},
{
"name": "Shell",
"bytes": "538"
},
{
"name": "Swift",
"bytes": "1250941"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "deeb0cca60727d91ab6c52f825c861ff",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "b0025ff52a0fa9f3268c94f81deb93d02c9302b0",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Santalales/Olacaceae/Rhaptostylum/Rhaptostylum yapacaniense/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
.. pynigma documentation master file, created by
sphinx-quickstart on Sat Nov 25 14:42:06 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to pynigma's documentation!
===================================
pynigma is a Python client for the `Enigma API`_.
.. _Enigma API: https://app.enigma.io/api
.. toctree::
:maxdepth: 2
:caption: Contents:
client
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
| {
"content_hash": "91408d331b7061016f67cc344242d9f7",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 76,
"avg_line_length": 21,
"alnum_prop": 0.6282051282051282,
"repo_name": "thejunglejane/pynigma",
"id": "b32bd932463bccf033ab7ecf0ecebe7a53a10ff1",
"size": "546",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/index.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "104626"
}
],
"symlink_target": ""
} |
package com.google.android.apps.mytracks.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
/**
* Utilities for EULA.
*
* @author Jimmy Shih
*/
public class EulaUtils {
private static final String EULA_PREFERENCE_FILE = "eula";
// Accepting Google mobile terms of service
private static final String ACCEPTED_EULA_PREFERENCE_KEY = "eula.google_mobile_tos_accepted";
private static final String SHOW_ENABLE_SYNC_PREFERENCE_KEY = "showEnableSync";
private EulaUtils() {}
/**
* Returns true if has accepted eula.
*
* @param context the context
*/
public static boolean hasAcceptedEula(Context context) {
return getValue(context, ACCEPTED_EULA_PREFERENCE_KEY, false);
}
/**
* Sets to true accepted eula.
*
* @param context the context
*/
public static void setAcceptedEula(Context context) {
setValue(context, ACCEPTED_EULA_PREFERENCE_KEY, true);
}
/**
* Returns true if should show enable sync.
*
* @param context the context
*/
public static boolean showEnableSync(Context context) {
return getValue(context, SHOW_ENABLE_SYNC_PREFERENCE_KEY, true);
}
/**
* Sets to false show enable sync.
*
* @param context the context
*/
public static void setShowEnableSync(Context context) {
setValue(context, SHOW_ENABLE_SYNC_PREFERENCE_KEY, false);
}
private static boolean getValue(Context context, String key, boolean defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
EULA_PREFERENCE_FILE, Context.MODE_PRIVATE);
return sharedPreferences.getBoolean(key, defaultValue);
}
@SuppressLint("CommitPrefEdits")
private static void setValue(Context context, String key, boolean value) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
EULA_PREFERENCE_FILE, Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
ApiAdapterFactory.getApiAdapter().applyPreferenceChanges(editor);
}
}
| {
"content_hash": "48fbf17ba1101bc50740cfafb69dd980",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 95,
"avg_line_length": 28.986486486486488,
"alnum_prop": 0.7277389277389278,
"repo_name": "TWilmer/mytracks",
"id": "ec03559d0647b48f2fe349247b0c958d521fe1a4",
"size": "2738",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "MyTracks/src/com/google/android/apps/mytracks/util/EulaUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1969601"
},
{
"name": "Protocol Buffer",
"bytes": "1596"
}
],
"symlink_target": ""
} |
package bookshop2.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.aries.util.BaseUtil;
import org.aries.util.ObjectUtil;
import org.aries.util.Validator;
import bookshop2.Book;
import bookshop2.BookKey;
public class BookUtil extends BaseUtil {
public static boolean isEmpty(Book book) {
if (book == null)
return true;
boolean status = false;
status |= StringUtils.isEmpty(book.getAuthor());
status |= StringUtils.isEmpty(book.getTitle());
return status;
}
public static boolean isEmpty(Collection<Book> bookList) {
if (bookList == null || bookList.size() == 0)
return true;
Iterator<Book> iterator = bookList.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
if (!isEmpty(book))
return false;
}
return true;
}
public static String toString(Book book) {
if (isEmpty(book))
return "Book: [uninitialized] "+book.toString();
String text = book.toString();
return text;
}
public static String toString(Collection<Book> bookList) {
if (isEmpty(bookList))
return "";
StringBuffer buf = new StringBuffer();
Iterator<Book> iterator = bookList.iterator();
for (int i=0; iterator.hasNext(); i++) {
Book book = iterator.next();
if (i > 0)
buf.append(", ");
String text = toString(book);
buf.append(text);
}
String text = StringEscapeUtils.escapeJavaScript(buf.toString());
return text;
}
public static Book create() {
Book book = new Book();
initialize(book);
return book;
}
public static void initialize(Book book) {
//nothing for now
}
public static boolean validate(Book book) {
if (book == null)
return false;
Validator validator = Validator.getValidator();
validator.notEmpty(book.getAuthor(), "\"Author\" must be specified");
validator.notNull(book.getBarCode(), "\"BarCode\" must be specified");
validator.notNull(book.getPrice(), "\"Price\" must be specified");
validator.notEmpty(book.getTitle(), "\"Title\" must be specified");
boolean isValid = validator.isValid();
return isValid;
}
public static boolean validate(Collection<Book> bookList) {
Validator validator = Validator.getValidator();
Iterator<Book> iterator = bookList.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
//TODO break or accumulate?
validate(book);
}
boolean isValid = validator.isValid();
return isValid;
}
public static void sortRecords(List<Book> bookList) {
Collections.sort(bookList, createBookComparator());
}
public static Collection<Book> sortRecords(Collection<Book> bookCollection) {
List<Book> list = new ArrayList<Book>(bookCollection);
Collections.sort(list, createBookComparator());
return list;
}
public static void sortRecordsByBarCode(List<Book> bookList) {
Collections.sort(bookList, new Comparator<Book>() {
public int compare(Book book1, Book book2) {
Long barCode1 = book1.getBarCode();
Long barCode2 = book2.getBarCode();
if (barCode1 == null && barCode2 == null)
return 0;
if (barCode1 == null)
return -1;
if (barCode2 == null)
return 1;
return barCode1.compareTo(barCode2);
}
});
}
public static Comparator<Book> createBookComparator() {
return new Comparator<Book>() {
public int compare(Book book1, Book book2) {
int status = book1.compareTo(book2);
return status;
}
};
}
public static Book clone(Book book) {
if (book == null)
return null;
Book clone = create();
clone.setId(ObjectUtil.clone(book.getId()));
clone.setBarCode(ObjectUtil.clone(book.getBarCode()));
clone.setAuthor(ObjectUtil.clone(book.getAuthor()));
clone.setTitle(ObjectUtil.clone(book.getTitle()));
clone.setPrice(ObjectUtil.clone(book.getPrice()));
clone.setQuantity(ObjectUtil.clone(book.getQuantity()));
return clone;
}
public static List<Book> clone(List<Book> bookList) {
if (bookList == null)
return null;
List<Book> newList = new ArrayList<Book>();
Iterator<Book> iterator = bookList.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
Book clone = clone(book);
newList.add(clone);
}
return newList;
}
public static Set<Book> clone(Set<Book> bookSet) {
if (bookSet == null)
return null;
Set<Book> newSet = new HashSet<Book>();
Iterator<Book> iterator = bookSet.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
Book clone = clone(book);
newSet.add(clone);
}
return newSet;
}
public static Map<BookKey, Book> clone(Map<BookKey, Book> bookMap) {
if (bookMap == null)
return null;
Map<BookKey, Book> newMap = new HashMap<BookKey, Book>();
Iterator<BookKey> iterator = bookMap.keySet().iterator();
while (iterator.hasNext()) {
BookKey key = iterator.next();
BookKey keyClone = clone(key);
Book book = bookMap.get(key);
Book clone = clone(book);
newMap.put(keyClone, clone);
}
return newMap;
}
public static BookKey clone(BookKey bookKey) {
if (bookKey == null)
return null;
BookKey clone = new BookKey();
clone.setAuthor(ObjectUtil.clone(bookKey.getAuthor()));
clone.setTitle(ObjectUtil.clone(bookKey.getTitle()));
return clone;
}
}
| {
"content_hash": "2315881fe726939028517b7b0136e953",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 78,
"avg_line_length": 27.18811881188119,
"alnum_prop": 0.6937363437727604,
"repo_name": "tfisher1226/ARIES",
"id": "9fe12720e5196ea8b4a79905b4e52dcb8d47d932",
"size": "5492",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bookshop2/bookshop2-model/src/main/java/bookshop2/util/BookUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1606"
},
{
"name": "CSS",
"bytes": "660469"
},
{
"name": "Common Lisp",
"bytes": "91717"
},
{
"name": "Emacs Lisp",
"bytes": "12403"
},
{
"name": "GAP",
"bytes": "86009"
},
{
"name": "HTML",
"bytes": "9381408"
},
{
"name": "Java",
"bytes": "25671734"
},
{
"name": "JavaScript",
"bytes": "304513"
},
{
"name": "Shell",
"bytes": "51942"
}
],
"symlink_target": ""
} |
* Original: [Release atom-shell v0.6.5 - electron/electron](https://github.com/electron/electron/releases/tag/v0.6.5)
Changelog:
* Makes atom-shell compile-able with VS 2010 Express.
* Visual Studio 2010 Express で atom-shell をコンパイル可能にしました
* 従来は Professional 版に依存していたのだろうか?
* Ship pdb file on Windows
* Windows 向けに pdb ファイルを提供するようにしました
* Visual Studio デバッガー対応
* Fix the empty `resources` folder on Windows distribution.
* Windows 仕向けの空の `resources` フォルダー問題を修正しました
* 空の `resources` フォルダーがリリース用イメージに含まれる問題と思われる
| {
"content_hash": "39fc4d05fa5a3a718ca8427de5f16129",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 117,
"avg_line_length": 40.15384615384615,
"alnum_prop": 0.7720306513409961,
"repo_name": "akabekobeko/electron-release-notes-ja-private-edition",
"id": "c68659b192c88914247ba2c4bd6de9daebd81ec5",
"size": "744",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "v0.x/v0.6/v0.6.5.ja.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#include "interface/khronos/common/khrn_int_common.h"
#include "interface/khronos/common/khrn_int_ids.h"
#include "interface/khronos/common/khrn_client.h"
#include "interface/khronos/common/khrn_client_rpc.h"
#include "interface/vchi/vchi.h"
#include <assert.h>
#include <string.h>
static VCHI_SERVICE_HANDLE_T khrn_handle;
static VCHI_SERVICE_HANDLE_T khhn_handle;
static VCHI_SERVICE_HANDLE_T khan_handle;
static void *workspace; /* for scatter/gather bulks */
static PLATFORM_MUTEX_T mutex;
static void khrn_callback(void *callback_param, VCHI_CALLBACK_REASON_T reason, void *msg_handle)
{
}
static void khan_callback(void *callback_param, VCHI_CALLBACK_REASON_T reason, void *msg_handle)
{
switch (reason) {
case VCHI_CALLBACK_MSG_AVAILABLE:
{
int msg[4];
uint32_t length;
int32_t success = vchi_msg_dequeue(khan_handle, msg, sizeof(msg), &length, VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE);
assert(success == 0);
vcos_assert(length == sizeof(msg));
if (msg[0] == ASYNC_COMMAND_DESTROY) {
/* todo: destroy */
} else {
PLATFORM_SEMAPHORE_T sem;
if (khronos_platform_semaphore_create(&sem, msg + 1, 1) == KHR_SUCCESS) {
switch (msg[0]) {
case ASYNC_COMMAND_WAIT:
khronos_platform_semaphore_acquire(&sem);
break;
case ASYNC_COMMAND_POST:
khronos_platform_semaphore_release(&sem);
break;
default:
UNREACHABLE();
break;
}
khronos_platform_semaphore_destroy(&sem);
}
}
break;
}
}
}
void vc_vchi_khronos_init(VCHI_INSTANCE_T initialise_instance,
VCHI_CONNECTION_T **connections,
uint32_t num_connections)
{
vcos_assert(num_connections == 1);
/*
create services
*/
struct {
VCHI_SERVICE_HANDLE_T *vchi_handle;
fourcc_t fourcc;
VCHI_CALLBACK_T callback;
} services[] = {
{ &khrn_handle, MAKE_FOURCC("KHRN"), khrn_callback },
{ &khhn_handle, MAKE_FOURCC("KHHN"), khrn_callback },
{ &khan_handle, MAKE_FOURCC("KHAN"), khan_callback } };
uint32_t i;
for (i = 0; i != (sizeof(services) / sizeof(*services)); ++i) {
SERVICE_CREATION_T parameters = { services[i].fourcc, // 4cc service code
connections[0], // passed in fn ptrs
0, // rx fifo size (unused)
0, // tx fifo size (unused)
services[i].callback, // service callback
NULL, // callback parameter
1, // want unaligned bulk rx
1, // want unaligned bulk tx
1 }; // want crc
int32_t success = vchi_service_open(initialise_instance, ¶meters, services[i].vchi_handle);
assert(success == 0);
}
/*
attach to process (there's just one)
*/
bool success = client_process_attach();
assert(success);
}
bool khclient_rpc_init(void)
{
workspace = khrn_platform_malloc(KHDISPATCH_WORKSPACE_SIZE, "rpc_workspace");
if(workspace == NULL)
{
return false;
}
if(platform_mutex_create(&mutex) != KHR_SUCCESS)
{
khrn_platform_free(workspace);
return false;
}
return true;
}
void rpc_term(void)
{
khrn_platform_free(workspace);
platform_mutex_destroy(&mutex);
}
static VCHI_SERVICE_HANDLE_T get_vchi_handle(CLIENT_THREAD_STATE_T *thread)
{
return thread->high_priority ? khhn_handle : khrn_handle;
}
static void check_workspace(uint32_t size)
{
/* todo: find a better way to handle scatter/gather bulks */
vcos_assert(size <= KHDISPATCH_WORKSPACE_SIZE);
}
static void merge_flush(CLIENT_THREAD_STATE_T *thread)
{
vcos_assert(thread->merge_pos >= CLIENT_MAKE_CURRENT_SIZE);
/*
don't transmit just a make current -- in the case that there is only a
make current in the merge buffer, we have already sent a control message
for the rpc call (and with it a make current) and own the big lock
*/
if (thread->merge_pos > CLIENT_MAKE_CURRENT_SIZE) {
int32_t success = vchi_msg_queue(get_vchi_handle(thread), thread->merge_buffer, thread->merge_pos, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL);
assert(success == 0);
thread->merge_pos = 0;
client_send_make_current(thread);
vcos_assert(thread->merge_pos == CLIENT_MAKE_CURRENT_SIZE);
}
}
void rpc_flush(void)
{
merge_flush(CLIENT_GET_THREAD_STATE());
}
void rpc_high_priority_begin(void)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
vcos_assert(!thread->high_priority);
merge_flush(thread);
thread->high_priority = true;
}
void rpc_high_priority_end(void)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
vcos_assert(thread->high_priority);
merge_flush(thread);
thread->high_priority = false;
}
uint32_t rpc_send_ctrl_longest(uint32_t len_min)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
uint32_t len = MERGE_BUFFER_SIZE - thread->merge_pos;
if (len < len_min) {
len = MERGE_BUFFER_SIZE - CLIENT_MAKE_CURRENT_SIZE;
}
return len;
}
void rpc_send_ctrl_begin(uint32_t len)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
vcos_assert(len == rpc_pad_ctrl(len));
if ((thread->merge_pos + len) > MERGE_BUFFER_SIZE) {
merge_flush(thread);
}
thread->merge_end = thread->merge_pos + len;
}
void rpc_send_ctrl_write(const uint32_t in[], uint32_t len)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
memcpy(thread->merge_buffer + thread->merge_pos, in, len);
thread->merge_pos += rpc_pad_ctrl(len);
vcos_assert(thread->merge_pos <= MERGE_BUFFER_SIZE);
}
void rpc_send_ctrl_end(void)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
vcos_assert(thread->merge_pos == thread->merge_end);
}
//#define CTRL_THRESHOLD (VCHI_MAX_MSG_SIZE >> 1)
#define CTRL_THRESHOLD (4096-32) //vchiq msgsize header size
static void send_bulk(CLIENT_THREAD_STATE_T *thread, const void *in, uint32_t len)
{
vcos_assert(len < 0x10000000);
int32_t success = (len <= CTRL_THRESHOLD) ?
vchi_msg_queue(get_vchi_handle(thread), in, len, VCHI_FLAGS_BLOCK_UNTIL_QUEUED, NULL) :
vchi_bulk_queue_transmit(get_vchi_handle(thread), in, len, VCHI_FLAGS_BLOCK_UNTIL_DATA_READ, NULL);
assert(success == 0);
}
static void recv_bulk(CLIENT_THREAD_STATE_T *thread, void *out, uint32_t len)
{
vcos_assert(len < 0x10000000);
uint32_t msg_len;
int32_t success = (len <= CTRL_THRESHOLD) ?
vchi_msg_dequeue(get_vchi_handle(thread), out, len, &msg_len, VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE) :
vchi_bulk_queue_receive(get_vchi_handle(thread), out, len, VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE, NULL);
assert(success == 0);
}
void rpc_send_bulk(const void *in, uint32_t len)
{
if (in && len) {
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
merge_flush(thread);
send_bulk(thread, in, len);
}
}
void rpc_send_bulk_gather(const void *in, uint32_t len, int32_t stride, uint32_t n)
{
if (in && len) {
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
merge_flush(thread);
if (len == stride) {
/* hopefully should be the common case */
send_bulk(thread, in, n * len);
} else {
check_workspace(n * len);
rpc_gather(workspace, in, len, stride, n);
send_bulk(thread, workspace, n * len);
}
}
}
uint32_t rpc_recv(void *out, uint32_t *len_io, RPC_RECV_FLAG_T flags)
{
CLIENT_THREAD_STATE_T *thread = CLIENT_GET_THREAD_STATE();
uint32_t res = 0;
uint32_t len;
bool recv_ctrl;
if (!len_io) { len_io = &len; }
recv_ctrl = flags & (RPC_RECV_FLAG_RES | RPC_RECV_FLAG_CTRL | RPC_RECV_FLAG_LEN); /* do we want to receive anything in the control channel at all? */
vcos_assert(recv_ctrl || (flags & RPC_RECV_FLAG_BULK)); /* must receive something... */
vcos_assert(!(flags & RPC_RECV_FLAG_CTRL) || !(flags & RPC_RECV_FLAG_BULK)); /* can't receive user data over both bulk and control... */
if (recv_ctrl || len_io[0]) { /* do nothing if we're just receiving bulk of length 0 */
merge_flush(thread);
if (recv_ctrl) {
void *ctrl_begin;
uint32_t ctrl_len;
VCHI_HELD_MSG_T held_msg;
int32_t success = vchi_msg_hold(get_vchi_handle(thread), &ctrl_begin, &ctrl_len, VCHI_FLAGS_BLOCK_UNTIL_OP_COMPLETE, &held_msg);
uint32_t *ctrl = (uint32_t *)ctrl_begin;
assert(success == 0);
assert(ctrl_len == rpc_pad_ctrl(ctrl_len));
if (flags & RPC_RECV_FLAG_LEN) {
len_io[0] = *(ctrl++);
}
if (flags & RPC_RECV_FLAG_RES) {
res = *(ctrl++);
}
if (flags & RPC_RECV_FLAG_CTRL) {
memcpy(out, ctrl, len_io[0]);
ctrl += rpc_pad_ctrl(len_io[0]) >> 2;
}
vcos_assert((uint8_t *)ctrl == ((uint8_t *)ctrl_begin + ctrl_len));
success = vchi_held_msg_release(&held_msg);
assert(success == 0);
}
if ((flags & RPC_RECV_FLAG_BULK) && len_io[0]) {
if (flags & RPC_RECV_FLAG_BULK_SCATTER) {
if ((len_io[0] == len_io[1]) && !len_io[3] && !len_io[4]) {
/* hopefully should be the common case */
recv_bulk(thread, out, len_io[2] * len_io[0]);
} else {
check_workspace(len_io[2] * len_io[0]);
recv_bulk(thread, workspace, len_io[2] * len_io[0]);
rpc_scatter(out, len_io[0], len_io[1], len_io[2], len_io[3], len_io[4], workspace);
}
} else {
recv_bulk(thread, out, len_io[0]);
}
}
}
return res;
}
void rpc_begin(void)
{
platform_mutex_acquire(&mutex);
}
void rpc_end(void)
{
platform_mutex_release(&mutex);
}
EGLDisplay khrn_platform_set_display_id(EGLNativeDisplayType display_id)
{
if (display_id == EGL_DEFAULT_DISPLAY)
return (EGLDisplay)1;
else
return EGL_NO_DISPLAY;
}
//dummy functions
static int xxx_position = 0;
uint32_t khrn_platform_get_window_position(EGLNativeWindowType win)
{
return xxx_position;
}
void khrn_platform_release_pixmap_info(EGLNativePixmapType pixmap, KHRN_IMAGE_WRAP_T *image)
{
/* Nothing to do */
}
////
| {
"content_hash": "2d8fe8e2c0abd544147d109e55079b27",
"timestamp": "",
"source": "github",
"line_count": 363,
"max_line_length": 152,
"avg_line_length": 29.43250688705234,
"alnum_prop": 0.5947210782478473,
"repo_name": "vanwinkeljan/rpi_vmcsx",
"id": "6fbf1aee75ce6640cdae27faae2ff4cd18bc95f9",
"size": "12334",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "interface/khronos/common/selfhosted/khrn_client_rpc_selfhosted.c",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "1695600"
},
{
"name": "C",
"bytes": "14832661"
},
{
"name": "C++",
"bytes": "579095"
},
{
"name": "Erlang",
"bytes": "5477"
},
{
"name": "M",
"bytes": "4081"
},
{
"name": "Objective-C",
"bytes": "7999"
},
{
"name": "Perl",
"bytes": "14757"
},
{
"name": "Python",
"bytes": "19054"
},
{
"name": "Ruby",
"bytes": "1004"
},
{
"name": "Scala",
"bytes": "1485"
},
{
"name": "Shell",
"bytes": "6593"
},
{
"name": "Tcl",
"bytes": "25"
},
{
"name": "TeX",
"bytes": "3008"
}
],
"symlink_target": ""
} |
require 'rails_helper'
module ActiveAdmin
RSpec.describe Resource, "Attributes" do
let(:application) { ActiveAdmin::Application.new }
let(:namespace) { ActiveAdmin::Namespace.new application, :admin }
let(:resource_config) { ActiveAdmin::Resource.new namespace, Post }
describe "#resource_attributes" do
subject do
resource_config.resource_attributes
end
it 'should return attributes hash' do
expect(subject).to eq( author_id: :author,
body: :body,
created_at: :created_at,
custom_category_id: :category,
foo_id: :foo_id,
position: :position,
published_date: :published_date,
starred: :starred,
title: :title,
updated_at: :updated_at)
end
end
describe "#association_columns" do
subject do
resource_config.association_columns
end
it 'should return associations' do
expect(subject).to eq([:author, :category])
end
end
describe "#content_columns" do
subject do
resource_config.content_columns
end
it 'should return columns without associations' do
expect(subject).to eq([:title, :body, :published_date, :position, :starred, :foo_id, :created_at, :updated_at])
end
end
end
end
| {
"content_hash": "df394dad75eb69aca9c8ebea9f8f721a",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 119,
"avg_line_length": 30.42,
"alnum_prop": 0.5424063116370809,
"repo_name": "cmunozgar/activeadmin",
"id": "62febb18ed0bb58623c1876dfb019f7da742bcc1",
"size": "1521",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/unit/resource/attributes_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "52499"
},
{
"name": "CoffeeScript",
"bytes": "18975"
},
{
"name": "Gherkin",
"bytes": "127369"
},
{
"name": "HTML",
"bytes": "21628"
},
{
"name": "JavaScript",
"bytes": "165"
},
{
"name": "Ruby",
"bytes": "681197"
}
],
"symlink_target": ""
} |
package org.kie.server.integrationtests.router.client;
import java.io.StringReader;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.kie.server.controller.client.exception.KieServerControllerHTTPClientException;
import org.kie.server.router.Configuration;
import org.kie.server.router.repository.ConfigurationMarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KieServerRouterClient implements AutoCloseable {
private static Logger logger = LoggerFactory.getLogger(KieServerRouterClient.class);
private static final String MANAGEMENT_LIST_URI_PART = "/mgmt/list";
private String routerBaseUrl;
private Client httpClient;
private String mediaType = MediaType.APPLICATION_JSON;
private ConfigurationMarshaller marshaller = new ConfigurationMarshaller();
public KieServerRouterClient(String routerBaseUrl) {
this.routerBaseUrl = routerBaseUrl;
httpClient = new ResteasyClientBuilder()
.establishConnectionTimeout(10, TimeUnit.SECONDS)
.socketTimeout(10, TimeUnit.SECONDS)
.build();
}
public Configuration getRouterConfig() {
return makeGetRequestAndCreateCustomResponse(routerBaseUrl + MANAGEMENT_LIST_URI_PART);
}
@Override
public void close() {
try {
httpClient.close();
} catch (Exception e) {
logger.error("Exception thrown while closing resources!", e);
}
}
private Configuration makeGetRequestAndCreateCustomResponse(String uri) {
WebTarget clientRequest = httpClient.target(uri);
Response response;
response = clientRequest.request(mediaType).get();
if ( response.getStatus() == Response.Status.OK.getStatusCode() ) {
return deserialize(response);
} else {
throw createExceptionForUnexpectedResponseCode( clientRequest, response );
}
}
private RuntimeException createExceptionForUnexpectedResponseCode(
WebTarget request,
Response response) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("Unexpected HTTP response code when requesting URI '");
stringBuffer.append(getClientRequestUri(request));
stringBuffer.append("'! Response code: ");
stringBuffer.append(response.getStatus());
try {
String responseEntity = response.readEntity(String.class);
stringBuffer.append(" Response message: ");
stringBuffer.append(responseEntity);
} catch (IllegalStateException e) {
response.close();
// Exception while reading response - most probably empty response and closed input stream
}
logger.debug( stringBuffer.toString());
return new KieServerControllerHTTPClientException(response.getStatus(), stringBuffer.toString());
}
private String getClientRequestUri(WebTarget clientRequest) {
String uri;
try {
uri = clientRequest.getUri().toString();
} catch (Exception e) {
throw new RuntimeException("Malformed client URL was specified!", e);
}
return uri;
}
private Configuration deserialize(Response response) {
try {
String content = response.readEntity(String.class);
logger.debug("About to deserialize content: \n '{}'", content);
if (content == null || content.isEmpty()) {
return null;
}
return marshaller.unmarshall(new StringReader(content));
} catch ( Exception e ) {
throw new RuntimeException( "Error while deserializing data received from server!", e );
} finally {
response.close();
}
}
}
| {
"content_hash": "80f8927c2c2e5ee0cafe399497979c40",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 105,
"avg_line_length": 36.072072072072075,
"alnum_prop": 0.6725774225774226,
"repo_name": "baldimir/droolsjbpm-integration",
"id": "3389f030388174efb2de6fa8be17e63fbe4d0f4c",
"size": "4580",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "kie-server-parent/kie-server-tests/kie-server-integ-tests-common/src/main/java/org/kie/server/integrationtests/router/client/KieServerRouterClient.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2569"
},
{
"name": "CSS",
"bytes": "134"
},
{
"name": "FreeMarker",
"bytes": "20776"
},
{
"name": "HTML",
"bytes": "24801"
},
{
"name": "Java",
"bytes": "9948962"
},
{
"name": "JavaScript",
"bytes": "138620"
},
{
"name": "Shell",
"bytes": "3525"
},
{
"name": "Visual Basic",
"bytes": "14419"
},
{
"name": "XSLT",
"bytes": "1094"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types = 1);
namespace FireflyIII\Support\Twig;
use FireflyIII\Models\PiggyBank as PB;
use Twig_Extension;
use Twig_SimpleFunction;
/**
*
* Class PiggyBank
*
* @package FireflyIII\Support\Twig
*/
class PiggyBank extends Twig_Extension
{
/**
*
*/
public function getFunctions(): array
{
$functions = [];
$functions[] = new Twig_SimpleFunction(
'currentRelevantRepAmount', function (PB $piggyBank) {
return $piggyBank->currentRelevantRep()->currentamount;
}
);
return $functions;
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName(): string
{
return 'FireflyIII\Support\Twig\PiggyBank';
}
}
| {
"content_hash": "f5aebbad62ed8eed1b78bf5ffaab5e49",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 67,
"avg_line_length": 18.454545454545453,
"alnum_prop": 0.603448275862069,
"repo_name": "tonicospinelli/firefly-iii",
"id": "4c101e21fbadc28144d93401e30ebc1097de3b43",
"size": "812",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/Support/Twig/PiggyBank.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "HTML",
"bytes": "377859"
},
{
"name": "JavaScript",
"bytes": "134697"
},
{
"name": "PHP",
"bytes": "1717078"
},
{
"name": "Shell",
"bytes": "3352"
}
],
"symlink_target": ""
} |
from sqlalchemy import Column, desc
from sqlalchemy import Index
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import and_
from sqlalchemy import func
from sqlalchemy import or_
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import aliased, Query
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.operators import is_
from findd.utils.crypto import hashfile
BASE = declarative_base()
class File(BASE):
__tablename__ = 'file'
path = Column(String, primary_key=True)
mtime = Column(Integer)
size = Column(Integer)
md5 = Column(String(32))
sha1 = Column(String(40))
sha224 = Column(String(56))
sha256 = Column(String(64))
sha384 = Column(String(96))
sha512 = Column(String(128))
def probably_equal(self, file_):
if file_ is None:
return False
return (self.size == file_.size and
self.sha512 == file_.sha512 and
self.sha384 == file_.sha384 and
self.sha256 == file_.sha256 and
self.sha224 == file_.sha224 and
self.sha1 == file_.sha1 and
self.md5 == file_.md5)
def __setitem__(self, k, v):
setattr(self, k, v)
def update(self, dict_):
for key, value in dict_.items():
self[key] = value
Index(
'idx_duplicates',
desc(File.size),
File.sha512,
File.sha384,
File.sha256,
File.sha224,
File.sha1,
File.md5,
File.path, # covering idx
File.mtime, # covering idx
unique=True, # covering idx
)
def create_schema(connectable):
BASE.metadata.create_all(connectable)
class FileRegistry(object):
def __init__(self, session: Session):
self.session = session
def update_hashes_if_needed(self):
file_alias = aliased(File)
files_to_update = self.session. \
query(File). \
distinct(). \
join(file_alias, and_(File.path != file_alias.path,
File.size == file_alias.size,
)).\
filter(or_(is_(File.sha512, None),
is_(File.sha384, None),
is_(File.sha256, None),
is_(File.sha224, None),
is_(File.sha1, None),
is_(File.md5, None),
))
for a_file in files_to_update:
a_file.update(hashfile(a_file.path))
self.session.add(a_file)
# commit big files immediately
if a_file.size > 1024 * 1024:
self.commit() # pragma: no cover
self.commit()
def find_duplicates(self, limit=-1, skip=0):
if limit == 0:
return
self.update_hashes_if_needed()
file_alias = aliased(File)
query = self.session. \
query(File). \
distinct(). \
join(file_alias, and_(File.path != file_alias.path,
File.size == file_alias.size,
File.sha512 == file_alias.sha512,
File.sha384 == file_alias.sha384,
File.sha256 == file_alias.sha256,
File.sha224 == file_alias.sha224,
File.sha1 == file_alias.sha1,
File.md5 == file_alias.md5,
)).\
order_by(desc(File.size))
duplicates = []
pivot_element = None
index = 0
for file_ in query:
if file_.probably_equal(pivot_element):
duplicates.append(file_)
continue
if len(duplicates) > 1 and len(duplicates[skip:]) > 0:
yield duplicates[skip:]
index = index + 1
if index == limit:
return
pivot_element = file_
duplicates = [file_]
if len(duplicates) > 1 and len(duplicates[skip:]) > 0:
yield duplicates[skip:]
def count(self):
return self.session.query(func.count(File.path)).scalar()
def delete(self, db_file: File):
self.session.delete(db_file)
def find_all(self) -> Query:
return self.session.query(File)
def add(self, entity) -> None:
self.session.add(entity)
def commit(self) -> None:
self.session.commit()
| {
"content_hash": "8d42ef4986b097fcb15d99a33fea89b0",
"timestamp": "",
"source": "github",
"line_count": 151,
"max_line_length": 67,
"avg_line_length": 29.980132450331126,
"alnum_prop": 0.5230837199028054,
"repo_name": "schnittstabil/findd",
"id": "b459f8054538780a797c48e198487e1a4d4f9151",
"size": "4527",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "findd/model.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Cucumber",
"bytes": "8050"
},
{
"name": "Python",
"bytes": "42488"
}
],
"symlink_target": ""
} |
<?php
namespace Hubzero\Events\Debug;
//use Hubzero\Stopwatch\Stopwatch;
use Hubzero\Events\DispatcherInterface;
use Hubzero\Events\Event;
use Closure;
/**
* Wrapper for event listeners to provide some extra
* infor for debugging purposes.
*/
class TraceableListener
{
/**
* Listener
*
* @var object
*/
private $listener;
/**
* Listener name
*
* @var string
*/
private $name;
/**
* Called status
*
* @var boolean
*/
private $called;
/**
* Propagation stopper status
*
* @var boolean
*/
private $stoppedPropagation;
/**
* Timer
*
* @var object
*/
private $stopwatch;
/**
* Constructor
*
* @param object $listener
* @param string $name
* @param object $stopwatch
* @return void
*/
public function __construct($listener, $name, $stopwatch)
{
$this->listener = $listener;
$this->name = $name;
$this->stopwatch = $stopwatch;
$this->called = false;
$this->stoppedPropagation = false;
}
/**
* Return the underlying lsitener
*
* @return object
*/
public function getWrappedListener()
{
return $this->listener;
}
/**
* Was this listener called?
*
* @return boolean
*/
public function wasCalled()
{
return $this->called;
}
/**
* Did this listener stop propagation?
*
* @return boolean
*/
public function stoppedPropagation()
{
return $this->stoppedPropagation;
}
/**
* Did this listener stop propagation?
*
* @return mixed
*/
public function trigger(Event $event)
{
$this->called = true;
//$e = $this->stopwatch->start($this->name, 'event_listener');
if ($this->listener instanceof Closure)
{
$response = call_user_func($this->listener, $event);
}
else
{
$response = call_user_func(array($this->listener, $event->getName()), $event);
}
/*if ($e->isStarted())
{
$e->stop();
}*/
if ($event->isStopped())
{
$this->stoppedPropagation = true;
}
return $response;
}
}
| {
"content_hash": "67025ceaccf1732b44fafc7e30b62571",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 81,
"avg_line_length": 15.007633587786259,
"alnum_prop": 0.6134282807731435,
"repo_name": "hubzero/framework",
"id": "c1a87bcd929b727222c34b935c17ec9b5695e9ee",
"size": "2136",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Events/Debug/TraceableListener.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "29"
},
{
"name": "PHP",
"bytes": "3050437"
}
],
"symlink_target": ""
} |
using System;
namespace Vexe.Editor.Types
{
/// <summary>
/// Implement this interface to create your custom operations
/// </summary>
public interface IUndoOp
{
/// <summary>
/// Defines what it is to be done
/// </summary>
void Perform();
/// <summary>
/// Defines how it is to be undone
/// </summary>
void Undo();
/// <summary>
/// A convenient delegate that gets executed after the operation has been performed
/// </summary>
Action OnPerformed { get; set; }
/// <summary>
/// A convenient delegate that gets executed after the operation has been undone
/// </summary>
Action OnUndone { get; set; }
}
} | {
"content_hash": "1868fd9c5256e6886d343e6aba1b364f",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 85,
"avg_line_length": 21.666666666666668,
"alnum_prop": 0.6446153846153846,
"repo_name": "unity-chicken/VFW",
"id": "d84f8fde7d5b8f5acebab2e6676be8f4fbc55fa4",
"size": "652",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "Assets/Plugins/Editor/Vexe/Types/BetterUndo/Operations/IUndoOp.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1085353"
}
],
"symlink_target": ""
} |
from .proxy_only_resource import ProxyOnlyResource
class HybridConnectionKey(ProxyOnlyResource):
"""Hybrid Connection key contract. This has the send key name and value for a
Hybrid Connection.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Resource Id.
:vartype id: str
:ivar name: Resource Name.
:vartype name: str
:param kind: Kind of resource.
:type kind: str
:ivar type: Resource type.
:vartype type: str
:ivar send_key_name: The name of the send key.
:vartype send_key_name: str
:ivar send_key_value: The value of the send key.
:vartype send_key_value: str
"""
_validation = {
'id': {'readonly': True},
'name': {'readonly': True},
'type': {'readonly': True},
'send_key_name': {'readonly': True},
'send_key_value': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'kind': {'key': 'kind', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
'send_key_name': {'key': 'properties.sendKeyName', 'type': 'str'},
'send_key_value': {'key': 'properties.sendKeyValue', 'type': 'str'},
}
def __init__(self, kind=None):
super(HybridConnectionKey, self).__init__(kind=kind)
self.send_key_name = None
self.send_key_value = None
| {
"content_hash": "27be87f6b40f2c6e2445d1c4bc13e7a8",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 81,
"avg_line_length": 32.22222222222222,
"alnum_prop": 0.5806896551724138,
"repo_name": "AutorestCI/azure-sdk-for-python",
"id": "6cf7f1f35bff516ee800453ad32693c39c3a2377",
"size": "1924",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "azure-mgmt-web/azure/mgmt/web/models/hybrid_connection_key.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "34619070"
}
],
"symlink_target": ""
} |
namespace IoT {
namespace Devices {
SerialDevice::SerialDevice()
{
}
SerialDevice::~SerialDevice()
{
}
} } // namespace IoT::Devices
| {
"content_hash": "9c2d07264b9a562dafb22f485fec44cb",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 29,
"avg_line_length": 9.333333333333334,
"alnum_prop": 0.6785714285714286,
"repo_name": "linuxvom/macchina.io",
"id": "aa553adb9321a9aed4b08fe008b0d4e662bb4cf1",
"size": "435",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "devices/Devices/src/SerialDevice.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2893"
},
{
"name": "C",
"bytes": "10363948"
},
{
"name": "C++",
"bytes": "12832452"
},
{
"name": "CMake",
"bytes": "44987"
},
{
"name": "CSS",
"bytes": "30785"
},
{
"name": "HTML",
"bytes": "67590"
},
{
"name": "JavaScript",
"bytes": "33398"
},
{
"name": "Makefile",
"bytes": "95259"
},
{
"name": "Objective-C",
"bytes": "2646"
},
{
"name": "Perl",
"bytes": "2054"
},
{
"name": "Shell",
"bytes": "60903"
}
],
"symlink_target": ""
} |
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ([
/* 0 */,
/* 1 */
/***/ ((module) => {
"use strict";
module.exports = require("vscode");
/***/ }),
/* 2 */
/***/ ((module) => {
// Markdown-it plugin to render GitHub-style task lists; see
//
// https://github.com/blog/1375-task-lists-in-gfm-issues-pulls-comments
// https://github.com/blog/1825-task-lists-in-all-markdown-documents
var disableCheckboxes = true;
var useLabelWrapper = false;
var useLabelAfter = false;
module.exports = function(md, options) {
if (options) {
disableCheckboxes = !options.enabled;
useLabelWrapper = !!options.label;
useLabelAfter = !!options.labelAfter;
}
md.core.ruler.after('inline', 'github-task-lists', function(state) {
var tokens = state.tokens;
for (var i = 2; i < tokens.length; i++) {
if (isTodoItem(tokens, i)) {
todoify(tokens[i], state.Token);
attrSet(tokens[i-2], 'class', 'task-list-item' + (!disableCheckboxes ? ' enabled' : ''));
attrSet(tokens[parentToken(tokens, i-2)], 'class', 'contains-task-list');
}
}
});
};
function attrSet(token, name, value) {
var index = token.attrIndex(name);
var attr = [name, value];
if (index < 0) {
token.attrPush(attr);
} else {
token.attrs[index] = attr;
}
}
function parentToken(tokens, index) {
var targetLevel = tokens[index].level - 1;
for (var i = index - 1; i >= 0; i--) {
if (tokens[i].level === targetLevel) {
return i;
}
}
return -1;
}
function isTodoItem(tokens, index) {
return isInline(tokens[index]) &&
isParagraph(tokens[index - 1]) &&
isListItem(tokens[index - 2]) &&
startsWithTodoMarkdown(tokens[index]);
}
function todoify(token, TokenConstructor) {
token.children.unshift(makeCheckbox(token, TokenConstructor));
token.children[1].content = token.children[1].content.slice(3);
token.content = token.content.slice(3);
if (useLabelWrapper) {
if (useLabelAfter) {
token.children.pop();
// Use large random number as id property of the checkbox.
var id = 'task-item-' + Math.ceil(Math.random() * (10000 * 1000) - 1000);
token.children[0].content = token.children[0].content.slice(0, -1) + ' id="' + id + '">';
token.children.push(afterLabel(token.content, id, TokenConstructor));
} else {
token.children.unshift(beginLabel(TokenConstructor));
token.children.push(endLabel(TokenConstructor));
}
}
}
function makeCheckbox(token, TokenConstructor) {
var checkbox = new TokenConstructor('html_inline', '', 0);
var disabledAttr = disableCheckboxes ? ' disabled="" ' : '';
if (token.content.indexOf('[ ] ') === 0) {
checkbox.content = '<input class="task-list-item-checkbox"' + disabledAttr + 'type="checkbox">';
} else if (token.content.indexOf('[x] ') === 0 || token.content.indexOf('[X] ') === 0) {
checkbox.content = '<input class="task-list-item-checkbox" checked=""' + disabledAttr + 'type="checkbox">';
}
return checkbox;
}
// these next two functions are kind of hacky; probably should really be a
// true block-level token with .tag=='label'
function beginLabel(TokenConstructor) {
var token = new TokenConstructor('html_inline', '', 0);
token.content = '<label>';
return token;
}
function endLabel(TokenConstructor) {
var token = new TokenConstructor('html_inline', '', 0);
token.content = '</label>';
return token;
}
function afterLabel(content, id, TokenConstructor) {
var token = new TokenConstructor('html_inline', '', 0);
token.content = '<label class="task-list-item-label" for="' + id + '">' + content + '</label>';
token.attrs = [{for: id}];
return token;
}
function isInline(token) { return token.type === 'inline'; }
function isParagraph(token) { return token.type === 'paragraph_open'; }
function isListItem(token) { return token.type === 'list_item_open'; }
function startsWithTodoMarkdown(token) {
// leading whitespace in a list item is already trimmed off by markdown-it
return token.content.indexOf('[ ] ') === 0 || token.content.indexOf('[x] ') === 0 || token.content.indexOf('[X] ') === 0;
}
/***/ })
/******/ ]);
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be in strict mode.
(() => {
"use strict";
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.activate = void 0;
const vscode_1 = __webpack_require__(1);
const markdown_it_task_lists_1 = __webpack_require__(2);
function activate() {
return {
extendMarkdownIt(md) {
return md.use(() => {
console.log('xx');
const config = vscode_1.workspace.getConfiguration('markdown-checkboxes');
const x = md.use(markdown_it_task_lists_1.default, {
enabled: config.get('enable'),
label: config.get('label'),
labelAfter: config.get('labelAfter')
});
const y = x.use(markdown_it_task_lists_1.default, {
enabled: config.get('enable'),
label: config.get('label'),
labelAfter: config.get('labelAfter')
});
return md;
});
}
};
}
exports.activate = activate;
})();
var __webpack_export_target__ = exports;
for(var i in __webpack_exports__) __webpack_export_target__[i] = __webpack_exports__[i];
if(__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, "__esModule", { value: true });
/******/ })()
;
//# sourceMappingURL=extension.js.map | {
"content_hash": "f7a8b102437fbdd452d3b4626808da74",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 122,
"avg_line_length": 32.79,
"alnum_prop": 0.5943885330893565,
"repo_name": "ealbertos/dotfiles",
"id": "f0131c7f4cfece55f65f23bce0d0514eb6d83d9a",
"size": "6558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vscode.symlink/extensions/bierner.markdown-checkbox-0.3.3/dist/web/extension.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "99972"
},
{
"name": "EJS",
"bytes": "2437"
},
{
"name": "HTML",
"bytes": "47081"
},
{
"name": "JavaScript",
"bytes": "3546995"
},
{
"name": "Less",
"bytes": "183"
},
{
"name": "Python",
"bytes": "134723"
},
{
"name": "Ruby",
"bytes": "127567"
},
{
"name": "Shell",
"bytes": "34790"
},
{
"name": "TSQL",
"bytes": "258"
},
{
"name": "TypeScript",
"bytes": "37162"
},
{
"name": "Vim Script",
"bytes": "60888"
},
{
"name": "Vim Snippet",
"bytes": "11523"
}
],
"symlink_target": ""
} |
// This script servers as an intermediary between oauth2.js and
// oauth2.html
// Get all ? params from this URL
var url = window.location.href;
var params = '?';
var index = url.indexOf(params);
if (index > -1) {
params = url.substring(index);
}
// Also append the current URL to the params
params += '&from=' + encodeURIComponent(url);
// Redirect back to the extension itself so that we have priveledged
// access again
var redirect = chrome.extension.getURL('/oauth2/oauth2.html');
window.location = redirect + params;
| {
"content_hash": "b6d1206d56548f6a9aa2d58db7d296d2",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 68,
"avg_line_length": 25.285714285714285,
"alnum_prop": 0.7137476459510358,
"repo_name": "bhalajin/tathya",
"id": "6bba9dc975c36a757081585c15f6548692ece69e",
"size": "1144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/My_plugin/oauth2/oauth2_inject.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import sys
import inspect
import copy
import pickle
from sympy.physics.units import meter
from sympy.utilities.pytest import XFAIL
from sympy.core.basic import Atom, Basic
from sympy.core.core import BasicMeta
from sympy.core.singleton import SingletonRegistry
from sympy.core.symbol import Dummy, Symbol, Wild
from sympy.core.numbers import (E, I, pi, oo, zoo, nan, Integer,
Rational, Float)
from sympy.core.relational import (Equality, GreaterThan, LessThan, Relational,
StrictGreaterThan, StrictLessThan, Unequality)
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.function import Derivative, Function, FunctionClass, Lambda, \
WildFunction
from sympy.sets.sets import Interval
from sympy.core.multidimensional import vectorize
from sympy.core.compatibility import HAS_GMPY
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy import symbols, S
from sympy.external import import_module
cloudpickle = import_module('cloudpickle')
excluded_attrs = set([
'_assumptions', # This is a local cache that isn't automatically filled on creation
'_mhash', # Cached after __hash__ is called but set to None after creation
'message', # This is an exception attribute that is present but deprecated in Py2 (can be removed when Py2 support is dropped
'is_EmptySet', # Deprecated from SymPy 1.5. This can be removed when is_EmptySet is removed.
])
def check(a, exclude=[], check_attr=True):
""" Check that pickling and copying round-trips.
"""
protocols = [0, 1, 2, copy.copy, copy.deepcopy]
# Python 2.x doesn't support the third pickling protocol
if sys.version_info >= (3,):
protocols.extend([3, 4])
if cloudpickle:
protocols.extend([cloudpickle])
for protocol in protocols:
if protocol in exclude:
continue
if callable(protocol):
if isinstance(a, BasicMeta):
# Classes can't be copied, but that's okay.
continue
b = protocol(a)
elif inspect.ismodule(protocol):
b = protocol.loads(protocol.dumps(a))
else:
b = pickle.loads(pickle.dumps(a, protocol))
d1 = dir(a)
d2 = dir(b)
assert set(d1) == set(d2)
if not check_attr:
continue
def c(a, b, d):
for i in d:
if i in excluded_attrs:
continue
if not hasattr(a, i):
continue
attr = getattr(a, i)
if not hasattr(attr, "__call__"):
assert hasattr(b, i), i
assert getattr(b, i) == attr, "%s != %s, protocol: %s" % (getattr(b, i), attr, protocol)
c(a, b, d1)
c(b, a, d2)
#================== core =========================
def test_core_basic():
for c in (Atom, Atom(),
Basic, Basic(),
# XXX: dynamically created types are not picklable
# BasicMeta, BasicMeta("test", (), {}),
SingletonRegistry, S):
check(c)
def test_core_symbol():
# make the Symbol a unique name that doesn't class with any other
# testing variable in this file since after this test the symbol
# having the same name will be cached as noncommutative
for c in (Dummy, Dummy("x", commutative=False), Symbol,
Symbol("_issue_3130", commutative=False), Wild, Wild("x")):
check(c)
def test_core_numbers():
for c in (Integer(2), Rational(2, 3), Float("1.2")):
check(c)
def test_core_float_copy():
# See gh-7457
y = Symbol("x") + 1.0
check(y) # does not raise TypeError ("argument is not an mpz")
def test_core_relational():
x = Symbol("x")
y = Symbol("y")
for c in (Equality, Equality(x, y), GreaterThan, GreaterThan(x, y),
LessThan, LessThan(x, y), Relational, Relational(x, y),
StrictGreaterThan, StrictGreaterThan(x, y), StrictLessThan,
StrictLessThan(x, y), Unequality, Unequality(x, y)):
check(c)
def test_core_add():
x = Symbol("x")
for c in (Add, Add(x, 4)):
check(c)
def test_core_mul():
x = Symbol("x")
for c in (Mul, Mul(x, 4)):
check(c)
def test_core_power():
x = Symbol("x")
for c in (Pow, Pow(x, 4)):
check(c)
def test_core_function():
x = Symbol("x")
for f in (Derivative, Derivative(x), Function, FunctionClass, Lambda,
WildFunction):
check(f)
def test_core_undefinedfunctions():
f = Function("f")
# Full XFAILed test below
exclude = list(range(5))
# https://github.com/cloudpipe/cloudpickle/issues/65
# https://github.com/cloudpipe/cloudpickle/issues/190
exclude.append(cloudpickle)
check(f, exclude=exclude)
@XFAIL
def test_core_undefinedfunctions_fail():
# This fails because f is assumed to be a class at sympy.basic.function.f
f = Function("f")
check(f)
def test_core_interval():
for c in (Interval, Interval(0, 2)):
check(c)
def test_core_multidimensional():
for c in (vectorize, vectorize(0)):
check(c)
def test_Singletons():
protocols = [0, 1, 2]
if sys.version_info >= (3,):
protocols.extend([3, 4])
copiers = [copy.copy, copy.deepcopy]
copiers += [lambda x: pickle.loads(pickle.dumps(x, proto))
for proto in protocols]
if cloudpickle:
copiers += [lambda x: cloudpickle.loads(cloudpickle.dumps(x))]
for obj in (Integer(-1), Integer(0), Integer(1), Rational(1, 2), pi, E, I,
oo, -oo, zoo, nan, S.GoldenRatio, S.TribonacciConstant,
S.EulerGamma, S.Catalan, S.EmptySet, S.IdentityFunction):
for func in copiers:
assert func(obj) is obj
#================== functions ===================
from sympy.functions import (Piecewise, lowergamma, acosh, chebyshevu,
chebyshevt, ln, chebyshevt_root, legendre, Heaviside, bernoulli, coth,
tanh, assoc_legendre, sign, arg, asin, DiracDelta, re, rf, Abs,
uppergamma, binomial, sinh, cos, cot, acos, acot, gamma, bell,
hermite, harmonic, LambertW, zeta, log, factorial, asinh, acoth, cosh,
dirichlet_eta, Eijk, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, chebyshevu_root, floor, atanh, sqrt, sin,
atan, ff, lucas, atan2, polygamma, exp)
def test_functions():
one_var = (acosh, ln, Heaviside, factorial, bernoulli, coth, tanh,
sign, arg, asin, DiracDelta, re, Abs, sinh, cos, cot, acos, acot,
gamma, bell, harmonic, LambertW, zeta, log, factorial, asinh,
acoth, cosh, dirichlet_eta, loggamma, erf, ceiling, im, fibonacci,
tribonacci, conjugate, tan, floor, atanh, sin, atan, lucas, exp)
two_var = (rf, ff, lowergamma, chebyshevu, chebyshevt, binomial,
atan2, polygamma, hermite, legendre, uppergamma)
x, y, z = symbols("x,y,z")
others = (chebyshevt_root, chebyshevu_root, Eijk(x, y, z),
Piecewise( (0, x < -1), (x**2, x <= 1), (x**3, True)),
assoc_legendre)
for cls in one_var:
check(cls)
c = cls(x)
check(c)
for cls in two_var:
check(cls)
c = cls(x, y)
check(c)
for cls in others:
check(cls)
#================== geometry ====================
from sympy.geometry.entity import GeometryEntity
from sympy.geometry.point import Point
from sympy.geometry.ellipse import Circle, Ellipse
from sympy.geometry.line import Line, LinearEntity, Ray, Segment
from sympy.geometry.polygon import Polygon, RegularPolygon, Triangle
def test_geometry():
p1 = Point(1, 2)
p2 = Point(2, 3)
p3 = Point(0, 0)
p4 = Point(0, 1)
for c in (
GeometryEntity, GeometryEntity(), Point, p1, Circle, Circle(p1, 2),
Ellipse, Ellipse(p1, 3, 4), Line, Line(p1, p2), LinearEntity,
LinearEntity(p1, p2), Ray, Ray(p1, p2), Segment, Segment(p1, p2),
Polygon, Polygon(p1, p2, p3, p4), RegularPolygon,
RegularPolygon(p1, 4, 5), Triangle, Triangle(p1, p2, p3)):
check(c, check_attr=False)
#================== integrals ====================
from sympy.integrals.integrals import Integral
def test_integrals():
x = Symbol("x")
for c in (Integral, Integral(x)):
check(c)
#==================== logic =====================
from sympy.core.logic import Logic
def test_logic():
for c in (Logic, Logic(1)):
check(c)
#================== matrices ====================
from sympy.matrices import Matrix, SparseMatrix
def test_matrices():
for c in (Matrix, Matrix([1, 2, 3]), SparseMatrix, SparseMatrix([[1, 2], [3, 4]])):
check(c)
#================== ntheory =====================
from sympy.ntheory.generate import Sieve
def test_ntheory():
for c in (Sieve, Sieve()):
check(c)
#================== physics =====================
from sympy.physics.paulialgebra import Pauli
from sympy.physics.units import Unit
def test_physics():
for c in (Unit, meter, Pauli, Pauli(1)):
check(c)
#================== plotting ====================
# XXX: These tests are not complete, so XFAIL them
@XFAIL
def test_plotting():
from sympy.plotting.color_scheme import ColorGradient, ColorScheme
from sympy.plotting.managed_window import ManagedWindow
from sympy.plotting.plot import Plot, ScreenShot
from sympy.plotting.plot_axes import PlotAxes, PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
from sympy.plotting.plot_camera import PlotCamera
from sympy.plotting.plot_controller import PlotController
from sympy.plotting.plot_curve import PlotCurve
from sympy.plotting.plot_interval import PlotInterval
from sympy.plotting.plot_mode import PlotMode
from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
from sympy.plotting.plot_object import PlotObject
from sympy.plotting.plot_surface import PlotSurface
from sympy.plotting.plot_window import PlotWindow
for c in (
ColorGradient, ColorGradient(0.2, 0.4), ColorScheme, ManagedWindow,
ManagedWindow, Plot, ScreenShot, PlotAxes, PlotAxesBase,
PlotAxesFrame, PlotAxesOrdinate, PlotCamera, PlotController,
PlotCurve, PlotInterval, PlotMode, Cartesian2D, Cartesian3D,
Cylindrical, ParametricCurve2D, ParametricCurve3D,
ParametricSurface, Polar, Spherical, PlotObject, PlotSurface,
PlotWindow):
check(c)
@XFAIL
def test_plotting2():
#from sympy.plotting.color_scheme import ColorGradient
from sympy.plotting.color_scheme import ColorScheme
#from sympy.plotting.managed_window import ManagedWindow
from sympy.plotting.plot import Plot
#from sympy.plotting.plot import ScreenShot
from sympy.plotting.plot_axes import PlotAxes
#from sympy.plotting.plot_axes import PlotAxesBase, PlotAxesFrame, PlotAxesOrdinate
#from sympy.plotting.plot_camera import PlotCamera
#from sympy.plotting.plot_controller import PlotController
#from sympy.plotting.plot_curve import PlotCurve
#from sympy.plotting.plot_interval import PlotInterval
#from sympy.plotting.plot_mode import PlotMode
#from sympy.plotting.plot_modes import Cartesian2D, Cartesian3D, Cylindrical, \
# ParametricCurve2D, ParametricCurve3D, ParametricSurface, Polar, Spherical
#from sympy.plotting.plot_object import PlotObject
#from sympy.plotting.plot_surface import PlotSurface
# from sympy.plotting.plot_window import PlotWindow
check(ColorScheme("rainbow"))
check(Plot(1, visible=False))
check(PlotAxes())
#================== polys =======================
from sympy import Poly, ZZ, QQ, lex
def test_pickling_polys_polytools():
from sympy.polys.polytools import PurePoly
# from sympy.polys.polytools import GroebnerBasis
x = Symbol('x')
for c in (Poly, Poly(x, x)):
check(c)
for c in (PurePoly, PurePoly(x)):
check(c)
# TODO: fix pickling of Options class (see GroebnerBasis._options)
# for c in (GroebnerBasis, GroebnerBasis([x**2 - 1], x, order=lex)):
# check(c)
def test_pickling_polys_polyclasses():
from sympy.polys.polyclasses import DMP, DMF, ANP
for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
check(c)
for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
check(c)
for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
check(c)
@XFAIL
def test_pickling_polys_rings():
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of rings works properly.
from sympy.polys.rings import PolyRing
ring = PolyRing("x,y,z", ZZ, lex)
for c in (PolyRing, ring):
check(c, exclude=[0, 1])
for c in (ring.dtype, ring.one):
check(c, exclude=[0, 1], check_attr=False) # TODO: Py3k
def test_pickling_polys_fields():
pass
# NOTE: can't use protocols < 2 because we have to execute __new__ to
# make sure caching of fields works properly.
# from sympy.polys.fields import FracField
# field = FracField("x,y,z", ZZ, lex)
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (FracField, field):
# check(c, exclude=[0, 1])
# TODO: AssertionError: assert id(obj) not in self.memo
# for c in (field.dtype, field.one):
# check(c, exclude=[0, 1])
def test_pickling_polys_elements():
from sympy.polys.domains.pythonrational import PythonRational
#from sympy.polys.domains.pythonfinitefield import PythonFiniteField
#from sympy.polys.domains.mpelements import MPContext
for c in (PythonRational, PythonRational(1, 7)):
check(c)
#gf = PythonFiniteField(17)
# TODO: fix pickling of ModularInteger
# for c in (gf.dtype, gf(5)):
# check(c)
#mp = MPContext()
# TODO: fix pickling of RealElement
# for c in (mp.mpf, mp.mpf(1.0)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (mp.mpc, mp.mpc(1.0, -1.5)):
# check(c)
def test_pickling_polys_domains():
# from sympy.polys.domains.pythonfinitefield import PythonFiniteField
from sympy.polys.domains.pythonintegerring import PythonIntegerRing
from sympy.polys.domains.pythonrationalfield import PythonRationalField
# TODO: fix pickling of ModularInteger
# for c in (PythonFiniteField, PythonFiniteField(17)):
# check(c)
for c in (PythonIntegerRing, PythonIntegerRing()):
check(c, check_attr=False)
for c in (PythonRationalField, PythonRationalField()):
check(c, check_attr=False)
if HAS_GMPY:
# from sympy.polys.domains.gmpyfinitefield import GMPYFiniteField
from sympy.polys.domains.gmpyintegerring import GMPYIntegerRing
from sympy.polys.domains.gmpyrationalfield import GMPYRationalField
# TODO: fix pickling of ModularInteger
# for c in (GMPYFiniteField, GMPYFiniteField(17)):
# check(c)
for c in (GMPYIntegerRing, GMPYIntegerRing()):
check(c, check_attr=False)
for c in (GMPYRationalField, GMPYRationalField()):
check(c, check_attr=False)
#from sympy.polys.domains.realfield import RealField
#from sympy.polys.domains.complexfield import ComplexField
from sympy.polys.domains.algebraicfield import AlgebraicField
#from sympy.polys.domains.polynomialring import PolynomialRing
#from sympy.polys.domains.fractionfield import FractionField
from sympy.polys.domains.expressiondomain import ExpressionDomain
# TODO: fix pickling of RealElement
# for c in (RealField, RealField(100)):
# check(c)
# TODO: fix pickling of ComplexElement
# for c in (ComplexField, ComplexField(100)):
# check(c)
for c in (AlgebraicField, AlgebraicField(QQ, sqrt(3))):
check(c, check_attr=False)
# TODO: AssertionError
# for c in (PolynomialRing, PolynomialRing(ZZ, "x,y,z")):
# check(c)
# TODO: AttributeError: 'PolyElement' object has no attribute 'ring'
# for c in (FractionField, FractionField(ZZ, "x,y,z")):
# check(c)
for c in (ExpressionDomain, ExpressionDomain()):
check(c, check_attr=False)
def test_pickling_polys_numberfields():
from sympy.polys.numberfields import AlgebraicNumber
for c in (AlgebraicNumber, AlgebraicNumber(sqrt(3))):
check(c, check_attr=False)
def test_pickling_polys_orderings():
from sympy.polys.orderings import (LexOrder, GradedLexOrder,
ReversedGradedLexOrder, InverseOrder)
# from sympy.polys.orderings import ProductOrder
for c in (LexOrder, LexOrder()):
check(c)
for c in (GradedLexOrder, GradedLexOrder()):
check(c)
for c in (ReversedGradedLexOrder, ReversedGradedLexOrder()):
check(c)
# TODO: Argh, Python is so naive. No lambdas nor inner function support in
# pickling module. Maybe someone could figure out what to do with this.
#
# for c in (ProductOrder, ProductOrder((LexOrder(), lambda m: m[:2]),
# (GradedLexOrder(), lambda m: m[2:]))):
# check(c)
for c in (InverseOrder, InverseOrder(LexOrder())):
check(c)
def test_pickling_polys_monomials():
from sympy.polys.monomials import MonomialOps, Monomial
x, y, z = symbols("x,y,z")
for c in (MonomialOps, MonomialOps(3)):
check(c)
for c in (Monomial, Monomial((1, 2, 3), (x, y, z))):
check(c)
def test_pickling_polys_errors():
from sympy.polys.polyerrors import (HeuristicGCDFailed,
HomomorphismFailed, IsomorphismFailed, ExtraneousFactors,
EvaluationFailed, RefinementFailed, CoercionFailed, NotInvertible,
NotReversible, NotAlgebraic, DomainError, PolynomialError,
UnificationFailed, GeneratorsError, GeneratorsNeeded,
UnivariatePolynomialError, MultivariatePolynomialError, OptionError,
FlagError)
# from sympy.polys.polyerrors import (ExactQuotientFailed,
# OperationNotSupported, ComputationFailed, PolificationFailed)
# x = Symbol('x')
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (ExactQuotientFailed, ExactQuotientFailed(x, 3*x, ZZ)):
# check(c)
# TODO: TypeError: can't pickle instancemethod objects
# for c in (OperationNotSupported, OperationNotSupported(Poly(x), Poly.gcd)):
# check(c)
for c in (HeuristicGCDFailed, HeuristicGCDFailed()):
check(c)
for c in (HomomorphismFailed, HomomorphismFailed()):
check(c)
for c in (IsomorphismFailed, IsomorphismFailed()):
check(c)
for c in (ExtraneousFactors, ExtraneousFactors()):
check(c)
for c in (EvaluationFailed, EvaluationFailed()):
check(c)
for c in (RefinementFailed, RefinementFailed()):
check(c)
for c in (CoercionFailed, CoercionFailed()):
check(c)
for c in (NotInvertible, NotInvertible()):
check(c)
for c in (NotReversible, NotReversible()):
check(c)
for c in (NotAlgebraic, NotAlgebraic()):
check(c)
for c in (DomainError, DomainError()):
check(c)
for c in (PolynomialError, PolynomialError()):
check(c)
for c in (UnificationFailed, UnificationFailed()):
check(c)
for c in (GeneratorsError, GeneratorsError()):
check(c)
for c in (GeneratorsNeeded, GeneratorsNeeded()):
check(c)
# TODO: PicklingError: Can't pickle <function <lambda> at 0x38578c0>: it's not found as __main__.<lambda>
# for c in (ComputationFailed, ComputationFailed(lambda t: t, 3, None)):
# check(c)
for c in (UnivariatePolynomialError, UnivariatePolynomialError()):
check(c)
for c in (MultivariatePolynomialError, MultivariatePolynomialError()):
check(c)
# TODO: TypeError: __init__() takes at least 3 arguments (1 given)
# for c in (PolificationFailed, PolificationFailed({}, x, x, False)):
# check(c)
for c in (OptionError, OptionError()):
check(c)
for c in (FlagError, FlagError()):
check(c)
#def test_pickling_polys_options():
#from sympy.polys.polyoptions import Options
# TODO: fix pickling of `symbols' flag
# for c in (Options, Options((), dict(domain='ZZ', polys=False))):
# check(c)
# TODO: def test_pickling_polys_rootisolation():
# RealInterval
# ComplexInterval
def test_pickling_polys_rootoftools():
from sympy.polys.rootoftools import CRootOf, RootSum
x = Symbol('x')
f = x**3 + x + 3
for c in (CRootOf, CRootOf(f, 0)):
check(c)
for c in (RootSum, RootSum(f, exp)):
check(c)
#================== printing ====================
from sympy.printing.latex import LatexPrinter
from sympy.printing.mathml import MathMLContentPrinter, MathMLPresentationPrinter
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.printing.printer import Printer
from sympy.printing.python import PythonPrinter
def test_printing():
for c in (LatexPrinter, LatexPrinter(), MathMLContentPrinter,
MathMLPresentationPrinter, PrettyPrinter, prettyForm, stringPict,
stringPict("a"), Printer, Printer(), PythonPrinter,
PythonPrinter()):
check(c)
@XFAIL
def test_printing1():
check(MathMLContentPrinter())
@XFAIL
def test_printing2():
check(MathMLPresentationPrinter())
@XFAIL
def test_printing3():
check(PrettyPrinter())
#================== series ======================
from sympy.series.limits import Limit
from sympy.series.order import Order
def test_series():
e = Symbol("e")
x = Symbol("x")
for c in (Limit, Limit(e, x, 1), Order, Order(e)):
check(c)
#================== concrete ==================
from sympy.concrete.products import Product
from sympy.concrete.summations import Sum
def test_concrete():
x = Symbol("x")
for c in (Product, Product(x, (x, 2, 4)), Sum, Sum(x, (x, 2, 4))):
check(c)
def test_deprecation_warning():
w = SymPyDeprecationWarning('value', 'feature', issue=12345, deprecated_since_version='1.0')
check(w)
| {
"content_hash": "1d23583e66a6de8f1377daa80463aae4",
"timestamp": "",
"source": "github",
"line_count": 696,
"max_line_length": 131,
"avg_line_length": 32.297413793103445,
"alnum_prop": 0.6403309755772054,
"repo_name": "kaushik94/sympy",
"id": "0ed5148d2fd02bec271d3448d078f23c90d68e1a",
"size": "22481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sympy/utilities/tests/test_pickling.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "5094"
},
{
"name": "Python",
"bytes": "13553568"
},
{
"name": "Ruby",
"bytes": "304"
},
{
"name": "Scheme",
"bytes": "125"
},
{
"name": "Shell",
"bytes": "4008"
},
{
"name": "TeX",
"bytes": "32356"
},
{
"name": "XSLT",
"bytes": "366202"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/UsbongImageViewerParentLayout"
android:id="@+id/parent_layout_id"
>
<ScrollView
style="@style/UsbongDefaultScrollView">
<LinearLayout style="@style/UsbongPhotoCaptureMainLayout">
<TextView android:id="@+id/photo_capture_textview"
style="@style/UsbongDefaultTextView"
android:text="@string/photo_capture_textview" />
<Button android:id="@+id/photo_capture_button"
style="@style/UsbongPhotoCaptureButton"
android:text="Take Photo" />
<ImageView android:id="@+id/CameraImage"
style="@style/UsbongCameraImageView"/>
</LinearLayout>
</ScrollView>
<LinearLayout
style="@style/UsbongDefaultBackNextButtonLayout">
<Button android:id="@+id/back_button"
style="@style/UsbongDefaultBackNextButton"
android:text="Back"/>
<Button android:id="@+id/next_button"
style="@style/UsbongDefaultBackNextButton"
android:text="Next"/>
</LinearLayout>
</LinearLayout> | {
"content_hash": "42251b18ad0351992f987f0e2f3c9c73",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 72,
"avg_line_length": 38.37931034482759,
"alnum_prop": 0.6792452830188679,
"repo_name": "usbong/usbong_pagtsing",
"id": "6925a2780cdc5a85af698563c6784360cd87468c",
"size": "1113",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/layout/photo_capture_screen.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "407336"
}
],
"symlink_target": ""
} |
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef _SAM4CP_0_
#define _SAM4CP_0_
#if defined __SAM4CP16B_0__
#include "sam4cp16b_0.h"
#else
#error Library does not support the specified device.
#endif
#endif /* _SAM4CP_0_ */
| {
"content_hash": "31cdfcfa3f43edf6f2313ccd36d45ef4",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 90,
"avg_line_length": 20.642857142857142,
"alnum_prop": 0.6643598615916955,
"repo_name": "femtoio/femto-usb-blink-example",
"id": "9d35f0ef6880fc02f46a4d106fc0cd428bb651d3",
"size": "1998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "blinky/blinky/asf-3.21.0/sam/utils/cmsis/sam4cp/include/sam4cp_0.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "178794"
},
{
"name": "C",
"bytes": "251878780"
},
{
"name": "C++",
"bytes": "47991929"
},
{
"name": "CSS",
"bytes": "2147"
},
{
"name": "HTML",
"bytes": "107322"
},
{
"name": "JavaScript",
"bytes": "588817"
},
{
"name": "Logos",
"bytes": "570108"
},
{
"name": "Makefile",
"bytes": "64558964"
},
{
"name": "Matlab",
"bytes": "10660"
},
{
"name": "Objective-C",
"bytes": "15780083"
},
{
"name": "Perl",
"bytes": "12845"
},
{
"name": "Python",
"bytes": "67293"
},
{
"name": "Scilab",
"bytes": "88572"
},
{
"name": "Shell",
"bytes": "126729"
}
],
"symlink_target": ""
} |
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
| {
"content_hash": "89b1fe291b2223edda6a26a977a0e48a",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 60,
"avg_line_length": 16.857142857142858,
"alnum_prop": 0.7796610169491526,
"repo_name": "hnliji1107/iosAppByObjectiveC",
"id": "0c6f39ede2d51a1f52a9ddf0dc23412180766679",
"size": "292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iosAppByObjectiveC/AppDelegate.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "885551"
}
],
"symlink_target": ""
} |
// Type definitions for webidl2 23.13
// Project: https://github.com/w3c/webidl2.js#readme
// Definitions by: Kagama Sascha Rosylight <https://github.com/saschanaz>
// ExE Boss <https://github.com/ExE-Boss>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace WebIDL2;
export {};
export function parse(str: string, options?: ParseOptions): IDLRootType[];
export type IDLRootType =
| CallbackType
| CallbackInterfaceType
| DictionaryType
| EnumType
| IncludesType
| InterfaceMixinType
| InterfaceType
| NamespaceType
| TypedefType;
export type IDLCallbackInterfaceMemberType = ConstantMemberType | OperationMemberType;
export type IDLInterfaceMemberType =
| AttributeMemberType
| ConstantMemberType
| ConstructorMemberType
| DeclarationMemberType
| OperationMemberType;
export type IDLInterfaceMixinMemberType = AttributeMemberType | ConstantMemberType | OperationMemberType;
export type IDLNamespaceMemberType = AttributeMemberType | OperationMemberType;
export type IDLTypeDescription = GenericTypeDescription | SingleTypeDescription | UnionTypeDescription;
export interface ParseOptions {
/** Boolean indicating whether the result should include EOF node or not. */
concrete?: boolean | undefined;
/** The source name, typically a filename. Errors and validation objects can indicate their origin if you pass a value. */
sourceName?: string | undefined;
}
export class WebIDLParseError extends Error {
constructor(options: {
message: string;
bareMessage: string;
context: string;
line: number;
sourceName?: string | undefined;
input: string;
tokens: Token[];
});
name: "WebIDLParseError";
/** the error message */
message: string;
bareMessage: string;
context: string;
/** the line at which the error occurred. */
line: number;
sourceName: string | undefined;
/** a short peek at the text at the point where the error happened */
input: string;
/** the five tokens at the point of error, as understood by the tokeniser */
tokens: Token[];
}
export interface Token {
type: string;
value: string;
trivia: string;
line: number;
index: number;
}
export interface AbstractBase {
/** String indicating the type of this node. */
type: string | null;
/** The container of this type. */
parent: AbstractBase | null;
/** A list of extended attributes. */
extAttrs: ExtendedAttribute[];
}
export interface AbstractTypeDescription extends AbstractBase {
/** Boolean indicating whether this is nullable or not. */
nullable: boolean;
/** The container of this type. */
parent:
| Argument
| AttributeMemberType
| CallbackType
| ConstantMemberType
| DeclarationMemberType
| FieldType
| OperationMemberType
| TypedefType
| UnionTypeDescription;
}
interface AbstractNonUnionTypeDescription extends AbstractTypeDescription {
/** String indicating the generic type (e.g. "Promise", "sequence"). The empty string otherwise. */
generic: IDLTypeDescription["generic"];
/** Boolean indicating whether this is a union type or not. */
union: false;
}
interface AbstractGenericTypeDescription extends AbstractNonUnionTypeDescription {
/**
* Contains the IDL type description for the type in the sequence,
* the eventual value of the promise, etc.
*/
idlType: IDLTypeDescription[];
}
export type GenericTypeDescription =
| FrozenArrayTypeDescription
| ObservableArrayTypeDescription
| PromiseTypeDescription
| RecordTypeDescription
| SequenceTypeDescription;
export interface FrozenArrayTypeDescription extends AbstractGenericTypeDescription {
generic: "FrozenArray";
idlType: [IDLTypeDescription];
}
export interface ObservableArrayTypeDescription extends AbstractGenericTypeDescription {
generic: "ObservableArray";
idlType: [IDLTypeDescription];
}
export interface PromiseTypeDescription extends AbstractGenericTypeDescription {
generic: "Promise";
idlType: [IDLTypeDescription];
}
export interface RecordTypeDescription extends AbstractGenericTypeDescription {
generic: "record";
idlType: [IDLTypeDescription, IDLTypeDescription];
}
export interface SequenceTypeDescription extends AbstractGenericTypeDescription {
generic: "sequence";
idlType: [IDLTypeDescription];
}
export interface SingleTypeDescription extends AbstractNonUnionTypeDescription {
generic: "";
/**
* In most cases, this will just be a string with the type name.
* If the type is a union, then this contains an array of the types it unites.
* If it is a generic type, it contains the IDL type description for the type in the sequence,
* the eventual value of the promise, etc.
*/
idlType: string;
}
export interface UnionTypeDescription extends AbstractTypeDescription {
/** String indicating the generic type (e.g. "Promise", "sequence"). The empty string otherwise. */
generic: "";
/** Boolean indicating whether this is a union type or not. */
union: true;
/**
* In most cases, this will just be a string with the type name.
* If the type is a union, then this contains an array of the types it unites.
* If it is a generic type, it contains the IDL type description for the type in the sequence,
* the eventual value of the promise, etc.
*/
idlType: IDLTypeDescription[];
}
export interface AbstractContainer extends AbstractBase {
/** The name of the container. */
name: string;
/** A boolean indicating whether this container is partial. */
partial: boolean;
/** An array of container members (attributes, operations, etc.). Empty if there are none. */
members: AbstractBase[];
}
export interface CallbackInterfaceType extends AbstractContainer {
type: "callback interface";
members: IDLCallbackInterfaceMemberType[];
inheritance: null;
parent: null;
}
export interface InterfaceType extends AbstractContainer {
type: "interface";
members: IDLInterfaceMemberType[];
/** A string giving the name of an interface this one inherits from, null otherwise. */
inheritance: string | null;
parent: null;
}
export interface InterfaceMixinType extends AbstractContainer {
type: "interface mixin";
members: IDLInterfaceMixinMemberType[];
inheritance: null;
parent: null;
}
export interface NamespaceType extends AbstractContainer {
type: "namespace";
members: IDLNamespaceMemberType[];
inheritance: null;
parent: null;
}
export interface CallbackType extends AbstractBase {
type: "callback";
/** The name of the callback. */
name: string;
/** An IDL Type describing what the callback returns. */
idlType: IDLTypeDescription;
/** A list of arguments, as in function paramters. */
arguments: Argument[];
parent: null;
}
export interface DictionaryType extends AbstractContainer {
type: "dictionary";
members: DictionaryMemberType[];
/** A string giving the name of a dictionary this one inherits from, null otherwise. */
inheritance: string | null;
parent: null;
}
export type DictionaryMemberType = FieldType;
export interface FieldType extends AbstractBase {
type: "field";
/** The name of the field. */
name: string;
/** Boolean indicating whether this is a required field. */
required: boolean;
/** An IDL Type describing what field's type. */
idlType: IDLTypeDescription;
/** A default value, absent if there is none. */
default: ValueDescription | null;
parent: DictionaryType;
}
export interface EnumType extends AbstractBase {
type: "enum";
/** The enum's name. */
name: string;
/** An array of values (strings). */
values: Array<{ type: "enum-value"; value: string; parent: EnumType }>;
/** The container of this type. */
parent: null;
}
export interface TypedefType extends AbstractBase {
type: "typedef";
/** The typedef's name. */
name: string;
/** An IDL Type describing what typedef's type. */
idlType: IDLTypeDescription;
parent: null;
}
export interface IncludesType extends AbstractBase {
type: "includes";
/** The interface that includes an interface mixin. */
target: string;
/** The interface mixin that is being included by the target. */
includes: string;
parent: null;
}
export interface ConstructorMemberType extends AbstractBase {
type: "constructor";
/** An array of arguments for the constructor operation. */
arguments: Argument[];
parent: InterfaceType;
}
export interface OperationMemberType extends AbstractBase {
type: "operation";
/** Special modifier if exists */
special: "getter" | "setter" | "deleter" | "static" | "stringifier" | null;
/** An IDL Type of what the operation returns. If a stringifier, may be absent. */
idlType: IDLTypeDescription | null;
/** The name of the operation. If a stringifier, may be null. */
name: string | null;
/** An array of arguments for the operation. */
arguments: Argument[];
parent: CallbackInterfaceType | InterfaceMixinType | InterfaceType | NamespaceType;
}
export interface AttributeMemberType extends AbstractBase {
type: "attribute";
/** The attribute's name. */
name: string;
/** Special modifier if exists */
special: "static" | "stringifier" | null;
/** True if it's an inherit attribute. */
inherit: boolean;
/** True if it's a read-only attribute. */
readonly: boolean;
/** An IDL Type for the attribute. */
idlType: IDLTypeDescription;
parent: InterfaceMixinType | InterfaceType | NamespaceType;
}
export interface ConstantMemberType extends AbstractBase {
type: "const";
/** Whether its type is nullable. */
nullable: boolean;
/** An IDL Type of the constant that represents a simple type, the type name. */
idlType: IDLTypeDescription;
/** The name of the constant. */
name: string;
/** The constant value */
value: ValueDescription;
parent: CallbackInterfaceType | InterfaceMixinType | InterfaceType;
}
interface AbstractDeclarationMemberType extends AbstractBase {
type: DeclarationMemberType["type"];
/** An array with one or more IDL Types representing the declared type arguments. */
idlType: IDLTypeDescription[];
/** Whether the iterable is declared as async. */
async: boolean;
/** Whether the maplike or setlike is declared as read only. */
readonly: boolean;
/** An array of arguments for the iterable declaration. */
arguments: Argument[];
parent: InterfaceMixinType | InterfaceType;
}
export type DeclarationMemberType =
| IterableDeclarationMemberType
| MaplikeDeclarationMemberType
| SetlikeDeclarationMemberType;
export interface IterableDeclarationMemberType extends AbstractDeclarationMemberType {
type: "iterable";
idlType: [IDLTypeDescription] | [IDLTypeDescription, IDLTypeDescription];
async: boolean;
readonly: false;
}
interface AbstractCollectionLikeMemberType extends AbstractDeclarationMemberType {
async: false;
readonly: boolean;
arguments: [];
}
export interface MaplikeDeclarationMemberType extends AbstractCollectionLikeMemberType {
type: "maplike";
idlType: [IDLTypeDescription, IDLTypeDescription];
}
export interface SetlikeDeclarationMemberType extends AbstractCollectionLikeMemberType {
type: "setlike";
idlType: [IDLTypeDescription];
}
export interface Argument extends AbstractBase {
type: "argument";
/** A default value, absent if there is none. */
default: ValueDescription | null;
/** True if the argument is optional. */
optional: boolean;
/** True if the argument is variadic. */
variadic: boolean;
/** An IDL Type describing the type of the argument. */
idlType: IDLTypeDescription;
/** The argument's name. */
name: string;
parent: CallbackType | ConstructorMemberType | ExtendedAttribute | OperationMemberType;
}
export interface ExtendedAttribute extends AbstractBase {
type: "extended-attribute";
/** The extended attribute's name. */
name: string;
/** If the extended attribute takes arguments or if its right-hand side does they are listed here. */
arguments: Argument[];
/** If there is a right-hand side, this will capture its type and value. */
rhs: ExtendedAttributeRightHandSide | null;
parent: IDLRootType | FieldType | IDLInterfaceMemberType;
}
// prettier-ignore
export type ExtendedAttributeRightHandSide =
| ExtendedAttributeRightHandSideBase
| ExtendedAttributeRightHandSideList;
export type ExtendedAttributeRightHandSideBase =
| ExtendedAttributeRightHandSideIdentifier
| ExtendedAttributeRightHandSideString
| ExtendedAttributeRightHandSideDecimal
| ExtendedAttributeRightHandSideInteger;
export type ExtendedAttributeRightHandSideList =
| ExtendedAttributeRightHandSideIdentifierList
| ExtendedAttributeRightHandSideStringList
| ExtendedAttributeRightHandSideDecimalList
| ExtendedAttributeRightHandSideIntegerList;
export interface ExtendedAttributeRightHandSideIdentifier {
type: "identifier";
value: string;
}
export interface ExtendedAttributeRightHandSideIdentifierList {
type: "identifier-list";
value: ExtendedAttributeRightHandSideIdentifier[];
}
export interface ExtendedAttributeRightHandSideString {
type: "string";
value: string;
}
export interface ExtendedAttributeRightHandSideStringList {
type: "string-list";
value: ExtendedAttributeRightHandSideString[];
}
export interface ExtendedAttributeRightHandSideDecimal {
type: "decimal";
value: string;
}
export interface ExtendedAttributeRightHandSideDecimalList {
type: "decimal-list";
value: ExtendedAttributeRightHandSideDecimal[];
}
export interface ExtendedAttributeRightHandSideInteger {
type: "integer";
value: string;
}
export interface ExtendedAttributeRightHandSideIntegerList {
type: "integer-list";
value: ExtendedAttributeRightHandSideInteger[];
}
export interface AbstractValueDescription extends AbstractBase {
parent: Argument | ConstantMemberType | FieldType;
}
export type ValueDescription =
| ValueDescriptionString
| ValueDescriptionNumber
| ValueDescriptionBoolean
| ValueDescriptionNull
| ValueDescriptionInfinity
| ValueDescriptionNaN
| ValueDescriptionSequence
| ValueDescriptionDictionary;
export interface ValueDescriptionString extends AbstractValueDescription {
type: "string";
value: string;
}
export interface ValueDescriptionNumber extends AbstractValueDescription {
type: "number";
value: string;
}
export interface ValueDescriptionBoolean extends AbstractValueDescription {
type: "boolean";
value: boolean;
}
export interface ValueDescriptionNull extends AbstractValueDescription {
type: "null";
}
export interface ValueDescriptionInfinity extends AbstractValueDescription {
type: "Infinity";
negative: boolean;
}
export interface ValueDescriptionNaN extends AbstractValueDescription {
type: "NaN";
}
export interface ValueDescriptionSequence extends AbstractValueDescription {
type: "sequence";
value: [];
}
export interface ValueDescriptionDictionary extends AbstractValueDescription {
type: "dictionary";
}
| {
"content_hash": "c6753678147c0032f2c46ece87f5bf50",
"timestamp": "",
"source": "github",
"line_count": 499,
"max_line_length": 126,
"avg_line_length": 31.248496993987978,
"alnum_prop": 0.7200666965946257,
"repo_name": "ChromeDevTools/devtools-frontend",
"id": "5b82369470f895e2e1c7eed36e0a6d100a42e202",
"size": "15593",
"binary": false,
"copies": "26",
"ref": "refs/heads/main",
"path": "node_modules/@types/webidl2/index.d.ts",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "615241"
},
{
"name": "Dart",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "317251"
},
{
"name": "JavaScript",
"bytes": "1401177"
},
{
"name": "LLVM",
"bytes": "1918"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Python",
"bytes": "133111"
},
{
"name": "Shell",
"bytes": "1122"
},
{
"name": "TypeScript",
"bytes": "15230731"
},
{
"name": "WebAssembly",
"bytes": "921"
}
],
"symlink_target": ""
} |
'use strict';
var errors = require('../../deps/errors');
var utils = require('../../utils');
var base64 = require('../../deps/binary/base64');
var btoa = base64.btoa;
var constants = require('./constants');
var readAsBinaryString = require('../../deps/binary/readAsBinaryString');
var b64StringToBlob = require('../../deps/binary/base64StringToBlobOrBuffer');
var createBlob = require('../../deps/binary/blob');
function tryCode(fun, that, args) {
try {
fun.apply(that, args);
} catch (err) { // shouldn't happen
if (typeof PouchDB !== 'undefined') {
PouchDB.emit('error', err);
}
}
}
exports.taskQueue = {
running: false,
queue: []
};
exports.applyNext = function () {
if (exports.taskQueue.running || !exports.taskQueue.queue.length) {
return;
}
exports.taskQueue.running = true;
var item = exports.taskQueue.queue.shift();
item.action(function (err, res) {
tryCode(item.callback, this, [err, res]);
exports.taskQueue.running = false;
process.nextTick(exports.applyNext);
});
};
exports.idbError = function (callback) {
return function (evt) {
var message = 'unknown_error';
if (evt.target && evt.target.error) {
message = evt.target.error.name || evt.target.error.message;
}
callback(errors.error(errors.IDB_ERROR, message, evt.type));
};
};
// Unfortunately, the metadata has to be stringified
// when it is put into the database, because otherwise
// IndexedDB can throw errors for deeply-nested objects.
// Originally we just used JSON.parse/JSON.stringify; now
// we use this custom vuvuzela library that avoids recursion.
// If we could do it all over again, we'd probably use a
// format for the revision trees other than JSON.
exports.encodeMetadata = function (metadata, winningRev, deleted) {
return {
data: utils.safeJsonStringify(metadata),
winningRev: winningRev,
deletedOrLocal: deleted ? '1' : '0',
seq: metadata.seq, // highest seq for this doc
id: metadata.id
};
};
exports.decodeMetadata = function (storedObject) {
if (!storedObject) {
return null;
}
var metadata = utils.safeJsonParse(storedObject.data);
metadata.winningRev = storedObject.winningRev;
metadata.deleted = storedObject.deletedOrLocal === '1';
metadata.seq = storedObject.seq;
return metadata;
};
// read the doc back out from the database. we don't store the
// _id or _rev because we already have _doc_id_rev.
exports.decodeDoc = function (doc) {
if (!doc) {
return doc;
}
var idx = doc._doc_id_rev.lastIndexOf(':');
doc._id = doc._doc_id_rev.substring(0, idx - 1);
doc._rev = doc._doc_id_rev.substring(idx + 1);
delete doc._doc_id_rev;
return doc;
};
// Read a blob from the database, encoding as necessary
// and translating from base64 if the IDB doesn't support
// native Blobs
exports.readBlobData = function (body, type, asBlob, callback) {
if (asBlob) {
if (!body) {
callback(createBlob([''], {type: type}));
} else if (typeof body !== 'string') { // we have blob support
callback(body);
} else { // no blob support
callback(b64StringToBlob(body, type));
}
} else { // as base64 string
if (!body) {
callback('');
} else if (typeof body !== 'string') { // we have blob support
readAsBinaryString(body, function (binary) {
callback(btoa(binary));
});
} else { // no blob support
callback(body);
}
}
};
exports.fetchAttachmentsIfNecessary = function (doc, opts, txn, cb) {
var attachments = Object.keys(doc._attachments || {});
if (!attachments.length) {
return cb && cb();
}
var numDone = 0;
function checkDone() {
if (++numDone === attachments.length && cb) {
cb();
}
}
function fetchAttachment(doc, att) {
var attObj = doc._attachments[att];
var digest = attObj.digest;
var req = txn.objectStore(constants.ATTACH_STORE).get(digest);
req.onsuccess = function (e) {
attObj.body = e.target.result.body;
checkDone();
};
}
attachments.forEach(function (att) {
if (opts.attachments && opts.include_docs) {
fetchAttachment(doc, att);
} else {
doc._attachments[att].stub = true;
checkDone();
}
});
};
// IDB-specific postprocessing necessary because
// we don't know whether we stored a true Blob or
// a base64-encoded string, and if it's a Blob it
// needs to be read outside of the transaction context
exports.postProcessAttachments = function (results, asBlob) {
return utils.Promise.all(results.map(function (row) {
if (row.doc && row.doc._attachments) {
var attNames = Object.keys(row.doc._attachments);
return utils.Promise.all(attNames.map(function (att) {
var attObj = row.doc._attachments[att];
if (!('body' in attObj)) { // already processed
return;
}
var body = attObj.body;
var type = attObj.content_type;
return new utils.Promise(function (resolve) {
exports.readBlobData(body, type, asBlob, function (data) {
row.doc._attachments[att] = utils.extend(
utils.pick(attObj, ['digest', 'content_type']),
{data: data}
);
resolve();
});
});
}));
}
}));
};
exports.compactRevs = function (revs, docId, txn) {
var possiblyOrphanedDigests = [];
var seqStore = txn.objectStore(constants.BY_SEQ_STORE);
var attStore = txn.objectStore(constants.ATTACH_STORE);
var attAndSeqStore = txn.objectStore(constants.ATTACH_AND_SEQ_STORE);
var count = revs.length;
function checkDone() {
count--;
if (!count) { // done processing all revs
deleteOrphanedAttachments();
}
}
function deleteOrphanedAttachments() {
if (!possiblyOrphanedDigests.length) {
return;
}
possiblyOrphanedDigests.forEach(function (digest) {
var countReq = attAndSeqStore.index('digestSeq').count(
IDBKeyRange.bound(
digest + '::', digest + '::\uffff', false, false));
countReq.onsuccess = function (e) {
var count = e.target.result;
if (!count) {
// orphaned
attStore.delete(digest);
}
};
});
}
revs.forEach(function (rev) {
var index = seqStore.index('_doc_id_rev');
var key = docId + "::" + rev;
index.getKey(key).onsuccess = function (e) {
var seq = e.target.result;
if (typeof seq !== 'number') {
return checkDone();
}
seqStore.delete(seq);
var cursor = attAndSeqStore.index('seq')
.openCursor(IDBKeyRange.only(seq));
cursor.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
var digest = cursor.value.digestSeq.split('::')[0];
possiblyOrphanedDigests.push(digest);
attAndSeqStore.delete(cursor.primaryKey);
cursor.continue();
} else { // done
checkDone();
}
};
};
});
};
exports.openTransactionSafely = function (idb, stores, mode) {
try {
return {
txn: idb.transaction(stores, mode)
};
} catch (err) {
return {
error: err
};
}
};
| {
"content_hash": "cf022492f8fa0b11f36f0abd0800534a",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 78,
"avg_line_length": 28.82730923694779,
"alnum_prop": 0.6232933964892727,
"repo_name": "mwksl/pouchdb",
"id": "83db1aef053ff52430d2da0c78d72f4aacdb8177",
"size": "7178",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/adapters/idb/utils.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "9709"
},
{
"name": "JavaScript",
"bytes": "2254522"
},
{
"name": "Shell",
"bytes": "10691"
}
],
"symlink_target": ""
} |
package org.apache.servicemix.store.memory;
import junit.framework.TestCase;
/**
* Test case for {@link MemoryStoreFactory}
*/
public class MemoryStoreFactoryTest extends TestCase {
private MemoryStoreFactory factory;
@Override
protected void setUp() throws Exception {
super.setUp();
factory = new MemoryStoreFactory();
}
public void testOpen() throws Exception {
assertTrue(factory.open("store1") instanceof MemoryStore);
factory.setTimeout(500);
assertTrue(factory.open("store1") instanceof MemoryStore);
assertTrue(factory.open("store2") instanceof TimeoutMemoryStore);
}
}
| {
"content_hash": "68b72a68385aca78b0b4a0e12797bde8",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 73,
"avg_line_length": 25.807692307692307,
"alnum_prop": 0.6870342771982116,
"repo_name": "apache/servicemix-utils",
"id": "4faac3864cd3d770d33590dd816b27d74d23e851",
"size": "1473",
"binary": false,
"copies": "2",
"ref": "refs/heads/trunk",
"path": "src/test/java/org/apache/servicemix/store/memory/MemoryStoreFactoryTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3644"
},
{
"name": "Java",
"bytes": "654670"
}
],
"symlink_target": ""
} |
title: OBIS - Ocean Biogeographic Information System
slug: obis-ocean-biogeographic-information-system
description: <p>A data repository for marine species datasets from all of the world's
oceans; it uses an extension of <a href="../standards/darwin-core.html">Darwin
Core</a> 2 as its data standard.</p>
website: http://iobis.org/node/304
subjects:
- life-sciences
disciplines:
- marine-science
- maritime-geography
- biogeography
- zoology
- marine-zoology
standards:
- darwin-core
layout: use_case
type: use_case
---
| {
"content_hash": "e4c37bf8e2592ff1d77d05a8e9f4a7b5",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 85,
"avg_line_length": 26.25,
"alnum_prop": 0.7638095238095238,
"repo_name": "gugek/metadata-directory",
"id": "9fbe863cdafc26ab7dad56f5e558b9abb64f861a",
"size": "529",
"binary": false,
"copies": "2",
"ref": "refs/heads/gh-pages",
"path": "use_cases/obis-ocean-biogeographic-information-system.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13804"
},
{
"name": "HTML",
"bytes": "42392"
},
{
"name": "JavaScript",
"bytes": "37269"
},
{
"name": "Ruby",
"bytes": "3087"
}
],
"symlink_target": ""
} |
/**
*
*/
package nl.wisdelft.cdf.server;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
/**
* @author Jasper Oosterman
* @created Mar 3, 2014
* @organization Delft University of Technology - Web Information Systems
*/
@Stateless
@Path("/clicktracker")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public class LinkClickedEndpoint {
@Inject
Event<LinkClicked> linkClicked;
/**
* A JPA EntityManager which is configured according to the
* {@code forge-default} persistence context defined in
* {@code /WEB-INF/persistence.xml}. Note that this field is not initialized
* by the application: it is injected by the EJB container.
*/
@PersistenceContext(unitName = "forge-default")
private EntityManager em;
@GET
@Path("/{link:.*}")
public Response get(@PathParam("link") String link, @Context HttpServletRequest request) {
try {
// get "all" info from the requester and store it
LinkClicked lnk = new LinkClicked(link);
lnk.setSessionID(request.getRequestedSessionId());
lnk.setRemoteHost(request.getRemoteHost());
lnk.setRemoteAddr(request.getRemoteAddr());
// store the link
em.persist(lnk);
// fire the event that a link has been clicked
linkClicked.fire(lnk);
URI uri = new URI(link);
return Response.temporaryRedirect(uri).build();
}
catch (URISyntaxException e) {
e.printStackTrace();
return Response.serverError().build();
}
}
}
| {
"content_hash": "7530760132fd82c80ae7e453b4c198d3",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 91,
"avg_line_length": 28.606060606060606,
"alnum_prop": 0.7489406779661016,
"repo_name": "WISDelft/AttendeeEngager",
"id": "8d5cd194cda6d5882889bf25e5dd29d36dbf5812",
"size": "1888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/nl/wisdelft/cdf/server/LinkClickedEndpoint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2144"
},
{
"name": "HTML",
"bytes": "57572"
},
{
"name": "Java",
"bytes": "151079"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Cleome icosandra L.
### Remarks
null | {
"content_hash": "040ccebe0738a9aa876be7ead82c87d2",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 10.846153846153847,
"alnum_prop": 0.7163120567375887,
"repo_name": "mdoering/backbone",
"id": "03a961299db1428a7a05e7e1ba2dca3ed781df09",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Cleomaceae/Polanisia/Polanisia icosandra/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<md-toolbar class="md-primary" layout="row" layout-padding layout-align="start center">
<h2 class="md-toolbar-tools">Todolist App</h2>
<md-button><i class="fa fa-users"></i> Logout</md-button>
</md-toolbar>
<md-toolbar layout="row" layout-padding class="md-primary md-hue-3" layout-align="start center" id="subheader">
<a href="#">Home</a><a href="#">Tasks</a>
</md-toolbar>
<md-content ng-controller="TestController as TestCtrl" id="theContent">
<md-progress-linear md-mode="indeterminate" ng-if="TestCtrl.isLoading"></md-progress-linear>
{{ TestCtrl.content }}
<md-divider></md-divider>
<md-input-container>
<label>Type your username</label>
<input type="text" ng-model="TestCtrl.username">
</md-input-container>
<md-radio-group ng-model="data.group1">
<md-radio-button value="Apple">Apple</md-radio-button>
<md-radio-button value="Banana"> Banana </md-radio-button>
<md-radio-button value="Mango">Mango</md-radio-button>
</md-radio-group>
<md-switch ng-model="data.cb1" aria-label="Switch 1">
Switch 1: {{ data.cb1 }}
</md-switch><md-divider></md-divider>
<p>Welcome, {{ TestCtrl.username }}</p>
</md-content>
| {
"content_hash": "434181fb680c8b061793f7e52c73290c",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 111,
"avg_line_length": 48.04,
"alnum_prop": 0.6627810158201499,
"repo_name": "desertlion/techtalk61",
"id": "8408960c6be1d965a0efb6eb92dd27157ce4450c",
"size": "1201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/pages/todolists.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1775"
},
{
"name": "CoffeeScript",
"bytes": "633"
},
{
"name": "HTML",
"bytes": "9522"
},
{
"name": "JavaScript",
"bytes": "10891"
},
{
"name": "Ruby",
"bytes": "21767"
}
],
"symlink_target": ""
} |
// Copyright 2017 The Bazel 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 io.bazel.rulesscala.exe;
import io.bazel.rulesscala.preconditions.Preconditions;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Metadata that describes the payload of the native launcher binary.
*
* <p>This object constructs the binary metadata lazily, to save memory.
*/
public final class LaunchInfo {
private final List<Entry> entries;
private LaunchInfo(List<Entry> entries) {
this.entries = entries;
}
/** Creates a new {@link Builder}. */
public static Builder builder() {
return new Builder();
}
/** Writes this object's entries to {@code out}, returns the total written amount in bytes. */
long write(OutputStream out) throws IOException {
long len = 0;
for (Entry e : entries) {
len += e.write(out);
out.write('\0');
++len;
}
return len;
}
/** Writes {@code s} to {@code out} encoded as UTF-8, returns the written length in bytes. */
private static long writeString(String s, OutputStream out) throws IOException {
byte[] b = s.getBytes(StandardCharsets.UTF_8);
out.write(b);
return b.length;
}
/** Represents one entry in {@link LaunchInfo.entries}. */
private interface Entry {
/** Writes this entry to {@code out}, returns the written length in bytes. */
long write(OutputStream out) throws IOException;
}
/** A key-value pair entry. */
private static final class KeyValuePair implements Entry {
private final String key;
private final String value;
public KeyValuePair(String key, String value) {
this.key = Preconditions.requireNotNull(key);
this.value = value;
}
@Override
public long write(OutputStream out) throws IOException {
long len = writeString(key, out);
len += writeString("=", out);
if (value != null && !value.isEmpty()) {
len += writeString(value, out);
}
return len;
}
}
/** A pair of a key and a delimiter-joined list of values. */
private static final class JoinedValues implements Entry {
private final String key;
private final String delimiter;
private final Iterable<String> values;
public JoinedValues(String key, String delimiter, Iterable<String> values) {
this.key = Preconditions.requireNotNull(key);
this.delimiter = Preconditions.requireNotNull(delimiter);
this.values = values;
}
@Override
public long write(OutputStream out) throws IOException {
long len = writeString(key, out);
len += writeString("=", out);
if (values != null) {
boolean first = true;
for (String v : values) {
if (first) {
first = false;
} else {
len += writeString(delimiter, out);
}
len += writeString(v, out);
}
}
return len;
}
}
/** Builder for {@link LaunchInfo} instances. */
public static final class Builder {
private List<Entry> entries = new ArrayList<>();
/** Builds a {@link LaunchInfo} from this builder. This builder may be reused. */
public LaunchInfo build() {
return new LaunchInfo(Collections.unmodifiableList(entries));
}
/**
* Adds a key-value pair entry.
*
* <p>Examples:
*
* <ul>
* <li>{@code key} is "foo" and {@code value} is "bar", the written value is "foo=bar\0"
* <li>{@code key} is "foo" and {@code value} is null or empty, the written value is "foo=\0"
* </ul>
*/
public Builder addKeyValuePair(String key, String value) {
Preconditions.requireNotNull(key);
if (!key.isEmpty()) {
entries.add(new KeyValuePair(key, value));
}
return this;
}
/**
* Adds a key and list of lazily-joined values.
*
* <p>Examples:
*
* <ul>
* <li>{@code key} is "foo", {@code delimiter} is ";", {@code values} is ["bar", "baz",
* "qux"], the written value is "foo=bar;baz;qux\0"
* <li>{@code key} is "foo", {@code delimiter} is irrelevant, {@code value} is null or empty,
* the written value is "foo=\0"
* </ul>
*/
public Builder addJoinedValues(String key, String delimiter, Iterable<String> values) {
Preconditions.requireNotNull(key);
Preconditions.requireNotNull(delimiter);
if (!key.isEmpty()) {
entries.add(new JoinedValues(key, delimiter, values));
}
return this;
}
}
}
| {
"content_hash": "0568d7bd9add8965a21e5b42acb483b8",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 99,
"avg_line_length": 30.982035928143713,
"alnum_prop": 0.6381909547738693,
"repo_name": "bazelbuild/rules_scala",
"id": "a130511c44479975ffd78a31ee11802b9c3bd923",
"size": "5174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/io/bazel/rulesscala/exe/LaunchInfo.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "101279"
},
{
"name": "Python",
"bytes": "173"
},
{
"name": "Scala",
"bytes": "134408"
},
{
"name": "Shell",
"bytes": "119167"
},
{
"name": "Starlark",
"bytes": "402942"
},
{
"name": "Thrift",
"bytes": "3441"
}
],
"symlink_target": ""
} |
var Intercept = {};
// Global variables
var inputDirection1 = null; // Stores the direction players are to move next
var inputDirection2 = null;
var speed = 4; // This is the number of pixels the player1 will move each frame
var start = false; // If the game has started or not
var gameEnded = false; // Is the Game over?
var pauseLabel;
// Set up grid coordinates the game is played on.
var grid = new Array(xTiles);
for(var i=0;i<xTiles;i++){
grid[i] = new Array(yTiles);
}
Intercept.Boot = function(game){
//No local variables needed for Boot state
};
// Declare the boot State
Intercept.Boot.prototype = {
preload: function(){
//PreLoader assets should go here
},
create: function(){
//Start the next state
this.state.start('PreLoader');
}
} | {
"content_hash": "f8067d849ddf734c8ec7b634c9c0f197",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 104,
"avg_line_length": 28.161290322580644,
"alnum_prop": 0.6151202749140894,
"repo_name": "TormundTargers/Intercept",
"id": "9e9aed88595994d91c6d678b41f07f64377ec55e",
"size": "892",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "states/Boot.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10837"
},
{
"name": "JavaScript",
"bytes": "1813"
}
],
"symlink_target": ""
} |
{-# LANGUAGE GADTs #-}
module Monitor ( Monitor
, newMonitor
, newMonitorFromSel
, updateDepth
, updateQuery
, updateFalsified
, updateProven
, updateInductive
, updateBad
, updateCounterexample
, updateInvariant
, waitFor
, Monitored
, notifyDepth
, notifyQuery
, notifyFalsified
, notifyProven
, notifyInductive
, notifyBad
, notifyCounterexample
, notifyInvariant
, DummyMonitor(..)
, Selector(..)
, dummyMonitorSel
, monitor ) where
import Control.Monad.IO.Class
import Domain
import System
import Utils.Miscellaneous
class Monitor c where
newMonitor :: MonadDomain m => System -> m c
-- use case ex: RecPdr
updateDepth :: MonadDomain m => c -> Int -> m ()
updateQuery :: MonadDomain m => c -> FunctionName -> Int -> Set m -> Set m -> m ()
updateFalsified :: MonadDomain m => c -> Maybe ([Element m], Relation m) -> m ()
updateProven :: MonadDomain m => c -> Maybe (Set m, Relation m) -> m ()
updateInductive :: MonadDomain m => c -> Bool -> m ()
-- use case ex: Pdr
updateBad :: MonadDomain m => c -> Element m -> m ()
updateCounterexample :: MonadDomain m => c -> [Element m] -> m ()
updateInvariant :: MonadDomain m => c -> Set m -> m ()
waitFor :: MonadIO m => c -> m ()
updateDepth = constM2 ()
updateQuery = constM5 ()
updateFalsified = constM2 ()
updateProven = constM2 ()
updateInductive = constM2 ()
updateBad = constM2 ()
updateCounterexample = constM2 ()
updateInvariant = constM2 ()
waitFor = constM ()
class MonadDomain m => Monitored m where
notifyDepth :: Int -> m ()
notifyQuery :: FunctionName -> Int -> Set m -> Set m -> m ()
notifyFalsified :: Maybe ([Element m], Relation m) -> m ()
notifyProven :: Maybe (Set m, Relation m) -> m ()
notifyInductive :: Bool -> m ()
notifyBad :: Element m -> m ()
notifyCounterexample :: [Element m] -> m ()
notifyInvariant :: Set m -> m ()
notifyDepth = constM ()
notifyQuery = constM4 ()
notifyFalsified = constM ()
notifyProven = constM ()
notifyInductive = constM ()
notifyBad = constM ()
notifyCounterexample = constM ()
notifyInvariant = constM ()
data Selector m where
Selector :: Monitor m => Selector m
data DummyMonitor = DummyMonitor
instance Monitor DummyMonitor where
newMonitor = constM DummyMonitor
dummyMonitorSel :: Selector DummyMonitor
dummyMonitorSel = Selector
newMonitorFromSel :: (MonadDomain d, Monitor m)
=> Selector m -> System -> d m
newMonitorFromSel _ = newMonitor
monitor :: (MonadSystem e s, Monitor m) => Selector m -> (m -> s a) -> s a
monitor sel = (getSystem >>= newMonitorFromSel sel >>=)
| {
"content_hash": "2466af2dd35bdd188fc9b6bdafd3606f",
"timestamp": "",
"source": "github",
"line_count": 110,
"max_line_length": 86,
"avg_line_length": 28.818181818181817,
"alnum_prop": 0.5479495268138801,
"repo_name": "d3sformal/bacon-core",
"id": "11433e4206cd2c5eeeeae328c1a4bb9c75cb563e",
"size": "3170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Monitor.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "167796"
}
],
"symlink_target": ""
} |
cask 'calq' do
version '1.4.6'
sha256 '3e12d3fe2aea2df0483e91081ff24558b7382bf7390b07ab9bd0b5912627ef86'
url "http://www.katoemba.net/download/Calq-#{version}.dmg.gz"
name 'Calq'
homepage 'http://www.katoemba.net/makesnosenseatall/calq/'
license :gratis
container :nested => "Calq-#{version}.dmg"
app 'Calq.app'
# This is a horrible hack to force the file extension. The
# backend code should be fixed so that this is not needed.
preflight do
system '/bin/mv', '--', staged_path.join("Calq-#{version}"), staged_path.join("Calq-#{version}.dmg")
end
zap :delete => '~/Library/Preferences/com.katoemba.calq.plist'
end
| {
"content_hash": "a8924bdfbd7c11f0390aa17c387bab11",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 104,
"avg_line_length": 31,
"alnum_prop": 0.706605222734255,
"repo_name": "williamboman/homebrew-cask",
"id": "7c61b81e07366b163ad64fbb2c38853357f2fa8a",
"size": "651",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Casks/calq.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "1860090"
},
{
"name": "Shell",
"bytes": "62151"
}
],
"symlink_target": ""
} |
#include "mbed_assert.h"
#include "serial_api.h"
#include "serial_api_hal.h"
#if DEVICE_SERIAL
#include "cmsis.h"
#include "pinmap.h"
#include <string.h>
#include "PeripheralPins.h"
#include "mbed_error.h"
#define UART_NUM (8)
static uint32_t serial_irq_ids[UART_NUM] = {0};
UART_HandleTypeDef uart_handlers[UART_NUM];
static uart_irq_handler irq_handler;
int stdio_uart_inited = 0;
serial_t stdio_uart;
void serial_init(serial_t *obj, PinName tx, PinName rx)
{
struct serial_s *obj_s = SERIAL_S(obj);
// Determine the UART to use (UART_1, UART_2, ...)
UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX);
UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX);
// Get the peripheral name (UART_1, UART_2, ...) from the pin and assign it to the object
obj_s->uart = (UARTName)pinmap_merge(uart_tx, uart_rx);
MBED_ASSERT(obj_s->uart != (UARTName)NC);
// Enable USART clock
switch (obj_s->uart) {
case UART_1:
__HAL_RCC_USART1_FORCE_RESET();
__HAL_RCC_USART1_RELEASE_RESET();
__HAL_RCC_USART1_CLK_ENABLE();
obj_s->index = 0;
break;
case UART_2:
__HAL_RCC_USART2_FORCE_RESET();
__HAL_RCC_USART2_RELEASE_RESET();
__HAL_RCC_USART2_CLK_ENABLE();
obj_s->index = 1;
break;
#if defined(USART3_BASE)
case UART_3:
__HAL_RCC_USART3_FORCE_RESET();
__HAL_RCC_USART3_RELEASE_RESET();
__HAL_RCC_USART3_CLK_ENABLE();
obj_s->index = 2;
break;
#endif
#if defined(UART4_BASE)
case UART_4:
__HAL_RCC_UART4_FORCE_RESET();
__HAL_RCC_UART4_RELEASE_RESET();
__HAL_RCC_UART4_CLK_ENABLE();
obj_s->index = 3;
break;
#endif
#if defined(UART5_BASE)
case UART_5:
__HAL_RCC_UART5_FORCE_RESET();
__HAL_RCC_UART5_RELEASE_RESET();
__HAL_RCC_UART5_CLK_ENABLE();
obj_s->index = 4;
break;
#endif
#if defined(USART6_BASE)
case UART_6:
__HAL_RCC_USART6_FORCE_RESET();
__HAL_RCC_USART6_RELEASE_RESET();
__HAL_RCC_USART6_CLK_ENABLE();
obj_s->index = 5;
break;
#endif
#if defined(UART7_BASE)
case UART_7:
__HAL_RCC_UART7_FORCE_RESET();
__HAL_RCC_UART7_RELEASE_RESET();
__HAL_RCC_UART7_CLK_ENABLE();
obj_s->index = 6;
break;
#endif
#if defined(UART8_BASE)
case UART_8:
__HAL_RCC_UART8_FORCE_RESET();
__HAL_RCC_UART8_RELEASE_RESET();
__HAL_RCC_UART8_CLK_ENABLE();
obj_s->index = 7;
break;
#endif
}
// Configure the UART pins
pinmap_pinout(tx, PinMap_UART_TX);
pinmap_pinout(rx, PinMap_UART_RX);
if (tx != NC) {
pin_mode(tx, PullUp);
}
if (rx != NC) {
pin_mode(rx, PullUp);
}
// Configure UART
obj_s->baudrate = 9600;
obj_s->databits = UART_WORDLENGTH_8B;
obj_s->stopbits = UART_STOPBITS_1;
obj_s->parity = UART_PARITY_NONE;
#if DEVICE_SERIAL_FC
obj_s->hw_flow_ctl = UART_HWCONTROL_NONE;
#endif
obj_s->pin_tx = tx;
obj_s->pin_rx = rx;
init_uart(obj);
// For stdio management
if (obj_s->uart == STDIO_UART) {
stdio_uart_inited = 1;
memcpy(&stdio_uart, obj, sizeof(serial_t));
}
}
void serial_free(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
// Reset UART and disable clock
switch (obj_s->index) {
case 0:
__USART1_FORCE_RESET();
__USART1_RELEASE_RESET();
__USART1_CLK_DISABLE();
break;
case 1:
__USART2_FORCE_RESET();
__USART2_RELEASE_RESET();
__USART2_CLK_DISABLE();
break;
#if defined(USART3_BASE)
case 2:
__USART3_FORCE_RESET();
__USART3_RELEASE_RESET();
__USART3_CLK_DISABLE();
break;
#endif
#if defined(UART4_BASE)
case 3:
__UART4_FORCE_RESET();
__UART4_RELEASE_RESET();
__UART4_CLK_DISABLE();
break;
#endif
#if defined(UART5_BASE)
case 4:
__UART5_FORCE_RESET();
__UART5_RELEASE_RESET();
__UART5_CLK_DISABLE();
break;
#endif
#if defined(USART6_BASE)
case 5:
__USART6_FORCE_RESET();
__USART6_RELEASE_RESET();
__USART6_CLK_DISABLE();
break;
#endif
#if defined(UART7_BASE)
case 6:
__UART7_FORCE_RESET();
__UART7_RELEASE_RESET();
__UART7_CLK_DISABLE();
break;
#endif
#if defined(UART8_BASE)
case 7:
__UART8_FORCE_RESET();
__UART8_RELEASE_RESET();
__UART8_CLK_DISABLE();
break;
#endif
}
// Configure GPIOs
pin_function(obj_s->pin_tx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
pin_function(obj_s->pin_rx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0));
serial_irq_ids[obj_s->index] = 0;
}
void serial_baud(serial_t *obj, int baudrate)
{
struct serial_s *obj_s = SERIAL_S(obj);
obj_s->baudrate = baudrate;
init_uart(obj);
}
/******************************************************************************
* INTERRUPTS HANDLING
******************************************************************************/
static void uart_irq(int id)
{
UART_HandleTypeDef * huart = &uart_handlers[id];
if (serial_irq_ids[id] != 0) {
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_TXE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_TXE) != RESET) {
irq_handler(serial_irq_ids[id], TxIrq);
}
}
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE) != RESET) {
irq_handler(serial_irq_ids[id], RxIrq);
/* Flag has been cleared when reading the content */
}
}
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, USART_IT_ERR) != RESET) {
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear ORE flag
}
}
}
}
static void uart1_irq(void)
{
uart_irq(0);
}
static void uart2_irq(void)
{
uart_irq(1);
}
#if defined(USART3_BASE)
static void uart3_irq(void)
{
uart_irq(2);
}
#endif
#if defined(UART4_BASE)
static void uart4_irq(void)
{
uart_irq(3);
}
#endif
#if defined(UART5_BASE)
static void uart5_irq(void)
{
uart_irq(4);
}
#endif
#if defined(USART6_BASE)
static void uart6_irq(void)
{
uart_irq(5);
}
#endif
#if defined(UART7_BASE)
static void uart7_irq(void)
{
uart_irq(6);
}
#endif
#if defined(UART8_BASE)
static void uart8_irq(void)
{
uart_irq(7);
}
#endif
void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id)
{
struct serial_s *obj_s = SERIAL_S(obj);
irq_handler = handler;
serial_irq_ids[obj_s->index] = id;
}
void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
IRQn_Type irq_n = (IRQn_Type)0;
uint32_t vector = 0;
switch (obj_s->index) {
case 0:
irq_n = USART1_IRQn;
vector = (uint32_t)&uart1_irq;
break;
case 1:
irq_n = USART2_IRQn;
vector = (uint32_t)&uart2_irq;
break;
#if defined(USART3_BASE)
case 2:
irq_n = USART3_IRQn;
vector = (uint32_t)&uart3_irq;
break;
#endif
#if defined(UART4_BASE)
case 3:
irq_n = UART4_IRQn;
vector = (uint32_t)&uart4_irq;
break;
#endif
#if defined(UART5_BASE)
case 4:
irq_n = UART5_IRQn;
vector = (uint32_t)&uart5_irq;
break;
#endif
#if defined(USART6_BASE)
case 5:
irq_n = USART6_IRQn;
vector = (uint32_t)&uart6_irq;
break;
#endif
#if defined(UART7_BASE)
case 6:
irq_n = UART7_IRQn;
vector = (uint32_t)&uart7_irq;
break;
#endif
#if defined(UART8_BASE)
case 7:
irq_n = UART8_IRQn;
vector = (uint32_t)&uart8_irq;
break;
#endif
}
if (enable) {
if (irq == RxIrq) {
__HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
} else { // TxIrq
__HAL_UART_ENABLE_IT(huart, UART_IT_TXE);
}
NVIC_SetVector(irq_n, vector);
NVIC_EnableIRQ(irq_n);
} else { // disable
int all_disabled = 0;
if (irq == RxIrq) {
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
// Check if TxIrq is disabled too
if ((huart->Instance->CR1 & USART_CR1_TXEIE) == 0) {
all_disabled = 1;
}
} else { // TxIrq
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
// Check if RxIrq is disabled too
if ((huart->Instance->CR1 & USART_CR1_RXNEIE) == 0) {
all_disabled = 1;
}
}
if (all_disabled) {
NVIC_DisableIRQ(irq_n);
}
}
}
/******************************************************************************
* READ/WRITE
******************************************************************************/
int serial_getc(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
while (!serial_readable(obj));
return (int)(huart->Instance->DR & (uint16_t)0x1FF);
}
void serial_putc(serial_t *obj, int c)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
while (!serial_writable(obj));
huart->Instance->DR = (uint32_t)(c & (uint16_t)0x1FF);
}
void serial_clear(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
huart->TxXferCount = 0;
huart->RxXferCount = 0;
}
void serial_break_set(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
HAL_LIN_SendBreak(huart);
}
#if DEVICE_SERIAL_ASYNCH
/******************************************************************************
* LOCAL HELPER FUNCTIONS
******************************************************************************/
/**
* Configure the TX buffer for an asynchronous write serial transaction
*
* @param obj The serial object.
* @param tx The buffer for sending.
* @param tx_length The number of words to transmit.
*/
static void serial_tx_buffer_set(serial_t *obj, void *tx, int tx_length, uint8_t width)
{
(void)width;
// Exit if a transmit is already on-going
if (serial_tx_active(obj)) {
return;
}
obj->tx_buff.buffer = tx;
obj->tx_buff.length = tx_length;
obj->tx_buff.pos = 0;
}
/**
* Configure the RX buffer for an asynchronous write serial transaction
*
* @param obj The serial object.
* @param tx The buffer for sending.
* @param tx_length The number of words to transmit.
*/
static void serial_rx_buffer_set(serial_t *obj, void *rx, int rx_length, uint8_t width)
{
(void)width;
// Exit if a reception is already on-going
if (serial_rx_active(obj)) {
return;
}
obj->rx_buff.buffer = rx;
obj->rx_buff.length = rx_length;
obj->rx_buff.pos = 0;
}
/**
* Configure events
*
* @param obj The serial object
* @param event The logical OR of the events to configure
* @param enable Set to non-zero to enable events, or zero to disable them
*/
static void serial_enable_event(serial_t *obj, int event, uint8_t enable)
{
struct serial_s *obj_s = SERIAL_S(obj);
// Shouldn't have to enable interrupt here, just need to keep track of the requested events.
if (enable) {
obj_s->events |= event;
} else {
obj_s->events &= ~event;
}
}
/**
* Get index of serial object TX IRQ, relating it to the physical peripheral.
*
* @param obj pointer to serial object
* @return internal NVIC TX IRQ index of U(S)ART peripheral
*/
static IRQn_Type serial_get_irq_n(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
IRQn_Type irq_n;
switch (obj_s->index) {
#if defined(USART1_BASE)
case 0:
irq_n = USART1_IRQn;
break;
#endif
#if defined(USART2_BASE)
case 1:
irq_n = USART2_IRQn;
break;
#endif
#if defined(USART3_BASE)
case 2:
irq_n = USART3_IRQn;
break;
#endif
#if defined(UART4_BASE)
case 3:
irq_n = UART4_IRQn;
break;
#endif
#if defined(UART5_BASE)
case 4:
irq_n = UART5_IRQn;
break;
#endif
#if defined(USART6_BASE)
case 5:
irq_n = USART6_IRQn;
break;
#endif
#if defined(UART7_BASE)
case 6:
irq_n = UART7_IRQn;
break;
#endif
#if defined(UART8_BASE)
case 7:
irq_n = UART8_IRQn;
break;
#endif
default:
irq_n = (IRQn_Type)0;
}
return irq_n;
}
/******************************************************************************
* MBED API FUNCTIONS
******************************************************************************/
/**
* Begin asynchronous TX transfer. The used buffer is specified in the serial
* object, tx_buff
*
* @param obj The serial object
* @param tx The buffer for sending
* @param tx_length The number of words to transmit
* @param tx_width The bit width of buffer word
* @param handler The serial handler
* @param event The logical OR of events to be registered
* @param hint A suggestion for how to use DMA with this transfer
* @return Returns number of data transfered, or 0 otherwise
*/
int serial_tx_asynch(serial_t *obj, const void *tx, size_t tx_length, uint8_t tx_width, uint32_t handler, uint32_t event, DMAUsage hint)
{
// TODO: DMA usage is currently ignored
(void) hint;
// Check buffer is ok
MBED_ASSERT(tx != (void*)0);
MBED_ASSERT(tx_width == 8); // support only 8b width
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef * huart = &uart_handlers[obj_s->index];
if (tx_length == 0) {
return 0;
}
// Set up buffer
serial_tx_buffer_set(obj, (void *)tx, tx_length, tx_width);
// Set up events
serial_enable_event(obj, SERIAL_EVENT_TX_ALL, 0); // Clear all events
serial_enable_event(obj, event, 1); // Set only the wanted events
// Enable interrupt
IRQn_Type irq_n = serial_get_irq_n(obj);
NVIC_ClearPendingIRQ(irq_n);
NVIC_DisableIRQ(irq_n);
NVIC_SetPriority(irq_n, 1);
NVIC_SetVector(irq_n, (uint32_t)handler);
NVIC_EnableIRQ(irq_n);
// the following function will enable UART_IT_TXE and error interrupts
if (HAL_UART_Transmit_IT(huart, (uint8_t*)tx, tx_length) != HAL_OK) {
return 0;
}
return tx_length;
}
/**
* Begin asynchronous RX transfer (enable interrupt for data collecting)
* The used buffer is specified in the serial object, rx_buff
*
* @param obj The serial object
* @param rx The buffer for sending
* @param rx_length The number of words to transmit
* @param rx_width The bit width of buffer word
* @param handler The serial handler
* @param event The logical OR of events to be registered
* @param handler The serial handler
* @param char_match A character in range 0-254 to be matched
* @param hint A suggestion for how to use DMA with this transfer
*/
void serial_rx_asynch(serial_t *obj, void *rx, size_t rx_length, uint8_t rx_width, uint32_t handler, uint32_t event, uint8_t char_match, DMAUsage hint)
{
// TODO: DMA usage is currently ignored
(void) hint;
/* Sanity check arguments */
MBED_ASSERT(obj);
MBED_ASSERT(rx != (void*)0);
MBED_ASSERT(rx_width == 8); // support only 8b width
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
serial_enable_event(obj, SERIAL_EVENT_RX_ALL, 0);
serial_enable_event(obj, event, 1);
// set CharMatch
obj->char_match = char_match;
serial_rx_buffer_set(obj, rx, rx_length, rx_width);
IRQn_Type irq_n = serial_get_irq_n(obj);
NVIC_ClearPendingIRQ(irq_n);
NVIC_DisableIRQ(irq_n);
NVIC_SetPriority(irq_n, 0);
NVIC_SetVector(irq_n, (uint32_t)handler);
NVIC_EnableIRQ(irq_n);
// following HAL function will enable the RXNE interrupt + error interrupts
HAL_UART_Receive_IT(huart, (uint8_t*)rx, rx_length);
}
/**
* Attempts to determine if the serial peripheral is already in use for TX
*
* @param obj The serial object
* @return Non-zero if the TX transaction is ongoing, 0 otherwise
*/
uint8_t serial_tx_active(serial_t *obj)
{
MBED_ASSERT(obj);
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
return ((HAL_UART_GetState(huart) == HAL_UART_STATE_BUSY_TX) ? 1 : 0);
}
/**
* Attempts to determine if the serial peripheral is already in use for RX
*
* @param obj The serial object
* @return Non-zero if the RX transaction is ongoing, 0 otherwise
*/
uint8_t serial_rx_active(serial_t *obj)
{
MBED_ASSERT(obj);
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
return ((HAL_UART_GetState(huart) == HAL_UART_STATE_BUSY_RX) ? 1 : 0);
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_TC) != RESET) {
__HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
}
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) {
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_PE) != RESET) {
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear PE flag
} else if (__HAL_UART_GET_FLAG(huart, UART_FLAG_FE) != RESET) {
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear FE flag
} else if (__HAL_UART_GET_FLAG(huart, UART_FLAG_NE) != RESET) {
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear NE flag
} else if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) != RESET) {
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear ORE flag
}
}
/**
* The asynchronous TX and RX handler.
*
* @param obj The serial object
* @return Returns event flags if a TX/RX transfer termination condition was met or 0 otherwise
*/
int serial_irq_handler_asynch(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
volatile int return_event = 0;
uint8_t *buf = (uint8_t*)(obj->rx_buff.buffer);
uint8_t i = 0;
// TX PART:
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_TC) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC) != RESET) {
// Return event SERIAL_EVENT_TX_COMPLETE if requested
if ((obj_s->events & SERIAL_EVENT_TX_COMPLETE ) != 0) {
return_event |= (SERIAL_EVENT_TX_COMPLETE & obj_s->events);
}
}
}
// Handle error events
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_PE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, USART_IT_ERR) != RESET) {
return_event |= (SERIAL_EVENT_RX_PARITY_ERROR & obj_s->events);
}
}
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_FE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, USART_IT_ERR) != RESET) {
return_event |= (SERIAL_EVENT_RX_FRAMING_ERROR & obj_s->events);
}
}
if (__HAL_UART_GET_FLAG(huart, UART_FLAG_ORE) != RESET) {
if (__HAL_UART_GET_IT_SOURCE(huart, USART_IT_ERR) != RESET) {
return_event |= (SERIAL_EVENT_RX_OVERRUN_ERROR & obj_s->events);
}
}
HAL_UART_IRQHandler(huart);
// Abort if an error occurs
if ((return_event & SERIAL_EVENT_RX_PARITY_ERROR) ||
(return_event & SERIAL_EVENT_RX_FRAMING_ERROR) ||
(return_event & SERIAL_EVENT_RX_OVERRUN_ERROR)) {
return return_event;
}
//RX PART
if (huart->RxXferSize != 0) {
obj->rx_buff.pos = huart->RxXferSize - huart->RxXferCount;
}
if ((huart->RxXferCount == 0) && (obj->rx_buff.pos >= (obj->rx_buff.length - 1))) {
return_event |= (SERIAL_EVENT_RX_COMPLETE & obj_s->events);
}
// Check if char_match is present
if (obj_s->events & SERIAL_EVENT_RX_CHARACTER_MATCH) {
if (buf != NULL) {
for (i = 0; i < obj->rx_buff.pos; i++) {
if (buf[i] == obj->char_match) {
obj->rx_buff.pos = i;
return_event |= (SERIAL_EVENT_RX_CHARACTER_MATCH & obj_s->events);
serial_rx_abort_asynch(obj);
break;
}
}
}
}
return return_event;
}
/**
* Abort the ongoing TX transaction. It disables the enabled interupt for TX and
* flush TX hardware buffer if TX FIFO is used
*
* @param obj The serial object
*/
void serial_tx_abort_asynch(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
__HAL_UART_DISABLE_IT(huart, UART_IT_TC);
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
// clear flags
__HAL_UART_CLEAR_FLAG(huart, UART_FLAG_TC);
// reset states
huart->TxXferCount = 0;
// update handle state
if(huart->gState == HAL_UART_STATE_BUSY_TX_RX) {
huart->gState = HAL_UART_STATE_BUSY_RX;
} else {
huart->gState = HAL_UART_STATE_READY;
}
}
/**
* Abort the ongoing RX transaction It disables the enabled interrupt for RX and
* flush RX hardware buffer if RX FIFO is used
*
* @param obj The serial object
*/
void serial_rx_abort_asynch(serial_t *obj)
{
struct serial_s *obj_s = SERIAL_S(obj);
UART_HandleTypeDef *huart = &uart_handlers[obj_s->index];
// disable interrupts
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
// clear flags
__HAL_UART_CLEAR_FLAG(huart, UART_FLAG_RXNE);
volatile uint32_t tmpval __attribute__((unused)) = huart->Instance->DR; // Clear error flags
// reset states
huart->RxXferCount = 0;
// update handle state
if(huart->RxState == HAL_UART_STATE_BUSY_TX_RX) {
huart->RxState = HAL_UART_STATE_BUSY_TX;
} else {
huart->RxState = HAL_UART_STATE_READY;
}
}
#endif
#if DEVICE_SERIAL_FC
/**
* Set HW Control Flow
* @param obj The serial object
* @param type The Control Flow type (FlowControlNone, FlowControlRTS, FlowControlCTS, FlowControlRTSCTS)
* @param rxflow Pin for the rxflow
* @param txflow Pin for the txflow
*/
void serial_set_flow_control(serial_t *obj, FlowControl type, PinName rxflow, PinName txflow)
{
struct serial_s *obj_s = SERIAL_S(obj);
// Determine the UART to use (UART_1, UART_2, ...)
UARTName uart_rts = (UARTName)pinmap_peripheral(rxflow, PinMap_UART_RTS);
UARTName uart_cts = (UARTName)pinmap_peripheral(txflow, PinMap_UART_CTS);
// Get the peripheral name (UART_1, UART_2, ...) from the pin and assign it to the object
obj_s->uart = (UARTName)pinmap_merge(uart_cts, uart_rts);
MBED_ASSERT(obj_s->uart != (UARTName)NC);
if(type == FlowControlNone) {
// Disable hardware flow control
obj_s->hw_flow_ctl = UART_HWCONTROL_NONE;
}
if (type == FlowControlRTS) {
// Enable RTS
MBED_ASSERT(uart_rts != (UARTName)NC);
obj_s->hw_flow_ctl = UART_HWCONTROL_RTS;
obj_s->pin_rts = rxflow;
// Enable the pin for RTS function
pinmap_pinout(rxflow, PinMap_UART_RTS);
}
if (type == FlowControlCTS) {
// Enable CTS
MBED_ASSERT(uart_cts != (UARTName)NC);
obj_s->hw_flow_ctl = UART_HWCONTROL_CTS;
obj_s->pin_cts = txflow;
// Enable the pin for CTS function
pinmap_pinout(txflow, PinMap_UART_CTS);
}
if (type == FlowControlRTSCTS) {
// Enable CTS & RTS
MBED_ASSERT(uart_rts != (UARTName)NC);
MBED_ASSERT(uart_cts != (UARTName)NC);
obj_s->hw_flow_ctl = UART_HWCONTROL_RTS_CTS;
obj_s->pin_rts = rxflow;
obj_s->pin_cts = txflow;
// Enable the pin for CTS function
pinmap_pinout(txflow, PinMap_UART_CTS);
// Enable the pin for RTS function
pinmap_pinout(rxflow, PinMap_UART_RTS);
}
init_uart(obj);
}
#endif
#endif
| {
"content_hash": "acfdb37292fa55bbec29c8fec0d98c99",
"timestamp": "",
"source": "github",
"line_count": 901,
"max_line_length": 151,
"avg_line_length": 27.948945615982243,
"alnum_prop": 0.5644110872845683,
"repo_name": "CalSol/mbed",
"id": "7f2389717567dad46b95dd1b017cec8708c68be1",
"size": "26951",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "targets/TARGET_STM/TARGET_STM32F2/serial_device.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "6823062"
},
{
"name": "Batchfile",
"bytes": "22"
},
{
"name": "C",
"bytes": "309708297"
},
{
"name": "C++",
"bytes": "9604357"
},
{
"name": "CMake",
"bytes": "5285"
},
{
"name": "HTML",
"bytes": "2063767"
},
{
"name": "Makefile",
"bytes": "122828"
},
{
"name": "Objective-C",
"bytes": "78797"
},
{
"name": "Perl",
"bytes": "2589"
},
{
"name": "Python",
"bytes": "1169583"
},
{
"name": "Shell",
"bytes": "70904"
},
{
"name": "XSLT",
"bytes": "5596"
}
],
"symlink_target": ""
} |
package com.wixpress.guineapig.entities.ui
case class TerminateExperimentResult(success: Boolean, specCanBeDeleted: Boolean, specKey: String)
| {
"content_hash": "a4ebf4b2252bce4809b6d562ecbf72e5",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 98,
"avg_line_length": 47.666666666666664,
"alnum_prop": 0.8461538461538461,
"repo_name": "wix/petri",
"id": "88476e359f6a2fe70c854fbad172e8e7b5c45e62",
"size": "143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "petri-backoffice-core/src/main/scala/com/wixpress/guineapig/entities/ui/TerminateExperimentResult.scala",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "166973"
},
{
"name": "HTML",
"bytes": "52557"
},
{
"name": "Java",
"bytes": "692422"
},
{
"name": "JavaScript",
"bytes": "1004602"
},
{
"name": "Scala",
"bytes": "218807"
}
],
"symlink_target": ""
} |
<!doctype html>
<html ng-app="web">
<head>
<meta charset="utf-8">
<title>web</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="../../../.tmp/serve/app/index.css" />
</head>
<body>
<div>
<div class="row header"></div>
<div class="row">
<div class="col-sm-3 left-nav">
</div>
<div class="col-sm-9 content-area"></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "7f876733cd24cb21c6adffd44e4d90ae",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 70,
"avg_line_length": 23.272727272727273,
"alnum_prop": 0.5234375,
"repo_name": "indraneelr/progbook",
"id": "eeca10fe347c5850e7fcb67a6cc4b6b62d5a0031",
"size": "512",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/app/dummy/mainpage-mockup.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2593"
},
{
"name": "HTML",
"bytes": "7437"
},
{
"name": "Java",
"bytes": "120234"
},
{
"name": "JavaScript",
"bytes": "42706"
}
],
"symlink_target": ""
} |
from django.contrib import messages
from django.utils.translation import ugettext as _
from filer.models import Clipboard
def discard_clipboard(clipboard):
clipboard.files.clear()
def discard_clipboard_files(clipboard, files):
clipboard.clipboarditem_set.filter(file__in=files).delete()
def delete_clipboard(clipboard):
for file_obj in clipboard.files.all():
file_obj.delete()
def get_user_clipboard(user):
if user.is_authenticated:
clipboard = Clipboard.objects.get_or_create(user=user)[0]
return clipboard
def move_file_to_clipboard(request, files, clipboard):
count = 0
file_names = [f.clean_actual_name for f in files]
already_existing = [
f.clean_actual_name
for f in clipboard.files.all() if f.clean_actual_name in file_names]
for file_obj in files:
if file_obj.clean_actual_name in already_existing:
messages.error(request, _('Clipboard already contains a file '
'named %s') % file_obj.clean_actual_name)
continue
if clipboard.append_file(file_obj):
file_obj.folder = None
file_obj.save()
count += 1
return count
def move_files_from_clipboard_to_folder(request, clipboard, folder):
return move_files_to_folder(request, clipboard.files.all(), folder)
def split_files_valid_for_destination(files, destination):
file_names = [f.clean_actual_name for f in files]
already_existing = [
f.clean_actual_name
for f in destination.entries_with_names(file_names)]
valid_files, invalid_files = [], []
for file_obj in files:
if file_obj.clean_actual_name in already_existing:
invalid_files.append(file_obj)
else:
valid_files.append(file_obj)
return valid_files, invalid_files
def move_files_to_folder(request, files, destination):
valid_files, invalid_files = split_files_valid_for_destination(
files, destination)
for file_obj in valid_files:
file_obj.folder = destination
file_obj.save()
for file_obj in invalid_files:
messages.error(
request, _("File or folder named %s already exists in "
"this folder.") % file_obj.clean_actual_name)
return valid_files
| {
"content_hash": "2ef21be1a53ccef98736a31e8f68f129",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 79,
"avg_line_length": 31.405405405405407,
"alnum_prop": 0.6497418244406197,
"repo_name": "pbs/django-filer",
"id": "fc750f59131ce33d4cb30e064fd8a2325031a4df",
"size": "2347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master_pbs",
"path": "filer/models/tools.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "8665"
},
{
"name": "HTML",
"bytes": "76095"
},
{
"name": "JavaScript",
"bytes": "47992"
},
{
"name": "Python",
"bytes": "757954"
},
{
"name": "Ruby",
"bytes": "799"
},
{
"name": "SCSS",
"bytes": "204269"
},
{
"name": "Shell",
"bytes": "1462"
}
],
"symlink_target": ""
} |
var prerender = require('./lib')
var server = prerender({
workers: process.env.PHANTOM_CLUSTER_NUM_WORKERS,
iterations: process.env.PHANTOM_WORKER_ITERATIONS || 10,
phantomArguments: ["--load-images=false", "--ignore-ssl-errors=true"],
phantomBasePort: process.env.PHANTOM_CLUSTER_BASE_PORT,
messageTimeout: process.env.PHANTOM_CLUSTER_MESSAGE_TIMEOUT
});
// server.use(prerender.whitelist());
server.use(prerender.blacklist());
// server.use(prerender.logger());
server.use(prerender.removeScriptTags());
server.use(prerender.httpHeaders());
// server.use(prerender.mongoCache());
// server.use(prerender.inMemoryHtmlCache());
// server.use(prerender.s3HtmlCache());
server.start();
| {
"content_hash": "b2176ad6984e4029f6be34cff425162e",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 74,
"avg_line_length": 35.35,
"alnum_prop": 0.7340876944837341,
"repo_name": "lammertw/prerender",
"id": "04e6e7c911e07b233e73e7f95e94ad7ed2dd8a5a",
"size": "707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "23494"
}
],
"symlink_target": ""
} |
.class final Landroid/app/NotificationGroup$1;
.super Ljava/lang/Object;
.source "NotificationGroup.java"
# interfaces
.implements Landroid/os/Parcelable$Creator;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/app/NotificationGroup;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x8
name = null
.end annotation
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/lang/Object;",
"Landroid/os/Parcelable$Creator",
"<",
"Landroid/app/NotificationGroup;",
">;"
}
.end annotation
# direct methods
.method constructor <init>()V
.locals 0
.prologue
.line 49
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/app/NotificationGroup;
.locals 2
.parameter "in"
.prologue
.line 51
new-instance v0, Landroid/app/NotificationGroup;
const/4 v1, 0x0
invoke-direct {v0, p1, v1}, Landroid/app/NotificationGroup;-><init>(Landroid/os/Parcel;Landroid/app/NotificationGroup$1;)V
return-object v0
.end method
.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
.locals 1
.parameter "x0"
.prologue
.line 49
invoke-virtual {p0, p1}, Landroid/app/NotificationGroup$1;->createFromParcel(Landroid/os/Parcel;)Landroid/app/NotificationGroup;
move-result-object v0
return-object v0
.end method
.method public newArray(I)[Landroid/app/NotificationGroup;
.locals 1
.parameter "size"
.prologue
.line 56
new-array v0, p1, [Landroid/app/NotificationGroup;
return-object v0
.end method
.method public bridge synthetic newArray(I)[Ljava/lang/Object;
.locals 1
.parameter "x0"
.prologue
.line 49
invoke-virtual {p0, p1}, Landroid/app/NotificationGroup$1;->newArray(I)[Landroid/app/NotificationGroup;
move-result-object v0
return-object v0
.end method
| {
"content_hash": "3a3143b87f20d01fca66c8ea23df57c9",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 132,
"avg_line_length": 22.096774193548388,
"alnum_prop": 0.7051094890510949,
"repo_name": "baidurom/devices-base_cm",
"id": "3df8ae71eb55e76872b4bb9cb7fb1f0aead6be9a",
"size": "2055",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.2",
"path": "vendor/aosp/framework.jar.out/smali/android/app/NotificationGroup$1.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12555"
}
],
"symlink_target": ""
} |
package org.openestate.is24.restapi.webapp;
| {
"content_hash": "f44dee57e358e5f851315f24c7b83a1c",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 43,
"avg_line_length": 22.5,
"alnum_prop": 0.8222222222222222,
"repo_name": "OpenEstate/OpenEstate-IS24-REST",
"id": "9e9df06a2be3442bf21342c80b97f9c22d108fc3",
"size": "649",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebApp/src/test/java/org/openestate/is24/restapi/webapp/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1098"
},
{
"name": "Java",
"bytes": "4988575"
},
{
"name": "PHP",
"bytes": "1641"
},
{
"name": "Shell",
"bytes": "14694"
}
],
"symlink_target": ""
} |
from django.shortcuts import render
from .forms import ContactForm
from django.core.mail import EmailMessage
from django.shortcuts import redirect
from django.template.loader import get_template
def main(request):
'''Главная страница сайта'''
context = {}
return render(request, 'index.html', context)
def about(request):
'''Страница "О компании"'''
context = {}
return render(request, 'about.html', context)
def signin(request):
context = {}
return render(request, 'signin.html', context)
def technical_support(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('Name', '')
contact_email = request.POST.get('Email', '')
topic = request.POST.get('Topic', '')
message = request.POST.get('Message', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'topic': topic,
'message': message,
}
content = template.render(context)
email = EmailMessage("New contact form submission", content, "Your website" + '',
['[email protected]'],
headers={'Reply-To': contact_email}
)
email.send()
return render(request, 'form_success_tech_sup.html', {'form': form_class, })
return render(request, 'technical_support.html', {'form': form_class, })
def contact(request):
form_class = ContactForm
# new logic!
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = request.POST.get('Name', '')
contact_email = request.POST.get('Email', '')
topic = request.POST.get('Topic', '')
message = request.POST.get('Message', '')
# Email the profile with the
# contact information
template = get_template('contact_template.txt')
context = {
'contact_name': contact_name,
'contact_email': contact_email,
'topic': topic,
'message': message,
}
content = template.render(context)
email = EmailMessage("New contact form submission", content, "Your website" + '',
['[email protected]'],
headers={'Reply-To': contact_email}
)
email.send()
return render(request, 'form_success_contact.html', {'form': form_class, })
return render(request, 'contact.html', {'form': form_class, })
def comment(request):
'''Страница "Отзывы"'''
context = {}
return render(request, 'comment.html', context)
| {
"content_hash": "de556465c51063c18403c46e778bc2a6",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 89,
"avg_line_length": 30.938144329896907,
"alnum_prop": 0.5608130623125624,
"repo_name": "DarkenNav/UnionFreeArts",
"id": "9057d836e2cc773f492c05c0810e5b1de5a573b6",
"size": "3052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebApp/WebSiteUnionFreeArts/main/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "924"
},
{
"name": "C#",
"bytes": "47259"
},
{
"name": "CSS",
"bytes": "160797"
},
{
"name": "HTML",
"bytes": "19319"
},
{
"name": "Java",
"bytes": "111080"
},
{
"name": "PLSQL",
"bytes": "13613"
},
{
"name": "Python",
"bytes": "14747"
}
],
"symlink_target": ""
} |
class ArticlesController < ApplicationController
http_basic_authenticate_with name: "admin", password: "admin", except: [:index, :show]
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
# Rails 会把实例变量传递给视图
# app/views/articles/show.html.erb
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
# render plain: params[:article].inspect
# 渲染 以 plain 形式,parmas hash,有一个 :article key 即 form_for 中的 :article
# parmas 中也可以获得到 URL 参数: ?name=somebody&[email protected] -> params[:somebody], parmas[:email]
# save to db
#@article = Article.new(params[:article])
#@article = Article.new(params.require(:article).permit(:title, :text))
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new' # 渲染 new 模板
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
| {
"content_hash": "dda1a1a630d95a4cc17f2ab718a977a3",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 106,
"avg_line_length": 25.24137931034483,
"alnum_prop": 0.5833333333333334,
"repo_name": "sharkspeed/dororis",
"id": "93c79d481c2a0ee82adf9934d388e641ec7fe327",
"size": "1538",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "packages/ruby/rails/beginner-blog/app/controllers/articles_controller.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Agda",
"bytes": "152"
},
{
"name": "AppleScript",
"bytes": "4936"
},
{
"name": "Assembly",
"bytes": "6654"
},
{
"name": "C",
"bytes": "568507"
},
{
"name": "C#",
"bytes": "2446"
},
{
"name": "C++",
"bytes": "15567"
},
{
"name": "CSS",
"bytes": "74090"
},
{
"name": "Clojure",
"bytes": "986"
},
{
"name": "CoffeeScript",
"bytes": "1055"
},
{
"name": "Crystal",
"bytes": "13171"
},
{
"name": "Dart",
"bytes": "22343"
},
{
"name": "Elixir",
"bytes": "27938"
},
{
"name": "Fortran",
"bytes": "400"
},
{
"name": "Go",
"bytes": "117383"
},
{
"name": "HTML",
"bytes": "780346"
},
{
"name": "Haskell",
"bytes": "33977"
},
{
"name": "Idris",
"bytes": "167"
},
{
"name": "Java",
"bytes": "105613"
},
{
"name": "JavaScript",
"bytes": "1453348"
},
{
"name": "Kotlin",
"bytes": "24078"
},
{
"name": "Lex",
"bytes": "1156"
},
{
"name": "Makefile",
"bytes": "22596"
},
{
"name": "Mako",
"bytes": "1976"
},
{
"name": "Objective-C",
"bytes": "1500"
},
{
"name": "PHP",
"bytes": "868941"
},
{
"name": "Python",
"bytes": "553417"
},
{
"name": "Racket",
"bytes": "11698"
},
{
"name": "Roff",
"bytes": "3741"
},
{
"name": "Ruby",
"bytes": "129923"
},
{
"name": "Rust",
"bytes": "27692"
},
{
"name": "Scala",
"bytes": "791"
},
{
"name": "Shell",
"bytes": "17297"
},
{
"name": "Smarty",
"bytes": "421"
},
{
"name": "Swift",
"bytes": "197600"
},
{
"name": "TeX",
"bytes": "3875"
},
{
"name": "TypeScript",
"bytes": "24815"
},
{
"name": "Vim script",
"bytes": "6936"
},
{
"name": "Vue",
"bytes": "32921"
},
{
"name": "Zig",
"bytes": "634"
}
],
"symlink_target": ""
} |
package Net::LDAP::FilterMatch;
use strict;
use Net::LDAP::Filter;
use Net::LDAP::Schema;
use vars qw($VERSION);
$VERSION = '0.17';
sub import {
shift;
push(@_, @Net::LDAP::Filter::approxMatchers) unless @_;
@Net::LDAP::Filter::approxMatchers = grep { eval "require $_" } @_ ;
}
package Net::LDAP::Filter;
use vars qw(@approxMatchers);
@approxMatchers = qw(
String::Approx
Text::Metaphone
Text::Soundex
);
sub _filterMatch($@);
sub _cis_equalityMatch($@);
sub _exact_equalityMatch($@);
sub _numeric_equalityMatch($@);
sub _cis_orderingMatch($@);
sub _numeric_orderingMatch($@);
sub _cis_greaterOrEqual($@);
sub _cis_lessOrEqual($@);
sub _cis_approxMatch($@);
sub _cis_substrings($@);
sub _exact_substrings($@);
# all known matches from the OL 2.2 schema,
*_bitStringMatch = \&_exact_equalityMatch;
*_booleanMatch = \&_cis_equalityMatch; # this might need to be reworked
*_caseExactIA5Match = \&_exact_equalityMatch;
*_caseExactIA5SubstringsMatch = \&_exact_substrings;
*_caseExactMatch = \&_exact_equalityMatch;
*_caseExactOrderingMatch = \&_exact_orderingMatch;
*_caseExactSubstringsMatch = \&_exact_substrings;
*_caseIgnoreIA5Match = \&_cis_equalityMatch;
*_caseIgnoreIA5SubstringsMatch = \&_cis_substrings;
*_caseIgnoreMatch = \&_cis_equalityMatch;
*_caseIgnoreOrderingMatch = \&_cis_orderingMatch;
*_caseIgnoreSubstringsMatch = \&_cis_substrings;
*_certificateExactMatch = \&_exact_equalityMatch;
*_certificateMatch = \&_exact_equalityMatch;
*_distinguishedNameMatch = \&_exact_equalityMatch;
*_generalizedTimeMatch = \&_exact_equalityMatch;
*_generalizedTimeOrderingMatch = \&_exact_orderingMatch;
*_integerBitAndMatch = \&_exact_equalityMatch; # this needs to be reworked
*_integerBitOrMatch = \&_exact_equalityMatch; # this needs to be reworked
*_integerFirstComponentMatch = \&_exact_equalityMatch;
*_integerMatch = \&_numeric_equalityMatch;
*_integerOrderingMatch = \&_numeric_orderingMatch;
*_numericStringMatch = \&_numeric_equalityMatch;
*_numericStringOrderingMatch = \&_numeric_orderingMatch;
*_numericStringSubstringsMatch = \&_numeric_substrings;
*_objectIdentifierFirstComponentMatch = \&_exact_equalityMatch; # this needs to be reworked
*_objectIdentifierMatch = \&_exact_equalityMatch;
*_octetStringMatch = \&_exact_equalityMatch;
*_octetStringOrderingMatch = \&_exact_orderingMatch;
*_octetStringSubstringsMatch = \&_exact_substrings;
*_telephoneNumberMatch = \&_exact_equalityMatch;
*_telephoneNumberSubstringsMatch = \&_exact_substrings;
*_uniqueMemberMatch = \&_cis_equalityMatch; # this needs to be reworked
sub match
{
my $self = shift;
my $entry = shift;
my $schema =shift;
return _filterMatch($self, $entry, $schema);
}
# map Ops to schema matches
my %op2schema = qw(
equalityMatch equality
greaterOrEqual equality
lessOrEqual ordering
approxMatch approx
substrings substr
);
sub _filterMatch($@)
{
my $filter = shift;
my $entry = shift;
my $schema = shift;
keys(%{$filter}); # re-initialize each() operator
my ($op, $args) = each(%{$filter});
# handle combined filters
if ($op eq 'and') { # '(&()...)' => fail on 1st mismatch
foreach my $subfilter (@{$args}) {
return 0 if (!_filterMatch($subfilter, $entry));
}
return 1; # all matched or '(&)' => succeed
}
if ($op eq 'or') { # '(|()...)' => succeed on 1st match
foreach my $subfilter (@{$args}) {
return 1 if (_filterMatch($subfilter, $entry));
}
return 0; # none matched or '(|)' => fail
}
if ($op eq 'not') {
return (! _filterMatch($args, $entry));
}
if ($op eq 'present') {
#return 1 if (lc($args) eq 'objectclass'); # "all match" filter
return ($entry->exists($args));
}
# handle basic filters
if ($op =~ /^(equalityMatch|greaterOrEqual|lessOrEqual|approxMatch|substrings)/o) {
my $attr;
my $assertion;
my $match;
if ($op eq 'substrings') {
$attr = $args->{'type'};
# build a regexp as assertion value
$assertion = join('.*', map { "\Q$_\E" } map { values %$_ } @{$args->{'substrings'}});
$assertion = '^'. $assertion if (exists $args->{'substrings'}[0]{'initial'});
$assertion .= '$' if (exists $args->{'substrings'}[-1]{'final'});
}
else {
$attr = $args->{'attributeDesc'};
$assertion = $args->{'assertionValue'}
}
my @values = $entry->get_value($attr);
# approx match is not standardized in schema
if ($schema and ($op ne 'approxMatch') ) {
# get matchingrule from schema, be sure that matching subs exist for every MR in your schema
$match='_' . $schema->matchingrule_for_attribute( $attr, $op2schema{$op})
or return undef;
}
else {
# fall back on build-in logic
$match='_cis_' . $op;
}
return eval( "$match".'($assertion,$op,@values)' ) ;
}
return undef; # all other filters => fail with error
}
sub _cis_equalityMatch($@)
{
my $assertion = shift;
my $op = shift;
return grep(/^\Q$assertion\E$/i, @_) ? 1 : 0;
}
sub _exact_equalityMatch($@)
{
my $assertion = shift;
my $op = shift;
return grep(/^\Q$assertion\E$/, @_) ? 1 : 0;
}
sub _numeric_equalityMatch($@)
{
my $assertion = shift;
my $op = shift;
return grep(/^\Q$assertion\E$/, @_) ? 1 : 0;
}
sub _cis_orderingMatch($@)
{
my $assertion = shift;
my $op = shift;
if ($op eq 'greaterOrEqual') {
return (grep { lc($_) ge lc($assertion) } @_) ? 1 : 0;
}
elsif ($op eq 'lessOrEqual') {
return (grep { lc($_) le lc($assertion) } @_) ? 1 : 0;
}
else {
return undef; #something went wrong
};
}
sub _exact_orderingMatch($@)
{
my $assertion = shift;
my $op = shift;
if ($op eq 'greaterOrEqual') {
return (grep { $_ ge $assertion } @_) ? 1 : 0;
}
elsif ($op eq 'lessOrEqual') {
return (grep { $_ le $assertion } @_) ? 1 : 0;
}
else {
return undef; #something went wrong
};
}
sub _numeric_orderingMatch($@)
{
my $assertion = shift;
my $op = shift;
if ($op eq 'greaterOrEqual') {
return (grep { $_ >= $assertion } @_) ? 1 : 0;
}
elsif ($op eq 'lessOrEqual') {
return (grep { $_ <= $assertion } @_) ? 1 : 0;
}
else {
return undef; #something went wrong
};
}
sub _cis_substrings($@)
{
my $regex=shift;
my $op=shift;
return 1 if ($regex =~ /^$/);
return grep(/\Q$regex\E/i, @_) ? 1 : 0;
}
sub _exact_substrings($@)
{
my $regex=shift;
my $op=shift;
return 1 if ($regex =~ /^$/);
return grep(/\Q$regex\E/, @_) ? 1 : 0;
}
# this one is here in case we don't use schema
sub _cis_greaterOrEqual($@)
{
my $assertion=shift;
my $op=shift;
if (grep(!/^-?\d+$/o, $assertion, @_)) { # numerical values only => compare numerically
return _cis_orderingMatch($assertion,$op,@_);
}
else {
return _numeric_orderingMatch($assertion,$op,@_);
}
}
*_cis_lessOrEqual = \&_cis_greaterOrEqual;
sub _cis_approxMatch($@)
{
my $assertion=shift;
my $op=shift;
foreach (@approxMatchers) {
# print "using $_\n";
if (/String::Approx/){
return String::Approx::amatch($assertion, @_) ? 1 : 0;
}
elsif (/Text::Metaphone/){
my $metamatch = Text::Metaphone::Metaphone($assertion);
return grep((Text::Metaphone::Metaphone($_) eq $metamatch), @_) ? 1 : 0;
}
elsif (/Text::Soundex/){
my $smatch = Text::Soundex::soundex($assertion);
return grep((Text::Soundex::soundex($_) eq $smatch), @_) ? 1 : 0;
}
}
#we really have nothing, use plain regexp
return 1 if ($assertion =~ /^$/);
return grep(/^$assertion$/i, @_) ? 1 : 0;
}
1;
__END__
=head1 NAME
Net::LDAP::FilterMatch - LDAP entry matching
=head1 SYNOPSIS
use Net::LDAP::Entry;
use Net::LDAP::Filter;
use Net::LDAP::FilterMatch;
my $entry = new Net::LDAP::Entry;
$entry->dn("cn=dummy entry");
$entry->add (
'cn' => 'dummy entry',
'street' => [ '1 some road','nowhere' ] );
my @filters = (qw/(cn=dummy*)
(ou=*)
(&(cn=dummy*)(street=*road))
(&(cn=dummy*)(!(street=nowhere)))/);
for (@filters) {
my $filter = Net::LDAP::Filter->new($_);
print $_,' : ', $filter->match($entry) ? 'match' : 'no match' ,"\n";
}
=head1 ABSTRACT
This extension of the class Net::LDAP::Filter provides entry matching
functionality on the Perl side.
Given an entry it will tell whether the entry matches the filter object.
It can be used on its own or as part of a Net::LDAP::Server based LDAP server.
=head1 METHOD
=over 4
=item match ( ENTRY [ ,SCHEMA ] )
Return whether ENTRY matches the filter object. If a schema object is provided,
the selection of matching algorithms will be derived from schema.
In case of error undef is returned.
=back
For approximate matching like (cn~=Schmidt) there are several modules that can
be used. By default the following modules will be tried in this order:
String::Approx
Text::Metaphone
Text::Soundex
If none of these modules is found it will fall back on a simple regexp algorithm.
If you want to specifically use one implementation only, simply do
use Net::LDAP::FilterMatch qw(Text::Soundex);
=head1 SEE ALSO
L<Net::LDAP::Filter>
=head1 COPYRIGHT
This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.
=head1 AUTHORS
Hans Klunder E<lt>[email protected]<gt>
Peter Marschall E<lt>[email protected]<gt>
=cut
# EOF
| {
"content_hash": "3d46da8ae430eee8e8021658e98f6071",
"timestamp": "",
"source": "github",
"line_count": 371,
"max_line_length": 98,
"avg_line_length": 25.38814016172507,
"alnum_prop": 0.6312772056481579,
"repo_name": "carlgao/lenga",
"id": "307fa99b472a9589f4c6ac6655a9160754b84f8c",
"size": "9692",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "images/lenny64-peon/usr/share/perl5/Net/LDAP/FilterMatch.pm",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "3281"
},
{
"name": "C#",
"bytes": "97763"
},
{
"name": "CSS",
"bytes": "39383"
},
{
"name": "Emacs Lisp",
"bytes": "6274490"
},
{
"name": "Frege",
"bytes": "463786"
},
{
"name": "IDL",
"bytes": "377510"
},
{
"name": "JavaScript",
"bytes": "1032063"
},
{
"name": "Mathematica",
"bytes": "11862"
},
{
"name": "Perl",
"bytes": "57841501"
},
{
"name": "Prolog",
"bytes": "9867"
},
{
"name": "Python",
"bytes": "10875379"
},
{
"name": "Ruby",
"bytes": "72162"
},
{
"name": "Shell",
"bytes": "22775"
},
{
"name": "Slash",
"bytes": "126702"
},
{
"name": "SystemVerilog",
"bytes": "105693"
},
{
"name": "TeX",
"bytes": "742855"
},
{
"name": "VimL",
"bytes": "1845"
},
{
"name": "XProc",
"bytes": "22962"
},
{
"name": "XSLT",
"bytes": "4075"
}
],
"symlink_target": ""
} |
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new AppBundle\AppBundle(),
new SaM\TestBundle\SaMTestBundle(),
new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function getRootDir()
{
return __DIR__;
}
public function getCacheDir()
{
return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
}
public function getLogDir()
{
return dirname(__DIR__).'/var/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
}
}
| {
"content_hash": "545028c83892e1a2bec0203c5d4562c8",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 92,
"avg_line_length": 33.21153846153846,
"alnum_prop": 0.6398378691372322,
"repo_name": "na-ringtail/gmstest",
"id": "cb6a4cff73c94979db8454fa395bfab7d59fed02",
"size": "1727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/AppKernel.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49"
},
{
"name": "HTML",
"bytes": "16528"
},
{
"name": "JavaScript",
"bytes": "3074"
},
{
"name": "PHP",
"bytes": "116003"
}
],
"symlink_target": ""
} |
require 'thor'
require 'rasana/api'
module Rasana
class CLI < Thor
attr_reader :api
map '-T' => :tasks
method_option :verbose, type: :boolean, aliases: '-v'
def initialize(*args)
super
@api = Api.new(options)
end
desc 'me', 'show your information'
def me
api.me.data.map do |k, v|
if k == 'workspaces'
puts "#{k}:"
v.map { |w| puts " - #{w.id}: '#{w.name}'" }
else
puts "#{k}: #{v}"
end
end
end
desc 'workspaces', 'all workspaces'
def workspaces
api.workspaces.data.map do |w|
puts "#{w.id}: #{w.name}"
end
end
desc 'projects', 'all projects'
def projects
api.projects.data.map do |w|
puts "#{w.id}: #{w.name}"
end
end
desc 'tags', 'all tags'
def tags
api.tags.data.map do |w|
puts "#{w.id}: #{w.name}"
end
end
desc 'tasks [--on workspace]', 'non-archived tasks'
option :on, banner: 'workspace', desc: 'tasks on specific workspace.'
long_desc <<-EOT
`asana tasks` will print out all non-archived tasks on all workspaces.
EOT
def tasks
data = options[:on] ? api.on(options[:on]).tasks.data : api.all_tasks
data.map do |t|
puts " * #{t.name}"
end
end
end
end
| {
"content_hash": "d18d31316a840c05c999ac5e32c67a59",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 75,
"avg_line_length": 21.83606557377049,
"alnum_prop": 0.53003003003003,
"repo_name": "memerelics/rasana",
"id": "6fed9c4527a3ea00f0ab8870a8320d7c35867bab",
"size": "1332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/rasana/cli.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "5986"
}
],
"symlink_target": ""
} |
@implementation Client
+ (instancetype)parseFromResultSet:(FMResultSet *)resultSet {
Client *client = [Client new];
client.registerId = @([resultSet intForColumn:@"id"]);
client.firstName = [resultSet stringForColumn:@"first_name"];
client.surname = [resultSet stringForColumn:@"surname"];
return client;
}
@end
| {
"content_hash": "fbeed62002de585fe849c8a594d61a16",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 65,
"avg_line_length": 28.25,
"alnum_prop": 0.6991150442477876,
"repo_name": "ciandtmobilestudio/iOS-DatabaseSample",
"id": "1244e8e9f2fc0d6358518da9a9851ee284888d49",
"size": "509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DatabaseSample/Database/Entities/Client.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "76519"
},
{
"name": "Ruby",
"bytes": "275"
}
],
"symlink_target": ""
} |
def main(request, response):
token = request.GET.first("token")
if request.server.stash.take(token) is not None:
return "1"
else:
return "0"
| {
"content_hash": "731268e06d25bedff2062545bda019ac",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 52,
"avg_line_length": 28.166666666666668,
"alnum_prop": 0.6094674556213018,
"repo_name": "youtube/cobalt",
"id": "3ae731052692e048a07d65a6e015fe5a76362098",
"size": "169",
"binary": false,
"copies": "164",
"ref": "refs/heads/master",
"path": "third_party/web_platform_tests/fetch/api/resources/clean-stash.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package org.apache.jena.rdfxml.xmlinput.states;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.jena.rdfxml.xmlinput.impl.AbsXMLContext ;
import org.apache.jena.rdfxml.xmlinput.impl.XMLHandler ;
import org.xml.sax.Attributes;
import org.xml.sax.SAXParseException;
public abstract class AbsXMLLiteral extends Frame {
boolean checkComposingChar = true;
static Map<String, String> xmlNameSpace = new TreeMap<>();
static {
xmlNameSpace.put("xml", xmlns);
xmlNameSpace.put("", "");
}
@Override
String suggestParsetypeLiteral() {
// shouldn't be called.
return "";
}
final protected StringBuffer rslt;
public final Map<String, String> namespaces;
private static String prefix(String qname) {
int colon = qname.indexOf(':');
return colon == -1?"":qname.substring(0,colon);
}
protected void append(String s) {
rslt.append(s);
}
private void append(char ch[], int s, int l) {
rslt.append(ch,s,l);
}
protected void append(char s) {
rslt.append(s);
}
public AbsXMLLiteral(FrameI p, AbsXMLContext x, StringBuffer r) {
super(p, x);
rslt = r;
namespaces = xmlNameSpace;
}
public AbsXMLLiteral(AbsXMLLiteral p, Map<String, String> ns) {
super(p, p.xml);
rslt = p.rslt;
namespaces = ns;
}
public AbsXMLLiteral(XMLHandler h,AbsXMLContext x) {
super(h, x);
rslt = new StringBuffer();
namespaces = xmlNameSpace;
}
private void useNameSpace(String prefix, String uri, Map<String, String> ns) {
if (!uri.equals(namespaces.get(prefix)))
ns.put(prefix, uri);
}
@Override
abstract public void endElement() throws SAXParseException;
void startLitElement(String uri, String rawName, Map<String, String> ns) {
append('<');
append(rawName);
useNameSpace(prefix(rawName),uri, ns);
}
private void appendAttrValue(String s) {
String replace;
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
switch (ch) {
case '&' :
replace = "&";
break;
case '<' :
replace = "<";
break;
case '"' :
replace = """;
break;
case 9 :
replace = "	";
break;
case 0xA :
replace = "
";
break;
case 0xD :
replace = "
";
break;
default :
replace = null;
}
if (replace != null) {
append(replace);
} else {
append(ch);
}
}
}
/** except all ampersands are replaced by &, all open angle
brackets (<) are replaced by &lt;, all closing angle brackets
(>) are replaced by &gt;, and all #xD characters are replaced
by &#xD;.
* @throws SAXParseException
*/
@Override
public void characters(char[] chrs, int start, int length) throws SAXParseException {
if (checkComposingChar)
checkComposingChar(taint,chrs, start, length);
checkComposingChar = false;
String replace;
char ch;
for (int i = 0; i < length; i++) {
ch = chrs[start+i];
switch (ch) {
case '&' :
replace = "&";
break;
case '<' :
replace = "<";
break;
case '>' :
replace = ">";
break;
case 0xD :
replace = "
";
break;
default :
replace = null;
}
if (replace != null) {
append(replace);
} else {
append(ch);
}
}
}
@Override
public void comment(char[] ch, int start, int length) throws SAXParseException {
append("<!--");
append(ch,start,length);
append("-->");
checkComposingChar = true;
}
@Override
public void processingInstruction(String target, String data) {
append("<?");
append(target);
append(' ');
append(data);
append("?>");
checkComposingChar = true;
}
@Override
public FrameI startElement(String uri, String localName, String rawName, Attributes atts) {
checkComposingChar = true;
Map<String, String> attrMap = new TreeMap<>();
Map<String, String> childNameSpaces = new TreeMap<>();
startLitElement( uri, rawName, childNameSpaces);
for (int i = atts.getLength()-1;i>=0;i--) {
String ns = atts.getURI(i);
String qname = atts.getQName(i);
String prefix = prefix(qname);
if (!prefix.equals(""))
useNameSpace(prefix,ns, childNameSpaces);
attrMap.put(qname,atts.getValue(i));
}
// At this stage, childNameSpaces contains the new visibly used
// namespaces (i.e. those not in this).
// attrMap contains the attributes
// Both are sorted correctly, so we just read them off,
// namespaces first.
Iterator<Map.Entry<String, String>> it = childNameSpaces.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
append(" xmlns");
String prefix = pair.getKey();
if (!"".equals(prefix)) {
append(':');
append(prefix);
}
append("=\"");
appendAttrValue(pair.getValue());
append('"');
}
it = attrMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
append(' ');
append(pair.getKey());
append("=\"");
appendAttrValue(pair.getValue());
append('"');
}
append('>');
// Now sort out our namespaces, so that
// child can see all of them.
if (childNameSpaces.isEmpty()) {
childNameSpaces = namespaces;
} else {
it = namespaces.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> pair = it.next();
String prefix = pair.getKey();
if (!childNameSpaces.containsKey(prefix))
childNameSpaces.put(prefix,pair.getValue());
// else prefix was overwritten with different value
}
}
return new InnerXMLLiteral(this, rawName, childNameSpaces);
}
}
| {
"content_hash": "c74caae50511413475e72e6ee172cc43",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 95,
"avg_line_length": 29.774058577405857,
"alnum_prop": 0.4991568296795953,
"repo_name": "apache/jena",
"id": "7198568ba7549c6aa02d8c4ecc3c951a15f77a69",
"size": "7921",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/states/AbsXMLLiteral.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22246"
},
{
"name": "C++",
"bytes": "5877"
},
{
"name": "CSS",
"bytes": "3241"
},
{
"name": "Dockerfile",
"bytes": "3341"
},
{
"name": "Elixir",
"bytes": "2548"
},
{
"name": "HTML",
"bytes": "69029"
},
{
"name": "Haml",
"bytes": "30030"
},
{
"name": "Java",
"bytes": "35185092"
},
{
"name": "JavaScript",
"bytes": "72788"
},
{
"name": "Lex",
"bytes": "82672"
},
{
"name": "Makefile",
"bytes": "198"
},
{
"name": "Perl",
"bytes": "35662"
},
{
"name": "Python",
"bytes": "416"
},
{
"name": "Ruby",
"bytes": "216471"
},
{
"name": "SCSS",
"bytes": "4242"
},
{
"name": "Shell",
"bytes": "264124"
},
{
"name": "Thrift",
"bytes": "3755"
},
{
"name": "Vue",
"bytes": "104702"
},
{
"name": "XSLT",
"bytes": "65126"
}
],
"symlink_target": ""
} |
package daemon // import "github.com/docker/docker/daemon"
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
cdcgroups "github.com/containerd/cgroups"
"github.com/containerd/containerd/containers"
coci "github.com/containerd/containerd/oci"
"github.com/containerd/containerd/pkg/apparmor"
"github.com/containerd/containerd/sys"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
daemonconfig "github.com/docker/docker/daemon/config"
"github.com/docker/docker/oci"
"github.com/docker/docker/oci/caps"
"github.com/docker/docker/pkg/idtools"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/rootless/specconv"
volumemounts "github.com/docker/docker/volume/mounts"
"github.com/moby/sys/mount"
"github.com/moby/sys/mountinfo"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/devices"
"github.com/opencontainers/runc/libcontainer/user"
specs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
const inContainerInitPath = "/sbin/" + daemonconfig.DefaultInitBinary
// WithRlimits sets the container's rlimits along with merging the daemon's rlimits
func WithRlimits(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
var rlimits []specs.POSIXRlimit
// We want to leave the original HostConfig alone so make a copy here
hostConfig := *c.HostConfig
// Merge with the daemon defaults
daemon.mergeUlimits(&hostConfig)
for _, ul := range hostConfig.Ulimits {
rlimits = append(rlimits, specs.POSIXRlimit{
Type: "RLIMIT_" + strings.ToUpper(ul.Name),
Soft: uint64(ul.Soft),
Hard: uint64(ul.Hard),
})
}
s.Process.Rlimits = rlimits
return nil
}
}
// WithLibnetwork sets the libnetwork hook
func WithLibnetwork(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
if s.Hooks == nil {
s.Hooks = &specs.Hooks{}
}
for _, ns := range s.Linux.Namespaces {
if ns.Type == "network" && ns.Path == "" && !c.Config.NetworkDisabled {
target := filepath.Join("/proc", strconv.Itoa(os.Getpid()), "exe")
shortNetCtlrID := stringid.TruncateID(daemon.netController.ID())
s.Hooks.Prestart = append(s.Hooks.Prestart, specs.Hook{
Path: target,
Args: []string{
"libnetwork-setkey",
"-exec-root=" + daemon.configStore.GetExecRoot(),
c.ID,
shortNetCtlrID,
},
})
}
}
return nil
}
}
// WithRootless sets the spec to the rootless configuration
func WithRootless(daemon *Daemon) coci.SpecOpts {
return func(_ context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
var v2Controllers []string
if daemon.getCgroupDriver() == cgroupSystemdDriver {
if cdcgroups.Mode() != cdcgroups.Unified {
return errors.New("rootless systemd driver doesn't support cgroup v1")
}
rootlesskitParentEUID := os.Getenv("ROOTLESSKIT_PARENT_EUID")
if rootlesskitParentEUID == "" {
return errors.New("$ROOTLESSKIT_PARENT_EUID is not set (requires RootlessKit v0.8.0)")
}
controllersPath := fmt.Sprintf("/sys/fs/cgroup/user.slice/user-%s.slice/cgroup.controllers", rootlesskitParentEUID)
controllersFile, err := ioutil.ReadFile(controllersPath)
if err != nil {
return err
}
v2Controllers = strings.Fields(string(controllersFile))
}
return specconv.ToRootless(s, v2Controllers)
}
}
// WithOOMScore sets the oom score
func WithOOMScore(score *int) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
s.Process.OOMScoreAdj = score
return nil
}
}
// WithSelinux sets the selinux labels
func WithSelinux(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
s.Process.SelinuxLabel = c.GetProcessLabel()
s.Linux.MountLabel = c.MountLabel
return nil
}
}
// WithApparmor sets the apparmor profile
func WithApparmor(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
if apparmor.HostSupports() {
var appArmorProfile string
if c.AppArmorProfile != "" {
appArmorProfile = c.AppArmorProfile
} else if c.HostConfig.Privileged {
appArmorProfile = unconfinedAppArmorProfile
} else {
appArmorProfile = defaultAppArmorProfile
}
if appArmorProfile == defaultAppArmorProfile {
// Unattended upgrades and other fun services can unload AppArmor
// profiles inadvertently. Since we cannot store our profile in
// /etc/apparmor.d, nor can we practically add other ways of
// telling the system to keep our profile loaded, in order to make
// sure that we keep the default profile enabled we dynamically
// reload it if necessary.
if err := ensureDefaultAppArmorProfile(); err != nil {
return err
}
}
s.Process.ApparmorProfile = appArmorProfile
}
return nil
}
}
// WithCapabilities sets the container's capabilties
func WithCapabilities(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
capabilities, err := caps.TweakCapabilities(
caps.DefaultCapabilities(),
c.HostConfig.CapAdd,
c.HostConfig.CapDrop,
c.HostConfig.Privileged,
)
if err != nil {
return err
}
return oci.SetCapabilities(s, capabilities)
}
}
func resourcePath(c *container.Container, getPath func() (string, error)) (string, error) {
p, err := getPath()
if err != nil {
return "", err
}
return c.GetResourcePath(p)
}
func getUser(c *container.Container, username string) (specs.User, error) {
var usr specs.User
passwdPath, err := resourcePath(c, user.GetPasswdPath)
if err != nil {
return usr, err
}
groupPath, err := resourcePath(c, user.GetGroupPath)
if err != nil {
return usr, err
}
execUser, err := user.GetExecUserPath(username, nil, passwdPath, groupPath)
if err != nil {
return usr, err
}
usr.UID = uint32(execUser.Uid)
usr.GID = uint32(execUser.Gid)
var addGroups []int
if len(c.HostConfig.GroupAdd) > 0 {
addGroups, err = user.GetAdditionalGroupsPath(c.HostConfig.GroupAdd, groupPath)
if err != nil {
return usr, err
}
}
for _, g := range append(execUser.Sgids, addGroups...) {
usr.AdditionalGids = append(usr.AdditionalGids, uint32(g))
}
return usr, nil
}
func setNamespace(s *specs.Spec, ns specs.LinuxNamespace) {
for i, n := range s.Linux.Namespaces {
if n.Type == ns.Type {
s.Linux.Namespaces[i] = ns
return
}
}
s.Linux.Namespaces = append(s.Linux.Namespaces, ns)
}
// WithNamespaces sets the container's namespaces
func WithNamespaces(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
userNS := false
// user
if c.HostConfig.UsernsMode.IsPrivate() {
uidMap := daemon.idMapping.UIDs()
if uidMap != nil {
userNS = true
ns := specs.LinuxNamespace{Type: "user"}
setNamespace(s, ns)
s.Linux.UIDMappings = specMapping(uidMap)
s.Linux.GIDMappings = specMapping(daemon.idMapping.GIDs())
}
}
// network
if !c.Config.NetworkDisabled {
ns := specs.LinuxNamespace{Type: "network"}
parts := strings.SplitN(string(c.HostConfig.NetworkMode), ":", 2)
if parts[0] == "container" {
nc, err := daemon.getNetworkedContainer(c.ID, c.HostConfig.NetworkMode.ConnectedContainer())
if err != nil {
return err
}
ns.Path = fmt.Sprintf("/proc/%d/ns/net", nc.State.GetPID())
if userNS {
// to share a net namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{Type: "user"}
nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", nc.State.GetPID())
setNamespace(s, nsUser)
}
} else if c.HostConfig.NetworkMode.IsHost() {
ns.Path = c.NetworkSettings.SandboxKey
}
setNamespace(s, ns)
}
// ipc
ipcMode := c.HostConfig.IpcMode
switch {
case ipcMode.IsContainer():
ns := specs.LinuxNamespace{Type: "ipc"}
ic, err := daemon.getIpcContainer(ipcMode.Container())
if err != nil {
return err
}
ns.Path = fmt.Sprintf("/proc/%d/ns/ipc", ic.State.GetPID())
setNamespace(s, ns)
if userNS {
// to share an IPC namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{Type: "user"}
nsUser.Path = fmt.Sprintf("/proc/%d/ns/user", ic.State.GetPID())
setNamespace(s, nsUser)
}
case ipcMode.IsHost():
oci.RemoveNamespace(s, "ipc")
case ipcMode.IsEmpty():
// A container was created by an older version of the daemon.
// The default behavior used to be what is now called "shareable".
fallthrough
case ipcMode.IsPrivate(), ipcMode.IsShareable(), ipcMode.IsNone():
ns := specs.LinuxNamespace{Type: "ipc"}
setNamespace(s, ns)
default:
return fmt.Errorf("Invalid IPC mode: %v", ipcMode)
}
// pid
if c.HostConfig.PidMode.IsContainer() {
pc, err := daemon.getPidContainer(c)
if err != nil {
return err
}
ns := specs.LinuxNamespace{
Type: "pid",
Path: fmt.Sprintf("/proc/%d/ns/pid", pc.State.GetPID()),
}
setNamespace(s, ns)
if userNS {
// to share a PID namespace, they must also share a user namespace
nsUser := specs.LinuxNamespace{
Type: "user",
Path: fmt.Sprintf("/proc/%d/ns/user", pc.State.GetPID()),
}
setNamespace(s, nsUser)
}
} else if c.HostConfig.PidMode.IsHost() {
oci.RemoveNamespace(s, "pid")
} else {
ns := specs.LinuxNamespace{Type: "pid"}
setNamespace(s, ns)
}
// uts
if c.HostConfig.UTSMode.IsHost() {
oci.RemoveNamespace(s, "uts")
s.Hostname = ""
}
// cgroup
if !c.HostConfig.CgroupnsMode.IsEmpty() {
cgroupNsMode := c.HostConfig.CgroupnsMode
if !cgroupNsMode.Valid() {
return fmt.Errorf("invalid cgroup namespace mode: %v", cgroupNsMode)
}
if cgroupNsMode.IsPrivate() {
nsCgroup := specs.LinuxNamespace{Type: "cgroup"}
setNamespace(s, nsCgroup)
}
}
return nil
}
}
func specMapping(s []idtools.IDMap) []specs.LinuxIDMapping {
var ids []specs.LinuxIDMapping
for _, item := range s {
ids = append(ids, specs.LinuxIDMapping{
HostID: uint32(item.HostID),
ContainerID: uint32(item.ContainerID),
Size: uint32(item.Size),
})
}
return ids
}
// Get the source mount point of directory passed in as argument. Also return
// optional fields.
func getSourceMount(source string) (string, string, error) {
// Ensure any symlinks are resolved.
sourcePath, err := filepath.EvalSymlinks(source)
if err != nil {
return "", "", err
}
mi, err := mountinfo.GetMounts(mountinfo.ParentsFilter(sourcePath))
if err != nil {
return "", "", err
}
if len(mi) < 1 {
return "", "", fmt.Errorf("Can't find mount point of %s", source)
}
// find the longest mount point
var idx, maxlen int
for i := range mi {
if len(mi[i].Mountpoint) > maxlen {
maxlen = len(mi[i].Mountpoint)
idx = i
}
}
return mi[idx].Mountpoint, mi[idx].Optional, nil
}
const (
sharedPropagationOption = "shared:"
slavePropagationOption = "master:"
)
// hasMountInfoOption checks if any of the passed any of the given option values
// are set in the passed in option string.
func hasMountInfoOption(opts string, vals ...string) bool {
for _, opt := range strings.Split(opts, " ") {
for _, val := range vals {
if strings.HasPrefix(opt, val) {
return true
}
}
}
return false
}
// Ensure mount point on which path is mounted, is shared.
func ensureShared(path string) error {
sourceMount, optionalOpts, err := getSourceMount(path)
if err != nil {
return err
}
// Make sure source mount point is shared.
if !hasMountInfoOption(optionalOpts, sharedPropagationOption) {
return errors.Errorf("path %s is mounted on %s but it is not a shared mount", path, sourceMount)
}
return nil
}
// Ensure mount point on which path is mounted, is either shared or slave.
func ensureSharedOrSlave(path string) error {
sourceMount, optionalOpts, err := getSourceMount(path)
if err != nil {
return err
}
if !hasMountInfoOption(optionalOpts, sharedPropagationOption, slavePropagationOption) {
return errors.Errorf("path %s is mounted on %s but it is not a shared or slave mount", path, sourceMount)
}
return nil
}
// Get the set of mount flags that are set on the mount that contains the given
// path and are locked by CL_UNPRIVILEGED. This is necessary to ensure that
// bind-mounting "with options" will not fail with user namespaces, due to
// kernel restrictions that require user namespace mounts to preserve
// CL_UNPRIVILEGED locked flags.
func getUnprivilegedMountFlags(path string) ([]string, error) {
var statfs unix.Statfs_t
if err := unix.Statfs(path, &statfs); err != nil {
return nil, err
}
// The set of keys come from https://github.com/torvalds/linux/blob/v4.13/fs/namespace.c#L1034-L1048.
unprivilegedFlags := map[uint64]string{
unix.MS_RDONLY: "ro",
unix.MS_NODEV: "nodev",
unix.MS_NOEXEC: "noexec",
unix.MS_NOSUID: "nosuid",
unix.MS_NOATIME: "noatime",
unix.MS_RELATIME: "relatime",
unix.MS_NODIRATIME: "nodiratime",
}
var flags []string
for mask, flag := range unprivilegedFlags {
if uint64(statfs.Flags)&mask == mask {
flags = append(flags, flag)
}
}
return flags, nil
}
var (
mountPropagationMap = map[string]int{
"private": mount.PRIVATE,
"rprivate": mount.RPRIVATE,
"shared": mount.SHARED,
"rshared": mount.RSHARED,
"slave": mount.SLAVE,
"rslave": mount.RSLAVE,
}
mountPropagationReverseMap = map[int]string{
mount.PRIVATE: "private",
mount.RPRIVATE: "rprivate",
mount.SHARED: "shared",
mount.RSHARED: "rshared",
mount.SLAVE: "slave",
mount.RSLAVE: "rslave",
}
)
// inSlice tests whether a string is contained in a slice of strings or not.
// Comparison is case sensitive
func inSlice(slice []string, s string) bool {
for _, ss := range slice {
if s == ss {
return true
}
}
return false
}
// WithMounts sets the container's mounts
func WithMounts(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) (err error) {
if err := daemon.setupContainerMountsRoot(c); err != nil {
return err
}
if err := daemon.setupIpcDirs(c); err != nil {
return err
}
defer func() {
if err != nil {
daemon.cleanupSecretDir(c)
}
}()
if err := daemon.setupSecretDir(c); err != nil {
return err
}
ms, err := daemon.setupMounts(c)
if err != nil {
return err
}
if !c.HostConfig.IpcMode.IsPrivate() && !c.HostConfig.IpcMode.IsEmpty() {
ms = append(ms, c.IpcMounts()...)
}
tmpfsMounts, err := c.TmpfsMounts()
if err != nil {
return err
}
ms = append(ms, tmpfsMounts...)
secretMounts, err := c.SecretMounts()
if err != nil {
return err
}
ms = append(ms, secretMounts...)
sort.Sort(mounts(ms))
mounts := ms
userMounts := make(map[string]struct{})
for _, m := range mounts {
userMounts[m.Destination] = struct{}{}
}
// Copy all mounts from spec to defaultMounts, except for
// - mounts overridden by a user supplied mount;
// - all mounts under /dev if a user supplied /dev is present;
// - /dev/shm, in case IpcMode is none.
// While at it, also
// - set size for /dev/shm from shmsize.
defaultMounts := s.Mounts[:0]
_, mountDev := userMounts["/dev"]
for _, m := range s.Mounts {
if _, ok := userMounts[m.Destination]; ok {
// filter out mount overridden by a user supplied mount
continue
}
if mountDev && strings.HasPrefix(m.Destination, "/dev/") {
// filter out everything under /dev if /dev is user-mounted
continue
}
if m.Destination == "/dev/shm" {
if c.HostConfig.IpcMode.IsNone() {
// filter out /dev/shm for "none" IpcMode
continue
}
// set size for /dev/shm mount from spec
sizeOpt := "size=" + strconv.FormatInt(c.HostConfig.ShmSize, 10)
m.Options = append(m.Options, sizeOpt)
}
defaultMounts = append(defaultMounts, m)
}
s.Mounts = defaultMounts
for _, m := range mounts {
if m.Source == "tmpfs" {
data := m.Data
parser := volumemounts.NewParser("linux")
options := []string{"noexec", "nosuid", "nodev", string(parser.DefaultPropagationMode())}
if data != "" {
options = append(options, strings.Split(data, ",")...)
}
merged, err := mount.MergeTmpfsOptions(options)
if err != nil {
return err
}
s.Mounts = append(s.Mounts, specs.Mount{Destination: m.Destination, Source: m.Source, Type: "tmpfs", Options: merged})
continue
}
mt := specs.Mount{Destination: m.Destination, Source: m.Source, Type: "bind"}
// Determine property of RootPropagation based on volume
// properties. If a volume is shared, then keep root propagation
// shared. This should work for slave and private volumes too.
//
// For slave volumes, it can be either [r]shared/[r]slave.
//
// For private volumes any root propagation value should work.
pFlag := mountPropagationMap[m.Propagation]
switch pFlag {
case mount.SHARED, mount.RSHARED:
if err := ensureShared(m.Source); err != nil {
return err
}
rootpg := mountPropagationMap[s.Linux.RootfsPropagation]
if rootpg != mount.SHARED && rootpg != mount.RSHARED {
s.Linux.RootfsPropagation = mountPropagationReverseMap[mount.SHARED]
}
case mount.SLAVE, mount.RSLAVE:
var fallback bool
if err := ensureSharedOrSlave(m.Source); err != nil {
// For backwards compatibility purposes, treat mounts from the daemon root
// as special since we automatically add rslave propagation to these mounts
// when the user did not set anything, so we should fallback to the old
// behavior which is to use private propagation which is normally the
// default.
if !strings.HasPrefix(m.Source, daemon.root) && !strings.HasPrefix(daemon.root, m.Source) {
return err
}
cm, ok := c.MountPoints[m.Destination]
if !ok {
return err
}
if cm.Spec.BindOptions != nil && cm.Spec.BindOptions.Propagation != "" {
// This means the user explicitly set a propagation, do not fallback in that case.
return err
}
fallback = true
logrus.WithField("container", c.ID).WithField("source", m.Source).Warn("Falling back to default propagation for bind source in daemon root")
}
if !fallback {
rootpg := mountPropagationMap[s.Linux.RootfsPropagation]
if rootpg != mount.SHARED && rootpg != mount.RSHARED && rootpg != mount.SLAVE && rootpg != mount.RSLAVE {
s.Linux.RootfsPropagation = mountPropagationReverseMap[mount.RSLAVE]
}
}
}
bindMode := "rbind"
if m.NonRecursive {
bindMode = "bind"
}
opts := []string{bindMode}
if !m.Writable {
opts = append(opts, "ro")
}
if pFlag != 0 {
opts = append(opts, mountPropagationReverseMap[pFlag])
}
// If we are using user namespaces, then we must make sure that we
// don't drop any of the CL_UNPRIVILEGED "locked" flags of the source
// "mount" when we bind-mount. The reason for this is that at the point
// when runc sets up the root filesystem, it is already inside a user
// namespace, and thus cannot change any flags that are locked.
if daemon.configStore.RemappedRoot != "" || sys.RunningInUserNS() {
unprivOpts, err := getUnprivilegedMountFlags(m.Source)
if err != nil {
return err
}
opts = append(opts, unprivOpts...)
}
mt.Options = opts
s.Mounts = append(s.Mounts, mt)
}
if s.Root.Readonly {
for i, m := range s.Mounts {
switch m.Destination {
case "/proc", "/dev/pts", "/dev/shm", "/dev/mqueue", "/dev":
continue
}
if _, ok := userMounts[m.Destination]; !ok {
if !inSlice(m.Options, "ro") {
s.Mounts[i].Options = append(s.Mounts[i].Options, "ro")
}
}
}
}
if c.HostConfig.Privileged {
// clear readonly for /sys
for i := range s.Mounts {
if s.Mounts[i].Destination == "/sys" {
clearReadOnly(&s.Mounts[i])
}
}
s.Linux.ReadonlyPaths = nil
s.Linux.MaskedPaths = nil
}
// TODO: until a kernel/mount solution exists for handling remount in a user namespace,
// we must clear the readonly flag for the cgroups mount (@mrunalp concurs)
if uidMap := daemon.idMapping.UIDs(); uidMap != nil || c.HostConfig.Privileged {
for i, m := range s.Mounts {
if m.Type == "cgroup" {
clearReadOnly(&s.Mounts[i])
}
}
}
return nil
}
}
// sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
// exist, so do not add the default ones if running on an old kernel.
func sysctlExists(s string) bool {
f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
_, err := os.Stat(f)
return err == nil
}
// WithCommonOptions sets common docker options
func WithCommonOptions(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
if c.BaseFS == nil {
return errors.New("populateCommonSpec: BaseFS of container " + c.ID + " is unexpectedly nil")
}
linkedEnv, err := daemon.setupLinkedContainers(c)
if err != nil {
return err
}
s.Root = &specs.Root{
Path: c.BaseFS.Path(),
Readonly: c.HostConfig.ReadonlyRootfs,
}
if err := c.SetupWorkingDirectory(daemon.idMapping.RootPair()); err != nil {
return err
}
cwd := c.Config.WorkingDir
if len(cwd) == 0 {
cwd = "/"
}
s.Process.Args = append([]string{c.Path}, c.Args...)
// only add the custom init if it is specified and the container is running in its
// own private pid namespace. It does not make sense to add if it is running in the
// host namespace or another container's pid namespace where we already have an init
if c.HostConfig.PidMode.IsPrivate() {
if (c.HostConfig.Init != nil && *c.HostConfig.Init) ||
(c.HostConfig.Init == nil && daemon.configStore.Init) {
s.Process.Args = append([]string{inContainerInitPath, "--", c.Path}, c.Args...)
path := daemon.configStore.InitPath
if path == "" {
path, err = exec.LookPath(daemonconfig.DefaultInitBinary)
if err != nil {
return err
}
}
s.Mounts = append(s.Mounts, specs.Mount{
Destination: inContainerInitPath,
Type: "bind",
Source: path,
Options: []string{"bind", "ro"},
})
}
}
s.Process.Cwd = cwd
s.Process.Env = c.CreateDaemonEnvironment(c.Config.Tty, linkedEnv)
s.Process.Terminal = c.Config.Tty
s.Hostname = c.Config.Hostname
setLinuxDomainname(c, s)
// Add default sysctls that are generally safe and useful; currently we
// grant the capabilities to allow these anyway. You can override if
// you want to restore the original behaviour.
// We do not set network sysctls if network namespace is host, or if we are
// joining an existing namespace, only if we create a new net namespace.
if c.HostConfig.NetworkMode.IsPrivate() {
// We cannot set up ping socket support in a user namespace
if !c.HostConfig.UsernsMode.IsPrivate() && sysctlExists("net.ipv4.ping_group_range") {
// allow unprivileged ICMP echo sockets without CAP_NET_RAW
s.Linux.Sysctl["net.ipv4.ping_group_range"] = "0 2147483647"
}
// allow opening any port less than 1024 without CAP_NET_BIND_SERVICE
if sysctlExists("net.ipv4.ip_unprivileged_port_start") {
s.Linux.Sysctl["net.ipv4.ip_unprivileged_port_start"] = "0"
}
}
return nil
}
}
// WithCgroups sets the container's cgroups
func WithCgroups(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
var cgroupsPath string
scopePrefix := "docker"
parent := "/docker"
useSystemd := UsingSystemd(daemon.configStore)
if useSystemd {
parent = "system.slice"
if daemon.configStore.Rootless {
parent = "user.slice"
}
}
if c.HostConfig.CgroupParent != "" {
parent = c.HostConfig.CgroupParent
} else if daemon.configStore.CgroupParent != "" {
parent = daemon.configStore.CgroupParent
}
if useSystemd {
cgroupsPath = parent + ":" + scopePrefix + ":" + c.ID
logrus.Debugf("createSpec: cgroupsPath: %s", cgroupsPath)
} else {
cgroupsPath = filepath.Join(parent, c.ID)
}
s.Linux.CgroupsPath = cgroupsPath
// the rest is only needed for CPU RT controller
if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
return nil
}
if cdcgroups.Mode() == cdcgroups.Unified {
return errors.New("daemon-scoped cpu-rt-period and cpu-rt-runtime are not implemented for cgroup v2")
}
// FIXME this is very expensive way to check if cpu rt is supported
sysInfo := daemon.RawSysInfo(true)
if !sysInfo.CPURealtime {
return errors.New("daemon-scoped cpu-rt-period and cpu-rt-runtime are not supported by the kernel")
}
p := cgroupsPath
if useSystemd {
initPath, err := cgroups.GetInitCgroup("cpu")
if err != nil {
return errors.Wrap(err, "unable to init CPU RT controller")
}
_, err = cgroups.GetOwnCgroup("cpu")
if err != nil {
return errors.Wrap(err, "unable to init CPU RT controller")
}
p = filepath.Join(initPath, s.Linux.CgroupsPath)
}
// Clean path to guard against things like ../../../BAD
parentPath := filepath.Dir(p)
if !filepath.IsAbs(parentPath) {
parentPath = filepath.Clean("/" + parentPath)
}
mnt, root, err := cgroups.FindCgroupMountpointAndRoot("", "cpu")
if err != nil {
return errors.Wrap(err, "unable to init CPU RT controller")
}
// When docker is run inside docker, the root is based of the host cgroup.
// Should this be handled in runc/libcontainer/cgroups ?
if strings.HasPrefix(root, "/docker/") {
root = "/"
}
mnt = filepath.Join(mnt, root)
if err := daemon.initCPURtController(mnt, parentPath); err != nil {
return errors.Wrap(err, "unable to init CPU RT controller")
}
return nil
}
}
// WithDevices sets the container's devices
func WithDevices(daemon *Daemon, c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
// Build lists of devices allowed and created within the container.
var devs []specs.LinuxDevice
devPermissions := s.Linux.Resources.Devices
if c.HostConfig.Privileged && !sys.RunningInUserNS() {
hostDevices, err := devices.HostDevices()
if err != nil {
return err
}
for _, d := range hostDevices {
devs = append(devs, oci.Device(d))
}
// adding device mappings in privileged containers
for _, deviceMapping := range c.HostConfig.Devices {
// issue a warning that custom cgroup permissions are ignored in privileged mode
if deviceMapping.CgroupPermissions != "rwm" {
logrus.WithField("container", c.ID).Warnf("custom %s permissions for device %s are ignored in privileged mode", deviceMapping.CgroupPermissions, deviceMapping.PathOnHost)
}
// issue a warning that the device path already exists via /dev mounting in privileged mode
if deviceMapping.PathOnHost == deviceMapping.PathInContainer {
logrus.WithField("container", c.ID).Warnf("path in container %s already exists in privileged mode", deviceMapping.PathInContainer)
continue
}
d, _, err := oci.DevicesFromPath(deviceMapping.PathOnHost, deviceMapping.PathInContainer, "rwm")
if err != nil {
return err
}
devs = append(devs, d...)
}
devPermissions = []specs.LinuxDeviceCgroup{
{
Allow: true,
Access: "rwm",
},
}
} else {
for _, deviceMapping := range c.HostConfig.Devices {
d, dPermissions, err := oci.DevicesFromPath(deviceMapping.PathOnHost, deviceMapping.PathInContainer, deviceMapping.CgroupPermissions)
if err != nil {
return err
}
devs = append(devs, d...)
devPermissions = append(devPermissions, dPermissions...)
}
var err error
devPermissions, err = oci.AppendDevicePermissionsFromCgroupRules(devPermissions, c.HostConfig.DeviceCgroupRules)
if err != nil {
return err
}
}
s.Linux.Devices = append(s.Linux.Devices, devs...)
s.Linux.Resources.Devices = devPermissions
for _, req := range c.HostConfig.DeviceRequests {
if err := daemon.handleDevice(req, s); err != nil {
return err
}
}
return nil
}
}
// WithResources applies the container resources
func WithResources(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
r := c.HostConfig.Resources
weightDevices, err := getBlkioWeightDevices(r)
if err != nil {
return err
}
readBpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceReadBps)
if err != nil {
return err
}
writeBpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceWriteBps)
if err != nil {
return err
}
readIOpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceReadIOps)
if err != nil {
return err
}
writeIOpsDevice, err := getBlkioThrottleDevices(r.BlkioDeviceWriteIOps)
if err != nil {
return err
}
memoryRes := getMemoryResources(r)
cpuRes, err := getCPUResources(r)
if err != nil {
return err
}
blkioWeight := r.BlkioWeight
specResources := &specs.LinuxResources{
Memory: memoryRes,
CPU: cpuRes,
BlockIO: &specs.LinuxBlockIO{
Weight: &blkioWeight,
WeightDevice: weightDevices,
ThrottleReadBpsDevice: readBpsDevice,
ThrottleWriteBpsDevice: writeBpsDevice,
ThrottleReadIOPSDevice: readIOpsDevice,
ThrottleWriteIOPSDevice: writeIOpsDevice,
},
Pids: getPidsLimit(r),
}
if s.Linux.Resources != nil && len(s.Linux.Resources.Devices) > 0 {
specResources.Devices = s.Linux.Resources.Devices
}
s.Linux.Resources = specResources
return nil
}
}
// WithSysctls sets the container's sysctls
func WithSysctls(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
// We merge the sysctls injected above with the HostConfig (latter takes
// precedence for backwards-compatibility reasons).
for k, v := range c.HostConfig.Sysctls {
s.Linux.Sysctl[k] = v
}
return nil
}
}
// WithUser sets the container's user
func WithUser(c *container.Container) coci.SpecOpts {
return func(ctx context.Context, _ coci.Client, _ *containers.Container, s *coci.Spec) error {
var err error
s.Process.User, err = getUser(c, c.Config.User)
return err
}
}
func (daemon *Daemon) createSpec(c *container.Container) (retSpec *specs.Spec, err error) {
var (
opts []coci.SpecOpts
s = oci.DefaultSpec()
)
opts = append(opts,
WithCommonOptions(daemon, c),
WithCgroups(daemon, c),
WithResources(c),
WithSysctls(c),
WithDevices(daemon, c),
WithUser(c),
WithRlimits(daemon, c),
WithNamespaces(daemon, c),
WithCapabilities(c),
WithSeccomp(daemon, c),
WithMounts(daemon, c),
WithLibnetwork(daemon, c),
WithApparmor(c),
WithSelinux(c),
WithOOMScore(&c.HostConfig.OomScoreAdj),
)
if c.NoNewPrivileges {
opts = append(opts, coci.WithNoNewPrivileges)
}
// Set the masked and readonly paths with regard to the host config options if they are set.
if c.HostConfig.MaskedPaths != nil {
opts = append(opts, coci.WithMaskedPaths(c.HostConfig.MaskedPaths))
}
if c.HostConfig.ReadonlyPaths != nil {
opts = append(opts, coci.WithReadonlyPaths(c.HostConfig.ReadonlyPaths))
}
if daemon.configStore.Rootless {
opts = append(opts, WithRootless(daemon))
}
return &s, coci.ApplyOpts(context.Background(), nil, &containers.Container{
ID: c.ID,
}, &s, opts...)
}
func clearReadOnly(m *specs.Mount) {
var opt []string
for _, o := range m.Options {
if o != "ro" {
opt = append(opt, o)
}
}
m.Options = opt
}
// mergeUlimits merge the Ulimits from HostConfig with daemon defaults, and update HostConfig
func (daemon *Daemon) mergeUlimits(c *containertypes.HostConfig) {
ulimits := c.Ulimits
// Merge ulimits with daemon defaults
ulIdx := make(map[string]struct{})
for _, ul := range ulimits {
ulIdx[ul.Name] = struct{}{}
}
for name, ul := range daemon.configStore.Ulimits {
if _, exists := ulIdx[name]; !exists {
ulimits = append(ulimits, ul)
}
}
c.Ulimits = ulimits
}
| {
"content_hash": "5916728e82661d58db2994e7bba500d0",
"timestamp": "",
"source": "github",
"line_count": 1075,
"max_line_length": 175,
"avg_line_length": 30.504186046511627,
"alnum_prop": 0.6809282751890705,
"repo_name": "kojiromike/docker",
"id": "5d9387611e2ab2280c5d886eebdc682a6d7649c5",
"size": "32792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "daemon/oci_linux.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "2684668"
},
{
"name": "Makefile",
"bytes": "3758"
},
{
"name": "Perl",
"bytes": "2199"
},
{
"name": "Shell",
"bytes": "198817"
},
{
"name": "VimL",
"bytes": "1317"
}
],
"symlink_target": ""
} |
What's on tap?
## Installation
gem install punky_brewster
## Command line tool
List beers:
$ punky_brewster
8 WIRED HOPWIRED $16.00/L 7.3%
ALL CHIEFS , NO INDIANS $14.00/L 6.0%
CROUCHER LOW RIDER IPA $12.00/L 2.7%
DALES ESB (EXTRA SPECIAL BITTER) $14.00/L 5.6%
...
Sort beers (can be sorted by `price`, `abv`, or `abv_per_dollar`):
$ punky_brewster --sort price
CROUCHER LOW RIDER IPA $12.00/L 2.7%
TUATARA ITI AMERICAN PALE ALE $12.50/L 5.8%
MUSSEL INN CAPTAIN COOKER $12.50/L 5.7%
VALKYRIE FRIGG RED PILSENER $13.50/L 5.0%
...
List beers sorted by most ABV per dollar:
$ punky_brewster --holla-for-dollar
MIKE'S VANILLA COFFEE PORTER $16.00/L 8.0% 0.50%/$
RAINDOGS OXYMORON BLACK IPA $14.50/L 7.0% 0.48%/$
GOLDEN EAGLE BIG YANK $16.00/L 7.5% 0.47%/$
MUSSEL INN CAPTAIN COOKER $12.50/L 5.7% 0.46%/$
...
## Ruby Library
```ruby
require 'punky_brewster'
BeerListRequest.new.beers
```
## JSON API Server
A simple `config.ru`:
```ruby
require 'punky_brewster/server'
run PunkyBrewster::Server
```
Mount alongside other Rack apps (Rails, Sinatra, etc.):
```ruby
require 'punky_brewster/server'
run Rack::URLMap.new("/punky_brewster/beers.json" => PunkyBrewster::Server)
```
Need JSONP? Use the `rack-contrib` gem:
```ruby
require 'rack/contrib/json'
require 'punky_brewster/server'
use Rack::JSONP
run PunkyBrewster::Server
```
Response:
```json
[
{
"name": "EPIC PALE ALE",
"price": 14.0,
"abv": 5.4,
"image_url": "http://www.punkybrewster.co.nz/uploads/..."
},
...
]
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
1. Fork it ( https://github.com/Aupajo/punky_brewster/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
| {
"content_hash": "25d73c1d162e6a67854d0016bc71b1df",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 315,
"avg_line_length": 26.305263157894736,
"alnum_prop": 0.6410564225690276,
"repo_name": "Aupajo/punky_brewster",
"id": "e34518e58c558001f435fc294062a86119314761",
"size": "2528",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "12799"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
package com.armadialogcreator.gui.main.controlPropertiesEditor;
import com.armadialogcreator.ArmaDialogCreator;
import com.armadialogcreator.core.sv.SVFileName;
import com.armadialogcreator.gui.fxcontrol.FileChooserPane;
import com.armadialogcreator.lang.Lang;
import com.armadialogcreator.util.ReadOnlyValueObserver;
import com.armadialogcreator.util.ValueObserver;
import javafx.scene.Node;
import javafx.scene.layout.StackPane;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ResourceBundle;
/**
A ValueEditor implementation for selecting files
@author Kayler
@since 06/27/2017. */
public class FileNameValueEditor implements ValueEditor<SVFileName> {
private final ResourceBundle bundle = Lang.ApplicationBundle();
protected final FileChooserPane chooserPane = new FileChooserPane(
ArmaDialogCreator.getPrimaryStage(),
FileChooserPane.ChooserType.FILE,
bundle.getString("ValueEditors.FileNameValueEditor.locate_file"),
null
);
private final StackPane masterPane = new StackPane(chooserPane);
private final ValueObserver<SVFileName> valueObserver = new ValueObserver<>(null);
public FileNameValueEditor() {
chooserPane.getChosenFileObserver().addListener((observer, oldValue, newValue) -> {
if (newValue == null) {
valueObserver.updateValue(null);
} else {
valueObserver.updateValue(new SVFileName(newValue));
}
});
}
@Override
public void submitCurrentData() {
}
@Override
@Nullable
public SVFileName getValue() {
return valueObserver.getValue();
}
@Override
public void setValue(SVFileName val) {
valueObserver.updateValue(val);
if (val == null) {
chooserPane.setChosenFile(null);
} else {
chooserPane.setChosenFile(val.getFile());
}
}
@Override
public @NotNull Node getRootNode() {
return masterPane;
}
@Override
public void focusToEditor() {
chooserPane.requestFocus();
}
@NotNull
@Override
public ReadOnlyValueObserver<SVFileName> getReadOnlyObserver() {
return valueObserver.getReadOnlyValueObserver();
}
@Override
public boolean displayFullWidth() {
return true;
}
}
| {
"content_hash": "4eb47205f9c263ce81c23d2d01d8845a",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 85,
"avg_line_length": 24.57471264367816,
"alnum_prop": 0.7736202057998129,
"repo_name": "kayler-renslow/arma-dialog-creator",
"id": "2979faad3a38ae2f8a6617a224a53fd0962fc866",
"size": "2138",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/armadialogcreator/gui/main/controlPropertiesEditor/FileNameValueEditor.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "12522"
},
{
"name": "C",
"bytes": "356"
},
{
"name": "C++",
"bytes": "2569"
},
{
"name": "CSS",
"bytes": "3252"
},
{
"name": "Java",
"bytes": "1919709"
}
],
"symlink_target": ""
} |
namespace filesystem {
namespace {
const char kUserDataDir[] = "user-data-dir";
} // namespace filesystem
FileSystemApp::FileSystemApp() : lock_table_(new LockTable) {}
FileSystemApp::~FileSystemApp() {}
void FileSystemApp::Initialize(mojo::Connector* connector,
const mojo::Identity& identity,
uint32_t id) {
tracing_.Initialize(connector, identity.name());
}
bool FileSystemApp::AcceptConnection(mojo::Connection* connection) {
connection->AddInterface<FileSystem>(this);
return true;
}
// |InterfaceFactory<Files>| implementation:
void FileSystemApp::Create(mojo::Connection* connection,
mojo::InterfaceRequest<FileSystem> request) {
new FileSystemImpl(connection, std::move(request), GetUserDataDir(),
lock_table_);
}
//static
base::FilePath FileSystemApp::GetUserDataDir() {
base::FilePath path;
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(kUserDataDir)) {
path = command_line->GetSwitchValuePath(kUserDataDir);
} else {
#if defined(OS_WIN)
CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &path));
#elif defined(OS_MACOSX)
CHECK(PathService::Get(base::DIR_APP_DATA, &path));
#elif defined(OS_ANDROID)
CHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &path));
#elif defined(OS_LINUX)
scoped_ptr<base::Environment> env(base::Environment::Create());
path = base::nix::GetXDGDirectory(env.get(),
base::nix::kXdgConfigHomeEnvVar,
base::nix::kDotConfigDir);
#else
NOTIMPLEMENTED();
#endif
path = path.Append(FILE_PATH_LITERAL("filesystem"));
}
if (!base::PathExists(path))
base::CreateDirectory(path);
return path;
}
} // namespace filesystem
| {
"content_hash": "c4624a40f98c70956a58c9a8f517654c",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 75,
"avg_line_length": 30.032258064516128,
"alnum_prop": 0.6530612244897959,
"repo_name": "was4444/chromium.src",
"id": "92f78b7aa68e29a671bc7a87597b820a59da5771",
"size": "2680",
"binary": false,
"copies": "1",
"ref": "refs/heads/nw15",
"path": "components/filesystem/file_system_app.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
require 'rails_helper'
RSpec.describe Card, :type => :model do
context "validations" do
it { should validate_presence_of(:title) }
it { should validate_presence_of(:trello_board_id) }
it { should validate_presence_of(:trello_list_id) }
it { should validate_presence_of(:frequency) }
it { should validate_inclusion_of(:frequency).in_array(Card::FREQUENCY.values) }
it "does not need :frequency_period if the frequency is 'Daily'" do
card = FactoryGirl.build(:card, frequency: Card::FREQUENCY['Daily'], frequency_period: nil)
expect(card).to be_valid
end
it "validates the presence of :frequency_period if the frequency is 'Weekly'" do
card = FactoryGirl.build(:card, frequency: Card::FREQUENCY['Weekly'], frequency_period: nil)
expect(card).to_not be_valid
card.frequency_period = 1
expect(card).to be_valid
end
it "validates the presence of :frequency_period if the frequency is 'Monthly'" do
card = FactoryGirl.build(:card, frequency: Card::FREQUENCY['Monthly'], frequency_period: nil)
expect(card).to_not be_valid
card.frequency_period = 1
expect(card).to be_valid
end
it "does not need :frequency_period if the frequency is 'Weekdays'" do
card = FactoryGirl.build(:card, frequency: Card::FREQUENCY['Weekdays'], frequency_period: nil)
expect(card).to be_valid
end
it "does not need :frequency_period if the frequency is 'Weekends'" do
card = FactoryGirl.build(:card, frequency: Card::FREQUENCY['Weekends'], frequency_period: nil)
expect(card).to be_valid
end
end
describe "callbacks" do
context "#track_card_creation_event" do
let(:user) { FactoryGirl.create(:user) }
it "enqueues a job to send card information to our analytics" do
expect(SendAnalyticsEventWorker).to receive(:perform_async).with(event: "Card created", user_id: user.id, properties: { frequency: "Weekdays" })
FactoryGirl.create(:card, :weekdays, user: user)
end
it "adds a frequency_period property to the job if it's set on the card" do
expect(SendAnalyticsEventWorker).to receive(:perform_async).with(hash_including(properties: { frequency: "Weekly", frequency_period: 4 }))
FactoryGirl.create(:card, :weekly, frequency_period: 4)
end
it "only enqueues the job on creation" do
card = FactoryGirl.create(:card, :weekdays)
expect(SendAnalyticsEventWorker).to_not receive(:perform_async)
card.update_attributes(title: "New title")
end
end
end
describe "#trello_api_parameters" do
it "returns the necessary parameters for creating a card through the Trello API" do
card = FactoryGirl.build(:card, title: "Trello Card", description: "Echo for Trello is awesome!")
api_params = card.trello_api_parameters
expect(api_params[:name]).to eq("Trello Card")
expect(api_params[:desc]).to eq("Echo for Trello is awesome!")
expect(api_params[:due]).to be_nil
end
end
describe "#set_next_run" do
before(:each) do
Timecop.freeze(Time.new(2015, 1, 21, 12, 0, 0)) # Wednesday
end
after(:each) do
Timecop.return
end
context "for daily cards" do
it "sets the next run to the next day if the frequency period is daily" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Daily'])
card.set_next_run
expect(card.next_run.day).to eq(22)
end
end
context "for weekly cards" do
it "sets the next run to the day of the selected weekday for the same week" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekly'], frequency_period: Date::DAYNAMES.index("Saturday"))
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Saturday"))
expect(card.next_run.day).to eq(24)
end
it "sets the next run to the day of the selected weekday for the next week if the weekday already passed" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekly'], frequency_period: Date::DAYNAMES.index("Monday"))
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Monday"))
expect(card.next_run.day).to eq(26)
end
it "properly sets the next run for the following day if set_next_run is run on the same day" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekly'], frequency_period: Date::DAYNAMES.index("Wednesday"))
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Wednesday"))
expect(card.next_run.day).to eq(28)
end
end
context "for monthly cards" do
it "sets the next run to the selected day of this month if the day has not passed" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Monthly'], frequency_period: 28)
card.set_next_run
expect(card.next_run.month).to eq(1)
expect(card.next_run.day).to eq(28)
end
it "sets the next run to the selected day of the next month if the day has already passed" do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Monthly'], frequency_period: 5)
card.set_next_run
expect(card.next_run.month).to eq(2)
expect(card.next_run.day).to eq(5)
end
it "sets the next run to the last day of the month if the selected day is greater than the last day of the month" do
Timecop.freeze(Time.new(2015, 1, 31, 12, 0, 0)) do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Monthly'], frequency_period: 30)
card.set_next_run
expect(card.next_run.month).to eq(2)
expect(card.next_run.day).to eq(28)
end
end
end
context "for weekday cards" do
it "sets the next run to the next day if the next day is a weekday" do
# January 28, 2015 == Wednesday
Timecop.freeze(Time.new(2015, 1, 28, 12, 0, 0)) do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekdays'])
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Thursday"))
expect(card.next_run.day).to eq(29)
end
end
it "sets the next run to the following Monday if the next day is a weekend" do
# January 23, 2015 == Friday
Timecop.freeze(Time.new(2015, 1, 23, 12, 0, 0)) do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekdays'])
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Monday"))
expect(card.next_run.day).to eq(26)
end
end
end
context "for weekend cards" do
it "sets the next run to the next day if the next day is a weekend" do
# January 24, 2015 == Saturday
Timecop.freeze(Time.new(2015, 1, 24, 12, 0, 0)) do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekends'])
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Sunday"))
expect(card.next_run.day).to eq(25)
end
end
it "sets the next run to the following Saturday if the next day is a weekday" do
# January 25, 2015 == Sunday
Timecop.freeze(Time.new(2015, 1, 25, 12, 0, 0)) do
card = FactoryGirl.create(:card, frequency: Card::FREQUENCY['Weekends'])
card.set_next_run
expect(card.next_run.wday).to eq(Date::DAYNAMES.index("Saturday"))
expect(card.next_run.day).to eq(31)
end
end
end
end
describe "#daily?" do
it "returns true if the card frequency is daily" do
card = FactoryGirl.build(:card)
expect(card.daily?).to be_truthy
end
it "returns false if the card frequency is not daily" do
card = FactoryGirl.build(:card, :weekly)
expect(card.daily?).to be_falsey
end
end
describe "#weekly?" do
it "returns true if the card frequency is weekly" do
card = FactoryGirl.build(:card, :weekly)
expect(card.weekly?).to be_truthy
end
it "returns false if the card frequency is not weekly" do
card = FactoryGirl.build(:card)
expect(card.weekly?).to be_falsey
end
end
describe "#monthly?" do
it "returns true if the card frequency is monthly" do
card = FactoryGirl.build(:card, :monthly)
expect(card.monthly?).to be_truthy
end
it "returns false if the card frequency is not monthly" do
card = FactoryGirl.build(:card, :weekly)
expect(card.monthly?).to be_falsey
end
end
describe "#disable!" do
let!(:card) { FactoryGirl.create(:card, next_run: 1.day.from_now) }
it "sets the `disabled` field to true" do
expect {
card.disable!
}.to change(card, :disabled).from(false).to(true)
end
it "sets the `next_run` field to nil" do
expect {
card.disable!
}.to change(card, :next_run).to(nil)
end
end
describe "#clear_failed_attempts!" do
it "resets the failed_attempts counter to zero" do
card = FactoryGirl.create(:card, failed_attempts: 2)
expect {
card.clear_failed_attempts!
}.to change(card, :failed_attempts).from(2).to(0)
end
end
describe "#increment_failed_attempts!" do
it "increments the failed_attempts counter" do
card = FactoryGirl.create(:card, failed_attempts: 1)
expect {
card.increment_failed_attempts!
}.to change(card, :failed_attempts).from(1).to(2)
end
end
describe ".create_pending_trello_cards" do
before(:all) do
Timecop.freeze
end
after(:all) do
Timecop.return
end
before(:each) do
allow(Snitcher).to receive(:snitch)
end
it "finds all cards where next_run is due and calls the async task to create the cards" do
card_1 = FactoryGirl.create(:card, next_run: 1.hour.ago)
card_2 = FactoryGirl.create(:card, next_run: 30.minutes.ago)
card_3 = FactoryGirl.create(:card, next_run: 1.day.from_now)
expect(CreateTrelloCardWorker).to receive(:perform_async).with(card_1.user_id, card_1.id)
expect(CreateTrelloCardWorker).to receive(:perform_async).with(card_2.user_id, card_2.id)
expect(CreateTrelloCardWorker).to_not receive(:perform_async).with(card_3.user_id, card_3.id)
Card.create_pending_trello_cards
end
it "does not call the async task to create a card if the card is disabled" do
card = FactoryGirl.create(:card, next_run: 1.hour.ago, disabled: true)
expect(CreateTrelloCardWorker).to_not receive(:perform_async).with(card.user_id, card.id)
Card.create_pending_trello_cards
end
it "pings Dead Man's Snitch" do
expect(Snitcher).to receive(:snitch)
Card.create_pending_trello_cards
end
end
end
| {
"content_hash": "9e688ddf7e0e068efd1a7337f8f4f1ce",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 152,
"avg_line_length": 37.54827586206896,
"alnum_prop": 0.6500137753696391,
"repo_name": "dennmart/echo_for_trello",
"id": "81f6cbbfa69f02a76ed8be4f9ea7e7d2ebf86c69",
"size": "10889",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/models/card_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4013"
},
{
"name": "CoffeeScript",
"bytes": "3671"
},
{
"name": "HTML",
"bytes": "50798"
},
{
"name": "JavaScript",
"bytes": "5749"
},
{
"name": "Ruby",
"bytes": "94312"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics.CodeAnalysis;
namespace PutridParrot.Delimited.Data.Exceptions
{
[Serializable, ExcludeFromCodeCoverage]
public class DelimitedStreamWriterException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public DelimitedStreamWriterException() { }
public DelimitedStreamWriterException(string message) : base(message) { }
public DelimitedStreamWriterException(string message, Exception inner) : base(message, inner) { }
protected DelimitedStreamWriterException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
| {
"content_hash": "4505b1641c963ee536499d4396fbeeb0",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 126,
"avg_line_length": 37.88,
"alnum_prop": 0.778247096092925,
"repo_name": "putridparrot/Delimited.Data",
"id": "3deb1f9361acbc53800a2a95204848003413baee",
"size": "949",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "PurtidParrot.Delimited.Data/Exceptions/DelimitedStreamWriterException.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "137076"
}
],
"symlink_target": ""
} |
module ShopifyAPI
module Errors
class MissingJwtTokenError < StandardError
end
end
end
| {
"content_hash": "367ab1c253733af0bfe4acdddbea8b4d",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 46,
"avg_line_length": 16.5,
"alnum_prop": 0.7575757575757576,
"repo_name": "Shopify/shopify_api",
"id": "7d8f065f69f1180d477bdc3d10da665770df604d",
"size": "146",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/shopify_api/errors/missing_jwt_token_error.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "10222418"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.cloudfront_2012_03_15.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.cloudfront_2012_03_15.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Invalidation Batch StAX Unmarshaller
*/
public class InvalidationBatchStaxUnmarshaller implements Unmarshaller<InvalidationBatch, StaxUnmarshallerContext> {
public InvalidationBatch unmarshall(StaxUnmarshallerContext context) throws Exception {
InvalidationBatch invalidationBatch = new InvalidationBatch();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument()) targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument()) return invalidationBatch;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("Path", targetDepth)) {
invalidationBatch.getPaths().add(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("CallerReference", targetDepth)) {
invalidationBatch.setCallerReference(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return invalidationBatch;
}
}
}
}
private static InvalidationBatchStaxUnmarshaller instance;
public static InvalidationBatchStaxUnmarshaller getInstance() {
if (instance == null) instance = new InvalidationBatchStaxUnmarshaller();
return instance;
}
}
| {
"content_hash": "84fdb3ba449886ebb6f8e8cd20d4f779",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 116,
"avg_line_length": 37.089285714285715,
"alnum_prop": 0.6730861819932595,
"repo_name": "SaiNadh001/aws-sdk-for-java",
"id": "9b3ba4c81e94b4a389c2745e28194e08eb685f5d",
"size": "2664",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/main/java/com/amazonaws/services/cloudfront_2012_03_15/model/transform/InvalidationBatchStaxUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "33064436"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
<File path="Categories/UILabel+Framing.html">
<Token>
<TokenIdentifier>//apple_ref/occ/cat/UILabel(Framing)</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/setSingleLineAtYPosition:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)setSingleLineAtYPosition:(CGFloat)yPosition</Declaration>
<Anchor>//api/name/setSingleLineAtYPosition:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/centerInHeight:forYOffset:cleanView:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)centerInHeight:(CGFloat)height forYOffset:(CGFloat)yOffset cleanView:(BOOL)cleanView</Declaration>
<Anchor>//api/name/centerInHeight:forYOffset:cleanView:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/alignToBaselineOfLabel:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)alignToBaselineOfLabel:(UILabel *)comparisonLabel</Declaration>
<Anchor>//api/name/alignToBaselineOfLabel:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/baselineYPosition</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (CGFloat)baselineYPosition</Declaration>
<Anchor>//api/name/baselineYPosition</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/alignBaselineToYPosition:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)alignBaselineToYPosition:(CGFloat)yPosition</Declaration>
<Anchor>//api/name/alignBaselineToYPosition:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/alignToXHeightOfLabel:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)alignToXHeightOfLabel:(UILabel *)comparisonLabel</Declaration>
<Anchor>//api/name/alignToXHeightOfLabel:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/cleanFontPadding</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)cleanFontPadding</Declaration>
<Anchor>//api/name/cleanFontPadding</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/resizeWithText:inWidth:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)resizeWithText:(NSString *)text inWidth:(CGFloat)width</Declaration>
<Anchor>//api/name/resizeWithText:inWidth:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/fixHeight</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)fixHeight</Declaration>
<Anchor>//api/name/fixHeight</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/fixHeightForMaxLines:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)fixHeightForMaxLines:(NSInteger)maximumNumberOfLines</Declaration>
<Anchor>//api/name/fixHeightForMaxLines:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/fixHeightForMaxHeight:</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)fixHeightForMaxHeight:(CGFloat)maximumHeight</Declaration>
<Anchor>//api/name/fixHeightForMaxHeight:</Anchor>
<NodeRef refid="17"/>
</Token>
<Token>
<TokenIdentifier>//apple_ref/occ/instm/UILabel/fixWidth</TokenIdentifier>
<Abstract type="html"></Abstract>
<DeclaredIn>UILabel+Framing.h</DeclaredIn>
<Declaration>- (void)fixWidth</Declaration>
<Anchor>//api/name/fixWidth</Anchor>
<NodeRef refid="17"/>
</Token>
</File>
</Tokens> | {
"content_hash": "971f6e4881be8d4b7986454763eeda01",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 122,
"avg_line_length": 29.969135802469136,
"alnum_prop": 0.6792996910401647,
"repo_name": "JamieREvans/UIKitPlus",
"id": "e1c2b51b73ed6ea881f6f5fe78b2b13ebd16036b",
"size": "4855",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "Pod/Documentation/docset/Contents/Resources/Tokens17.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "96587"
},
{
"name": "Objective-C++",
"bytes": "3676"
},
{
"name": "Ruby",
"bytes": "778"
}
],
"symlink_target": ""
} |
#include "all_logs_vtab.hh"
#include "base/attr_line.hh"
#include "config.h"
static auto intern_lifetime = intern_string::get_table_lifetime();
all_logs_vtab::all_logs_vtab()
: log_vtab_impl(intern_string::lookup("all_logs")),
alv_msg_meta(
intern_string::lookup("log_msg_format"), value_kind_t::VALUE_TEXT, 0),
alv_schema_meta(
intern_string::lookup("log_msg_schema"), value_kind_t::VALUE_TEXT, 1)
{
this->alv_msg_meta.lvm_identifier = true;
this->alv_schema_meta.lvm_identifier = true;
}
void
all_logs_vtab::get_columns(std::vector<vtab_column>& cols) const
{
cols.emplace_back(
vtab_column(this->alv_msg_meta.lvm_name.get())
.with_comment(
"The message format with variables replaced by hash marks"));
cols.emplace_back(this->alv_schema_meta.lvm_name.get(),
SQLITE3_TEXT,
"",
true,
"The ID for the message schema");
}
void
all_logs_vtab::extract(logfile* lf,
uint64_t line_number,
logline_value_vector& values)
{
auto& line = values.lvv_sbr;
auto* format = lf->get_format_ptr();
logline_value_vector sub_values;
this->vi_attrs.clear();
sub_values.lvv_sbr = line;
format->annotate(line_number, this->vi_attrs, sub_values, false);
auto body = find_string_attr_range(this->vi_attrs, &SA_BODY);
if (body.lr_start == -1) {
body.lr_start = 0;
body.lr_end = line.length();
}
data_scanner ds(
line.to_string_fragment().sub_range(body.lr_start, body.lr_end));
data_parser dp(&ds);
std::string str;
dp.dp_msg_format = &str;
dp.parse();
values.lvv_values.emplace_back(this->alv_msg_meta, std::move(str));
values.lvv_values.emplace_back(this->alv_schema_meta,
dp.dp_schema_id.to_string());
}
bool
all_logs_vtab::next(log_cursor& lc, logfile_sub_source& lss)
{
return true;
}
| {
"content_hash": "07ca2f5e33b4e16410f34652fddfa41d",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 80,
"avg_line_length": 28.180555555555557,
"alnum_prop": 0.5879743716116314,
"repo_name": "tstack/lnav",
"id": "f4468a6faadae2ea9a0be9291c55695949c31bb9",
"size": "3566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/all_logs_vtab.cc",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "210621"
},
{
"name": "C++",
"bytes": "6051045"
},
{
"name": "CMake",
"bytes": "78666"
},
{
"name": "M4",
"bytes": "146853"
},
{
"name": "Makefile",
"bytes": "36558"
},
{
"name": "Python",
"bytes": "17645"
},
{
"name": "Roff",
"bytes": "61535"
},
{
"name": "Shell",
"bytes": "162703"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:drawable="@color/AB_Green_ContentDisplay" />
</selector> | {
"content_hash": "7d657670d21d3138ff3c59f4a8663c65",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 92,
"avg_line_length": 42.8,
"alnum_prop": 0.7242990654205608,
"repo_name": "Apptitive/Apptitive-Content-Display",
"id": "c36371ddbf3d6009a254e2c71064506963eb6732",
"size": "214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content display/src/main/res/drawable/switch_selector.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "1904"
},
{
"name": "Java",
"bytes": "186570"
}
],
"symlink_target": ""
} |
namespace IdentityServer.UnitTests.Common
{
internal interface IAuthenticationSchemeHandler
{
}
} | {
"content_hash": "4066997f3c6f81f84d9e17511b6f7939",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 51,
"avg_line_length": 18.333333333333332,
"alnum_prop": 0.7545454545454545,
"repo_name": "chrisowhite/IdentityServer4",
"id": "5d15946328b479482f4ae03da9fdde4b8c141145",
"size": "112",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "test/IdentityServer.UnitTests/Common/IAuthenticationSchemeHandler.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1857609"
},
{
"name": "CSS",
"bytes": "3268"
},
{
"name": "JavaScript",
"bytes": "169"
},
{
"name": "PowerShell",
"bytes": "6089"
},
{
"name": "Shell",
"bytes": "6186"
}
],
"symlink_target": ""
} |
require_relative "test_helper"
class UtmParamsTest < Minitest::Test
def test_default
message = UtmParamsMailer.welcome.deliver_now
refute_body "utm", message
assert_nil ahoy_message.utm_campaign
assert_nil ahoy_message.utm_medium
assert_nil ahoy_message.utm_source
end
def test_basic
message = UtmParamsMailer.basic.deliver_now
assert_body "utm_campaign=basic", message
assert_body "utm_medium=email", message
assert_body "utm_source=utm_params_mailer", message
assert_equal "basic", ahoy_message.utm_campaign
assert_equal "email", ahoy_message.utm_medium
assert_equal "utm_params_mailer", ahoy_message.utm_source
end
def test_array_params
message = UtmParamsMailer.array_params.deliver_now
assert_body "baz%5B%5D=1&baz%5B%5D=2", message
end
def test_nested
message = UtmParamsMailer.nested.deliver_now
assert_body "utm_medium=email", message
assert_body '<img src="image.png"></a>', message
end
def test_multiple
message = UtmParamsMailer.multiple.deliver_now
assert_body "utm_campaign=second", message
end
def test_head_element
message = UtmParamsMailer.head_element.deliver_now
assert_body '<head>', message
assert_body '</head>', message
end
def test_doctype
message = UtmParamsMailer.doctype.deliver_now
assert_body '<!DOCTYPE html>', message
end
def test_body_style
message = UtmParamsMailer.body_style.deliver_now
assert_body '<body style="background-color:#ABC123;">', message
end
end
| {
"content_hash": "2f4626e0f8067ec7c3504be5e64005a1",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 67,
"avg_line_length": 29.07547169811321,
"alnum_prop": 0.7177157689811811,
"repo_name": "ankane/ahoy_email",
"id": "fad91282c42f2c978ca0c2e98c747f7373571cc4",
"size": "1541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/utm_params_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "43909"
}
],
"symlink_target": ""
} |
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
header('Access-Control-Allow-Origin: *');
class preciario_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function getRecords() {
try {
$this->db->select("P.ID, P.Nombre AS Nombre, P.Tipo AS Tipo, P.FechaCreacion AS 'Fecha', "
. "(CASE "
. "WHEN P.Cliente_ID IS NULL THEN 'No especifica' "
. "ELSE (SELECT C.Nombre FROM Clientes AS C WHERE C.ID = P.Cliente_ID) "
. "END) AS Cliente "
. "", false);
$this->db->from('preciarios AS P');
// $this->db->where('P.Cliente_ID', $Cliente_ID);
$this->db->where('P.Estatus', 'Activo');
$query = $this->db->get();
$str = $this->db->last_query();
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getPreciarioByID($ID) {
try {
$this->db->select('P.*', false);
$this->db->from('preciarios AS P');
$this->db->where('P.ID', $ID);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getPreciariosActivosByCliente($Cliente_ID) {
try {
$this->db->select('P.ID as ID, P.Nombre as Preciario', false);
$this->db->from('preciarios AS P');
// $this->db->where('P.Cliente_ID', $Cliente_ID);
$this->db->where('P.Estatus', 'Activo');
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getPreciarios() {
try {
$this->db->select('P.ID as ID, P.Nombre as Preciario', false);
$this->db->from('preciarios AS P');
$this->db->order_by('P.Nombre', 'ASC');
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getPreciariosByCliente($Cliente_ID) {
try {
$this->db->select('P.ID as ID, P.Nombre as Preciario', false);
$this->db->from('preciarios AS P');
// $this->db->where('P.Cliente_ID', $Cliente_ID);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getConceptosXPreciarioID($ID) {
try {
$this->db->select('PC.ID,CONCAT("<span style=\'font-size:14px;\' class=\"badge badge-danger\">",PC.Clave,"</span>") AS Clave, '
. 'CONCAT("<p class=\" CustomDetalleDescripcion \">",UPPER(PC.Descripcion),"</p>") AS Descripcion, '
. 'PC.Unidad AS Unidad, '
. 'CONCAT("<span style=\'font-size:14px;\' class=\"badge badge-success\">$",FORMAT(PC.Costo,2),"</span>") AS Costo, '
. 'PC.Moneda AS Moneda,'
. 'CONCAT("<span class=\"fa fa-cog fa-lg\" '
. 'onclick=\"onEditarConceptoPreciarioXID(",PC.ID,")\"></span>") AS Editar,'
. 'CONCAT("<span class=\"fa fa-times fa-lg\" onclick=\"onEliminarConceptoPreciario(this,",PC.ID,")\"></span>") AS Eliminar', false);
$this->db->from('preciarioconceptos AS PC');
$this->db->where('PC.Preciarios_ID', $ID);
$this->db->order_by('PC.ID', 'ASC');
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
//print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getConceptoByID($ID) {
try {
$this->db->select('PC.*', false);
$this->db->from('preciarioconceptos AS PC');
$this->db->where('PC.ID', $ID);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getConceptoByClaveXDescripcion($ID, $CLAVE, $DESCRIPCION) {
try {
$this->db->select('PC.ID,CONCAT("<span class=\"label label-danger\">",PC.Clave,"</span>") AS Clave, PC.Descripcion AS "Descripción", PC.Unidad AS Unidad, CONCAT("<span class=\"label label-success\">$",FORMAT(PC.Costo,2),"</span>") AS Costo, PC.Moneda AS Moneda', false);
$this->db->from('preciarioconceptos AS PC');
$this->db->where('PC.Preciarios_ID', $ID);
if ($CLAVE !== '') {
$this->db->where("PC.Clave LIKE '%$CLAVE%'", null, false);
}
if ($DESCRIPCION !== '') {
$this->db->where("PC.Descripcion LIKE '%$DESCRIPCION%'", null, false);
}
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getCategoriasXPreciarioID($ID) {
try {
$this->db->select('PC.ID,CONCAT(PC.Clave," - ",PC.Descripcion) AS Categoria', false);
$this->db->from('preciariocategorias AS PC');
$this->db->where('PC.Preciario_ID', $ID);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getSubCategoriasXCategoriaIDXPreciarioID($ID, $IDC) {
try {
$this->db->select('PSC.ID,CONCAT(PSC.Clave," - ",PSC.Descripcion) AS Subcategoria', false);
$this->db->from('preciariosubcategorias AS PSC');
if (isset($ID) && $ID !== '') {
$this->db->where('PSC.Preciario_ID', $ID);
}
if (isset($IDC) && $IDC !== '') {
$this->db->where('PSC.PreciarioCategoria_ID', $IDC);
}
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getSubSubCategoriasXSubCategoriaXCategoriaIDXPreciarioID($ID, $IDC, $IDSC) {
try {
$this->db->select('PSSC.ID,CONCAT(PSSC.Clave," - ",PSSC.Descripcion) AS SubSubCategoria', false);
$this->db->from('preciariosubsubcategoria AS PSSC');
if (isset($ID) && $ID !== '') {
$this->db->where('PSSC.Preciario_ID', $ID);
}
if (isset($IDC) && $IDC !== '') {
$this->db->where('PSSC.PreciarioCategoria_ID', $IDC);
}
if (isset($IDC) && $IDC !== '') {
$this->db->where('PSSC.PreciarioSubCategorias_ID', $IDSC);
}
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getCategoriasByPreciarioID($ID) {
try {
$this->db->select('PC.ID, PC.Clave AS Clave, PC.Descripcion AS "Descripción", '
. '(SELECT COUNT(*) FROM preciariosubcategorias AS PSC WHERE PSC.Preciario_ID = PC.Preciario_ID AND PSC.PreciarioCategoria_ID = PC.ID) AS NSUB', false);
$this->db->from('preciariocategorias AS PC');
$this->db->where('PC.Preciario_ID', $ID);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getSubCategoriasByCategoriaIDPreciarioID($ID, $IDC) {
try {
$this->db->select("PSC.ID, PSC.Clave AS Clave, PSC.Descripcion AS \"Descripción\", "
. "(SELECT COUNT(*) FROM preciariosubsubcategoria AS PSSC WHERE PSSC.Preciario_ID = PSC.Preciario_ID AND PSSC.PreciarioCategoria_ID = PSC.ID) AS NSUB,"
. "(SELECT COUNT(*) FROM preciarioconceptos AS PC "
. "WHERE PC.Preciarios_ID = PSC.Preciario_ID "
. "AND PC.PreciarioCategorias_ID = PSC.PreciarioCategoria_ID AND PC.PreciarioSubCategorias_ID = PSC.ID) AS NCON", false);
$this->db->from('preciariosubcategorias AS PSC');
$this->db->where('PSC.Preciario_ID', $ID);
$this->db->where('PSC.PreciarioCategoria_ID', $IDC);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getSubSubCategoriasBySubCategoriaIDCategoriaIDPreciarioID($ID, $IDC, $IDSC) {
try {
$this->db->select("PSSC.ID, PSSC.Clave AS Clave, PSSC.Descripcion AS \"Descripción\", "
. "(SELECT COUNT(*) FROM preciarioconceptos AS PC "
. "WHERE PC.Preciarios_ID = $ID "
. "AND PC.PreciarioCategorias_ID = $IDC "
. "AND PC.PreciarioSubCategorias_ID = $IDSC "
. "AND PC.PreciarioSubSubCategoria_ID = PSSC.ID) AS NSUB,"
. "(SELECT COUNT(*) FROM preciarioconceptos AS PC "
. "WHERE PC.Preciarios_ID = $ID "
. "AND PC.PreciarioCategorias_ID = $IDC "
. "AND PC.PreciarioSubCategorias_ID = $IDSC "
. "AND PC.PreciarioSubSubCategoria_ID = PSSC.ID ) AS NCON", false);
$this->db->from('preciariosubsubcategoria AS PSSC');
$this->db->where('PSSC.Preciario_ID', $ID);
$this->db->where('PSSC.PreciarioCategoria_ID', $IDC);
$this->db->where('PSSC.PreciarioSubCategorias_ID', $IDSC);
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getConceptosBySubSubCategoriaIDSubCategoriaIDCategoriaIDPreciarioID($ID, $IDC, $IDSC, $IDSSC) {
try {
$this->db->select("PC.ID, "
. "CONCAT('<span class=\"label label-danger\">',"
. "PC.Clave"
. ",'</span>')"
. " AS Clave, "
. "PC.Descripcion AS \"Descripción\", PC.Unidad AS Unidad, "
. "CONCAT('<span class=\"label label-success\">',\"$\",FORMAT(PC.Costo,2),'</span>') AS Costo, PC.Moneda AS Moneda", false);
$this->db->from('preciarioconceptos AS PC');
if ($ID !== NULL && $ID !== '') {
$this->db->where('PC.Preciarios_ID', $ID);
}
if ($IDC !== NULL && $IDC !== '') {
$this->db->where('PC.PreciarioCategorias_ID', $IDC);
}
if ($IDSC !== NULL && $IDSC !== '') {
$this->db->where('PC.PreciarioSubCategorias_ID', $IDSC);
}
if ($IDSSC !== NULL && $IDSSC !== '') {
$this->db->where('PC.PreciarioSubSubCategoria_ID', $IDSSC);
}
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function getClientes() {
try {
$this->db->select('C.ID, C.Nombre AS Cliente', false);
$this->db->from('Clientes AS C');
$query = $this->db->get();
/*
* FOR DEBUG ONLY
*/
$str = $this->db->last_query();
// print $str;
$data = $query->result();
return $data;
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onAgregar($array) {
try {
$this->db->insert("preciarios", $array);
// print $str = $this->db->last_query();
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$LastIdInserted = $row['LAST_INSERT_ID()'];
return $LastIdInserted;
// print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onAgregarPreciarioConceptos($array) {
try {
$this->db->insert("preciarioconceptos", $array);
// print $str = $this->db->last_query();
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$LastIdInserted = $row['LAST_INSERT_ID()'];
return $LastIdInserted;
print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onAgregarPreciarioCategoria($array) {
try {
$this->db->insert("preciariocategorias", $array);
// print $str = $this->db->last_query();
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$LastIdInserted = $row['LAST_INSERT_ID()'];
return $LastIdInserted;
print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onAgregarPreciarioSubCategoria($array) {
try {
$this->db->insert("preciariosubcategorias", $array);
// print $str = $this->db->last_query();
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$LastIdInserted = $row['LAST_INSERT_ID()'];
return $LastIdInserted;
print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onAgregarPreciarioSubSubCategoria($array) {
try {
$this->db->insert("preciariosubsubcategoria", $array);
// print $str = $this->db->last_query();
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$LastIdInserted = $row['LAST_INSERT_ID()'];
return $LastIdInserted;
// print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onModificar($ID, $DATA) {
try {
$this->db->where('ID', $ID);
$this->db->update("preciarios", $DATA);
print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onEliminar($ID) {
try {
$this->db->where('Preciario_ID', $ID);
$this->db->delete("preciariosubsubcategoria");
$this->db->where('Preciarios_ID', $ID);
$this->db->delete("preciarioconceptos");
$this->db->where('Preciario_ID', $ID);
$this->db->delete("preciariosubcategorias");
$this->db->where('Preciario_ID', $ID);
$this->db->delete("preciariocategorias");
$this->db->where('id', $ID);
$this->db->delete("preciarios");
// print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onEliminarConcepto($ID) {
try {
$this->db->where('ID', $ID);
$this->db->delete("preciarioconceptos");
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function onEditarConcepto($ID, $DATA) {
try {
$this->db->where('ID', $ID);
$this->db->update("preciarioconceptos", $DATA);
print $str = $this->db->last_query();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
}
| {
"content_hash": "fe25d1c96e5d6604d214925e6ea70bfe",
"timestamp": "",
"source": "github",
"line_count": 488,
"max_line_length": 282,
"avg_line_length": 37.53893442622951,
"alnum_prop": 0.47633604454391615,
"repo_name": "JYovan/AYR",
"id": "9c96b5d7d3db640487a456bc3d95ae1bce73cd5b",
"size": "18324",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/preciario_model.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "215610"
},
{
"name": "HTML",
"bytes": "41035"
},
{
"name": "Hack",
"bytes": "468232"
},
{
"name": "JavaScript",
"bytes": "9360084"
},
{
"name": "PHP",
"bytes": "3305191"
},
{
"name": "PLpgSQL",
"bytes": "2028"
},
{
"name": "SQLPL",
"bytes": "2577"
}
],
"symlink_target": ""
} |
(function() {
var plugins = [];
if (Dive && Dive.plugins) plugins = Dive.plugins;
Dive.identity = function(i) { return i; };
Dive.into = function(dest_, orig_, mergeStrategy) {
var opt,
dest = dest_ || {},
orig = orig_ || {};
switch (mergeStrategy) {
case 'add':
for (opt in orig)
if (orig.hasOwnProperty(opt)) {
if (dest.hasOwnProperty(opt))
dest[opt] += orig[opt];
else dest[opt] = orig[opt];
}
break;
default:
for (opt in orig)
if (orig.hasOwnProperty(opt))
dest[opt] = orig[opt];
break;
}
return dest;
};
Dive.map = function(f, coll) {
if (coll == undefined)
return function(coll2) { return Dive.map(f, coll2); };
var results = [];
for (var i = 0; i < coll.length; i++) {
f.$index = i;
results.push(f.call(f, coll[i]));
}
delete f.$index;
return results;
};
Dive.filter = function(f, coll) {
if (coll == undefined)
return function(coll2) { return Dive.filter(f, coll2); };
var results = [];
for (var i = 0; i < coll.length; i++) {
f.$index = i;
if (f(coll[i])) results.push(coll[i]);
}
return results;
};
Dive.mapSome = function(f, coll) {
if (coll == undefined)
return function(coll2) { return Dive.mapSome(f, coll2); };
return Dive.map(f, Dive.filter(function(c) {
return c != null && c != undefined;
}, coll));
};
Dive.take = function(n, coll) {
if (coll == undefined)
if (n == undefined || n == null) return Dive.identity;
else return function(coll2) { return Dive.take(n, coll2); };
if (n == undefined || n == null) return coll;
else return coll.slice(0, n);
};
Dive.takeWhile = function(f, coll) {
if (coll == undefined)
return function(coll2) { return Dive.takeWhile(f, coll2); };
var n = 0;
while (f(coll[i])) n++;
return coll.slice(0, n);
};
Dive.repeat = function(n, val) {
if (val == undefined)
return function(val2) { return Dive.repeat(n, val2); };
var arr = new Array(n);
for (var i = 0; i < n; i++)
arr[i] = val;
return arr;
};
Dive.pipe = function(val) {
if (arguments.length <= 1) return val;
var result = val;
for (var i = 1; i < arguments.length; i++) {
var fn = arguments[i];
if (typeof fn !== "function")
throw new Error("Dive: pipe argument " + i + "is not a function");
else result = fn(result);
}
return result;
};
for (var p = 0; p < plugins.length; p++) {
if (typeof plugins[p] === 'function') plugins[p]();
}
})();
| {
"content_hash": "3dadfe9da9bf248e7e12ca01c1a71751",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 72,
"avg_line_length": 23.547169811320753,
"alnum_prop": 0.5705128205128205,
"repo_name": "intelie/dive",
"id": "8319b4438da7ceda7cadbcfb98f33a787e6e5fcd",
"size": "2496",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/core.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Clojure",
"bytes": "2015"
},
{
"name": "JavaScript",
"bytes": "24698"
}
],
"symlink_target": ""
} |
package org.apache.geode.cache.query.internal.cq.spi;
import java.io.DataInput;
import java.io.IOException;
import org.apache.geode.cache.query.internal.cq.CqService;
import org.apache.geode.cache.query.internal.cq.ServerCQ;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.tier.sockets.CommandRegistry;
public interface CqServiceFactory {
void initialize();
/**
* Create a new CqService for the given cache
*/
CqService create(InternalCache cache, CommandRegistry commandRegistry);
ServerCQ readCqQuery(DataInput in) throws ClassNotFoundException, IOException;
}
| {
"content_hash": "9ec76e3a4ab1e26114c5eff4cbfd4a0b",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 80,
"avg_line_length": 28.59090909090909,
"alnum_prop": 0.7980922098569158,
"repo_name": "smgoller/geode",
"id": "d5197a3cb20b8016d043a79c878613033520df9b",
"size": "1418",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "geode-core/src/main/java/org/apache/geode/cache/query/internal/cq/spi/CqServiceFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104031"
},
{
"name": "Dockerfile",
"bytes": "15956"
},
{
"name": "Go",
"bytes": "40709"
},
{
"name": "Groovy",
"bytes": "41926"
},
{
"name": "HTML",
"bytes": "4037528"
},
{
"name": "Java",
"bytes": "33124128"
},
{
"name": "JavaScript",
"bytes": "1780821"
},
{
"name": "Python",
"bytes": "29801"
},
{
"name": "Ruby",
"bytes": "1801"
},
{
"name": "SCSS",
"bytes": "2677"
},
{
"name": "Shell",
"bytes": "274196"
}
],
"symlink_target": ""
} |
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost {
//
// Traversal Categories
//
struct no_traversal_tag {};
struct incrementable_traversal_tag
: no_traversal_tag
{
// incrementable_traversal_tag() {}
// incrementable_traversal_tag(std::output_iterator_tag const&) {};
};
struct single_pass_traversal_tag
: incrementable_traversal_tag
{
// single_pass_traversal_tag() {}
// single_pass_traversal_tag(std::input_iterator_tag const&) {};
};
struct forward_traversal_tag
: single_pass_traversal_tag
{
// forward_traversal_tag() {}
// forward_traversal_tag(std::forward_iterator_tag const&) {};
};
struct bidirectional_traversal_tag
: forward_traversal_tag
{
// bidirectional_traversal_tag() {};
// bidirectional_traversal_tag(std::bidirectional_iterator_tag const&) {};
};
struct random_access_traversal_tag
: bidirectional_traversal_tag
{
// random_access_traversal_tag() {};
// random_access_traversal_tag(std::random_access_iterator_tag const&) {};
};
namespace detail
{
//
// Convert a "strictly old-style" iterator category to a traversal
// tag. This is broken out into a separate metafunction to reduce
// the cost of instantiating iterator_category_to_traversal, below,
// for new-style types.
//
template <class Cat>
struct old_category_to_traversal
: mpl::eval_if<
is_convertible<Cat,std::random_access_iterator_tag>
, mpl::identity<random_access_traversal_tag>
, mpl::eval_if<
is_convertible<Cat,std::bidirectional_iterator_tag>
, mpl::identity<bidirectional_traversal_tag>
, mpl::eval_if<
is_convertible<Cat,std::forward_iterator_tag>
, mpl::identity<forward_traversal_tag>
, mpl::eval_if<
is_convertible<Cat,std::input_iterator_tag>
, mpl::identity<single_pass_traversal_tag>
, mpl::eval_if<
is_convertible<Cat,std::output_iterator_tag>
, mpl::identity<incrementable_traversal_tag>
, void
>
>
>
>
>
{};
# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
template <>
struct old_category_to_traversal<int>
{
typedef int type;
};
# endif
template <class Traversal>
struct pure_traversal_tag
: mpl::eval_if<
is_convertible<Traversal,random_access_traversal_tag>
, mpl::identity<random_access_traversal_tag>
, mpl::eval_if<
is_convertible<Traversal,bidirectional_traversal_tag>
, mpl::identity<bidirectional_traversal_tag>
, mpl::eval_if<
is_convertible<Traversal,forward_traversal_tag>
, mpl::identity<forward_traversal_tag>
, mpl::eval_if<
is_convertible<Traversal,single_pass_traversal_tag>
, mpl::identity<single_pass_traversal_tag>
, mpl::eval_if<
is_convertible<Traversal,incrementable_traversal_tag>
, mpl::identity<incrementable_traversal_tag>
, void
>
>
>
>
>
{
};
# if BOOST_WORKAROUND(BOOST_MSVC, < 1300)
template <>
struct pure_traversal_tag<int>
{
typedef int type;
};
# endif
} // namespace detail
//
// Convert an iterator category into a traversal tag
//
template <class Cat>
struct iterator_category_to_traversal
: mpl::eval_if< // if already convertible to a traversal tag, we're done.
is_convertible<Cat,incrementable_traversal_tag>
, mpl::identity<Cat>
, pdalboost::detail::old_category_to_traversal<Cat>
>
{};
// Trait to get an iterator's traversal category
template <class Iterator = mpl::_1>
struct iterator_traversal
: iterator_category_to_traversal<
typename pdalboost::detail::iterator_traits<Iterator>::iterator_category
>
{};
# ifdef BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT
// Hack because BOOST_MPL_AUX_LAMBDA_SUPPORT doesn't seem to work
// out well. Instantiating the nested apply template also
// requires instantiating iterator_traits on the
// placeholder. Instead we just specialize it as a metafunction
// class.
template <>
struct iterator_traversal<mpl::_1>
{
template <class T>
struct apply : iterator_traversal<T>
{};
};
template <>
struct iterator_traversal<mpl::_>
: iterator_traversal<mpl::_1>
{};
# endif
} // namespace pdalboost
#include <boost/iterator/detail/config_undef.hpp>
#endif // BOOST_ITERATOR_CATEGORIES_HPP
| {
"content_hash": "41466d6654ac5d04978b641731e4452f",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 80,
"avg_line_length": 28.612121212121213,
"alnum_prop": 0.6142766363058674,
"repo_name": "verma/PDAL",
"id": "9ee44b635e2bdd7e735d0de1815bd947b2a131c2",
"size": "5391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "boost/boost/iterator/iterator_categories.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "755744"
},
{
"name": "C#",
"bytes": "51165"
},
{
"name": "C++",
"bytes": "58234219"
},
{
"name": "CSS",
"bytes": "65128"
},
{
"name": "JavaScript",
"bytes": "81726"
},
{
"name": "Lasso",
"bytes": "1053782"
},
{
"name": "Perl",
"bytes": "4925"
},
{
"name": "Python",
"bytes": "12600"
},
{
"name": "Shell",
"bytes": "40033"
},
{
"name": "XSLT",
"bytes": "7284"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Collections;
namespace Nest
{
public class PropertyWalker
{
private readonly Type _type;
private readonly IPropertyVisitor _visitor;
private readonly int _maxRecursion;
private readonly ConcurrentDictionary<Type, int> _seenTypes;
public PropertyWalker(Type type, IPropertyVisitor visitor, int maxRecursion = 0)
{
_type = GetUnderlyingType(type);
_visitor = visitor ?? new NoopPropertyVisitor();
_maxRecursion = maxRecursion;
_seenTypes = new ConcurrentDictionary<Type, int>();
_seenTypes.TryAdd(_type, 0);
}
private PropertyWalker(Type type, IPropertyVisitor visitor, int maxRecursion, ConcurrentDictionary<Type, int> seenTypes)
{
_type = type;
_visitor = visitor;
_maxRecursion = maxRecursion;
_seenTypes = seenTypes;
}
public IProperties GetProperties(ConcurrentDictionary<Type, int> seenTypes = null, int maxRecursion = 0)
{
var properties = new Properties();
int seen;
if (seenTypes != null && seenTypes.TryGetValue(_type, out seen) && seen > maxRecursion)
return properties;
foreach (var propertyInfo in _type.GetProperties())
{
var attribute = ElasticsearchPropertyAttributeBase.From(propertyInfo);
if (attribute != null && attribute.Ignore)
continue;
var property = GetProperty(propertyInfo, attribute);
var withCLrOrigin = property as IPropertyWithClrOrigin;
if (withCLrOrigin != null)
withCLrOrigin.ClrOrigin = propertyInfo;
properties.Add(propertyInfo, property);
}
return properties;
}
private IProperty GetProperty(PropertyInfo propertyInfo, ElasticsearchPropertyAttributeBase attribute)
{
var property = _visitor.Visit(propertyInfo, attribute);
if (property != null)
return property;
if (propertyInfo.GetGetMethod().IsStatic)
return null;
if (attribute != null)
property = attribute;
else
property = InferProperty(propertyInfo.PropertyType);
var objectProperty = property as IObjectProperty;
if (objectProperty != null)
{
var type = GetUnderlyingType(propertyInfo.PropertyType);
var seenTypes = new ConcurrentDictionary<Type, int>(_seenTypes);
seenTypes.AddOrUpdate(type, 0, (t, i) => ++i);
var walker = new PropertyWalker(type, _visitor, _maxRecursion, seenTypes);
objectProperty.Properties = walker.GetProperties(seenTypes, _maxRecursion);
}
_visitor.Visit(property, propertyInfo, attribute);
return property;
}
private IProperty InferProperty(Type type)
{
type = GetUnderlyingType(type);
if (type == typeof(string))
return new TextProperty
{
Fields = new Properties
{
{ "keyword", new KeywordProperty() }
}
};
if (type.IsEnumType())
return new NumberProperty(NumberType.Integer);
if (type.IsValue())
{
switch (type.Name)
{
case "Int32":
case "UInt16":
return new NumberProperty(NumberType.Integer);
case "Int16":
case "Byte":
return new NumberProperty(NumberType.Short);
case "SByte":
return new NumberProperty(NumberType.Byte);
case "Int64":
case "UInt32":
case "TimeSpan":
return new NumberProperty(NumberType.Long);
case "Single":
return new NumberProperty(NumberType.Float);
case "Decimal":
case "Double":
case "UInt64":
return new NumberProperty(NumberType.Double);
case "DateTime":
case "DateTimeOffset":
return new DateProperty();
case "Boolean":
return new BooleanProperty();
case "Char":
case "Guid":
return new KeywordProperty();
}
}
if (type == typeof(GeoLocation))
return new GeoPointProperty();
if (type == typeof(CompletionField))
return new CompletionProperty();
if (type == typeof(Attachment))
return new AttachmentProperty();
return new ObjectProperty();
}
private Type GetUnderlyingType(Type type)
{
if (type.IsArray)
return type.GetElementType();
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsGenericType && type.GetGenericArguments().Length == 1
&& (typeInfo.ImplementedInterfaces.HasAny(t => t == typeof(IEnumerable)) || Nullable.GetUnderlyingType(type) != null))
return type.GetGenericArguments()[0];
return type;
}
}
}
| {
"content_hash": "4e6270906dcead3b1050c9f2b71c3b23",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 122,
"avg_line_length": 28.251572327044027,
"alnum_prop": 0.6645146927871772,
"repo_name": "TheFireCookie/elasticsearch-net",
"id": "5b56e1de1ae201342c6a80100571267de43992a0",
"size": "4494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Nest/Mapping/Visitor/PropertyWalker.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1511"
},
{
"name": "C#",
"bytes": "7306106"
},
{
"name": "F#",
"bytes": "33028"
},
{
"name": "HTML",
"bytes": "401915"
},
{
"name": "Shell",
"bytes": "698"
},
{
"name": "Smalltalk",
"bytes": "3426"
}
],
"symlink_target": ""
} |
require 'spec_helper'
module Refinery
describe Page do
let(:page) do
::Refinery::Page.create!({
:title => 'RSpec is great for testing too',
:deletable => true
})
end
let(:child) { page.children.create(:title => 'The child page') }
def page_cannot_be_destroyed
page.destroy.should == false
end
def turn_off_marketable_urls
::Refinery::Setting.set(:use_marketable_urls, {:value => false, :scoping => 'pages'})
end
def turn_on_marketable_urls
::Refinery::Setting.set(:use_marketable_urls, {:value => true, :scoping => 'pages'})
end
def create_page_parts
page.parts.create(:title => 'body', :content => "I'm the first page part for this page.")
page.parts.create(:title => 'side body', :content => 'Closely followed by the second page part.')
end
context 'cannot be deleted under certain rules' do
it 'if link_url is present' do
page.link_url = '/plugin-name'
page_cannot_be_destroyed
end
it 'if refinery team deems it so' do
page.deletable = false
page_cannot_be_destroyed
end
it 'if menu_match is present' do
page.menu_match = '^/RSpec is great for testing too.*$'
page_cannot_be_destroyed
end
it 'unless you really want it to! >:]' do
page.destroy.should be
end
end
context 'page urls' do
it 'return a full path' do
page.path.should == 'RSpec is great for testing too'
end
it 'and all of its parent page titles, reversed' do
child.path.should == 'RSpec is great for testing too - The child page'
end
it 'or normally ;-)' do
child.path({:reversed => false}).should == 'The child page - RSpec is great for testing too'
end
it 'returns its url' do
page.link_url = '/contact'
page.url.should == '/contact'
end
it 'returns its path with marketable urls' do
page.url[:id].should be_nil
page.url[:path].should == ['rspec-is-great-for-testing-too']
end
it 'returns its path underneath its parent with marketable urls' do
child.url[:id].should be_nil
child.url[:path].should == [page.url[:path].first, 'the-child-page']
end
it 'no path parameter without marketable urls' do
turn_off_marketable_urls
page.url[:path].should be_nil
page.url[:id].should == 'rspec-is-great-for-testing-too'
turn_on_marketable_urls
end
it "doesn't mention its parent without marketable urls" do
turn_off_marketable_urls
child.url[:id].should == 'the-child-page'
child.url[:path].should be_nil
turn_on_marketable_urls
end
end
context 'home page' do
it 'responds as the home page' do
page.link_url = '/'
page.home?.should == true
end
it 'responds as a normal page when not set to home page' do
page.home?.should == false
end
end
context 'content sections (page parts)' do
before { create_page_parts }
it 'return the content when using content_for' do
page.content_for(:body).should == "<p>I'm the first page part for this page.</p>"
page.content_for('BoDY').should == "<p>I'm the first page part for this page.</p>"
end
it 'return all page part content' do
page.all_page_part_content.should == "<p>I'm the first page part for this page.</p> <p>Closely followed by the second page part.</p>"
end
it 'reposition correctly' do
page.parts.first.position = 6
page.parts.last.position = 4
page.parts.first.position.should == 6
page.parts.last.position.should == 4
page.reposition_parts!
page.parts.first.position.should == 0
page.parts.last.position.should == 1
end
end
context 'draft pages' do
it 'not live when set to draft' do
page.draft = true
page.live?.should_not be
end
it 'live when not set to draft' do
page.draft = false
page.live?.should be
end
end
context "should add url suffix" do
let(:reserved_word) { ::Refinery::Page.friendly_id_config.reserved_words.last }
let(:page_with_reserved_title) do
::Refinery::Page.create!({
:title => reserved_word,
:deletable => true
})
end
let(:child_with_reserved_title_parent) do
page_with_reserved_title.children.create(:title => 'reserved title child page')
end
before { turn_on_marketable_urls }
it 'when title is set to a reserved word' do
page_with_reserved_title.url[:path].should == ["#{reserved_word}-page"]
end
it "when parent page title is set to a reserved word" do
child_with_reserved_title_parent.url[:path].should == ["#{reserved_word}-page", 'reserved-title-child-page']
end
end
context 'meta data' do
context 'responds to' do
it 'meta_keywords' do
page.respond_to?(:meta_keywords)
end
it 'meta_description' do
page.respond_to?(:meta_description)
end
it 'browser_title' do
page.respond_to?(:browser_title)
end
end
context 'allows us to assign to' do
it 'meta_keywords' do
page.meta_keywords = 'Some, great, keywords'
page.meta_keywords.should == 'Some, great, keywords'
end
it 'meta_description' do
page.meta_description = 'This is my description of the page for search results.'
page.meta_description.should == 'This is my description of the page for search results.'
end
it 'browser_title' do
page.browser_title = 'An awesome browser title for SEO'
page.browser_title.should == 'An awesome browser title for SEO'
end
end
context 'allows us to update' do
it 'meta_keywords' do
page.meta_keywords = 'Some, great, keywords'
page.save
page.reload
page.meta_keywords.should == 'Some, great, keywords'
end
it 'meta_description' do
page.meta_description = 'This is my description of the page for search results.'
page.save
page.reload
page.meta_description.should == 'This is my description of the page for search results.'
end
it 'browser_title' do
page.browser_title = 'An awesome browser title for SEO'
page.save
page.reload
page.browser_title.should == 'An awesome browser title for SEO'
end
end
end
end
end
| {
"content_hash": "f7bf4aa4995832e2ce9c32f59e0e862f",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 141,
"avg_line_length": 29.43859649122807,
"alnum_prop": 0.5966924910607867,
"repo_name": "koa/refinerycms",
"id": "77c3f0db2c3afe6be0f803ec73540fabc2ed14ca",
"size": "6712",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pages/spec/models/refinery/page_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "336913"
},
{
"name": "Ruby",
"bytes": "376941"
}
],
"symlink_target": ""
} |
require 'pgit'
#TODO: Find a way to make execute! just be a call on children tasks
module PGit
class Project
class Add
extend Forwardable
attr_reader :adder
def initialize(app)
@app = app
raise PGit::Error::User, 'Project path already exists. See `pgit proj update --help.`' if app.exists?
@reuse_adder = PGit::Project::ReuseApiTokenAdder.new(app.project, app.projects)
end
def execute!
@reuse_adder.execute!
@adder = PGit::Project::InteractiveAdder.new(@reuse_adder.project)
adder.execute!
adder.save!
puts "Successfully added the project!"
end
end
end
end
| {
"content_hash": "c82c65dc8fe36b93165bcada88c2c518",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 109,
"avg_line_length": 24.142857142857142,
"alnum_prop": 0.6346153846153846,
"repo_name": "Edderic/pgit",
"id": "c4c97c6338678d3ce79d820add244cfcdbe42296",
"size": "676",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pgit/project/add.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "163398"
}
],
"symlink_target": ""
} |
using Newtonsoft.Json;
namespace OpenStack.Networking.v2.Operator
{
/// <summary>
/// Extended definition of a network resource, with cloud operator functionality exposed.
/// </summary>
public class NetworkDefinition : v2.NetworkDefinition
{
/// <inheritdoc cref="Network.IsExternal" />
[JsonProperty("router:external")]
public bool? IsExternal { get; set; }
}
}
| {
"content_hash": "000caba29511aab3d7dbdbe0a0686492",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 93,
"avg_line_length": 29.571428571428573,
"alnum_prop": 0.6618357487922706,
"repo_name": "ONLYOFFICE/CommunityServer",
"id": "fc222c42c92d232ba6c04d0877a51aa1af2b8c77",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "redistributable/openstack.net/src/corelib/Networking/v2/Operator/NetworkDefinition.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "9505"
},
{
"name": "ASP.NET",
"bytes": "1543455"
},
{
"name": "Batchfile",
"bytes": "11616"
},
{
"name": "C",
"bytes": "261"
},
{
"name": "C#",
"bytes": "37439795"
},
{
"name": "C++",
"bytes": "10200"
},
{
"name": "CSS",
"bytes": "632783"
},
{
"name": "Classic ASP",
"bytes": "43003"
},
{
"name": "F#",
"bytes": "9164"
},
{
"name": "HTML",
"bytes": "1350144"
},
{
"name": "Handlebars",
"bytes": "942"
},
{
"name": "JavaScript",
"bytes": "10480939"
},
{
"name": "Less",
"bytes": "1348959"
},
{
"name": "Makefile",
"bytes": "3611"
},
{
"name": "Perl",
"bytes": "6729"
},
{
"name": "PowerShell",
"bytes": "21562"
},
{
"name": "Procfile",
"bytes": "15"
},
{
"name": "Ruby",
"bytes": "30941"
},
{
"name": "Shell",
"bytes": "36554"
},
{
"name": "VBScript",
"bytes": "1225"
},
{
"name": "Visual Basic .NET",
"bytes": "13062"
},
{
"name": "XSLT",
"bytes": "105207"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "f75fb5c48780c6bb39f10d4c7a86e82f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "c943d4ce60d129d68c10e8f5aa436ac24b74c7a2",
"size": "198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Chromista/Ochrophyta/Phaeophyceae/Scytosiphonales/Scytosiphonaceae/Analipus/Analipus filiformis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<license>
<eula>
Tais termos se encontra em formulação.
</eula>
</license> | {
"content_hash": "a11c76165bd616964e74fd81a01afd4f",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 40,
"avg_line_length": 20.333333333333332,
"alnum_prop": 0.639344262295082,
"repo_name": "erickmcarvalho/effectweb-project",
"id": "93bac50ef4af618ec914480cbeb9eadaafdbb705",
"size": "124",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/modules/setup/xml/license.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ActionScript",
"bytes": "321037"
},
{
"name": "ApacheConf",
"bytes": "213"
},
{
"name": "CSS",
"bytes": "121850"
},
{
"name": "HTML",
"bytes": "207"
},
{
"name": "JavaScript",
"bytes": "181701"
},
{
"name": "PHP",
"bytes": "2282620"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Mengjiao
*/
public class User {
String id;
String name;
String passwd;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPasswd(String passwd){
this.passwd=passwd;
}
public String getPasswd(){
return passwd;
}
}
| {
"content_hash": "d64cd44e8f3e2f02e91c85f1ee148bd5",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 79,
"avg_line_length": 20.314285714285713,
"alnum_prop": 0.5625879043600562,
"repo_name": "infsci2560sp16/full-stack-web-project-NamkiuZhang",
"id": "2001f435009fab8890d5c3d4fbc33b4d92f1ddd8",
"size": "711",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/User.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5186"
},
{
"name": "CSS",
"bytes": "3934"
},
{
"name": "FreeMarker",
"bytes": "6345"
},
{
"name": "HTML",
"bytes": "9855"
},
{
"name": "Java",
"bytes": "2772"
},
{
"name": "JavaScript",
"bytes": "3463"
},
{
"name": "Shell",
"bytes": "7112"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FFFFFF">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="#2B2525"
android:gravity="center_vertical"
android:paddingStart="15dp"
android:paddingEnd="15dp">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/volver"
android:layout_width="35dp"
android:layout_height="40dp"
android:layout_gravity="center_vertical"
android:background="@android:color/white"
android:backgroundTint="@android:color/white"
android:clickable="true"
android:src="@drawable/back_button"
android:focusable="true" />
</com.google.android.material.appbar.AppBarLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.imageview.ShapeableImageView
android:id="@+id/imageViewHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_centerInParent="true"
android:contentDescription="@string/about_image"
android:src="@drawable/mboehao_help" />
<com.google.android.material.textview.MaterialTextView
android:id="@+id/version_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/version_number"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#795FCA"
android:layout_marginTop="15dp"
android:layout_gravity="center"
android:layout_below="@+id/imageViewHelp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout> | {
"content_hash": "ce6ebba7462cbe6b6e8b6b48cfccb684",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 111,
"avg_line_length": 40.92857142857143,
"alnum_prop": 0.6548865619546248,
"repo_name": "jokoframework/Mboehao",
"id": "9a88aacb0d2a4b5f76837cd54cddf27c1a1da302",
"size": "2292",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/src/main/res/layout/activity_about.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "409709"
}
],
"symlink_target": ""
} |
package org.wso2.carbon.bpmn.rest.service.base;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ActivitiIllegalArgumentException;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.ExecutionQueryProperty;
import org.activiti.engine.impl.persistence.entity.VariableInstanceEntity;
import org.activiti.engine.query.QueryProperty;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ExecutionQuery;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.apache.poi.util.IOUtils;
import org.wso2.carbon.bpmn.rest.common.RestResponseFactory;
import org.wso2.carbon.bpmn.rest.common.exception.BPMNConflictException;
import org.wso2.carbon.bpmn.rest.common.exception.BPMNContentNotSupportedException;
import org.wso2.carbon.bpmn.rest.common.utils.BPMNOSGIService;
import org.wso2.carbon.bpmn.rest.common.utils.Utils;
import org.wso2.carbon.bpmn.rest.engine.variable.QueryVariable;
import org.wso2.carbon.bpmn.rest.engine.variable.RestVariable;
import org.wso2.carbon.bpmn.rest.model.common.DataResponse;
import org.wso2.carbon.bpmn.rest.model.correlation.CorrelationActionRequest;
import org.wso2.carbon.bpmn.rest.model.runtime.*;
import javax.activation.DataHandler;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.*;
public class BaseExecutionService {
private static final Log log = LogFactory.getLog(BaseExecutionService.class);
//@Context
//protected UriInfo uriInfo;
protected static Map<String, QueryProperty> allowedSortProperties = new HashMap<String, QueryProperty>();
protected static final List<String> allPropertiesList = new ArrayList<>();
static {
allowedSortProperties.put("processDefinitionId", ExecutionQueryProperty.PROCESS_DEFINITION_ID);
allowedSortProperties.put("processDefinitionKey", ExecutionQueryProperty.PROCESS_DEFINITION_KEY);
allowedSortProperties.put("processInstanceId", ExecutionQueryProperty.PROCESS_INSTANCE_ID);
allowedSortProperties.put("tenantId", ExecutionQueryProperty.TENANT_ID);
}
static {
allPropertiesList.add("start");
allPropertiesList.add("size");
allPropertiesList.add("order");
allPropertiesList.add("sort");
allPropertiesList.add("id");
allPropertiesList.add("activityId");
allPropertiesList.add("processDefinitionKey");
allPropertiesList.add("processDefinitionId");
allPropertiesList.add("processInstanceId");
allPropertiesList.add("messageEventSubscriptionName");
allPropertiesList.add("signalEventSubscriptionName");
allPropertiesList.add("parentId");
allPropertiesList.add("tenantId");
allPropertiesList.add("tenantIdLike");
allPropertiesList.add("withoutTenantId");
}
protected DataResponse getQueryResponse(ExecutionQueryRequest queryRequest,
Map<String, String> requestParams, UriInfo uriInfo) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
ExecutionQuery query = runtimeService.createExecutionQuery();
// Populate query based on request
if (queryRequest.getId() != null) {
query.executionId(queryRequest.getId());
requestParams.put("id", queryRequest.getId());
}
if (queryRequest.getProcessInstanceId() != null) {
query.processInstanceId(queryRequest.getProcessInstanceId());
requestParams.put("processInstanceId", queryRequest.getProcessInstanceId());
}
if (queryRequest.getProcessDefinitionKey() != null) {
query.processDefinitionKey(queryRequest.getProcessDefinitionKey());
requestParams.put("processDefinitionKey", queryRequest.getProcessDefinitionKey());
}
if (queryRequest.getProcessDefinitionId() != null) {
query.processDefinitionId(queryRequest.getProcessDefinitionId());
requestParams.put("processDefinitionId", queryRequest.getProcessDefinitionId());
}
if (queryRequest.getProcessBusinessKey() != null) {
query.processInstanceBusinessKey(queryRequest.getProcessBusinessKey());
requestParams.put("processInstanceBusinessKey", queryRequest.getProcessBusinessKey());
}
if (queryRequest.getActivityId() != null) {
query.activityId(queryRequest.getActivityId());
requestParams.put("activityId", queryRequest.getActivityId());
}
if (queryRequest.getParentId() != null) {
query.parentId(queryRequest.getParentId());
requestParams.put("parentId", queryRequest.getParentId());
}
if (queryRequest.getMessageEventSubscriptionName() != null) {
query.messageEventSubscriptionName(queryRequest.getMessageEventSubscriptionName());
requestParams.put("messageEventSubscriptionName", queryRequest.getMessageEventSubscriptionName());
}
if (queryRequest.getSignalEventSubscriptionName() != null) {
query.signalEventSubscriptionName(queryRequest.getSignalEventSubscriptionName());
requestParams.put("signalEventSubscriptionName", queryRequest.getSignalEventSubscriptionName());
}
if (queryRequest.getVariables() != null) {
addVariables(query, queryRequest.getVariables(), false);
}
if (queryRequest.getProcessInstanceVariables() != null) {
addVariables(query, queryRequest.getProcessInstanceVariables(), true);
}
if (queryRequest.getTenantId() != null) {
query.executionTenantId(queryRequest.getTenantId());
requestParams.put("tenantId", queryRequest.getTenantId());
}
if (queryRequest.getTenantIdLike() != null) {
query.executionTenantIdLike(queryRequest.getTenantIdLike());
requestParams.put("tenantIdLike", queryRequest.getTenantIdLike());
}
if (Boolean.TRUE.equals(queryRequest.getWithoutTenantId())) {
query.executionWithoutTenantId();
requestParams.put("withoutTenantId", queryRequest.getWithoutTenantId().toString());
}
DataResponse dataResponse = new ExecutionPaginateList(new RestResponseFactory(), uriInfo)
.paginateList(requestParams, queryRequest, query, "processInstanceId", allowedSortProperties);
return dataResponse;
}
protected void addVariables(ExecutionQuery processInstanceQuery, List<QueryVariable> variables, boolean process) {
for (QueryVariable variable : variables) {
if (variable.getVariableOperation() == null) {
throw new ActivitiIllegalArgumentException("Variable operation is missing for variable: " + variable.getName());
}
if (variable.getValue() == null) {
throw new ActivitiIllegalArgumentException("Variable value is missing for variable: " + variable.getName());
}
boolean nameLess = variable.getName() == null;
Object actualValue = new RestResponseFactory().getVariableValue(variable);
// A value-only query is only possible using equals-operator
if (nameLess && variable.getVariableOperation() != QueryVariable.QueryVariableOperation.EQUALS) {
throw new ActivitiIllegalArgumentException("Value-only query (without a variable-name) is only supported when using 'equals' operation.");
}
switch (variable.getVariableOperation()) {
case EQUALS:
if (nameLess) {
if (process) {
processInstanceQuery.processVariableValueEquals(actualValue);
} else {
processInstanceQuery.variableValueEquals(actualValue);
}
} else {
if (process) {
processInstanceQuery.processVariableValueEquals(variable.getName(), actualValue);
} else {
processInstanceQuery.variableValueEquals(variable.getName(), actualValue);
}
}
break;
case EQUALS_IGNORE_CASE:
if (actualValue instanceof String) {
if (process) {
processInstanceQuery.processVariableValueEqualsIgnoreCase(variable.getName(), (String) actualValue);
} else {
processInstanceQuery.variableValueEqualsIgnoreCase(variable.getName(), (String) actualValue);
}
} else {
throw new ActivitiIllegalArgumentException("Only string variable values are supported when ignoring casing, but was: "
+ actualValue.getClass().getName());
}
break;
case NOT_EQUALS:
if (process) {
processInstanceQuery.processVariableValueNotEquals(variable.getName(), actualValue);
} else {
processInstanceQuery.variableValueNotEquals(variable.getName(), actualValue);
}
break;
case NOT_EQUALS_IGNORE_CASE:
if (actualValue instanceof String) {
if (process) {
processInstanceQuery.processVariableValueNotEqualsIgnoreCase(variable.getName(), (String) actualValue);
} else {
processInstanceQuery.variableValueNotEqualsIgnoreCase(variable.getName(), (String) actualValue);
}
} else {
throw new ActivitiIllegalArgumentException("Only string variable values are supported when ignoring casing, but was: "
+ actualValue.getClass().getName());
}
break;
default:
throw new ActivitiIllegalArgumentException("Unsupported variable query operation: " + variable.getVariableOperation());
}
}
}
protected Execution getExecutionFromRequest(String executionId) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
if (execution == null) {
throw new ActivitiObjectNotFoundException("Could not find an execution with id '" + executionId + "'.", Execution.class);
}
return execution;
}
protected Map<String, Object> getVariablesToSet(ExecutionActionRequest actionRequest) {
Map<String, Object> variablesToSet = new HashMap<String, Object>();
for (RestVariable var : actionRequest.getVariables()) {
if (var.getName() == null) {
throw new ActivitiIllegalArgumentException("Variable name is required");
}
Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
variablesToSet.put(var.getName(), actualVariableValue);
}
return variablesToSet;
}
protected Map<String, Object> getVariablesToSet(CorrelationActionRequest correlationActionRequest) {
Map<String, Object> variablesToSet = new HashMap<String, Object>();
for (RestVariable var : correlationActionRequest.getVariables()) {
if (var.getName() == null) {
throw new ActivitiIllegalArgumentException("Variable name is required");
}
Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
variablesToSet.put(var.getName(), actualVariableValue);
}
return variablesToSet;
}
protected List<RestVariable> processVariables(Execution execution, String scope, int variableType, UriInfo uriInfo) {
List<RestVariable> result = new ArrayList<RestVariable>();
Map<String, RestVariable> variableMap = new HashMap<String, RestVariable>();
// Check if it's a valid execution to get the variables for
RestVariable.RestVariableScope variableScope = RestVariable.getScopeFromString(scope);
if (variableScope == null) {
// Use both local and global variables
addLocalVariables(execution, variableType, variableMap, uriInfo);
addGlobalVariables(execution, variableType, variableMap, uriInfo);
} else if (variableScope == RestVariable.RestVariableScope.GLOBAL) {
addGlobalVariables(execution, variableType, variableMap, uriInfo);
} else if (variableScope == RestVariable.RestVariableScope.LOCAL) {
addLocalVariables(execution, variableType, variableMap, uriInfo);
}
// Get unique variables from map
result.addAll(variableMap.values());
return result;
}
protected void addLocalVariables(Execution execution, int variableType, Map<String, RestVariable> variableMap,
UriInfo uriInfo) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
Map<String, Object> rawLocalvariables = runtimeService.getVariablesLocal(execution.getId());
List<RestVariable> localVariables = new RestResponseFactory().createRestVariables(rawLocalvariables,
execution.getId(), variableType, RestVariable.RestVariableScope.LOCAL, uriInfo.getBaseUri().toString());
for (RestVariable var : localVariables) {
variableMap.put(var.getName(), var);
}
}
protected void addGlobalVariables(Execution execution, int variableType, Map<String, RestVariable> variableMap, UriInfo uriInfo) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
Map<String, Object> rawVariables = runtimeService.getVariables(execution.getId());
List<RestVariable> globalVariables = new RestResponseFactory().createRestVariables(rawVariables,
execution.getId(), variableType, RestVariable.RestVariableScope.GLOBAL, uriInfo.getBaseUri().toString());
// Overlay global variables over local ones. In case they are present the values are not overridden,
// since local variables get precedence over global ones at all times.
for (RestVariable var : globalVariables) {
if (!variableMap.containsKey(var.getName())) {
variableMap.put(var.getName(), var);
}
}
}
public void deleteAllLocalVariables(Execution execution) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
Collection<String> currentVariables = runtimeService.getVariablesLocal(execution.getId()).keySet();
runtimeService.removeVariablesLocal(execution.getId(), currentVariables);
}
protected RestVariable createBinaryExecutionVariable(Execution execution, int responseVariableType, UriInfo
uriInfo, boolean isNew, MultipartBody multipartBody) {
boolean debugEnabled = log.isDebugEnabled();
Response.ResponseBuilder responseBuilder = Response.ok();
List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();
int attachmentSize = attachments.size();
if (attachmentSize <= 0) {
throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
}
AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();
for (int i = 0; i < attachmentSize; i++) {
org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);
String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
String contentType = attachment.getHeader("Content-Type");
if (debugEnabled) {
log.debug("Going to iterate:" + i);
log.debug("contentDisposition:" + contentDispositionHeaderValue);
}
if (contentDispositionHeaderValue != null) {
contentDispositionHeaderValue = contentDispositionHeaderValue.trim();
Map<String, String> contentDispositionHeaderValueMap = Utils.processContentDispositionHeader
(contentDispositionHeaderValue);
String dispositionName = contentDispositionHeaderValueMap.get("name");
DataHandler dataHandler = attachment.getDataHandler();
OutputStream outputStream = null;
if ("name".equals(dispositionName)) {
try {
outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
}
if (outputStream != null) {
String fileName = outputStream.toString();
attachmentDataHolder.setName(fileName);
}
} else if ("type".equals(dispositionName)) {
try {
outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
}
if (outputStream != null) {
String typeName = outputStream.toString();
attachmentDataHolder.setType(typeName);
}
} else if ("scope".equals(dispositionName)) {
try {
outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured", e);
}
if (outputStream != null) {
String description = outputStream.toString();
attachmentDataHolder.setScope(description);
}
}
if (contentType != null) {
if ("file".equals(dispositionName)) {
InputStream inputStream = null;
try {
inputStream = dataHandler.getInputStream();
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("Error Occured During processing empty body.",
e);
}
if (inputStream != null) {
attachmentDataHolder.setContentType(contentType);
byte[] attachmentArray = new byte[0];
try {
attachmentArray = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
}
attachmentDataHolder.setAttachmentArray(attachmentArray);
}
}
}
}
}
attachmentDataHolder.printDebug();
if (attachmentDataHolder.getName() == null) {
throw new ActivitiIllegalArgumentException("Attachment name is required.");
}
if (attachmentDataHolder.getAttachmentArray() == null) {
throw new ActivitiIllegalArgumentException("Empty attachment body was found in request body after " +
"decoding the request" +
".");
}
String variableScope = attachmentDataHolder.getScope();
String variableName = attachmentDataHolder.getName();
String variableType = attachmentDataHolder.getType();
if (log.isDebugEnabled()) {
log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:" + variableType);
}
try {
// Validate input and set defaults
if (variableName == null) {
throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
}
if (variableType != null) {
if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory
.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
throw new ActivitiIllegalArgumentException("Only 'binary' and 'serializable' are supported as variable type.");
}
} else {
variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
}
RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
if (variableScope != null) {
scope = RestVariable.getScopeFromString(variableScope);
}
if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
// Use raw bytes as variable value
setVariable(execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);
} else {
// Try deserializing the object
InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
ObjectInputStream stream = new ObjectInputStream(inputStream);
Object value = stream.readObject();
setVariable(execution, variableName, value, scope, isNew);
stream.close();
}
if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType,
null, null, execution.getId(), uriInfo.getBaseUri().toString());
} else {
return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null,
execution.getId(), null, uriInfo.getBaseUri().toString());
}
} catch (IOException ioe) {
throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
} catch (ClassNotFoundException ioe) {
throw new BPMNContentNotSupportedException("The provided body contains a serialized object for which the class is nog found: " + ioe
.getMessage());
}
}
protected Response createExecutionVariable(Execution execution, boolean override, int variableType,
HttpServletRequest httpServletRequest, UriInfo uriInfo) {
Object result = null;
Response.ResponseBuilder responseBuilder = Response.ok();
List<RestVariable> inputVariables = new ArrayList<>();
List<RestVariable> resultVariables = new ArrayList<>();
if (Utils.isApplicationJsonRequest(httpServletRequest)) {
try {
ObjectMapper objectMapper = new ObjectMapper();
@SuppressWarnings("unchecked")
List<Object> variableObjects = (List<Object>) objectMapper.readValue(httpServletRequest.getInputStream(), List.class);
for (Object restObject : variableObjects) {
RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class);
inputVariables.add(restVariable);
}
} catch (Exception e) {
throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e);
}
} else if (Utils.isApplicationXmlRequest(httpServletRequest)) {
JAXBContext jaxbContext = null;
try {
jaxbContext = JAXBContext.newInstance(RestVariableCollection.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller.
unmarshal(httpServletRequest.getInputStream());
if (restVariableCollection == null) {
throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " +
"RestVariable Collection instance.");
}
List<RestVariable> restVariableList = restVariableCollection.getRestVariables();
if (restVariableList.size() == 0) {
throw new ActivitiIllegalArgumentException("xml request body could not identify any rest " +
"variables to be updated");
}
for (RestVariable restVariable : restVariableList) {
inputVariables.add(restVariable);
}
} catch (JAXBException | IOException e) {
throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " +
"RestVariable instance.", e);
}
}
if (inputVariables.size() == 0) {
throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create.");
}
RestVariable.RestVariableScope sharedScope = null;
RestVariable.RestVariableScope varScope = null;
Map<String, Object> variablesToSet = new HashMap<String, Object>();
for (RestVariable var : inputVariables) {
// Validate if scopes match
varScope = var.getVariableScope();
if (var.getName() == null) {
throw new ActivitiIllegalArgumentException("Variable name is required");
}
if (varScope == null) {
varScope = RestVariable.RestVariableScope.LOCAL;
}
if (sharedScope == null) {
sharedScope = varScope;
}
if (varScope != sharedScope) {
throw new ActivitiIllegalArgumentException("Only allowed to update multiple variables in the same scope.");
}
if (!override && hasVariableOnScope(execution, var.getName(), varScope)) {
throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'.");
}
Object actualVariableValue = new RestResponseFactory().getVariableValue(var);
variablesToSet.put(var.getName(), actualVariableValue);
resultVariables.add(new RestResponseFactory().createRestVariable(var.getName(), actualVariableValue, varScope,
execution.getId(), variableType, false, uriInfo.getBaseUri().toString()));
}
if (!variablesToSet.isEmpty()) {
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
if (sharedScope == RestVariable.RestVariableScope.LOCAL) {
runtimeService.setVariablesLocal(execution.getId(), variablesToSet);
} else {
if (execution.getParentId() != null) {
// Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists
runtimeService.setVariables(execution.getParentId(), variablesToSet);
} else {
// Standalone task, no global variables possible
throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process.");
}
}
}
RestVariableCollection restVariableCollection = new RestVariableCollection();
restVariableCollection.setRestVariables(resultVariables);
responseBuilder.entity(restVariableCollection);
return responseBuilder.status(Response.Status.CREATED).build();
}
/* protected RestVariable setBinaryVariable(@Context HttpServletRequest httpServletRequest,
Execution execution, int responseVariableType, boolean isNew, UriInfo uriInfo) {
byte[] byteArray = null;
try {
byteArray = Utils.processMultiPartFile(httpServletRequest, "file content");
} catch (IOException e) {
throw new ActivitiIllegalArgumentException("No file content was found in request body during multipart " +
"processing" +
".");
}
if (byteArray == null) {
throw new ActivitiIllegalArgumentException("No file content was found in request body.");
}
String variableScope = uriInfo.getQueryParameters().getFirst("scope");
String variableName = uriInfo.getQueryParameters().getFirst("name");
String variableType = uriInfo.getQueryParameters().getFirst("type");
if (log.isDebugEnabled()) {
log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:" + variableType);
}
try {
// Validate input and set defaults
if (variableName == null) {
throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
}
if (variableType != null) {
if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType) && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
throw new ActivitiIllegalArgumentException("Only 'binary' and 'serializable' are supported as variable type.");
}
} else {
variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
}
RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
if (variableScope != null) {
scope = RestVariable.getScopeFromString(variableScope);
}
if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
// Use raw bytes as variable value
setVariable(execution, variableName, byteArray, scope, isNew);
} else {
// Try deserializing the object
InputStream inputStream = new ByteArrayInputStream(byteArray);
ObjectInputStream stream = new ObjectInputStream(inputStream);
Object value = stream.readObject();
setVariable(execution, variableName, value, scope, isNew);
stream.close();
}
if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {
return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType,
null, null, execution.getId(), uriInfo.getBaseUri().toString());
} else {
return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null,
execution.getId(), null, uriInfo.getBaseUri().toString());
}
} catch (IOException ioe) {
throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
} catch (ClassNotFoundException ioe) {
throw new BPMNContentNotSupportedException("The provided body contains a serialized object for which the class is nog found: " + ioe
.getMessage());
}
}*/
protected void setVariable(Execution execution, String name, Object value, RestVariable.RestVariableScope scope, boolean isNew) {
// Create can only be done on new variables. Existing variables should be updated using PUT
boolean hasVariable = hasVariableOnScope(execution, name, scope);
if (isNew && hasVariable) {
throw new ActivitiException("Variable '" + name + "' is already present on execution '" + execution.getId() + "'.");
}
if (!isNew && !hasVariable) {
throw new ActivitiObjectNotFoundException("Execution '" + execution.getId() + "' doesn't have a variable with name: '" + name + "'.", null);
}
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
if (scope == RestVariable.RestVariableScope.LOCAL) {
runtimeService.setVariableLocal(execution.getId(), name, value);
} else {
if (execution.getParentId() != null) {
runtimeService.setVariable(execution.getParentId(), name, value);
} else {
runtimeService.setVariable(execution.getId(), name, value);
}
}
}
protected boolean hasVariableOnScope(Execution execution, String variableName, RestVariable.RestVariableScope scope) {
boolean variableFound = false;
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
if (scope == RestVariable.RestVariableScope.GLOBAL) {
if (execution.getParentId() != null && runtimeService.hasVariable(execution.getParentId(), variableName)) {
variableFound = true;
}
} else if (scope == RestVariable.RestVariableScope.LOCAL) {
if (runtimeService.hasVariableLocal(execution.getId(), variableName)) {
variableFound = true;
}
}
return variableFound;
}
public RestVariable getVariableFromRequest(Execution execution, String variableName, String scope,
boolean includeBinary, UriInfo uriInfo) {
boolean variableFound = false;
Object value = null;
if (execution == null) {
throw new ActivitiObjectNotFoundException("Could not find an execution", Execution.class);
}
RuntimeService runtimeService = BPMNOSGIService.getRumtimeService();
RestVariable.RestVariableScope variableScope = RestVariable.getScopeFromString(scope);
if (variableScope == null) {
// First, check local variables (which have precedence when no scope is supplied)
if (runtimeService.hasVariableLocal(execution.getId(), variableName)) {
value = runtimeService.getVariableLocal(execution.getId(), variableName);
variableScope = RestVariable.RestVariableScope.LOCAL;
variableFound = true;
} else {
if (execution.getParentId() != null) {
value = runtimeService.getVariable(execution.getParentId(), variableName);
variableScope = RestVariable.RestVariableScope.GLOBAL;
variableFound = true;
}
}
} else if (variableScope == RestVariable.RestVariableScope.GLOBAL) {
// Use parent to get variables
if (execution.getParentId() != null) {
value = runtimeService.getVariable(execution.getParentId(), variableName);
variableScope = RestVariable.RestVariableScope.GLOBAL;
variableFound = true;
}
} else if (variableScope == RestVariable.RestVariableScope.LOCAL) {
value = runtimeService.getVariableLocal(execution.getId(), variableName);
variableScope = RestVariable.RestVariableScope.LOCAL;
variableFound = true;
}
if (!variableFound) {
throw new ActivitiObjectNotFoundException("Execution '" + execution.getId() +
"' doesn't have a variable with name: '" + variableName + "'.", VariableInstanceEntity.class);
} else {
return constructRestVariable(variableName, value, variableScope, execution.getId(), includeBinary, uriInfo);
}
}
protected RestVariable constructRestVariable(String variableName, Object value,
RestVariable.RestVariableScope variableScope, String executionId,
boolean includeBinary, UriInfo uriInfo) {
return new RestResponseFactory().createRestVariable(variableName, value, variableScope, executionId,
RestResponseFactory.VARIABLE_EXECUTION, includeBinary, uriInfo.getBaseUri().toString());
}
protected RestVariable setSimpleVariable(RestVariable restVariable, Execution execution, boolean isNew, UriInfo
uriInfo) {
if (restVariable.getName() == null) {
throw new ActivitiIllegalArgumentException("Variable name is required");
}
// Figure out scope, revert to local is omitted
RestVariable.RestVariableScope scope = restVariable.getVariableScope();
if (scope == null) {
scope = RestVariable.RestVariableScope.LOCAL;
}
Object actualVariableValue = new RestResponseFactory().getVariableValue(restVariable);
setVariable(execution, restVariable.getName(), actualVariableValue, scope, isNew);
return constructRestVariable(restVariable.getName(), restVariable.getValue(), scope,
execution.getId(), false, uriInfo);
}
}
| {
"content_hash": "1b88fb45afc1dff1deadfaa4c81ad7b6",
"timestamp": "",
"source": "github",
"line_count": 783,
"max_line_length": 165,
"avg_line_length": 48.58876117496807,
"alnum_prop": 0.626521224865291,
"repo_name": "chathurace/carbon-business-process",
"id": "8731faca2f375a82054235ac7978d23d11930f49",
"size": "38696",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/bpmn/org.wso2.carbon.bpmn.rest/src/main/java/org/wso2/carbon/bpmn/rest/service/base/BaseExecutionService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "153131"
},
{
"name": "HTML",
"bytes": "33350"
},
{
"name": "Java",
"bytes": "5441947"
},
{
"name": "JavaScript",
"bytes": "1092772"
}
],
"symlink_target": ""
} |
// Karma configuration
// Generated on Wed Dec 31 2014 12:16:12 GMT-0500 (EST)
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '.',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['qunit'],
// list of files / patterns to load in the browser
files: [
'src/**/*.js',
'test/**/*.js'
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'junit'],
junitReporter: {
outputFile: 'test-results.xml'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],//['PhantomJS','Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true
});
};
| {
"content_hash": "e5fd275a13502e6a56c0840a4a6049e4",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 124,
"avg_line_length": 28.26153846153846,
"alnum_prop": 0.5949918345127926,
"repo_name": "timbeynart/gradle-node-demo",
"id": "71f070d64b77679f5f009bbd3879d8d61f2135d7",
"size": "1837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "karma.conf.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "2745"
}
],
"symlink_target": ""
} |
<?php
$this->pageTitle=Yii::app()->name . ' - '.UserModule::t("Login");
$this->breadcrumbs=array(
UserModule::t("Login"),
);
?>
<h1><?php echo UserModule::t("Login"); ?></h1>
<p><?php echo UserModule::t("Please fill out the following form with your login credentials:"); ?></p>
<?php $form=$this->beginWidget('ext.bootstrap.widgets.TbActiveForm', array(
'type'=>'horizontal',
)); ?>
<fieldset>
<legend><?php echo UserModule::t('Fields with <span class="required">*</span> are required.'); ?></legend>
<?php echo $form->errorSummary($model); ?>
<?php echo $form->textFieldRow($model,'username'); ?>
<?php echo $form->passwordFieldRow($model,'password',
array('hint'=>CHtml::link(UserModule::t("Lost Password?"),Yii::app()->getModule('user')->recoveryUrl))
); ?>
<?php echo $form->checkBoxRow($model,'rememberMe'); ?>
</fieldset>
<div class="form-actions">
<?php $this->widget('bootstrap.widgets.TbButton',array(
'label'=>UserModule::t("Login"),
'buttonType'=>'submit',
'type'=>'primary',
)); ?>
<?php $this->widget('bootstrap.widgets.TbButton',array(
'label'=>UserModule::t("Register"),
'buttonType'=>'link',
'type'=>'warning',
'url'=>Yii::app()->getModule('user')->registrationUrl,
)); ?>
</div>
<?php $this->endWidget(); ?> | {
"content_hash": "b8e3fe5c5fcc8f1376229a46bb0491fc",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 114,
"avg_line_length": 31.04255319148936,
"alnum_prop": 0.5524331734064428,
"repo_name": "fmahtab/yii",
"id": "98fa6a90cc72e45cfda2c7501a4a5f554dc592dc",
"size": "1459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/cli/views/webapp/protected/modules/user/views/user/login.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "442"
},
{
"name": "Batchfile",
"bytes": "1352"
},
{
"name": "CSS",
"bytes": "205219"
},
{
"name": "HTML",
"bytes": "36567"
},
{
"name": "JavaScript",
"bytes": "1241101"
},
{
"name": "Makefile",
"bytes": "1852"
},
{
"name": "PHP",
"bytes": "23881548"
},
{
"name": "PLpgSQL",
"bytes": "1946"
},
{
"name": "Shell",
"bytes": "1768"
}
],
"symlink_target": ""
} |
package controllers
import (
"github.com/nubleer/revel"
)
type Sample2 struct {
*revel.Controller
}
func (c Sample2) Index() revel.Result {
return c.Render()
}
func (c Sample2) HandleSubmit(
username, firstname, lastname string,
age int,
password, passwordConfirm, email, emailConfirm string,
termsOfUse bool) revel.Result {
// Validation rules
c.Validation.Required(username)
c.Validation.MinSize(username, 6)
c.Validation.Required(firstname)
c.Validation.Required(lastname)
c.Validation.Required(age)
c.Validation.Range(age, 16, 120)
c.Validation.Required(password)
c.Validation.MinSize(password, 6)
c.Validation.Required(passwordConfirm)
c.Validation.Required(passwordConfirm == password).Message("Your passwords do not match.")
c.Validation.Required(email)
c.Validation.Email(email)
c.Validation.Required(emailConfirm)
c.Validation.Required(emailConfirm == email).Message("Your email addresses do not match.")
c.Validation.Required(termsOfUse == true).Message("Please agree to the terms.")
// Handle errors
if c.Validation.HasErrors() {
c.Validation.Keep()
c.FlashParams()
return c.Redirect(Sample2.Index)
}
// Ok, display the created user
return c.Render(username, firstname, lastname, age, password, email)
}
| {
"content_hash": "fe1f4df2eddfcc5356bf2a1a268a0cbb",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 91,
"avg_line_length": 26.72340425531915,
"alnum_prop": 0.7587579617834395,
"repo_name": "nubleer/revel",
"id": "432bcced29c89b2947e904092a20b5d029c58c37",
"size": "1256",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/validation/app/controllers/sample2.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1726"
},
{
"name": "Go",
"bytes": "317490"
},
{
"name": "HTML",
"bytes": "14424"
},
{
"name": "NewLisp",
"bytes": "118"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User agent detail - Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="../circle.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
<h5 class="header light">
Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
</h5>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /><small>vendor/whichbrowser/parser/tests/data/television/lg.yaml</small></td><td> </td><td>Webkit 537.31</td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td>television</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-027cff01-4a76-491b-ace3-9289fcbc172f">Detail</a>
<!-- Modal Structure -->
<div id="modal-027cff01-4a76-491b-ace3-9289fcbc172f" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[headers] => User-Agent: Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
[result] => Array
(
[browser] => Array
(
[family] => Array
(
[name] => Chrome
[version] => 26
)
[type] => browser
)
[engine] => Array
(
[name] => Webkit
[version] => 537.31
)
[device] => Array
(
[type] => television
[manufacturer] => LG
[series] => webOS TV
)
)
[readable] => a LG webOS TV
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Chrome 26.0</td><td>WebKit </td><td>Linux </td><td style="border-left: 1px solid #555"></td><td></td><td>Desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.0624</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a>
<!-- Modal Structure -->
<div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapFull result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*\) applewebkit\/.* \(khtml,.*like gecko.*\) chrome\/26\..*safari\/.*$/
[browser_name_pattern] => mozilla/5.0 (*linux*) applewebkit/* (khtml,*like gecko*) chrome/26.*safari/*
[parent] => Chrome 26.0
[comment] => Chrome 26.0
[browser] => Chrome
[browser_type] => Browser
[browser_bits] => 32
[browser_maker] => Google Inc
[browser_modus] => unknown
[version] => 26.0
[majorver] => 26
[minorver] => 0
[platform] => Linux
[platform_version] => unknown
[platform_description] => Linux
[platform_bits] => 32
[platform_maker] => Linux Foundation
[alpha] =>
[beta] =>
[win16] =>
[win32] =>
[win64] =>
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[javascript] => 1
[vbscript] =>
[javaapplets] =>
[activexcontrols] =>
[ismobiledevice] =>
[istablet] =>
[issyndicationreader] =>
[crawler] =>
[isfake] =>
[isanonymized] =>
[ismodified] =>
[cssversion] => 3
[aolversion] => 0
[device_name] => Linux Desktop
[device_maker] => Various
[device_type] => Desktop
[device_pointing_method] => mouse
[device_code_name] => Linux Desktop
[device_brand_name] => unknown
[renderingengine_name] => WebKit
[renderingengine_version] => unknown
[renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3.
[renderingengine_maker] => Apple Inc
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td><td>Chrome </td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Desktop</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.0156</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-42bb56ba-b834-47c5-bea0-c0270e9ab371">Detail</a>
<!-- Modal Structure -->
<div id="modal-42bb56ba-b834-47c5-bea0-c0270e9ab371" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapLite result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*\) applewebkit\/.* \(khtml.* like gecko\) chrome\/.*safari\/.*$/
[browser_name_pattern] => mozilla/5.0 (*linux*) applewebkit/* (khtml* like gecko) chrome/*safari/*
[parent] => Chrome Generic
[comment] => Chrome Generic
[browser] => Chrome
[browser_type] => unknown
[browser_bits] => 0
[browser_maker] => unknown
[browser_modus] => unknown
[version] => 0.0
[majorver] => 0
[minorver] => 0
[platform] => Linux
[platform_version] => unknown
[platform_description] => unknown
[platform_bits] => 0
[platform_maker] => unknown
[alpha] => false
[beta] => false
[win16] => false
[win32] => false
[win64] => false
[frames] => false
[iframes] => false
[tables] => false
[cookies] => false
[backgroundsounds] => false
[javascript] => false
[vbscript] => false
[javaapplets] => false
[activexcontrols] => false
[ismobiledevice] =>
[istablet] =>
[issyndicationreader] => false
[crawler] => false
[isfake] => false
[isanonymized] => false
[ismodified] => false
[cssversion] => 0
[aolversion] => 0
[device_name] => unknown
[device_maker] => unknown
[device_type] => Desktop
[device_pointing_method] => unknown
[device_code_name] => unknown
[device_brand_name] => unknown
[renderingengine_name] => unknown
[renderingengine_version] => unknown
[renderingengine_description] => unknown
[renderingengine_maker] => unknown
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Chrome 26.0</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.0156</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a>
<!-- Modal Structure -->
<div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>BrowscapPhp result detail</h4>
<p><pre><code class="php">stdClass Object
(
[browser_name_regex] => /^mozilla\/5\.0 \(.*linux.*\) applewebkit\/.* \(khtml,.*like gecko.*\) chrome\/26\..*safari\/.*$/
[browser_name_pattern] => mozilla/5.0 (*linux*) applewebkit/* (khtml,*like gecko*) chrome/26.*safari/*
[parent] => Chrome 26.0
[comment] => Chrome 26.0
[browser] => Chrome
[browser_type] => unknown
[browser_bits] => 0
[browser_maker] => Google Inc
[browser_modus] => unknown
[version] => 26.0
[majorver] => 26
[minorver] => 0
[platform] => Linux
[platform_version] => unknown
[platform_description] => unknown
[platform_bits] => 0
[platform_maker] => unknown
[alpha] => false
[beta] => false
[win16] => false
[win32] => false
[win64] => false
[frames] => false
[iframes] => false
[tables] => false
[cookies] => false
[backgroundsounds] => false
[javascript] => false
[vbscript] => false
[javaapplets] => false
[activexcontrols] => false
[ismobiledevice] =>
[istablet] =>
[issyndicationreader] => false
[crawler] =>
[isfake] => false
[isanonymized] => false
[ismodified] => false
[cssversion] => 0
[aolversion] => 0
[device_name] => unknown
[device_maker] => unknown
[device_type] => Desktop
[device_pointing_method] => mouse
[device_code_name] => unknown
[device_brand_name] => unknown
[renderingengine_name] => unknown
[renderingengine_version] => unknown
[renderingengine_description] => unknown
[renderingengine_maker] => unknown
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a>
<!-- Modal Structure -->
<div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] => Linux
[browser] => Chrome
[version] => 26.0.1410.33
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a>
<!-- Modal Structure -->
<div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>JenssegersAgent result detail</h4>
<p><pre><code class="php">Array
(
[browserName] => Chrome
[browserVersion] => 26.0.1410.33
[osName] => Linux
[osVersion] =>
[deviceModel] => WebKit
[isMobile] =>
[isRobot] =>
[botName] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"></td><td></td><td>media-player</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.234</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a>
<!-- Modal Structure -->
<div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>NeutrinoApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[mobile_screen_height] => 0
[is_mobile] =>
[type] => media-player
[mobile_brand] =>
[mobile_model] =>
[version] => 26.0.1410.33
[is_android] =>
[browser_name] => Chrome
[operating_system_family] => Linux
[operating_system_version] =>
[is_ios] =>
[producer] => LG
[operating_system] => Linux
[mobile_screen_width] => 0
[mobile_browser] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td>Chrome 26.0</td><td>WebKit </td><td>GNU/Linux </td><td style="border-left: 1px solid #555"></td><td></td><td>desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a>
<!-- Modal Structure -->
<div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => Chrome
[short_name] => CH
[version] => 26.0
[engine] => WebKit
)
[operatingSystem] => Array
(
[name] => GNU/Linux
[short_name] => LIN
[version] =>
[platform] =>
)
[device] => Array
(
[brand] =>
[brandName] =>
[model] =>
[device] => 0
[deviceName] => desktop
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] =>
[isTablet] =>
[isTV] =>
[isDesktop] => 1
[isMobile] =>
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a>
<!-- Modal Structure -->
<div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>SinergiBrowserDetector result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Sinergi\BrowserDetector\Browser Object
(
[userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
)
[name:Sinergi\BrowserDetector\Browser:private] => Chrome
[version:Sinergi\BrowserDetector\Browser:private] => 26.0.1410.33
[isRobot:Sinergi\BrowserDetector\Browser:private] =>
[isChromeFrame:Sinergi\BrowserDetector\Browser:private] =>
[isFacebookWebView:Sinergi\BrowserDetector\Browser:private] =>
[isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] =>
)
[operatingSystem] => Sinergi\BrowserDetector\Os Object
(
[name:Sinergi\BrowserDetector\Os:private] => Linux
[version:Sinergi\BrowserDetector\Os:private] => unknown
[isMobile:Sinergi\BrowserDetector\Os:private] =>
[userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
)
)
[device] => Sinergi\BrowserDetector\Device Object
(
[name:Sinergi\BrowserDetector\Device:private] => unknown
[userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
)
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>Chrome 26.0.1410</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a>
<!-- Modal Structure -->
<div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] => 26
[minor] => 0
[patch] => 1410
[family] => Chrome
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Linux
)
[device] => UAParser\Result\Device Object
(
[brand] =>
[model] =>
[family] => Other
)
[originalUserAgent] => Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Chrome 26.0.1410.33</td><td>WebKit 537.31</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Desktop</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.156</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a>
<!-- Modal Structure -->
<div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentApiCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[platform_name] => Linux
[platform_version] => Linux
[platform_type] => Desktop
[browser_name] => Chrome
[browser_version] => 26.0.1410.33
[engine_name] => WebKit
[engine_version] => 537.31
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.1248</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a>
<!-- Modal Structure -->
<div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UserAgentStringCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[agent_type] => Browser
[agent_name] => Chrome
[agent_version] => 26.0.1410.33
[os_type] => Linux
[os_name] => Linux
[os_versionName] =>
[os_versionNumber] =>
[os_producer] =>
[os_producerURL] =>
[linux_distibution] => Null
[agent_language] =>
[agent_languageTag] =>
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Chrome 26.0.1410.33</td><td>WebKit 537.31</td><td>Linux </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.2496</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a>
<!-- Modal Structure -->
<div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhatIsMyBrowserCom result detail</h4>
<p><pre><code class="php">stdClass Object
(
[operating_system_name] => Linux
[simple_sub_description_string] =>
[simple_browser_string] => Chrome 26 on Linux
[browser_version] => 26
[extra_info] => Array
(
)
[operating_platform] =>
[extra_info_table] => Array
(
)
[layout_engine_name] => WebKit
[detected_addons] => Array
(
)
[operating_system_flavour_code] =>
[hardware_architecture] =>
[operating_system_flavour] =>
[operating_system_frameworks] => Array
(
)
[browser_name_code] => chrome
[operating_system_version] =>
[simple_operating_platform_string] =>
[is_abusive] =>
[layout_engine_version] => 537.31
[browser_capabilities] => Array
(
)
[operating_platform_vendor_name] =>
[operating_system] => Linux
[operating_system_version_full] =>
[operating_platform_code] =>
[browser_name] => Chrome
[operating_system_name_code] => linux
[user_agent] => Mozilla/5.0 (Linux; NetCast; U) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.33 Safari/537.31 SmartTV/5.0
[browser_version_full] => 26.0.1410.33
[browser] => Chrome 26
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td> </td><td>Webkit 537.31</td><td> </td><td style="border-left: 1px solid #555">LG</td><td>webOS TV</td><td>television</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a>
<!-- Modal Structure -->
<div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[family] => Array
(
[name] => Chrome
[version] => 26
)
[type] => browser
)
[engine] => Array
(
[name] => Webkit
[version] => 537.31
)
[device] => Array
(
[type] => television
[manufacturer] => LG
[series] => webOS TV
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>pc</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a>
<!-- Modal Structure -->
<div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Woothee result detail</h4>
<p><pre><code class="php">Array
(
[name] => Chrome
[vendor] => Google
[version] => 26.0.1410.33
[category] => pc
[os] => Linux
[os_version] => UNKNOWN
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td>Chrome 26.0.1410.33</td><td><i class="material-icons">close</i></td><td>Linux </td><td style="border-left: 1px solid #555"></td><td>SmartTV</td><td>Smart-TV</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.0156</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a>
<!-- Modal Structure -->
<div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => true
[is_mobile] => false
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => false
[is_html_preferred] => true
[advertised_device_os] => Linux
[advertised_device_os_version] =>
[advertised_browser] => Chrome
[advertised_browser_version] => 26.0.1410.33
[complete_device_name] => Generic SmartTV
[device_name] => Generic SmartTV
[form_factor] => Smart-TV
[is_phone] => false
[is_app_webview] => false
)
[all] => Array
(
[brand_name] => Generic
[model_name] => SmartTV
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => false
[device_claims_web_support] => true
[has_qwerty_keyboard] => true
[can_skip_aligned_link_row] => true
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] =>
[mobile_browser_version] =>
[device_os_version] =>
[pointing_method] =>
[release_date] => 2011_january
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => false
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => false
[softkey_support] => false
[table_support] => false
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => false
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => false
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => false
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => none
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => true
[xhtml_honors_bgcolor] => true
[xhtml_supports_forms_in_table] => true
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => true
[xhtml_select_as_radiobutton] => true
[xhtml_select_as_popup] => true
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => false
[xhtml_supports_css_cell_table_coloring] => false
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => false
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => utf8
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => none
[xhtmlmp_preferred_mime_type] => text/html
[xhtml_table_support] => false
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => full
[xhtml_avoid_accesskeys] => true
[xhtml_can_embed_video] => play_and_stop
[ajax_support_javascript] => true
[ajax_manipulate_css] => true
[ajax_support_getelementbyid] => true
[ajax_support_inner_html] => true
[ajax_xhr_type] => standard
[ajax_manipulate_dom] => true
[ajax_support_events] => true
[ajax_support_event_listener] => true
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 4
[preferred_markup] => html_web_4_0
[wml_1_1] => false
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => false
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => true
[html_web_4_0] => true
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 685
[resolution_height] => 600
[columns] => 120
[max_image_width] => 650
[max_image_height] => 600
[rows] => 200
[physical_screen_width] => 400
[physical_screen_height] => 400
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => false
[bmp] => true
[epoc_bmp] => false
[gif_animated] => true
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => true
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 65536
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 3200
[wifi] => true
[sdio] => false
[vpn] => false
[has_cellular_radio] => false
[max_deck_size] => 100000
[max_url_length_in_requests] => 128
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => false
[inline_support] => false
[oma_support] => false
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => true
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => false
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => true
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => true
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => true
[progressive_download] => true
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => html4
[viewport_supported] => false
[viewport_width] => width_equals_max_image_width
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => true
[is_smarttv] => true
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => A
[is_sencha_touch_ok] => true
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td>Maple Browser </td><td><i class="material-icons">close</i></td><td>GNU/Linux </td><td style="border-left: 1px solid #555">Samsung Smart TV</td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a>
<!-- Modal Structure -->
<div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Zsxsoft result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[link] => http://www.freethetvchallenge.com/details/faq
[title] => Maple Browser
[code] => maplebrowser
[version] =>
[name] => Maple Browser
[image] => img/16/browser/maplebrowser.png
)
[os] => Array
(
[link] => http://www.linux.org/
[name] => GNU/Linux
[version] =>
[code] => linux
[x64] =>
[title] => GNU/Linux
[type] => os
[dir] => os
[image] => img/16/os/linux.png
)
[device] => Array
(
[link] => http://www.samsung.com/us/experience/smart-tv/
[title] => Samsung Smart TV
[model] =>
[brand] => Samsung Smart TV
[code] => samsung
[dir] => device
[type] => device
[image] => img/16/device/samsung.png
)
[platform] => Array
(
[link] => http://www.samsung.com/us/experience/smart-tv/
[title] => Samsung Smart TV
[model] =>
[brand] => Samsung Smart TV
[code] => samsung
[dir] => device
[type] => device
[image] => img/16/device/samsung.png
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-05-10 07:52:20</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | {
"content_hash": "0f69e5bb6d00f5f91ecb2601d797517b",
"timestamp": "",
"source": "github",
"line_count": 1394,
"max_line_length": 875,
"avg_line_length": 40.329268292682926,
"alnum_prop": 0.5399420124868817,
"repo_name": "ThaDafinser/UserAgentParserComparison",
"id": "c71eca452cc895b6209fa9f3e7f91f75e72db9e8",
"size": "56220",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v5/user-agent-detail/18/dd/18ddeef7-14f1-46ca-ac75-ed5c01746b50.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2060859160"
}
],
"symlink_target": ""
} |
"""convert Gettext PO localization files to PHP localization files
see: http://translate.sourceforge.net/wiki/toolkit/po2php for examples and
usage instructions
"""
from translate.misc import quote
from translate.storage import po
from translate.storage import php
eol = "\n"
class rephp:
def __init__(self, templatefile):
self.templatefile = templatefile
self.inputdict = {}
def convertstore(self, inputstore, includefuzzy=False):
self.inmultilinemsgid = False
self.inecho = False
self.makestoredict(inputstore, includefuzzy)
outputlines = []
for line in self.templatefile.readlines():
outputstr = self.convertline(line)
outputlines.append(outputstr)
return outputlines
def makestoredict(self, store, includefuzzy=False):
'''make a dictionary of the translations'''
for unit in store.units:
if includefuzzy or not unit.isfuzzy():
for location in unit.getlocations():
inputstring = unit.target
if len(inputstring.strip()) == 0:
inputstring = unit.source
self.inputdict[location] = inputstring
def convertline(self, line):
line = unicode(line, 'utf-8')
returnline = ""
# handle multiline msgid if we're in one
if self.inmultilinemsgid:
# see if there's more
endpos = line.rfind("%s;" % self.quotechar)
# if there was no '; or the quote is escaped, we have to continue
if endpos >= 0 and line[endpos-1] != '\\':
self.inmultilinemsgid = False
# if we're echoing...
if self.inecho:
returnline = line
# otherwise, this could be a comment
elif line.strip()[:2] == '//' or line.strip()[:2] == '/*':
returnline = quote.rstripeol(line)+eol
else:
line = quote.rstripeol(line)
equalspos = line.find('=')
hashpos = line.find("#")
# if no equals, just repeat it
if equalspos == -1:
returnline = quote.rstripeol(line)+eol
elif 0 <= hashpos < equalspos:
# Assume that this is a '#' comment line
returnline = quote.rstripeol(line)+eol
# otherwise, this is a definition
else:
# now deal with the current string...
key = line[:equalspos].strip()
lookupkey = key.replace(" ", "")
# Calculate space around the equal sign
prespace = line[len(line[:equalspos].rstrip()):equalspos]
postspacestart = len(line[equalspos+1:])
postspaceend = len(line[equalspos+1:].lstrip())
postspace = line[equalspos+1:equalspos+(postspacestart-postspaceend)+1]
self.quotechar = line[equalspos+(postspacestart-postspaceend)+1]
inlinecomment_pos = line.rfind("%s;" % self.quotechar)
if inlinecomment_pos > -1:
inlinecomment = line[inlinecomment_pos+2:]
else:
inlinecomment = ""
if self.inputdict.has_key(lookupkey):
self.inecho = False
value = php.phpencode(self.inputdict[lookupkey], self.quotechar)
if isinstance(value, str):
value = value.decode('utf8')
returnline = key + prespace + "=" + postspace + self.quotechar + value + self.quotechar + ';' + inlinecomment + eol
else:
self.inecho = True
returnline = line+eol
# no string termination means carry string on to next line
endpos = line.rfind("%s;" % self.quotechar)
# if there was no '; or the quote is escaped, we have to continue
if endpos == -1 or line[endpos-1] == '\\':
self.inmultilinemsgid = True
if isinstance(returnline, unicode):
returnline = returnline.encode('utf-8')
return returnline
def convertphp(inputfile, outputfile, templatefile, includefuzzy=False):
inputstore = po.pofile(inputfile)
if templatefile is None:
raise ValueError("must have template file for php files")
# convertor = po2php()
else:
convertor = rephp(templatefile)
outputphplines = convertor.convertstore(inputstore, includefuzzy)
outputfile.writelines(outputphplines)
return 1
def main(argv=None):
# handle command line options
from translate.convert import convert
formats = {("po", "php"): ("php", convertphp)}
parser = convert.ConvertOptionParser(formats, usetemplates=True, description=__doc__)
parser.add_fuzzy_option()
parser.run(argv)
if __name__ == '__main__':
main()
| {
"content_hash": "4849cba25fc994246752ca48614be8de",
"timestamp": "",
"source": "github",
"line_count": 119,
"max_line_length": 135,
"avg_line_length": 41.436974789915965,
"alnum_prop": 0.5712837152707362,
"repo_name": "dbbhattacharya/kitsune",
"id": "8527660dc2f62df1ad1da1d3733410dda6a1f51c",
"size": "5760",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "vendor/packages/translate-toolkit/translate/convert/po2php.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "2694"
},
{
"name": "CSS",
"bytes": "276585"
},
{
"name": "HTML",
"bytes": "600145"
},
{
"name": "JavaScript",
"bytes": "800276"
},
{
"name": "Python",
"bytes": "2762831"
},
{
"name": "Shell",
"bytes": "6720"
},
{
"name": "Smarty",
"bytes": "1752"
}
],
"symlink_target": ""
} |
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try {
var pageTracker = _gat._getTracker("UA-10256201-1");
pageTracker._trackPageview();
} catch(err) {}
function setCurrent(elem){
var i, a;
for(i=0; (a = elem.parentNode.childNodes[i]); i++){
a.className = "";
}
elem.className="current";
}
function setContent(id, path){
var cid = id;
$.get(path, function(data){
$("#"+cid).html(data);
});
}
function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
for(i=0; (a = document.getElementsByTagName("li")[i]); i++) {
if(a.getAttribute("title")) {
if(a.getAttribute("title")==title) {
a.className = "current";
} else {
a.className = "";
}
}
}
}
function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}
function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}
jQuery(document).ready(function(){
jQuery(".ui-accordion-container").accordion({
header: ".ui-accordion-header",
autoHeight: false,
clearStyle: true,
alwaysOpen: false
});
jQuery(function($){
jQuery.datepicker.regional['zh-CN'] = {
clearText: '清除', clearStatus: '清除已选日期',
closeText: '关闭', closeStatus: '不改变当前选择',
prevText: '<上月', prevStatus: '显示上月',
prevBigText: '<<', prevBigStatus: '显示上一年',
nextText: '下月>', nextStatus: '显示下月',
nextBigText: '>>', nextBigStatus: '显示下一年',
currentText: '今天', currentStatus: '显示本月',
monthNames: ['一月','二月','三月','四月','五月','六月',
'七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['一','二','三','四','五','六',
'七','八','九','十','十一','十二'],
monthStatus: '选择月份', yearStatus: '选择年份',
weekHeader: '周', weekStatus: '年内周次',
dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
dayNamesMin: ['日','一','二','三','四','五','六'],
dayStatus: '设置 DD 为一周起始', dateStatus: '选择 m月 d日, DD',
dateFormat: 'yy-mm-dd', firstDay: 1,
initStatus: '请选择日期', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['zh-CN']);
});
jQuery('#ui-datepicker').datepicker({
changeFirstDay: false
});
jQuery("textarea > br").each( function() { jQuery(this).replaceWith( "\n" ); } );
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = "http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf";
SyntaxHighlighter.all();
dp.SyntaxHighlighter.HighlightAll("code");
});
// Call this function when the page has been loaded
function initialize() {
var searchControl = new google.search.SearchControl();
// create a drawOptions object
var drawOptions = new google.search.DrawOptions();
// tell the searcher to draw itself in tabbed mode
drawOptions.setDrawMode(google.search.SearchControl.DRAW_MODE_LINEAR);
// create a searcher options object
var searchOptions = new google.search.SearcherOptions();
// set up for open expansion mode
searchOptions.setExpandMode(google.search.SearchControl.EXPAND_MODE_CLOSED);
//searchControl.addSearcher(new google.search.LocalSearch(),searchOptions);
var siteSearch = new google.search.WebSearch();
siteSearch.setUserDefinedLabel("站内");
siteSearch.setUserDefinedClassSuffix("siteSearch");
siteSearch.setSiteRestriction(document.location.hostname);
searchControl.addSearcher(siteSearch,searchOptions);
searchControl.addSearcher(new google.search.WebSearch(),searchOptions);
searchControl.addSearcher(new google.search.BlogSearch(),searchOptions);
searchControl.addSearcher(new google.search.VideoSearch(),searchOptions);
//searchControl.addSearcher(new google.search.NewsSearch(),searchOptions);
searchControl.addSearcher(new google.search.ImageSearch(),searchOptions);
//searchControl.addSearcher(new google.search.BookSearch(),searchOptions);
searchControl.draw(document.getElementById("searchcontrol"),drawOptions);
}
google.setOnLoadCallback(initialize); | {
"content_hash": "4230313ddc939b63fc19a2430680c957",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 130,
"avg_line_length": 39.00617283950617,
"alnum_prop": 0.5860104446906156,
"repo_name": "lvbeck/niubi",
"id": "1fd50615aa2010a6def334e06f2afead236e0f5f",
"size": "6635",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/js/main.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "11144"
},
{
"name": "Python",
"bytes": "1172311"
}
],
"symlink_target": ""
} |
ModTweaker allows you to add or remove Extra Utilities 2 Resonator Recipes
## Calling
You can call the Resonator package using `mods.extrautils2.Resonator`
## Removing
```zenscript
//mods.extrautils2.Resonator.remove(IItemStack outout);
mods.extrautils2.Resonator.remove(<minecraft:redstone>);
```
## Сложение
```zenscript
<br />//1 GP = 100 energy
//mods.extrautils2.Resonator.add(IItemStack output, IItemStack input, int energy, @Optional boolean addOwnerTag);
mods.extrautils2.Resonator.add(<minecraft:redstone_block>, <minecraft:gold_block>, 100);
mods.extrautils2.Resonator.add(<minecraft:gold_block>, <minecraft:iron_block>, 200, false);
``` | {
"content_hash": "105fa4e1ec1305ad0f061852b609f913",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 113,
"avg_line_length": 31.095238095238095,
"alnum_prop": 0.7702909647779479,
"repo_name": "jaredlll08/CraftTweaker-Documentation",
"id": "7e8299ccc47ad95cd14ba9e1f5b60f58602cf58c",
"size": "674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "translations/ru/docs/Mods/Modtweaker/Extra_Utilities_2/Resonator.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "195475"
},
{
"name": "HTML",
"bytes": "11110"
},
{
"name": "JavaScript",
"bytes": "155278"
}
],
"symlink_target": ""
} |
class Room;
class Sprite {
public:
Sprite();
virtual ~Sprite();
// Comparison functions For draw-order sorting
bool operator< (const Sprite& rhs) const {
return position.y + size.h < rhs.position.y + rhs.size.h;
}
struct PointerCompare {
bool operator()(const Sprite* l, const Sprite* r) {
return *l < *r;
}
};
void Draw(Camera);
Position GetPosition() { return position; };
Size GetSize() { return size; };
Skin* GetSkin() { return skin; };
bool IsMirrored() { return isMirrored; };
void SetPosition(int x, int y);
void SetRoom(Room* room) { this->room = room; };
virtual void Update();
// Virtual methods for PhysicsBody
virtual void Move(std::vector<Sprite*>*);
virtual void PostMove();
protected:
bool isMirrored;
Position position;
Room* room;
Size size;
Skin* skin;
};
#endif // SPRITE_HPP
| {
"content_hash": "b6289a7825c15ab18b94081870b645d2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 69,
"avg_line_length": 26.846153846153847,
"alnum_prop": 0.5367717287488061,
"repo_name": "andmatand/kitty-town",
"id": "a49654a31086de63c77b7de8d0b59438e236e6ed",
"size": "1216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sprite.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "36468"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Selens est
un village
géographiquement positionné dans le département de l'Aisne en Picardie. On dénombrait 237 habitants en 2008.</p>
<p>Le parc de logements, à Selens, se décomposait en 2011 en zero appartements et 122 maisons soit
un marché plutôt équilibré.</p>
<p>Si vous envisagez de emmenager à Selens, vous pourrez aisément trouver une maison à vendre. </p>
<p>À proximité de Selens sont positionnées géographiquement les communes de
<a href="{{VLROOT}}/immobilier/bourguignon-sous-coucy_02107/">Bourguignon-sous-Coucy</a> à 5 km, 90 habitants,
<a href="{{VLROOT}}/immobilier/besme_02078/">Besmé</a> localisée à 5 km, 154 habitants,
<a href="{{VLROOT}}/immobilier/vezaponin_02793/">Vézaponin</a> située à 4 km, 124 habitants,
<a href="{{VLROOT}}/immobilier/trosly-loire_02750/">Trosly-Loire</a> localisée à 2 km, 583 habitants,
<a href="{{VLROOT}}/immobilier/guny_02363/">Guny</a> localisée à 4 km, 432 habitants,
<a href="{{VLROOT}}/immobilier/champs_02159/">Champs</a> à 5 km, 285 habitants,
entre autres. De plus, Selens est située à seulement 29 km de <a href="{{VLROOT}}/immobilier/compiegne_60159/">Compiègne</a>.</p>
</div>
| {
"content_hash": "c0c928403dc9fb38c539f123464f37a6",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 135,
"avg_line_length": 72.47058823529412,
"alnum_prop": 0.7353896103896104,
"repo_name": "donaldinou/frontend",
"id": "27d4a06676e7fb79bdbb8daba4017ceb8abca95d",
"size": "1264",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/02704.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
package br.com.cominotti.olympics_api.server.application.use_cases;
public class ListCompetitorsUseCaseInput {
}
| {
"content_hash": "73f515019461eefa4028106da33e2acb",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 67,
"avg_line_length": 24,
"alnum_prop": 0.7916666666666666,
"repo_name": "dcominottim/olympics-api",
"id": "bbe313410f15b840a538a4861a9f1d102210ad7f",
"size": "120",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/br/com/cominotti/olympics_api/server/application/use_cases/ListCompetitorsUseCaseInput.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "68923"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a5d240bb4b76d44f070e2842fe195aa9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "961853ace78b2ac61bd113a77e2a34d3c336b5b4",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Solanales/Convolvulaceae/Merremia/Merremia maypurensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
var expect = require('expect.js');
var utils = require('../src/utils');
require('mocha');
describe('Utils module', function () {
it('capitalize should handle null', function (done) {
expect(utils.capitalize(null)).to.be(null);
done();
});
it('capitalize should handle single chars', function (done) {
expect(utils.capitalize('a')).to.be('A');
done();
});
it('capitalize should handle longer strings', function (done) {
expect(utils.capitalize('abc')).to.be('Abc');
done();
});
}); | {
"content_hash": "55eba0d39424c5fd9e4b89097c86c522",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 64,
"avg_line_length": 27.88888888888889,
"alnum_prop": 0.647410358565737,
"repo_name": "metadevpro/baucis-openapi3",
"id": "fcc42a68f79584fc51417b0df88dbb2ee4fdbcab",
"size": "502",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/utils.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "97724"
}
],
"symlink_target": ""
} |
(function() {
var method;
var noop = function noop() {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
// Place any jQuery/helper plugins in here.
| {
"content_hash": "7ef5c1b48a034830341faa6c30d7940b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 76,
"avg_line_length": 27.2,
"alnum_prop": 0.5352941176470588,
"repo_name": "pixelmord/frondly",
"id": "467b82d6e1782ea53c7fdc6acc2dbb176bc88a01",
"size": "739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/plugins.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "215505"
},
{
"name": "JavaScript",
"bytes": "169617"
},
{
"name": "Ruby",
"bytes": "1730"
}
],
"symlink_target": ""
} |
#include <linux/jiffies.h>
#include <linux/slab.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/rcupdate.h>
#include <linux/export.h>
#include <net/mac80211.h>
#include <net/ieee80211_radiotap.h>
#include <asm/unaligned.h>
#include "ieee80211_i.h"
#include "driver-ops.h"
#include "led.h"
#include "mesh.h"
#include "wep.h"
#include "wpa.h"
#include "tkip.h"
#include "wme.h"
#include "rate.h"
static inline void ieee80211_rx_stats(struct net_device *dev, u32 len)
{
struct pcpu_sw_netstats *tstats = this_cpu_ptr(dev->tstats);
u64_stats_update_begin(&tstats->syncp);
tstats->rx_packets++;
tstats->rx_bytes += len;
u64_stats_update_end(&tstats->syncp);
}
static u8 *ieee80211_get_bssid(struct ieee80211_hdr *hdr, size_t len,
enum nl80211_iftype type)
{
__le16 fc = hdr->frame_control;
if (ieee80211_is_data(fc)) {
if (len < 24) /* drop incorrect hdr len (data) */
return NULL;
if (ieee80211_has_a4(fc))
return NULL;
if (ieee80211_has_tods(fc))
return hdr->addr1;
if (ieee80211_has_fromds(fc))
return hdr->addr2;
return hdr->addr3;
}
if (ieee80211_is_mgmt(fc)) {
if (len < 24) /* drop incorrect hdr len (mgmt) */
return NULL;
return hdr->addr3;
}
if (ieee80211_is_ctl(fc)) {
if (ieee80211_is_pspoll(fc))
return hdr->addr1;
if (ieee80211_is_back_req(fc)) {
switch (type) {
case NL80211_IFTYPE_STATION:
return hdr->addr2;
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
return hdr->addr1;
default:
break; /* fall through to the return */
}
}
}
return NULL;
}
/*
* monitor mode reception
*
* This function cleans up the SKB, i.e. it removes all the stuff
* only useful for monitoring.
*/
static struct sk_buff *remove_monitor_info(struct ieee80211_local *local,
struct sk_buff *skb,
unsigned int rtap_vendor_space)
{
if (ieee80211_hw_check(&local->hw, RX_INCLUDES_FCS)) {
if (likely(skb->len > FCS_LEN))
__pskb_trim(skb, skb->len - FCS_LEN);
else {
/* driver bug */
WARN_ON(1);
dev_kfree_skb(skb);
return NULL;
}
}
__pskb_pull(skb, rtap_vendor_space);
return skb;
}
static inline bool should_drop_frame(struct sk_buff *skb, int present_fcs_len,
unsigned int rtap_vendor_space)
{
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
struct ieee80211_hdr *hdr;
hdr = (void *)(skb->data + rtap_vendor_space);
if (status->flag & (RX_FLAG_FAILED_FCS_CRC |
RX_FLAG_FAILED_PLCP_CRC))
return true;
if (unlikely(skb->len < 16 + present_fcs_len + rtap_vendor_space))
return true;
if (ieee80211_is_ctl(hdr->frame_control) &&
!ieee80211_is_pspoll(hdr->frame_control) &&
!ieee80211_is_back_req(hdr->frame_control))
return true;
return false;
}
static int
ieee80211_rx_radiotap_hdrlen(struct ieee80211_local *local,
struct ieee80211_rx_status *status,
struct sk_buff *skb)
{
int len;
/* always present fields */
len = sizeof(struct ieee80211_radiotap_header) + 8;
/* allocate extra bitmaps */
if (status->chains)
len += 4 * hweight8(status->chains);
if (ieee80211_have_rx_timestamp(status)) {
len = ALIGN(len, 8);
len += 8;
}
if (ieee80211_hw_check(&local->hw, SIGNAL_DBM))
len += 1;
/* antenna field, if we don't have per-chain info */
if (!status->chains)
len += 1;
/* padding for RX_FLAGS if necessary */
len = ALIGN(len, 2);
if (status->flag & RX_FLAG_HT) /* HT info */
len += 3;
if (status->flag & RX_FLAG_AMPDU_DETAILS) {
len = ALIGN(len, 4);
len += 8;
}
if (status->flag & RX_FLAG_VHT) {
len = ALIGN(len, 2);
len += 12;
}
if (status->chains) {
/* antenna and antenna signal fields */
len += 2 * hweight8(status->chains);
}
if (status->flag & RX_FLAG_RADIOTAP_VENDOR_DATA) {
struct ieee80211_vendor_radiotap *rtap = (void *)skb->data;
/* vendor presence bitmap */
len += 4;
/* alignment for fixed 6-byte vendor data header */
len = ALIGN(len, 2);
/* vendor data header */
len += 6;
if (WARN_ON(rtap->align == 0))
rtap->align = 1;
len = ALIGN(len, rtap->align);
len += rtap->len + rtap->pad;
}
return len;
}
/*
* ieee80211_add_rx_radiotap_header - add radiotap header
*
* add a radiotap header containing all the fields which the hardware provided.
*/
static void
ieee80211_add_rx_radiotap_header(struct ieee80211_local *local,
struct sk_buff *skb,
struct ieee80211_rate *rate,
int rtap_len, bool has_fcs)
{
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
struct ieee80211_radiotap_header *rthdr;
unsigned char *pos;
__le32 *it_present;
u32 it_present_val;
u16 rx_flags = 0;
u16 channel_flags = 0;
int mpdulen, chain;
unsigned long chains = status->chains;
struct ieee80211_vendor_radiotap rtap = {};
if (status->flag & RX_FLAG_RADIOTAP_VENDOR_DATA) {
rtap = *(struct ieee80211_vendor_radiotap *)skb->data;
/* rtap.len and rtap.pad are undone immediately */
skb_pull(skb, sizeof(rtap) + rtap.len + rtap.pad);
}
mpdulen = skb->len;
if (!(has_fcs && ieee80211_hw_check(&local->hw, RX_INCLUDES_FCS)))
mpdulen += FCS_LEN;
rthdr = (struct ieee80211_radiotap_header *)skb_push(skb, rtap_len);
memset(rthdr, 0, rtap_len - rtap.len - rtap.pad);
it_present = &rthdr->it_present;
/* radiotap header, set always present flags */
rthdr->it_len = cpu_to_le16(rtap_len);
it_present_val = BIT(IEEE80211_RADIOTAP_FLAGS) |
BIT(IEEE80211_RADIOTAP_CHANNEL) |
BIT(IEEE80211_RADIOTAP_RX_FLAGS);
if (!status->chains)
it_present_val |= BIT(IEEE80211_RADIOTAP_ANTENNA);
for_each_set_bit(chain, &chains, IEEE80211_MAX_CHAINS) {
it_present_val |=
BIT(IEEE80211_RADIOTAP_EXT) |
BIT(IEEE80211_RADIOTAP_RADIOTAP_NAMESPACE);
put_unaligned_le32(it_present_val, it_present);
it_present++;
it_present_val = BIT(IEEE80211_RADIOTAP_ANTENNA) |
BIT(IEEE80211_RADIOTAP_DBM_ANTSIGNAL);
}
if (status->flag & RX_FLAG_RADIOTAP_VENDOR_DATA) {
it_present_val |= BIT(IEEE80211_RADIOTAP_VENDOR_NAMESPACE) |
BIT(IEEE80211_RADIOTAP_EXT);
put_unaligned_le32(it_present_val, it_present);
it_present++;
it_present_val = rtap.present;
}
put_unaligned_le32(it_present_val, it_present);
pos = (void *)(it_present + 1);
/* the order of the following fields is important */
/* IEEE80211_RADIOTAP_TSFT */
if (ieee80211_have_rx_timestamp(status)) {
/* padding */
while ((pos - (u8 *)rthdr) & 7)
*pos++ = 0;
put_unaligned_le64(
ieee80211_calculate_rx_timestamp(local, status,
mpdulen, 0),
pos);
rthdr->it_present |= cpu_to_le32(1 << IEEE80211_RADIOTAP_TSFT);
pos += 8;
}
/* IEEE80211_RADIOTAP_FLAGS */
if (has_fcs && ieee80211_hw_check(&local->hw, RX_INCLUDES_FCS))
*pos |= IEEE80211_RADIOTAP_F_FCS;
if (status->flag & (RX_FLAG_FAILED_FCS_CRC | RX_FLAG_FAILED_PLCP_CRC))
*pos |= IEEE80211_RADIOTAP_F_BADFCS;
if (status->flag & RX_FLAG_SHORTPRE)
*pos |= IEEE80211_RADIOTAP_F_SHORTPRE;
pos++;
/* IEEE80211_RADIOTAP_RATE */
if (!rate || status->flag & (RX_FLAG_HT | RX_FLAG_VHT)) {
/*
* Without rate information don't add it. If we have,
* MCS information is a separate field in radiotap,
* added below. The byte here is needed as padding
* for the channel though, so initialise it to 0.
*/
*pos = 0;
} else {
int shift = 0;
rthdr->it_present |= cpu_to_le32(1 << IEEE80211_RADIOTAP_RATE);
if (status->flag & RX_FLAG_10MHZ)
shift = 1;
else if (status->flag & RX_FLAG_5MHZ)
shift = 2;
*pos = DIV_ROUND_UP(rate->bitrate, 5 * (1 << shift));
}
pos++;
/* IEEE80211_RADIOTAP_CHANNEL */
put_unaligned_le16(status->freq, pos);
pos += 2;
if (status->flag & RX_FLAG_10MHZ)
channel_flags |= IEEE80211_CHAN_HALF;
else if (status->flag & RX_FLAG_5MHZ)
channel_flags |= IEEE80211_CHAN_QUARTER;
if (status->band == IEEE80211_BAND_5GHZ)
channel_flags |= IEEE80211_CHAN_OFDM | IEEE80211_CHAN_5GHZ;
else if (status->flag & (RX_FLAG_HT | RX_FLAG_VHT))
channel_flags |= IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
else if (rate && rate->flags & IEEE80211_RATE_ERP_G)
channel_flags |= IEEE80211_CHAN_OFDM | IEEE80211_CHAN_2GHZ;
else if (rate)
channel_flags |= IEEE80211_CHAN_CCK | IEEE80211_CHAN_2GHZ;
else
channel_flags |= IEEE80211_CHAN_2GHZ;
put_unaligned_le16(channel_flags, pos);
pos += 2;
/* IEEE80211_RADIOTAP_DBM_ANTSIGNAL */
if (ieee80211_hw_check(&local->hw, SIGNAL_DBM) &&
!(status->flag & RX_FLAG_NO_SIGNAL_VAL)) {
*pos = status->signal;
rthdr->it_present |=
cpu_to_le32(1 << IEEE80211_RADIOTAP_DBM_ANTSIGNAL);
pos++;
}
/* IEEE80211_RADIOTAP_LOCK_QUALITY is missing */
if (!status->chains) {
/* IEEE80211_RADIOTAP_ANTENNA */
*pos = status->antenna;
pos++;
}
/* IEEE80211_RADIOTAP_DB_ANTNOISE is not used */
/* IEEE80211_RADIOTAP_RX_FLAGS */
/* ensure 2 byte alignment for the 2 byte field as required */
if ((pos - (u8 *)rthdr) & 1)
*pos++ = 0;
if (status->flag & RX_FLAG_FAILED_PLCP_CRC)
rx_flags |= IEEE80211_RADIOTAP_F_RX_BADPLCP;
put_unaligned_le16(rx_flags, pos);
pos += 2;
if (status->flag & RX_FLAG_HT) {
unsigned int stbc;
rthdr->it_present |= cpu_to_le32(1 << IEEE80211_RADIOTAP_MCS);
*pos++ = local->hw.radiotap_mcs_details;
*pos = 0;
if (status->flag & RX_FLAG_SHORT_GI)
*pos |= IEEE80211_RADIOTAP_MCS_SGI;
if (status->flag & RX_FLAG_40MHZ)
*pos |= IEEE80211_RADIOTAP_MCS_BW_40;
if (status->flag & RX_FLAG_HT_GF)
*pos |= IEEE80211_RADIOTAP_MCS_FMT_GF;
if (status->flag & RX_FLAG_LDPC)
*pos |= IEEE80211_RADIOTAP_MCS_FEC_LDPC;
stbc = (status->flag & RX_FLAG_STBC_MASK) >> RX_FLAG_STBC_SHIFT;
*pos |= stbc << IEEE80211_RADIOTAP_MCS_STBC_SHIFT;
pos++;
*pos++ = status->rate_idx;
}
if (status->flag & RX_FLAG_AMPDU_DETAILS) {
u16 flags = 0;
/* ensure 4 byte alignment */
while ((pos - (u8 *)rthdr) & 3)
pos++;
rthdr->it_present |=
cpu_to_le32(1 << IEEE80211_RADIOTAP_AMPDU_STATUS);
put_unaligned_le32(status->ampdu_reference, pos);
pos += 4;
if (status->flag & RX_FLAG_AMPDU_LAST_KNOWN)
flags |= IEEE80211_RADIOTAP_AMPDU_LAST_KNOWN;
if (status->flag & RX_FLAG_AMPDU_IS_LAST)
flags |= IEEE80211_RADIOTAP_AMPDU_IS_LAST;
if (status->flag & RX_FLAG_AMPDU_DELIM_CRC_ERROR)
flags |= IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_ERR;
if (status->flag & RX_FLAG_AMPDU_DELIM_CRC_KNOWN)
flags |= IEEE80211_RADIOTAP_AMPDU_DELIM_CRC_KNOWN;
put_unaligned_le16(flags, pos);
pos += 2;
if (status->flag & RX_FLAG_AMPDU_DELIM_CRC_KNOWN)
*pos++ = status->ampdu_delimiter_crc;
else
*pos++ = 0;
*pos++ = 0;
}
if (status->flag & RX_FLAG_VHT) {
u16 known = local->hw.radiotap_vht_details;
rthdr->it_present |= cpu_to_le32(1 << IEEE80211_RADIOTAP_VHT);
put_unaligned_le16(known, pos);
pos += 2;
/* flags */
if (status->flag & RX_FLAG_SHORT_GI)
*pos |= IEEE80211_RADIOTAP_VHT_FLAG_SGI;
/* in VHT, STBC is binary */
if (status->flag & RX_FLAG_STBC_MASK)
*pos |= IEEE80211_RADIOTAP_VHT_FLAG_STBC;
if (status->vht_flag & RX_VHT_FLAG_BF)
*pos |= IEEE80211_RADIOTAP_VHT_FLAG_BEAMFORMED;
pos++;
/* bandwidth */
if (status->vht_flag & RX_VHT_FLAG_80MHZ)
*pos++ = 4;
else if (status->vht_flag & RX_VHT_FLAG_160MHZ)
*pos++ = 11;
else if (status->flag & RX_FLAG_40MHZ)
*pos++ = 1;
else /* 20 MHz */
*pos++ = 0;
/* MCS/NSS */
*pos = (status->rate_idx << 4) | status->vht_nss;
pos += 4;
/* coding field */
if (status->flag & RX_FLAG_LDPC)
*pos |= IEEE80211_RADIOTAP_CODING_LDPC_USER0;
pos++;
/* group ID */
pos++;
/* partial_aid */
pos += 2;
}
for_each_set_bit(chain, &chains, IEEE80211_MAX_CHAINS) {
*pos++ = status->chain_signal[chain];
*pos++ = chain;
}
if (status->flag & RX_FLAG_RADIOTAP_VENDOR_DATA) {
/* ensure 2 byte alignment for the vendor field as required */
if ((pos - (u8 *)rthdr) & 1)
*pos++ = 0;
*pos++ = rtap.oui[0];
*pos++ = rtap.oui[1];
*pos++ = rtap.oui[2];
*pos++ = rtap.subns;
put_unaligned_le16(rtap.len, pos);
pos += 2;
/* align the actual payload as requested */
while ((pos - (u8 *)rthdr) & (rtap.align - 1))
*pos++ = 0;
/* data (and possible padding) already follows */
}
}
/*
* This function copies a received frame to all monitor interfaces and
* returns a cleaned-up SKB that no longer includes the FCS nor the
* radiotap header the driver might have added.
*/
static struct sk_buff *
ieee80211_rx_monitor(struct ieee80211_local *local, struct sk_buff *origskb,
struct ieee80211_rate *rate)
{
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(origskb);
struct ieee80211_sub_if_data *sdata;
int rt_hdrlen, needed_headroom;
struct sk_buff *skb, *skb2;
struct net_device *prev_dev = NULL;
int present_fcs_len = 0;
unsigned int rtap_vendor_space = 0;
if (unlikely(status->flag & RX_FLAG_RADIOTAP_VENDOR_DATA)) {
struct ieee80211_vendor_radiotap *rtap = (void *)origskb->data;
rtap_vendor_space = sizeof(*rtap) + rtap->len + rtap->pad;
}
/*
* First, we may need to make a copy of the skb because
* (1) we need to modify it for radiotap (if not present), and
* (2) the other RX handlers will modify the skb we got.
*
* We don't need to, of course, if we aren't going to return
* the SKB because it has a bad FCS/PLCP checksum.
*/
if (ieee80211_hw_check(&local->hw, RX_INCLUDES_FCS))
present_fcs_len = FCS_LEN;
/* ensure hdr->frame_control and vendor radiotap data are in skb head */
if (!pskb_may_pull(origskb, 2 + rtap_vendor_space)) {
dev_kfree_skb(origskb);
return NULL;
}
if (!local->monitors) {
if (should_drop_frame(origskb, present_fcs_len,
rtap_vendor_space)) {
dev_kfree_skb(origskb);
return NULL;
}
return remove_monitor_info(local, origskb, rtap_vendor_space);
}
/* room for the radiotap header based on driver features */
rt_hdrlen = ieee80211_rx_radiotap_hdrlen(local, status, origskb);
needed_headroom = rt_hdrlen - rtap_vendor_space;
if (should_drop_frame(origskb, present_fcs_len, rtap_vendor_space)) {
/* only need to expand headroom if necessary */
skb = origskb;
origskb = NULL;
/*
* This shouldn't trigger often because most devices have an
* RX header they pull before we get here, and that should
* be big enough for our radiotap information. We should
* probably export the length to drivers so that we can have
* them allocate enough headroom to start with.
*/
if (skb_headroom(skb) < needed_headroom &&
pskb_expand_head(skb, needed_headroom, 0, GFP_ATOMIC)) {
dev_kfree_skb(skb);
return NULL;
}
} else {
/*
* Need to make a copy and possibly remove radiotap header
* and FCS from the original.
*/
skb = skb_copy_expand(origskb, needed_headroom, 0, GFP_ATOMIC);
origskb = remove_monitor_info(local, origskb,
rtap_vendor_space);
if (!skb)
return origskb;
}
/* prepend radiotap information */
ieee80211_add_rx_radiotap_header(local, skb, rate, rt_hdrlen, true);
skb_reset_mac_header(skb);
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
list_for_each_entry_rcu(sdata, &local->interfaces, list) {
if (sdata->vif.type != NL80211_IFTYPE_MONITOR)
continue;
if (sdata->u.mntr_flags & MONITOR_FLAG_COOK_FRAMES)
continue;
if (!ieee80211_sdata_running(sdata))
continue;
if (prev_dev) {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2) {
skb2->dev = prev_dev;
netif_receive_skb(skb2);
}
}
prev_dev = sdata->dev;
ieee80211_rx_stats(sdata->dev, skb->len);
}
if (prev_dev) {
skb->dev = prev_dev;
netif_receive_skb(skb);
} else
dev_kfree_skb(skb);
return origskb;
}
static void ieee80211_parse_qos(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
int tid, seqno_idx, security_idx;
/* does the frame have a qos control field? */
if (ieee80211_is_data_qos(hdr->frame_control)) {
u8 *qc = ieee80211_get_qos_ctl(hdr);
/* frame has qos control */
tid = *qc & IEEE80211_QOS_CTL_TID_MASK;
if (*qc & IEEE80211_QOS_CTL_A_MSDU_PRESENT)
status->rx_flags |= IEEE80211_RX_AMSDU;
seqno_idx = tid;
security_idx = tid;
} else {
/*
* IEEE 802.11-2007, 7.1.3.4.1 ("Sequence Number field"):
*
* Sequence numbers for management frames, QoS data
* frames with a broadcast/multicast address in the
* Address 1 field, and all non-QoS data frames sent
* by QoS STAs are assigned using an additional single
* modulo-4096 counter, [...]
*
* We also use that counter for non-QoS STAs.
*/
seqno_idx = IEEE80211_NUM_TIDS;
security_idx = 0;
if (ieee80211_is_mgmt(hdr->frame_control))
security_idx = IEEE80211_NUM_TIDS;
tid = 0;
}
rx->seqno_idx = seqno_idx;
rx->security_idx = security_idx;
/* Set skb->priority to 1d tag if highest order bit of TID is not set.
* For now, set skb->priority to 0 for other cases. */
rx->skb->priority = (tid > 7) ? 0 : tid;
}
/**
* DOC: Packet alignment
*
* Drivers always need to pass packets that are aligned to two-byte boundaries
* to the stack.
*
* Additionally, should, if possible, align the payload data in a way that
* guarantees that the contained IP header is aligned to a four-byte
* boundary. In the case of regular frames, this simply means aligning the
* payload to a four-byte boundary (because either the IP header is directly
* contained, or IV/RFC1042 headers that have a length divisible by four are
* in front of it). If the payload data is not properly aligned and the
* architecture doesn't support efficient unaligned operations, mac80211
* will align the data.
*
* With A-MSDU frames, however, the payload data address must yield two modulo
* four because there are 14-byte 802.3 headers within the A-MSDU frames that
* push the IP header further back to a multiple of four again. Thankfully, the
* specs were sane enough this time around to require padding each A-MSDU
* subframe to a length that is a multiple of four.
*
* Padding like Atheros hardware adds which is between the 802.11 header and
* the payload is not supported, the driver is required to move the 802.11
* header to be directly in front of the payload in that case.
*/
static void ieee80211_verify_alignment(struct ieee80211_rx_data *rx)
{
#ifdef CONFIG_MAC80211_VERBOSE_DEBUG
WARN_ONCE((unsigned long)rx->skb->data & 1,
"unaligned packet at 0x%p\n", rx->skb->data);
#endif
}
/* rx handlers */
static int ieee80211_is_unicast_robust_mgmt_frame(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
if (is_multicast_ether_addr(hdr->addr1))
return 0;
return ieee80211_is_robust_mgmt_frame(skb);
}
static int ieee80211_is_multicast_robust_mgmt_frame(struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
if (!is_multicast_ether_addr(hdr->addr1))
return 0;
return ieee80211_is_robust_mgmt_frame(skb);
}
/* Get the BIP key index from MMIE; return -1 if this is not a BIP frame */
static int ieee80211_get_mmie_keyidx(struct sk_buff *skb)
{
struct ieee80211_mgmt *hdr = (struct ieee80211_mgmt *) skb->data;
struct ieee80211_mmie *mmie;
struct ieee80211_mmie_16 *mmie16;
if (skb->len < 24 + sizeof(*mmie) || !is_multicast_ether_addr(hdr->da))
return -1;
if (!ieee80211_is_robust_mgmt_frame(skb))
return -1; /* not a robust management frame */
mmie = (struct ieee80211_mmie *)
(skb->data + skb->len - sizeof(*mmie));
if (mmie->element_id == WLAN_EID_MMIE &&
mmie->length == sizeof(*mmie) - 2)
return le16_to_cpu(mmie->key_id);
mmie16 = (struct ieee80211_mmie_16 *)
(skb->data + skb->len - sizeof(*mmie16));
if (skb->len >= 24 + sizeof(*mmie16) &&
mmie16->element_id == WLAN_EID_MMIE &&
mmie16->length == sizeof(*mmie16) - 2)
return le16_to_cpu(mmie16->key_id);
return -1;
}
static int iwl80211_get_cs_keyid(const struct ieee80211_cipher_scheme *cs,
struct sk_buff *skb)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
__le16 fc;
int hdrlen;
u8 keyid;
fc = hdr->frame_control;
hdrlen = ieee80211_hdrlen(fc);
if (skb->len < hdrlen + cs->hdr_len)
return -EINVAL;
skb_copy_bits(skb, hdrlen + cs->key_idx_off, &keyid, 1);
keyid &= cs->key_idx_mask;
keyid >>= cs->key_idx_shift;
return keyid;
}
static ieee80211_rx_result ieee80211_rx_mesh_check(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
char *dev_addr = rx->sdata->vif.addr;
if (ieee80211_is_data(hdr->frame_control)) {
if (is_multicast_ether_addr(hdr->addr1)) {
if (ieee80211_has_tods(hdr->frame_control) ||
!ieee80211_has_fromds(hdr->frame_control))
return RX_DROP_MONITOR;
if (ether_addr_equal(hdr->addr3, dev_addr))
return RX_DROP_MONITOR;
} else {
if (!ieee80211_has_a4(hdr->frame_control))
return RX_DROP_MONITOR;
if (ether_addr_equal(hdr->addr4, dev_addr))
return RX_DROP_MONITOR;
}
}
/* If there is not an established peer link and this is not a peer link
* establisment frame, beacon or probe, drop the frame.
*/
if (!rx->sta || sta_plink_state(rx->sta) != NL80211_PLINK_ESTAB) {
struct ieee80211_mgmt *mgmt;
if (!ieee80211_is_mgmt(hdr->frame_control))
return RX_DROP_MONITOR;
if (ieee80211_is_action(hdr->frame_control)) {
u8 category;
/* make sure category field is present */
if (rx->skb->len < IEEE80211_MIN_ACTION_SIZE)
return RX_DROP_MONITOR;
mgmt = (struct ieee80211_mgmt *)hdr;
category = mgmt->u.action.category;
if (category != WLAN_CATEGORY_MESH_ACTION &&
category != WLAN_CATEGORY_SELF_PROTECTED)
return RX_DROP_MONITOR;
return RX_CONTINUE;
}
if (ieee80211_is_probe_req(hdr->frame_control) ||
ieee80211_is_probe_resp(hdr->frame_control) ||
ieee80211_is_beacon(hdr->frame_control) ||
ieee80211_is_auth(hdr->frame_control))
return RX_CONTINUE;
return RX_DROP_MONITOR;
}
return RX_CONTINUE;
}
static void ieee80211_release_reorder_frame(struct ieee80211_sub_if_data *sdata,
struct tid_ampdu_rx *tid_agg_rx,
int index,
struct sk_buff_head *frames)
{
struct sk_buff_head *skb_list = &tid_agg_rx->reorder_buf[index];
struct sk_buff *skb;
struct ieee80211_rx_status *status;
lockdep_assert_held(&tid_agg_rx->reorder_lock);
if (skb_queue_empty(skb_list))
goto no_frame;
if (!ieee80211_rx_reorder_ready(skb_list)) {
__skb_queue_purge(skb_list);
goto no_frame;
}
/* release frames from the reorder ring buffer */
tid_agg_rx->stored_mpdu_num--;
while ((skb = __skb_dequeue(skb_list))) {
status = IEEE80211_SKB_RXCB(skb);
status->rx_flags |= IEEE80211_RX_DEFERRED_RELEASE;
__skb_queue_tail(frames, skb);
}
no_frame:
tid_agg_rx->head_seq_num = ieee80211_sn_inc(tid_agg_rx->head_seq_num);
}
static void ieee80211_release_reorder_frames(struct ieee80211_sub_if_data *sdata,
struct tid_ampdu_rx *tid_agg_rx,
u16 head_seq_num,
struct sk_buff_head *frames)
{
int index;
lockdep_assert_held(&tid_agg_rx->reorder_lock);
while (ieee80211_sn_less(tid_agg_rx->head_seq_num, head_seq_num)) {
index = tid_agg_rx->head_seq_num % tid_agg_rx->buf_size;
ieee80211_release_reorder_frame(sdata, tid_agg_rx, index,
frames);
}
}
/*
* Timeout (in jiffies) for skb's that are waiting in the RX reorder buffer. If
* the skb was added to the buffer longer than this time ago, the earlier
* frames that have not yet been received are assumed to be lost and the skb
* can be released for processing. This may also release other skb's from the
* reorder buffer if there are no additional gaps between the frames.
*
* Callers must hold tid_agg_rx->reorder_lock.
*/
#define HT_RX_REORDER_BUF_TIMEOUT (HZ / 10)
static void ieee80211_sta_reorder_release(struct ieee80211_sub_if_data *sdata,
struct tid_ampdu_rx *tid_agg_rx,
struct sk_buff_head *frames)
{
int index, i, j;
lockdep_assert_held(&tid_agg_rx->reorder_lock);
/* release the buffer until next missing frame */
index = tid_agg_rx->head_seq_num % tid_agg_rx->buf_size;
if (!ieee80211_rx_reorder_ready(&tid_agg_rx->reorder_buf[index]) &&
tid_agg_rx->stored_mpdu_num) {
/*
* No buffers ready to be released, but check whether any
* frames in the reorder buffer have timed out.
*/
int skipped = 1;
for (j = (index + 1) % tid_agg_rx->buf_size; j != index;
j = (j + 1) % tid_agg_rx->buf_size) {
if (!ieee80211_rx_reorder_ready(
&tid_agg_rx->reorder_buf[j])) {
skipped++;
continue;
}
if (skipped &&
!time_after(jiffies, tid_agg_rx->reorder_time[j] +
HT_RX_REORDER_BUF_TIMEOUT))
goto set_release_timer;
/* don't leave incomplete A-MSDUs around */
for (i = (index + 1) % tid_agg_rx->buf_size; i != j;
i = (i + 1) % tid_agg_rx->buf_size)
__skb_queue_purge(&tid_agg_rx->reorder_buf[i]);
ht_dbg_ratelimited(sdata,
"release an RX reorder frame due to timeout on earlier frames\n");
ieee80211_release_reorder_frame(sdata, tid_agg_rx, j,
frames);
/*
* Increment the head seq# also for the skipped slots.
*/
tid_agg_rx->head_seq_num =
(tid_agg_rx->head_seq_num +
skipped) & IEEE80211_SN_MASK;
skipped = 0;
}
} else while (ieee80211_rx_reorder_ready(
&tid_agg_rx->reorder_buf[index])) {
ieee80211_release_reorder_frame(sdata, tid_agg_rx, index,
frames);
index = tid_agg_rx->head_seq_num % tid_agg_rx->buf_size;
}
if (tid_agg_rx->stored_mpdu_num) {
j = index = tid_agg_rx->head_seq_num % tid_agg_rx->buf_size;
for (; j != (index - 1) % tid_agg_rx->buf_size;
j = (j + 1) % tid_agg_rx->buf_size) {
if (ieee80211_rx_reorder_ready(
&tid_agg_rx->reorder_buf[j]))
break;
}
set_release_timer:
if (!tid_agg_rx->removed)
mod_timer(&tid_agg_rx->reorder_timer,
tid_agg_rx->reorder_time[j] + 1 +
HT_RX_REORDER_BUF_TIMEOUT);
} else {
del_timer(&tid_agg_rx->reorder_timer);
}
}
/*
* As this function belongs to the RX path it must be under
* rcu_read_lock protection. It returns false if the frame
* can be processed immediately, true if it was consumed.
*/
static bool ieee80211_sta_manage_reorder_buf(struct ieee80211_sub_if_data *sdata,
struct tid_ampdu_rx *tid_agg_rx,
struct sk_buff *skb,
struct sk_buff_head *frames)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
u16 sc = le16_to_cpu(hdr->seq_ctrl);
u16 mpdu_seq_num = (sc & IEEE80211_SCTL_SEQ) >> 4;
u16 head_seq_num, buf_size;
int index;
bool ret = true;
spin_lock(&tid_agg_rx->reorder_lock);
/*
* Offloaded BA sessions have no known starting sequence number so pick
* one from first Rxed frame for this tid after BA was started.
*/
if (unlikely(tid_agg_rx->auto_seq)) {
tid_agg_rx->auto_seq = false;
tid_agg_rx->ssn = mpdu_seq_num;
tid_agg_rx->head_seq_num = mpdu_seq_num;
}
buf_size = tid_agg_rx->buf_size;
head_seq_num = tid_agg_rx->head_seq_num;
/* frame with out of date sequence number */
if (ieee80211_sn_less(mpdu_seq_num, head_seq_num)) {
dev_kfree_skb(skb);
goto out;
}
/*
* If frame the sequence number exceeds our buffering window
* size release some previous frames to make room for this one.
*/
if (!ieee80211_sn_less(mpdu_seq_num, head_seq_num + buf_size)) {
head_seq_num = ieee80211_sn_inc(
ieee80211_sn_sub(mpdu_seq_num, buf_size));
/* release stored frames up to new head to stack */
ieee80211_release_reorder_frames(sdata, tid_agg_rx,
head_seq_num, frames);
}
/* Now the new frame is always in the range of the reordering buffer */
index = mpdu_seq_num % tid_agg_rx->buf_size;
/* check if we already stored this frame */
if (ieee80211_rx_reorder_ready(&tid_agg_rx->reorder_buf[index])) {
dev_kfree_skb(skb);
goto out;
}
/*
* If the current MPDU is in the right order and nothing else
* is stored we can process it directly, no need to buffer it.
* If it is first but there's something stored, we may be able
* to release frames after this one.
*/
if (mpdu_seq_num == tid_agg_rx->head_seq_num &&
tid_agg_rx->stored_mpdu_num == 0) {
if (!(status->flag & RX_FLAG_AMSDU_MORE))
tid_agg_rx->head_seq_num =
ieee80211_sn_inc(tid_agg_rx->head_seq_num);
ret = false;
goto out;
}
/* put the frame in the reordering buffer */
__skb_queue_tail(&tid_agg_rx->reorder_buf[index], skb);
if (!(status->flag & RX_FLAG_AMSDU_MORE)) {
tid_agg_rx->reorder_time[index] = jiffies;
tid_agg_rx->stored_mpdu_num++;
ieee80211_sta_reorder_release(sdata, tid_agg_rx, frames);
}
out:
spin_unlock(&tid_agg_rx->reorder_lock);
return ret;
}
/*
* Reorder MPDUs from A-MPDUs, keeping them on a buffer. Returns
* true if the MPDU was buffered, false if it should be processed.
*/
static void ieee80211_rx_reorder_ampdu(struct ieee80211_rx_data *rx,
struct sk_buff_head *frames)
{
struct sk_buff *skb = rx->skb;
struct ieee80211_local *local = rx->local;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data;
struct sta_info *sta = rx->sta;
struct tid_ampdu_rx *tid_agg_rx;
u16 sc;
u8 tid, ack_policy;
if (!ieee80211_is_data_qos(hdr->frame_control) ||
is_multicast_ether_addr(hdr->addr1))
goto dont_reorder;
/*
* filter the QoS data rx stream according to
* STA/TID and check if this STA/TID is on aggregation
*/
if (!sta)
goto dont_reorder;
ack_policy = *ieee80211_get_qos_ctl(hdr) &
IEEE80211_QOS_CTL_ACK_POLICY_MASK;
tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK;
tid_agg_rx = rcu_dereference(sta->ampdu_mlme.tid_rx[tid]);
if (!tid_agg_rx)
goto dont_reorder;
/* qos null data frames are excluded */
if (unlikely(hdr->frame_control & cpu_to_le16(IEEE80211_STYPE_NULLFUNC)))
goto dont_reorder;
/* not part of a BA session */
if (ack_policy != IEEE80211_QOS_CTL_ACK_POLICY_BLOCKACK &&
ack_policy != IEEE80211_QOS_CTL_ACK_POLICY_NORMAL)
goto dont_reorder;
/* new, potentially un-ordered, ampdu frame - process it */
/* reset session timer */
if (tid_agg_rx->timeout)
tid_agg_rx->last_rx = jiffies;
/* if this mpdu is fragmented - terminate rx aggregation session */
sc = le16_to_cpu(hdr->seq_ctrl);
if (sc & IEEE80211_SCTL_FRAG) {
skb->pkt_type = IEEE80211_SDATA_QUEUE_TYPE_FRAME;
skb_queue_tail(&rx->sdata->skb_queue, skb);
ieee80211_queue_work(&local->hw, &rx->sdata->work);
return;
}
/*
* No locking needed -- we will only ever process one
* RX packet at a time, and thus own tid_agg_rx. All
* other code manipulating it needs to (and does) make
* sure that we cannot get to it any more before doing
* anything with it.
*/
if (ieee80211_sta_manage_reorder_buf(rx->sdata, tid_agg_rx, skb,
frames))
return;
dont_reorder:
__skb_queue_tail(frames, skb);
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_check_dup(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
/*
* Drop duplicate 802.11 retransmissions
* (IEEE 802.11-2012: 9.3.2.10 "Duplicate detection and recovery")
*/
if (rx->skb->len < 24)
return RX_CONTINUE;
if (ieee80211_is_ctl(hdr->frame_control) ||
ieee80211_is_qos_nullfunc(hdr->frame_control) ||
is_multicast_ether_addr(hdr->addr1))
return RX_CONTINUE;
if (!rx->sta)
return RX_CONTINUE;
if (unlikely(ieee80211_has_retry(hdr->frame_control) &&
rx->sta->last_seq_ctrl[rx->seqno_idx] == hdr->seq_ctrl)) {
I802_DEBUG_INC(rx->local->dot11FrameDuplicateCount);
rx->sta->rx_stats.num_duplicates++;
return RX_DROP_UNUSABLE;
} else if (!(status->flag & RX_FLAG_AMSDU_MORE)) {
rx->sta->last_seq_ctrl[rx->seqno_idx] = hdr->seq_ctrl;
}
return RX_CONTINUE;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_check(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
/* Drop disallowed frame classes based on STA auth/assoc state;
* IEEE 802.11, Chap 5.5.
*
* mac80211 filters only based on association state, i.e. it drops
* Class 3 frames from not associated stations. hostapd sends
* deauth/disassoc frames when needed. In addition, hostapd is
* responsible for filtering on both auth and assoc states.
*/
if (ieee80211_vif_is_mesh(&rx->sdata->vif))
return ieee80211_rx_mesh_check(rx);
if (unlikely((ieee80211_is_data(hdr->frame_control) ||
ieee80211_is_pspoll(hdr->frame_control)) &&
rx->sdata->vif.type != NL80211_IFTYPE_ADHOC &&
rx->sdata->vif.type != NL80211_IFTYPE_WDS &&
rx->sdata->vif.type != NL80211_IFTYPE_OCB &&
(!rx->sta || !test_sta_flag(rx->sta, WLAN_STA_ASSOC)))) {
/*
* accept port control frames from the AP even when it's not
* yet marked ASSOC to prevent a race where we don't set the
* assoc bit quickly enough before it sends the first frame
*/
if (rx->sta && rx->sdata->vif.type == NL80211_IFTYPE_STATION &&
ieee80211_is_data_present(hdr->frame_control)) {
unsigned int hdrlen;
__be16 ethertype;
hdrlen = ieee80211_hdrlen(hdr->frame_control);
if (rx->skb->len < hdrlen + 8)
return RX_DROP_MONITOR;
skb_copy_bits(rx->skb, hdrlen + 6, ðertype, 2);
if (ethertype == rx->sdata->control_port_protocol)
return RX_CONTINUE;
}
if (rx->sdata->vif.type == NL80211_IFTYPE_AP &&
cfg80211_rx_spurious_frame(rx->sdata->dev,
hdr->addr2,
GFP_ATOMIC))
return RX_DROP_UNUSABLE;
return RX_DROP_MONITOR;
}
return RX_CONTINUE;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_check_more_data(struct ieee80211_rx_data *rx)
{
struct ieee80211_local *local;
struct ieee80211_hdr *hdr;
struct sk_buff *skb;
local = rx->local;
skb = rx->skb;
hdr = (struct ieee80211_hdr *) skb->data;
if (!local->pspolling)
return RX_CONTINUE;
if (!ieee80211_has_fromds(hdr->frame_control))
/* this is not from AP */
return RX_CONTINUE;
if (!ieee80211_is_data(hdr->frame_control))
return RX_CONTINUE;
if (!ieee80211_has_moredata(hdr->frame_control)) {
/* AP has no more frames buffered for us */
local->pspolling = false;
return RX_CONTINUE;
}
/* more data bit is set, let's request a new frame from the AP */
ieee80211_send_pspoll(local, rx->sdata);
return RX_CONTINUE;
}
static void sta_ps_start(struct sta_info *sta)
{
struct ieee80211_sub_if_data *sdata = sta->sdata;
struct ieee80211_local *local = sdata->local;
struct ps_data *ps;
int tid;
if (sta->sdata->vif.type == NL80211_IFTYPE_AP ||
sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
ps = &sdata->bss->ps;
else
return;
atomic_inc(&ps->num_sta_ps);
set_sta_flag(sta, WLAN_STA_PS_STA);
if (!ieee80211_hw_check(&local->hw, AP_LINK_PS))
drv_sta_notify(local, sdata, STA_NOTIFY_SLEEP, &sta->sta);
ps_dbg(sdata, "STA %pM aid %d enters power save mode\n",
sta->sta.addr, sta->sta.aid);
ieee80211_clear_fast_xmit(sta);
if (!sta->sta.txq[0])
return;
for (tid = 0; tid < ARRAY_SIZE(sta->sta.txq); tid++) {
struct txq_info *txqi = to_txq_info(sta->sta.txq[tid]);
if (!skb_queue_len(&txqi->queue))
set_bit(tid, &sta->txq_buffered_tids);
else
clear_bit(tid, &sta->txq_buffered_tids);
}
}
static void sta_ps_end(struct sta_info *sta)
{
ps_dbg(sta->sdata, "STA %pM aid %d exits power save mode\n",
sta->sta.addr, sta->sta.aid);
if (test_sta_flag(sta, WLAN_STA_PS_DRIVER)) {
/*
* Clear the flag only if the other one is still set
* so that the TX path won't start TX'ing new frames
* directly ... In the case that the driver flag isn't
* set ieee80211_sta_ps_deliver_wakeup() will clear it.
*/
clear_sta_flag(sta, WLAN_STA_PS_STA);
ps_dbg(sta->sdata, "STA %pM aid %d driver-ps-blocked\n",
sta->sta.addr, sta->sta.aid);
return;
}
set_sta_flag(sta, WLAN_STA_PS_DELIVER);
clear_sta_flag(sta, WLAN_STA_PS_STA);
ieee80211_sta_ps_deliver_wakeup(sta);
}
int ieee80211_sta_ps_transition(struct ieee80211_sta *pubsta, bool start)
{
struct sta_info *sta = container_of(pubsta, struct sta_info, sta);
bool in_ps;
WARN_ON(!ieee80211_hw_check(&sta->local->hw, AP_LINK_PS));
/* Don't let the same PS state be set twice */
in_ps = test_sta_flag(sta, WLAN_STA_PS_STA);
if ((start && in_ps) || (!start && !in_ps))
return -EINVAL;
if (start)
sta_ps_start(sta);
else
sta_ps_end(sta);
return 0;
}
EXPORT_SYMBOL(ieee80211_sta_ps_transition);
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_uapsd_and_pspoll(struct ieee80211_rx_data *rx)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_hdr *hdr = (void *)rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
int tid, ac;
if (!rx->sta)
return RX_CONTINUE;
if (sdata->vif.type != NL80211_IFTYPE_AP &&
sdata->vif.type != NL80211_IFTYPE_AP_VLAN)
return RX_CONTINUE;
/*
* The device handles station powersave, so don't do anything about
* uAPSD and PS-Poll frames (the latter shouldn't even come up from
* it to mac80211 since they're handled.)
*/
if (ieee80211_hw_check(&sdata->local->hw, AP_LINK_PS))
return RX_CONTINUE;
/*
* Don't do anything if the station isn't already asleep. In
* the uAPSD case, the station will probably be marked asleep,
* in the PS-Poll case the station must be confused ...
*/
if (!test_sta_flag(rx->sta, WLAN_STA_PS_STA))
return RX_CONTINUE;
if (unlikely(ieee80211_is_pspoll(hdr->frame_control))) {
if (!test_sta_flag(rx->sta, WLAN_STA_SP)) {
if (!test_sta_flag(rx->sta, WLAN_STA_PS_DRIVER))
ieee80211_sta_ps_deliver_poll_response(rx->sta);
else
set_sta_flag(rx->sta, WLAN_STA_PSPOLL);
}
/* Free PS Poll skb here instead of returning RX_DROP that would
* count as an dropped frame. */
dev_kfree_skb(rx->skb);
return RX_QUEUED;
} else if (!ieee80211_has_morefrags(hdr->frame_control) &&
!(status->rx_flags & IEEE80211_RX_DEFERRED_RELEASE) &&
ieee80211_has_pm(hdr->frame_control) &&
(ieee80211_is_data_qos(hdr->frame_control) ||
ieee80211_is_qos_nullfunc(hdr->frame_control))) {
tid = *ieee80211_get_qos_ctl(hdr) & IEEE80211_QOS_CTL_TID_MASK;
ac = ieee802_1d_to_ac[tid & 7];
/*
* If this AC is not trigger-enabled do nothing.
*
* NB: This could/should check a separate bitmap of trigger-
* enabled queues, but for now we only implement uAPSD w/o
* TSPEC changes to the ACs, so they're always the same.
*/
if (!(rx->sta->sta.uapsd_queues & BIT(ac)))
return RX_CONTINUE;
/* if we are in a service period, do nothing */
if (test_sta_flag(rx->sta, WLAN_STA_SP))
return RX_CONTINUE;
if (!test_sta_flag(rx->sta, WLAN_STA_PS_DRIVER))
ieee80211_sta_ps_deliver_uapsd(rx->sta);
else
set_sta_flag(rx->sta, WLAN_STA_UAPSD);
}
return RX_CONTINUE;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_sta_process(struct ieee80211_rx_data *rx)
{
struct sta_info *sta = rx->sta;
struct sk_buff *skb = rx->skb;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
int i;
if (!sta)
return RX_CONTINUE;
/*
* Update last_rx only for IBSS packets which are for the current
* BSSID and for station already AUTHORIZED to avoid keeping the
* current IBSS network alive in cases where other STAs start
* using different BSSID. This will also give the station another
* chance to restart the authentication/authorization in case
* something went wrong the first time.
*/
if (rx->sdata->vif.type == NL80211_IFTYPE_ADHOC) {
u8 *bssid = ieee80211_get_bssid(hdr, rx->skb->len,
NL80211_IFTYPE_ADHOC);
if (ether_addr_equal(bssid, rx->sdata->u.ibss.bssid) &&
test_sta_flag(sta, WLAN_STA_AUTHORIZED)) {
sta->rx_stats.last_rx = jiffies;
if (ieee80211_is_data(hdr->frame_control) &&
!is_multicast_ether_addr(hdr->addr1)) {
sta->rx_stats.last_rate_idx =
status->rate_idx;
sta->rx_stats.last_rate_flag =
status->flag;
sta->rx_stats.last_rate_vht_flag =
status->vht_flag;
sta->rx_stats.last_rate_vht_nss =
status->vht_nss;
}
}
} else if (rx->sdata->vif.type == NL80211_IFTYPE_OCB) {
sta->rx_stats.last_rx = jiffies;
} else if (!is_multicast_ether_addr(hdr->addr1)) {
/*
* Mesh beacons will update last_rx when if they are found to
* match the current local configuration when processed.
*/
sta->rx_stats.last_rx = jiffies;
if (ieee80211_is_data(hdr->frame_control)) {
sta->rx_stats.last_rate_idx = status->rate_idx;
sta->rx_stats.last_rate_flag = status->flag;
sta->rx_stats.last_rate_vht_flag = status->vht_flag;
sta->rx_stats.last_rate_vht_nss = status->vht_nss;
}
}
if (rx->sdata->vif.type == NL80211_IFTYPE_STATION)
ieee80211_sta_rx_notify(rx->sdata, hdr);
sta->rx_stats.fragments++;
sta->rx_stats.bytes += rx->skb->len;
if (!(status->flag & RX_FLAG_NO_SIGNAL_VAL)) {
sta->rx_stats.last_signal = status->signal;
ewma_signal_add(&sta->rx_stats.avg_signal, -status->signal);
}
if (status->chains) {
sta->rx_stats.chains = status->chains;
for (i = 0; i < ARRAY_SIZE(status->chain_signal); i++) {
int signal = status->chain_signal[i];
if (!(status->chains & BIT(i)))
continue;
sta->rx_stats.chain_signal_last[i] = signal;
ewma_signal_add(&sta->rx_stats.chain_signal_avg[i],
-signal);
}
}
/*
* Change STA power saving mode only at the end of a frame
* exchange sequence.
*/
if (!ieee80211_hw_check(&sta->local->hw, AP_LINK_PS) &&
!ieee80211_has_morefrags(hdr->frame_control) &&
!(status->rx_flags & IEEE80211_RX_DEFERRED_RELEASE) &&
(rx->sdata->vif.type == NL80211_IFTYPE_AP ||
rx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN) &&
/* PM bit is only checked in frames where it isn't reserved,
* in AP mode it's reserved in non-bufferable management frames
* (cf. IEEE 802.11-2012 8.2.4.1.7 Power Management field)
*/
(!ieee80211_is_mgmt(hdr->frame_control) ||
ieee80211_is_bufferable_mmpdu(hdr->frame_control))) {
if (test_sta_flag(sta, WLAN_STA_PS_STA)) {
if (!ieee80211_has_pm(hdr->frame_control))
sta_ps_end(sta);
} else {
if (ieee80211_has_pm(hdr->frame_control))
sta_ps_start(sta);
}
}
/* mesh power save support */
if (ieee80211_vif_is_mesh(&rx->sdata->vif))
ieee80211_mps_rx_h_sta_process(sta, hdr);
/*
* Drop (qos-)data::nullfunc frames silently, since they
* are used only to control station power saving mode.
*/
if (ieee80211_is_nullfunc(hdr->frame_control) ||
ieee80211_is_qos_nullfunc(hdr->frame_control)) {
I802_DEBUG_INC(rx->local->rx_handlers_drop_nullfunc);
/*
* If we receive a 4-addr nullfunc frame from a STA
* that was not moved to a 4-addr STA vlan yet send
* the event to userspace and for older hostapd drop
* the frame to the monitor interface.
*/
if (ieee80211_has_a4(hdr->frame_control) &&
(rx->sdata->vif.type == NL80211_IFTYPE_AP ||
(rx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
!rx->sdata->u.vlan.sta))) {
if (!test_and_set_sta_flag(sta, WLAN_STA_4ADDR_EVENT))
cfg80211_rx_unexpected_4addr_frame(
rx->sdata->dev, sta->sta.addr,
GFP_ATOMIC);
return RX_DROP_MONITOR;
}
/*
* Update counter and free packet here to avoid
* counting this as a dropped packed.
*/
sta->rx_stats.packets++;
dev_kfree_skb(rx->skb);
return RX_QUEUED;
}
return RX_CONTINUE;
} /* ieee80211_rx_h_sta_process */
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_decrypt(struct ieee80211_rx_data *rx)
{
struct sk_buff *skb = rx->skb;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
int keyidx;
int hdrlen;
ieee80211_rx_result result = RX_DROP_UNUSABLE;
struct ieee80211_key *sta_ptk = NULL;
int mmie_keyidx = -1;
__le16 fc;
const struct ieee80211_cipher_scheme *cs = NULL;
/*
* Key selection 101
*
* There are four types of keys:
* - GTK (group keys)
* - IGTK (group keys for management frames)
* - PTK (pairwise keys)
* - STK (station-to-station pairwise keys)
*
* When selecting a key, we have to distinguish between multicast
* (including broadcast) and unicast frames, the latter can only
* use PTKs and STKs while the former always use GTKs and IGTKs.
* Unless, of course, actual WEP keys ("pre-RSNA") are used, then
* unicast frames can also use key indices like GTKs. Hence, if we
* don't have a PTK/STK we check the key index for a WEP key.
*
* Note that in a regular BSS, multicast frames are sent by the
* AP only, associated stations unicast the frame to the AP first
* which then multicasts it on their behalf.
*
* There is also a slight problem in IBSS mode: GTKs are negotiated
* with each station, that is something we don't currently handle.
* The spec seems to expect that one negotiates the same key with
* every station but there's no such requirement; VLANs could be
* possible.
*/
/* start without a key */
rx->key = NULL;
fc = hdr->frame_control;
if (rx->sta) {
int keyid = rx->sta->ptk_idx;
if (ieee80211_has_protected(fc) && rx->sta->cipher_scheme) {
cs = rx->sta->cipher_scheme;
keyid = iwl80211_get_cs_keyid(cs, rx->skb);
if (unlikely(keyid < 0))
return RX_DROP_UNUSABLE;
}
sta_ptk = rcu_dereference(rx->sta->ptk[keyid]);
}
if (!ieee80211_has_protected(fc))
mmie_keyidx = ieee80211_get_mmie_keyidx(rx->skb);
if (!is_multicast_ether_addr(hdr->addr1) && sta_ptk) {
rx->key = sta_ptk;
if ((status->flag & RX_FLAG_DECRYPTED) &&
(status->flag & RX_FLAG_IV_STRIPPED))
return RX_CONTINUE;
/* Skip decryption if the frame is not protected. */
if (!ieee80211_has_protected(fc))
return RX_CONTINUE;
} else if (mmie_keyidx >= 0) {
/* Broadcast/multicast robust management frame / BIP */
if ((status->flag & RX_FLAG_DECRYPTED) &&
(status->flag & RX_FLAG_IV_STRIPPED))
return RX_CONTINUE;
if (mmie_keyidx < NUM_DEFAULT_KEYS ||
mmie_keyidx >= NUM_DEFAULT_KEYS + NUM_DEFAULT_MGMT_KEYS)
return RX_DROP_MONITOR; /* unexpected BIP keyidx */
if (rx->sta)
rx->key = rcu_dereference(rx->sta->gtk[mmie_keyidx]);
if (!rx->key)
rx->key = rcu_dereference(rx->sdata->keys[mmie_keyidx]);
} else if (!ieee80211_has_protected(fc)) {
/*
* The frame was not protected, so skip decryption. However, we
* need to set rx->key if there is a key that could have been
* used so that the frame may be dropped if encryption would
* have been expected.
*/
struct ieee80211_key *key = NULL;
struct ieee80211_sub_if_data *sdata = rx->sdata;
int i;
if (ieee80211_is_mgmt(fc) &&
is_multicast_ether_addr(hdr->addr1) &&
(key = rcu_dereference(rx->sdata->default_mgmt_key)))
rx->key = key;
else {
if (rx->sta) {
for (i = 0; i < NUM_DEFAULT_KEYS; i++) {
key = rcu_dereference(rx->sta->gtk[i]);
if (key)
break;
}
}
if (!key) {
for (i = 0; i < NUM_DEFAULT_KEYS; i++) {
key = rcu_dereference(sdata->keys[i]);
if (key)
break;
}
}
if (key)
rx->key = key;
}
return RX_CONTINUE;
} else {
u8 keyid;
/*
* The device doesn't give us the IV so we won't be
* able to look up the key. That's ok though, we
* don't need to decrypt the frame, we just won't
* be able to keep statistics accurate.
* Except for key threshold notifications, should
* we somehow allow the driver to tell us which key
* the hardware used if this flag is set?
*/
if ((status->flag & RX_FLAG_DECRYPTED) &&
(status->flag & RX_FLAG_IV_STRIPPED))
return RX_CONTINUE;
hdrlen = ieee80211_hdrlen(fc);
if (cs) {
keyidx = iwl80211_get_cs_keyid(cs, rx->skb);
if (unlikely(keyidx < 0))
return RX_DROP_UNUSABLE;
} else {
if (rx->skb->len < 8 + hdrlen)
return RX_DROP_UNUSABLE; /* TODO: count this? */
/*
* no need to call ieee80211_wep_get_keyidx,
* it verifies a bunch of things we've done already
*/
skb_copy_bits(rx->skb, hdrlen + 3, &keyid, 1);
keyidx = keyid >> 6;
}
/* check per-station GTK first, if multicast packet */
if (is_multicast_ether_addr(hdr->addr1) && rx->sta)
rx->key = rcu_dereference(rx->sta->gtk[keyidx]);
/* if not found, try default key */
if (!rx->key) {
rx->key = rcu_dereference(rx->sdata->keys[keyidx]);
/*
* RSNA-protected unicast frames should always be
* sent with pairwise or station-to-station keys,
* but for WEP we allow using a key index as well.
*/
if (rx->key &&
rx->key->conf.cipher != WLAN_CIPHER_SUITE_WEP40 &&
rx->key->conf.cipher != WLAN_CIPHER_SUITE_WEP104 &&
!is_multicast_ether_addr(hdr->addr1))
rx->key = NULL;
}
}
if (rx->key) {
if (unlikely(rx->key->flags & KEY_FLAG_TAINTED))
return RX_DROP_MONITOR;
/* TODO: add threshold stuff again */
} else {
return RX_DROP_MONITOR;
}
switch (rx->key->conf.cipher) {
case WLAN_CIPHER_SUITE_WEP40:
case WLAN_CIPHER_SUITE_WEP104:
result = ieee80211_crypto_wep_decrypt(rx);
break;
case WLAN_CIPHER_SUITE_TKIP:
result = ieee80211_crypto_tkip_decrypt(rx);
break;
case WLAN_CIPHER_SUITE_CCMP:
result = ieee80211_crypto_ccmp_decrypt(
rx, IEEE80211_CCMP_MIC_LEN);
break;
case WLAN_CIPHER_SUITE_CCMP_256:
result = ieee80211_crypto_ccmp_decrypt(
rx, IEEE80211_CCMP_256_MIC_LEN);
break;
case WLAN_CIPHER_SUITE_AES_CMAC:
result = ieee80211_crypto_aes_cmac_decrypt(rx);
break;
case WLAN_CIPHER_SUITE_BIP_CMAC_256:
result = ieee80211_crypto_aes_cmac_256_decrypt(rx);
break;
case WLAN_CIPHER_SUITE_BIP_GMAC_128:
case WLAN_CIPHER_SUITE_BIP_GMAC_256:
result = ieee80211_crypto_aes_gmac_decrypt(rx);
break;
case WLAN_CIPHER_SUITE_GCMP:
case WLAN_CIPHER_SUITE_GCMP_256:
result = ieee80211_crypto_gcmp_decrypt(rx);
break;
default:
result = ieee80211_crypto_hw_decrypt(rx);
}
/* the hdr variable is invalid after the decrypt handlers */
/* either the frame has been decrypted or will be dropped */
status->flag |= RX_FLAG_DECRYPTED;
return result;
}
static inline struct ieee80211_fragment_entry *
ieee80211_reassemble_add(struct ieee80211_sub_if_data *sdata,
unsigned int frag, unsigned int seq, int rx_queue,
struct sk_buff **skb)
{
struct ieee80211_fragment_entry *entry;
entry = &sdata->fragments[sdata->fragment_next++];
if (sdata->fragment_next >= IEEE80211_FRAGMENT_MAX)
sdata->fragment_next = 0;
if (!skb_queue_empty(&entry->skb_list))
__skb_queue_purge(&entry->skb_list);
__skb_queue_tail(&entry->skb_list, *skb); /* no need for locking */
*skb = NULL;
entry->first_frag_time = jiffies;
entry->seq = seq;
entry->rx_queue = rx_queue;
entry->last_frag = frag;
entry->ccmp = 0;
entry->extra_len = 0;
return entry;
}
static inline struct ieee80211_fragment_entry *
ieee80211_reassemble_find(struct ieee80211_sub_if_data *sdata,
unsigned int frag, unsigned int seq,
int rx_queue, struct ieee80211_hdr *hdr)
{
struct ieee80211_fragment_entry *entry;
int i, idx;
idx = sdata->fragment_next;
for (i = 0; i < IEEE80211_FRAGMENT_MAX; i++) {
struct ieee80211_hdr *f_hdr;
idx--;
if (idx < 0)
idx = IEEE80211_FRAGMENT_MAX - 1;
entry = &sdata->fragments[idx];
if (skb_queue_empty(&entry->skb_list) || entry->seq != seq ||
entry->rx_queue != rx_queue ||
entry->last_frag + 1 != frag)
continue;
f_hdr = (struct ieee80211_hdr *)entry->skb_list.next->data;
/*
* Check ftype and addresses are equal, else check next fragment
*/
if (((hdr->frame_control ^ f_hdr->frame_control) &
cpu_to_le16(IEEE80211_FCTL_FTYPE)) ||
!ether_addr_equal(hdr->addr1, f_hdr->addr1) ||
!ether_addr_equal(hdr->addr2, f_hdr->addr2))
continue;
if (time_after(jiffies, entry->first_frag_time + 2 * HZ)) {
__skb_queue_purge(&entry->skb_list);
continue;
}
return entry;
}
return NULL;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_defragment(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr;
u16 sc;
__le16 fc;
unsigned int frag, seq;
struct ieee80211_fragment_entry *entry;
struct sk_buff *skb;
struct ieee80211_rx_status *status;
hdr = (struct ieee80211_hdr *)rx->skb->data;
fc = hdr->frame_control;
if (ieee80211_is_ctl(fc))
return RX_CONTINUE;
sc = le16_to_cpu(hdr->seq_ctrl);
frag = sc & IEEE80211_SCTL_FRAG;
if (is_multicast_ether_addr(hdr->addr1)) {
I802_DEBUG_INC(rx->local->dot11MulticastReceivedFrameCount);
goto out_no_led;
}
if (likely(!ieee80211_has_morefrags(fc) && frag == 0))
goto out;
I802_DEBUG_INC(rx->local->rx_handlers_fragments);
if (skb_linearize(rx->skb))
return RX_DROP_UNUSABLE;
/*
* skb_linearize() might change the skb->data and
* previously cached variables (in this case, hdr) need to
* be refreshed with the new data.
*/
hdr = (struct ieee80211_hdr *)rx->skb->data;
seq = (sc & IEEE80211_SCTL_SEQ) >> 4;
if (frag == 0) {
/* This is the first fragment of a new frame. */
entry = ieee80211_reassemble_add(rx->sdata, frag, seq,
rx->seqno_idx, &(rx->skb));
if (rx->key &&
(rx->key->conf.cipher == WLAN_CIPHER_SUITE_CCMP ||
rx->key->conf.cipher == WLAN_CIPHER_SUITE_CCMP_256) &&
ieee80211_has_protected(fc)) {
int queue = rx->security_idx;
/* Store CCMP PN so that we can verify that the next
* fragment has a sequential PN value. */
entry->ccmp = 1;
memcpy(entry->last_pn,
rx->key->u.ccmp.rx_pn[queue],
IEEE80211_CCMP_PN_LEN);
}
return RX_QUEUED;
}
/* This is a fragment for a frame that should already be pending in
* fragment cache. Add this fragment to the end of the pending entry.
*/
entry = ieee80211_reassemble_find(rx->sdata, frag, seq,
rx->seqno_idx, hdr);
if (!entry) {
I802_DEBUG_INC(rx->local->rx_handlers_drop_defrag);
return RX_DROP_MONITOR;
}
/* Verify that MPDUs within one MSDU have sequential PN values.
* (IEEE 802.11i, 8.3.3.4.5) */
if (entry->ccmp) {
int i;
u8 pn[IEEE80211_CCMP_PN_LEN], *rpn;
int queue;
if (!rx->key ||
(rx->key->conf.cipher != WLAN_CIPHER_SUITE_CCMP &&
rx->key->conf.cipher != WLAN_CIPHER_SUITE_CCMP_256))
return RX_DROP_UNUSABLE;
memcpy(pn, entry->last_pn, IEEE80211_CCMP_PN_LEN);
for (i = IEEE80211_CCMP_PN_LEN - 1; i >= 0; i--) {
pn[i]++;
if (pn[i])
break;
}
queue = rx->security_idx;
rpn = rx->key->u.ccmp.rx_pn[queue];
if (memcmp(pn, rpn, IEEE80211_CCMP_PN_LEN))
return RX_DROP_UNUSABLE;
memcpy(entry->last_pn, pn, IEEE80211_CCMP_PN_LEN);
}
skb_pull(rx->skb, ieee80211_hdrlen(fc));
__skb_queue_tail(&entry->skb_list, rx->skb);
entry->last_frag = frag;
entry->extra_len += rx->skb->len;
if (ieee80211_has_morefrags(fc)) {
rx->skb = NULL;
return RX_QUEUED;
}
rx->skb = __skb_dequeue(&entry->skb_list);
if (skb_tailroom(rx->skb) < entry->extra_len) {
I802_DEBUG_INC(rx->local->rx_expand_skb_head_defrag);
if (unlikely(pskb_expand_head(rx->skb, 0, entry->extra_len,
GFP_ATOMIC))) {
I802_DEBUG_INC(rx->local->rx_handlers_drop_defrag);
__skb_queue_purge(&entry->skb_list);
return RX_DROP_UNUSABLE;
}
}
while ((skb = __skb_dequeue(&entry->skb_list))) {
memcpy(skb_put(rx->skb, skb->len), skb->data, skb->len);
dev_kfree_skb(skb);
}
/* Complete frame has been reassembled - process it now */
status = IEEE80211_SKB_RXCB(rx->skb);
out:
ieee80211_led_rx(rx->local);
out_no_led:
if (rx->sta)
rx->sta->rx_stats.packets++;
return RX_CONTINUE;
}
static int ieee80211_802_1x_port_control(struct ieee80211_rx_data *rx)
{
if (unlikely(!rx->sta || !test_sta_flag(rx->sta, WLAN_STA_AUTHORIZED)))
return -EACCES;
return 0;
}
static int ieee80211_drop_unencrypted(struct ieee80211_rx_data *rx, __le16 fc)
{
struct sk_buff *skb = rx->skb;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
/*
* Pass through unencrypted frames if the hardware has
* decrypted them already.
*/
if (status->flag & RX_FLAG_DECRYPTED)
return 0;
/* Drop unencrypted frames if key is set. */
if (unlikely(!ieee80211_has_protected(fc) &&
!ieee80211_is_nullfunc(fc) &&
ieee80211_is_data(fc) && rx->key))
return -EACCES;
return 0;
}
static int ieee80211_drop_unencrypted_mgmt(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
__le16 fc = hdr->frame_control;
/*
* Pass through unencrypted frames if the hardware has
* decrypted them already.
*/
if (status->flag & RX_FLAG_DECRYPTED)
return 0;
if (rx->sta && test_sta_flag(rx->sta, WLAN_STA_MFP)) {
if (unlikely(!ieee80211_has_protected(fc) &&
ieee80211_is_unicast_robust_mgmt_frame(rx->skb) &&
rx->key)) {
if (ieee80211_is_deauth(fc) ||
ieee80211_is_disassoc(fc))
cfg80211_rx_unprot_mlme_mgmt(rx->sdata->dev,
rx->skb->data,
rx->skb->len);
return -EACCES;
}
/* BIP does not use Protected field, so need to check MMIE */
if (unlikely(ieee80211_is_multicast_robust_mgmt_frame(rx->skb) &&
ieee80211_get_mmie_keyidx(rx->skb) < 0)) {
if (ieee80211_is_deauth(fc) ||
ieee80211_is_disassoc(fc))
cfg80211_rx_unprot_mlme_mgmt(rx->sdata->dev,
rx->skb->data,
rx->skb->len);
return -EACCES;
}
/*
* When using MFP, Action frames are not allowed prior to
* having configured keys.
*/
if (unlikely(ieee80211_is_action(fc) && !rx->key &&
ieee80211_is_robust_mgmt_frame(rx->skb)))
return -EACCES;
}
return 0;
}
static int
__ieee80211_data_to_8023(struct ieee80211_rx_data *rx, bool *port_control)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
bool check_port_control = false;
struct ethhdr *ehdr;
int ret;
*port_control = false;
if (ieee80211_has_a4(hdr->frame_control) &&
sdata->vif.type == NL80211_IFTYPE_AP_VLAN && !sdata->u.vlan.sta)
return -1;
if (sdata->vif.type == NL80211_IFTYPE_STATION &&
!!sdata->u.mgd.use_4addr != !!ieee80211_has_a4(hdr->frame_control)) {
if (!sdata->u.mgd.use_4addr)
return -1;
else
check_port_control = true;
}
if (is_multicast_ether_addr(hdr->addr1) &&
sdata->vif.type == NL80211_IFTYPE_AP_VLAN && sdata->u.vlan.sta)
return -1;
ret = ieee80211_data_to_8023(rx->skb, sdata->vif.addr, sdata->vif.type);
if (ret < 0)
return ret;
ehdr = (struct ethhdr *) rx->skb->data;
if (ehdr->h_proto == rx->sdata->control_port_protocol)
*port_control = true;
else if (check_port_control)
return -1;
return 0;
}
/*
* requires that rx->skb is a frame with ethernet header
*/
static bool ieee80211_frame_allowed(struct ieee80211_rx_data *rx, __le16 fc)
{
static const u8 pae_group_addr[ETH_ALEN] __aligned(2)
= { 0x01, 0x80, 0xC2, 0x00, 0x00, 0x03 };
struct ethhdr *ehdr = (struct ethhdr *) rx->skb->data;
/*
* Allow EAPOL frames to us/the PAE group address regardless
* of whether the frame was encrypted or not.
*/
if (ehdr->h_proto == rx->sdata->control_port_protocol &&
(ether_addr_equal(ehdr->h_dest, rx->sdata->vif.addr) ||
ether_addr_equal(ehdr->h_dest, pae_group_addr)))
return true;
if (ieee80211_802_1x_port_control(rx) ||
ieee80211_drop_unencrypted(rx, fc))
return false;
return true;
}
/*
* requires that rx->skb is a frame with ethernet header
*/
static void
ieee80211_deliver_skb(struct ieee80211_rx_data *rx)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct net_device *dev = sdata->dev;
struct sk_buff *skb, *xmit_skb;
struct ethhdr *ehdr = (struct ethhdr *) rx->skb->data;
struct sta_info *dsta;
skb = rx->skb;
xmit_skb = NULL;
ieee80211_rx_stats(dev, skb->len);
if ((sdata->vif.type == NL80211_IFTYPE_AP ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN) &&
!(sdata->flags & IEEE80211_SDATA_DONT_BRIDGE_PACKETS) &&
(sdata->vif.type != NL80211_IFTYPE_AP_VLAN || !sdata->u.vlan.sta)) {
if (is_multicast_ether_addr(ehdr->h_dest)) {
/*
* send multicast frames both to higher layers in
* local net stack and back to the wireless medium
*/
xmit_skb = skb_copy(skb, GFP_ATOMIC);
if (!xmit_skb)
net_info_ratelimited("%s: failed to clone multicast frame\n",
dev->name);
} else {
dsta = sta_info_get(sdata, skb->data);
if (dsta) {
/*
* The destination station is associated to
* this AP (in this VLAN), so send the frame
* directly to it and do not pass it to local
* net stack.
*/
xmit_skb = skb;
skb = NULL;
}
}
}
#ifndef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
if (skb) {
/* 'align' will only take the values 0 or 2 here since all
* frames are required to be aligned to 2-byte boundaries
* when being passed to mac80211; the code here works just
* as well if that isn't true, but mac80211 assumes it can
* access fields as 2-byte aligned (e.g. for ether_addr_equal)
*/
int align;
align = (unsigned long)(skb->data + sizeof(struct ethhdr)) & 3;
if (align) {
if (WARN_ON(skb_headroom(skb) < 3)) {
dev_kfree_skb(skb);
skb = NULL;
} else {
u8 *data = skb->data;
size_t len = skb_headlen(skb);
skb->data -= align;
memmove(skb->data, data, len);
skb_set_tail_pointer(skb, len);
}
}
}
#endif
if (skb) {
/* deliver to local stack */
skb->protocol = eth_type_trans(skb, dev);
memset(skb->cb, 0, sizeof(skb->cb));
if (rx->napi)
napi_gro_receive(rx->napi, skb);
else
netif_receive_skb(skb);
}
if (xmit_skb) {
/*
* Send to wireless media and increase priority by 256 to
* keep the received priority instead of reclassifying
* the frame (see cfg80211_classify8021d).
*/
xmit_skb->priority += 256;
xmit_skb->protocol = htons(ETH_P_802_3);
skb_reset_network_header(xmit_skb);
skb_reset_mac_header(xmit_skb);
dev_queue_xmit(xmit_skb);
}
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_amsdu(struct ieee80211_rx_data *rx)
{
struct net_device *dev = rx->sdata->dev;
struct sk_buff *skb = rx->skb;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)skb->data;
__le16 fc = hdr->frame_control;
struct sk_buff_head frame_list;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
if (unlikely(!ieee80211_is_data(fc)))
return RX_CONTINUE;
if (unlikely(!ieee80211_is_data_present(fc)))
return RX_DROP_MONITOR;
if (!(status->rx_flags & IEEE80211_RX_AMSDU))
return RX_CONTINUE;
if (ieee80211_has_a4(hdr->frame_control) &&
rx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
!rx->sdata->u.vlan.sta)
return RX_DROP_UNUSABLE;
if (is_multicast_ether_addr(hdr->addr1) &&
((rx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
rx->sdata->u.vlan.sta) ||
(rx->sdata->vif.type == NL80211_IFTYPE_STATION &&
rx->sdata->u.mgd.use_4addr)))
return RX_DROP_UNUSABLE;
skb->dev = dev;
__skb_queue_head_init(&frame_list);
if (skb_linearize(skb))
return RX_DROP_UNUSABLE;
ieee80211_amsdu_to_8023s(skb, &frame_list, dev->dev_addr,
rx->sdata->vif.type,
rx->local->hw.extra_tx_headroom, true);
while (!skb_queue_empty(&frame_list)) {
rx->skb = __skb_dequeue(&frame_list);
if (!ieee80211_frame_allowed(rx, fc)) {
dev_kfree_skb(rx->skb);
continue;
}
ieee80211_deliver_skb(rx);
}
return RX_QUEUED;
}
#ifdef CONFIG_MAC80211_MESH
static ieee80211_rx_result
ieee80211_rx_h_mesh_fwding(struct ieee80211_rx_data *rx)
{
struct ieee80211_hdr *fwd_hdr, *hdr;
struct ieee80211_tx_info *info;
struct ieee80211s_hdr *mesh_hdr;
struct sk_buff *skb = rx->skb, *fwd_skb;
struct ieee80211_local *local = rx->local;
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh;
u16 q, hdrlen;
hdr = (struct ieee80211_hdr *) skb->data;
hdrlen = ieee80211_hdrlen(hdr->frame_control);
/* make sure fixed part of mesh header is there, also checks skb len */
if (!pskb_may_pull(rx->skb, hdrlen + 6))
return RX_DROP_MONITOR;
mesh_hdr = (struct ieee80211s_hdr *) (skb->data + hdrlen);
/* make sure full mesh header is there, also checks skb len */
if (!pskb_may_pull(rx->skb,
hdrlen + ieee80211_get_mesh_hdrlen(mesh_hdr)))
return RX_DROP_MONITOR;
/* reload pointers */
hdr = (struct ieee80211_hdr *) skb->data;
mesh_hdr = (struct ieee80211s_hdr *) (skb->data + hdrlen);
if (ieee80211_drop_unencrypted(rx, hdr->frame_control))
return RX_DROP_MONITOR;
/* frame is in RMC, don't forward */
if (ieee80211_is_data(hdr->frame_control) &&
is_multicast_ether_addr(hdr->addr1) &&
mesh_rmc_check(rx->sdata, hdr->addr3, mesh_hdr))
return RX_DROP_MONITOR;
if (!ieee80211_is_data(hdr->frame_control))
return RX_CONTINUE;
if (!mesh_hdr->ttl)
return RX_DROP_MONITOR;
if (mesh_hdr->flags & MESH_FLAGS_AE) {
struct mesh_path *mppath;
char *proxied_addr;
char *mpp_addr;
if (is_multicast_ether_addr(hdr->addr1)) {
mpp_addr = hdr->addr3;
proxied_addr = mesh_hdr->eaddr1;
} else if (mesh_hdr->flags & MESH_FLAGS_AE_A5_A6) {
/* has_a4 already checked in ieee80211_rx_mesh_check */
mpp_addr = hdr->addr4;
proxied_addr = mesh_hdr->eaddr2;
} else {
return RX_DROP_MONITOR;
}
rcu_read_lock();
mppath = mpp_path_lookup(sdata, proxied_addr);
if (!mppath) {
mpp_path_add(sdata, proxied_addr, mpp_addr);
} else {
spin_lock_bh(&mppath->state_lock);
if (!ether_addr_equal(mppath->mpp, mpp_addr))
memcpy(mppath->mpp, mpp_addr, ETH_ALEN);
spin_unlock_bh(&mppath->state_lock);
}
rcu_read_unlock();
}
/* Frame has reached destination. Don't forward */
if (!is_multicast_ether_addr(hdr->addr1) &&
ether_addr_equal(sdata->vif.addr, hdr->addr3))
return RX_CONTINUE;
q = ieee80211_select_queue_80211(sdata, skb, hdr);
if (ieee80211_queue_stopped(&local->hw, q)) {
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, dropped_frames_congestion);
return RX_DROP_MONITOR;
}
skb_set_queue_mapping(skb, q);
if (!--mesh_hdr->ttl) {
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, dropped_frames_ttl);
goto out;
}
if (!ifmsh->mshcfg.dot11MeshForwarding)
goto out;
fwd_skb = skb_copy(skb, GFP_ATOMIC);
if (!fwd_skb) {
net_info_ratelimited("%s: failed to clone mesh frame\n",
sdata->name);
goto out;
}
fwd_hdr = (struct ieee80211_hdr *) fwd_skb->data;
fwd_hdr->frame_control &= ~cpu_to_le16(IEEE80211_FCTL_RETRY);
info = IEEE80211_SKB_CB(fwd_skb);
memset(info, 0, sizeof(*info));
info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING;
info->control.vif = &rx->sdata->vif;
info->control.jiffies = jiffies;
if (is_multicast_ether_addr(fwd_hdr->addr1)) {
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, fwded_mcast);
memcpy(fwd_hdr->addr2, sdata->vif.addr, ETH_ALEN);
/* update power mode indication when forwarding */
ieee80211_mps_set_frame_flags(sdata, NULL, fwd_hdr);
} else if (!mesh_nexthop_lookup(sdata, fwd_skb)) {
/* mesh power mode flags updated in mesh_nexthop_lookup */
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, fwded_unicast);
} else {
/* unable to resolve next hop */
mesh_path_error_tx(sdata, ifmsh->mshcfg.element_ttl,
fwd_hdr->addr3, 0,
WLAN_REASON_MESH_PATH_NOFORWARD,
fwd_hdr->addr2);
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, dropped_frames_no_route);
kfree_skb(fwd_skb);
return RX_DROP_MONITOR;
}
IEEE80211_IFSTA_MESH_CTR_INC(ifmsh, fwded_frames);
ieee80211_add_pending_skb(local, fwd_skb);
out:
if (is_multicast_ether_addr(hdr->addr1))
return RX_CONTINUE;
return RX_DROP_MONITOR;
}
#endif
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_data(struct ieee80211_rx_data *rx)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_local *local = rx->local;
struct net_device *dev = sdata->dev;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)rx->skb->data;
__le16 fc = hdr->frame_control;
bool port_control;
int err;
if (unlikely(!ieee80211_is_data(hdr->frame_control)))
return RX_CONTINUE;
if (unlikely(!ieee80211_is_data_present(hdr->frame_control)))
return RX_DROP_MONITOR;
if (rx->sta) {
/* The seqno index has the same property as needed
* for the rx_msdu field, i.e. it is IEEE80211_NUM_TIDS
* for non-QoS-data frames. Here we know it's a data
* frame, so count MSDUs.
*/
rx->sta->rx_stats.msdu[rx->seqno_idx]++;
}
/*
* Send unexpected-4addr-frame event to hostapd. For older versions,
* also drop the frame to cooked monitor interfaces.
*/
if (ieee80211_has_a4(hdr->frame_control) &&
sdata->vif.type == NL80211_IFTYPE_AP) {
if (rx->sta &&
!test_and_set_sta_flag(rx->sta, WLAN_STA_4ADDR_EVENT))
cfg80211_rx_unexpected_4addr_frame(
rx->sdata->dev, rx->sta->sta.addr, GFP_ATOMIC);
return RX_DROP_MONITOR;
}
err = __ieee80211_data_to_8023(rx, &port_control);
if (unlikely(err))
return RX_DROP_UNUSABLE;
if (!ieee80211_frame_allowed(rx, fc))
return RX_DROP_MONITOR;
/* directly handle TDLS channel switch requests/responses */
if (unlikely(((struct ethhdr *)rx->skb->data)->h_proto ==
cpu_to_be16(ETH_P_TDLS))) {
struct ieee80211_tdls_data *tf = (void *)rx->skb->data;
if (pskb_may_pull(rx->skb,
offsetof(struct ieee80211_tdls_data, u)) &&
tf->payload_type == WLAN_TDLS_SNAP_RFTYPE &&
tf->category == WLAN_CATEGORY_TDLS &&
(tf->action_code == WLAN_TDLS_CHANNEL_SWITCH_REQUEST ||
tf->action_code == WLAN_TDLS_CHANNEL_SWITCH_RESPONSE)) {
skb_queue_tail(&local->skb_queue_tdls_chsw, rx->skb);
schedule_work(&local->tdls_chsw_work);
if (rx->sta)
rx->sta->rx_stats.packets++;
return RX_QUEUED;
}
}
if (rx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN &&
unlikely(port_control) && sdata->bss) {
sdata = container_of(sdata->bss, struct ieee80211_sub_if_data,
u.ap);
dev = sdata->dev;
rx->sdata = sdata;
}
rx->skb->dev = dev;
if (local->ps_sdata && local->hw.conf.dynamic_ps_timeout > 0 &&
!is_multicast_ether_addr(
((struct ethhdr *)rx->skb->data)->h_dest) &&
(!local->scanning &&
!test_bit(SDATA_STATE_OFFCHANNEL, &sdata->state))) {
mod_timer(&local->dynamic_ps_timer, jiffies +
msecs_to_jiffies(local->hw.conf.dynamic_ps_timeout));
}
ieee80211_deliver_skb(rx);
return RX_QUEUED;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_ctrl(struct ieee80211_rx_data *rx, struct sk_buff_head *frames)
{
struct sk_buff *skb = rx->skb;
struct ieee80211_bar *bar = (struct ieee80211_bar *)skb->data;
struct tid_ampdu_rx *tid_agg_rx;
u16 start_seq_num;
u16 tid;
if (likely(!ieee80211_is_ctl(bar->frame_control)))
return RX_CONTINUE;
if (ieee80211_is_back_req(bar->frame_control)) {
struct {
__le16 control, start_seq_num;
} __packed bar_data;
struct ieee80211_event event = {
.type = BAR_RX_EVENT,
};
if (!rx->sta)
return RX_DROP_MONITOR;
if (skb_copy_bits(skb, offsetof(struct ieee80211_bar, control),
&bar_data, sizeof(bar_data)))
return RX_DROP_MONITOR;
tid = le16_to_cpu(bar_data.control) >> 12;
tid_agg_rx = rcu_dereference(rx->sta->ampdu_mlme.tid_rx[tid]);
if (!tid_agg_rx)
return RX_DROP_MONITOR;
start_seq_num = le16_to_cpu(bar_data.start_seq_num) >> 4;
event.u.ba.tid = tid;
event.u.ba.ssn = start_seq_num;
event.u.ba.sta = &rx->sta->sta;
/* reset session timer */
if (tid_agg_rx->timeout)
mod_timer(&tid_agg_rx->session_timer,
TU_TO_EXP_TIME(tid_agg_rx->timeout));
spin_lock(&tid_agg_rx->reorder_lock);
/* release stored frames up to start of BAR */
ieee80211_release_reorder_frames(rx->sdata, tid_agg_rx,
start_seq_num, frames);
spin_unlock(&tid_agg_rx->reorder_lock);
drv_event_callback(rx->local, rx->sdata, &event);
kfree_skb(skb);
return RX_QUEUED;
}
/*
* After this point, we only want management frames,
* so we can drop all remaining control frames to
* cooked monitor interfaces.
*/
return RX_DROP_MONITOR;
}
static void ieee80211_process_sa_query_req(struct ieee80211_sub_if_data *sdata,
struct ieee80211_mgmt *mgmt,
size_t len)
{
struct ieee80211_local *local = sdata->local;
struct sk_buff *skb;
struct ieee80211_mgmt *resp;
if (!ether_addr_equal(mgmt->da, sdata->vif.addr)) {
/* Not to own unicast address */
return;
}
if (!ether_addr_equal(mgmt->sa, sdata->u.mgd.bssid) ||
!ether_addr_equal(mgmt->bssid, sdata->u.mgd.bssid)) {
/* Not from the current AP or not associated yet. */
return;
}
if (len < 24 + 1 + sizeof(resp->u.action.u.sa_query)) {
/* Too short SA Query request frame */
return;
}
skb = dev_alloc_skb(sizeof(*resp) + local->hw.extra_tx_headroom);
if (skb == NULL)
return;
skb_reserve(skb, local->hw.extra_tx_headroom);
resp = (struct ieee80211_mgmt *) skb_put(skb, 24);
memset(resp, 0, 24);
memcpy(resp->da, mgmt->sa, ETH_ALEN);
memcpy(resp->sa, sdata->vif.addr, ETH_ALEN);
memcpy(resp->bssid, sdata->u.mgd.bssid, ETH_ALEN);
resp->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT |
IEEE80211_STYPE_ACTION);
skb_put(skb, 1 + sizeof(resp->u.action.u.sa_query));
resp->u.action.category = WLAN_CATEGORY_SA_QUERY;
resp->u.action.u.sa_query.action = WLAN_ACTION_SA_QUERY_RESPONSE;
memcpy(resp->u.action.u.sa_query.trans_id,
mgmt->u.action.u.sa_query.trans_id,
WLAN_SA_QUERY_TR_ID_LEN);
ieee80211_tx_skb(sdata, skb);
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_mgmt_check(struct ieee80211_rx_data *rx)
{
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *) rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
/*
* From here on, look only at management frames.
* Data and control frames are already handled,
* and unknown (reserved) frames are useless.
*/
if (rx->skb->len < 24)
return RX_DROP_MONITOR;
if (!ieee80211_is_mgmt(mgmt->frame_control))
return RX_DROP_MONITOR;
if (rx->sdata->vif.type == NL80211_IFTYPE_AP &&
ieee80211_is_beacon(mgmt->frame_control) &&
!(rx->flags & IEEE80211_RX_BEACON_REPORTED)) {
int sig = 0;
if (ieee80211_hw_check(&rx->local->hw, SIGNAL_DBM))
sig = status->signal;
cfg80211_report_obss_beacon(rx->local->hw.wiphy,
rx->skb->data, rx->skb->len,
status->freq, sig);
rx->flags |= IEEE80211_RX_BEACON_REPORTED;
}
if (ieee80211_drop_unencrypted_mgmt(rx))
return RX_DROP_UNUSABLE;
return RX_CONTINUE;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_action(struct ieee80211_rx_data *rx)
{
struct ieee80211_local *local = rx->local;
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *) rx->skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
int len = rx->skb->len;
if (!ieee80211_is_action(mgmt->frame_control))
return RX_CONTINUE;
/* drop too small frames */
if (len < IEEE80211_MIN_ACTION_SIZE)
return RX_DROP_UNUSABLE;
if (!rx->sta && mgmt->u.action.category != WLAN_CATEGORY_PUBLIC &&
mgmt->u.action.category != WLAN_CATEGORY_SELF_PROTECTED &&
mgmt->u.action.category != WLAN_CATEGORY_SPECTRUM_MGMT)
return RX_DROP_UNUSABLE;
switch (mgmt->u.action.category) {
case WLAN_CATEGORY_HT:
/* reject HT action frames from stations not supporting HT */
if (!rx->sta->sta.ht_cap.ht_supported)
goto invalid;
if (sdata->vif.type != NL80211_IFTYPE_STATION &&
sdata->vif.type != NL80211_IFTYPE_MESH_POINT &&
sdata->vif.type != NL80211_IFTYPE_AP_VLAN &&
sdata->vif.type != NL80211_IFTYPE_AP &&
sdata->vif.type != NL80211_IFTYPE_ADHOC)
break;
/* verify action & smps_control/chanwidth are present */
if (len < IEEE80211_MIN_ACTION_SIZE + 2)
goto invalid;
switch (mgmt->u.action.u.ht_smps.action) {
case WLAN_HT_ACTION_SMPS: {
struct ieee80211_supported_band *sband;
enum ieee80211_smps_mode smps_mode;
/* convert to HT capability */
switch (mgmt->u.action.u.ht_smps.smps_control) {
case WLAN_HT_SMPS_CONTROL_DISABLED:
smps_mode = IEEE80211_SMPS_OFF;
break;
case WLAN_HT_SMPS_CONTROL_STATIC:
smps_mode = IEEE80211_SMPS_STATIC;
break;
case WLAN_HT_SMPS_CONTROL_DYNAMIC:
smps_mode = IEEE80211_SMPS_DYNAMIC;
break;
default:
goto invalid;
}
/* if no change do nothing */
if (rx->sta->sta.smps_mode == smps_mode)
goto handled;
rx->sta->sta.smps_mode = smps_mode;
sband = rx->local->hw.wiphy->bands[status->band];
rate_control_rate_update(local, sband, rx->sta,
IEEE80211_RC_SMPS_CHANGED);
goto handled;
}
case WLAN_HT_ACTION_NOTIFY_CHANWIDTH: {
struct ieee80211_supported_band *sband;
u8 chanwidth = mgmt->u.action.u.ht_notify_cw.chanwidth;
enum ieee80211_sta_rx_bandwidth max_bw, new_bw;
/* If it doesn't support 40 MHz it can't change ... */
if (!(rx->sta->sta.ht_cap.cap &
IEEE80211_HT_CAP_SUP_WIDTH_20_40))
goto handled;
if (chanwidth == IEEE80211_HT_CHANWIDTH_20MHZ)
max_bw = IEEE80211_STA_RX_BW_20;
else
max_bw = ieee80211_sta_cap_rx_bw(rx->sta);
/* set cur_max_bandwidth and recalc sta bw */
rx->sta->cur_max_bandwidth = max_bw;
new_bw = ieee80211_sta_cur_vht_bw(rx->sta);
if (rx->sta->sta.bandwidth == new_bw)
goto handled;
rx->sta->sta.bandwidth = new_bw;
sband = rx->local->hw.wiphy->bands[status->band];
rate_control_rate_update(local, sband, rx->sta,
IEEE80211_RC_BW_CHANGED);
goto handled;
}
default:
goto invalid;
}
break;
case WLAN_CATEGORY_PUBLIC:
if (len < IEEE80211_MIN_ACTION_SIZE + 1)
goto invalid;
if (sdata->vif.type != NL80211_IFTYPE_STATION)
break;
if (!rx->sta)
break;
if (!ether_addr_equal(mgmt->bssid, sdata->u.mgd.bssid))
break;
if (mgmt->u.action.u.ext_chan_switch.action_code !=
WLAN_PUB_ACTION_EXT_CHANSW_ANN)
break;
if (len < offsetof(struct ieee80211_mgmt,
u.action.u.ext_chan_switch.variable))
goto invalid;
goto queue;
case WLAN_CATEGORY_VHT:
if (sdata->vif.type != NL80211_IFTYPE_STATION &&
sdata->vif.type != NL80211_IFTYPE_MESH_POINT &&
sdata->vif.type != NL80211_IFTYPE_AP_VLAN &&
sdata->vif.type != NL80211_IFTYPE_AP &&
sdata->vif.type != NL80211_IFTYPE_ADHOC)
break;
/* verify action code is present */
if (len < IEEE80211_MIN_ACTION_SIZE + 1)
goto invalid;
switch (mgmt->u.action.u.vht_opmode_notif.action_code) {
case WLAN_VHT_ACTION_OPMODE_NOTIF: {
u8 opmode;
/* verify opmode is present */
if (len < IEEE80211_MIN_ACTION_SIZE + 2)
goto invalid;
opmode = mgmt->u.action.u.vht_opmode_notif.operating_mode;
ieee80211_vht_handle_opmode(rx->sdata, rx->sta,
opmode, status->band);
goto handled;
}
default:
break;
}
break;
case WLAN_CATEGORY_BACK:
if (sdata->vif.type != NL80211_IFTYPE_STATION &&
sdata->vif.type != NL80211_IFTYPE_MESH_POINT &&
sdata->vif.type != NL80211_IFTYPE_AP_VLAN &&
sdata->vif.type != NL80211_IFTYPE_AP &&
sdata->vif.type != NL80211_IFTYPE_ADHOC)
break;
/* verify action_code is present */
if (len < IEEE80211_MIN_ACTION_SIZE + 1)
break;
switch (mgmt->u.action.u.addba_req.action_code) {
case WLAN_ACTION_ADDBA_REQ:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.addba_req)))
goto invalid;
break;
case WLAN_ACTION_ADDBA_RESP:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.addba_resp)))
goto invalid;
break;
case WLAN_ACTION_DELBA:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.delba)))
goto invalid;
break;
default:
goto invalid;
}
goto queue;
case WLAN_CATEGORY_SPECTRUM_MGMT:
/* verify action_code is present */
if (len < IEEE80211_MIN_ACTION_SIZE + 1)
break;
switch (mgmt->u.action.u.measurement.action_code) {
case WLAN_ACTION_SPCT_MSR_REQ:
if (status->band != IEEE80211_BAND_5GHZ)
break;
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.measurement)))
break;
if (sdata->vif.type != NL80211_IFTYPE_STATION)
break;
ieee80211_process_measurement_req(sdata, mgmt, len);
goto handled;
case WLAN_ACTION_SPCT_CHL_SWITCH: {
u8 *bssid;
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.chan_switch)))
break;
if (sdata->vif.type != NL80211_IFTYPE_STATION &&
sdata->vif.type != NL80211_IFTYPE_ADHOC &&
sdata->vif.type != NL80211_IFTYPE_MESH_POINT)
break;
if (sdata->vif.type == NL80211_IFTYPE_STATION)
bssid = sdata->u.mgd.bssid;
else if (sdata->vif.type == NL80211_IFTYPE_ADHOC)
bssid = sdata->u.ibss.bssid;
else if (sdata->vif.type == NL80211_IFTYPE_MESH_POINT)
bssid = mgmt->sa;
else
break;
if (!ether_addr_equal(mgmt->bssid, bssid))
break;
goto queue;
}
}
break;
case WLAN_CATEGORY_SA_QUERY:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.sa_query)))
break;
switch (mgmt->u.action.u.sa_query.action) {
case WLAN_ACTION_SA_QUERY_REQUEST:
if (sdata->vif.type != NL80211_IFTYPE_STATION)
break;
ieee80211_process_sa_query_req(sdata, mgmt, len);
goto handled;
}
break;
case WLAN_CATEGORY_SELF_PROTECTED:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.self_prot.action_code)))
break;
switch (mgmt->u.action.u.self_prot.action_code) {
case WLAN_SP_MESH_PEERING_OPEN:
case WLAN_SP_MESH_PEERING_CLOSE:
case WLAN_SP_MESH_PEERING_CONFIRM:
if (!ieee80211_vif_is_mesh(&sdata->vif))
goto invalid;
if (sdata->u.mesh.user_mpm)
/* userspace handles this frame */
break;
goto queue;
case WLAN_SP_MGK_INFORM:
case WLAN_SP_MGK_ACK:
if (!ieee80211_vif_is_mesh(&sdata->vif))
goto invalid;
break;
}
break;
case WLAN_CATEGORY_MESH_ACTION:
if (len < (IEEE80211_MIN_ACTION_SIZE +
sizeof(mgmt->u.action.u.mesh_action.action_code)))
break;
if (!ieee80211_vif_is_mesh(&sdata->vif))
break;
if (mesh_action_is_path_sel(mgmt) &&
!mesh_path_sel_is_hwmp(sdata))
break;
goto queue;
}
return RX_CONTINUE;
invalid:
status->rx_flags |= IEEE80211_RX_MALFORMED_ACTION_FRM;
/* will return in the next handlers */
return RX_CONTINUE;
handled:
if (rx->sta)
rx->sta->rx_stats.packets++;
dev_kfree_skb(rx->skb);
return RX_QUEUED;
queue:
rx->skb->pkt_type = IEEE80211_SDATA_QUEUE_TYPE_FRAME;
skb_queue_tail(&sdata->skb_queue, rx->skb);
ieee80211_queue_work(&local->hw, &sdata->work);
if (rx->sta)
rx->sta->rx_stats.packets++;
return RX_QUEUED;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_userspace_mgmt(struct ieee80211_rx_data *rx)
{
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
int sig = 0;
/* skip known-bad action frames and return them in the next handler */
if (status->rx_flags & IEEE80211_RX_MALFORMED_ACTION_FRM)
return RX_CONTINUE;
/*
* Getting here means the kernel doesn't know how to handle
* it, but maybe userspace does ... include returned frames
* so userspace can register for those to know whether ones
* it transmitted were processed or returned.
*/
if (ieee80211_hw_check(&rx->local->hw, SIGNAL_DBM))
sig = status->signal;
if (cfg80211_rx_mgmt(&rx->sdata->wdev, status->freq, sig,
rx->skb->data, rx->skb->len, 0)) {
if (rx->sta)
rx->sta->rx_stats.packets++;
dev_kfree_skb(rx->skb);
return RX_QUEUED;
}
return RX_CONTINUE;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_action_return(struct ieee80211_rx_data *rx)
{
struct ieee80211_local *local = rx->local;
struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *) rx->skb->data;
struct sk_buff *nskb;
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(rx->skb);
if (!ieee80211_is_action(mgmt->frame_control))
return RX_CONTINUE;
/*
* For AP mode, hostapd is responsible for handling any action
* frames that we didn't handle, including returning unknown
* ones. For all other modes we will return them to the sender,
* setting the 0x80 bit in the action category, as required by
* 802.11-2012 9.24.4.
* Newer versions of hostapd shall also use the management frame
* registration mechanisms, but older ones still use cooked
* monitor interfaces so push all frames there.
*/
if (!(status->rx_flags & IEEE80211_RX_MALFORMED_ACTION_FRM) &&
(sdata->vif.type == NL80211_IFTYPE_AP ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN))
return RX_DROP_MONITOR;
if (is_multicast_ether_addr(mgmt->da))
return RX_DROP_MONITOR;
/* do not return rejected action frames */
if (mgmt->u.action.category & 0x80)
return RX_DROP_UNUSABLE;
nskb = skb_copy_expand(rx->skb, local->hw.extra_tx_headroom, 0,
GFP_ATOMIC);
if (nskb) {
struct ieee80211_mgmt *nmgmt = (void *)nskb->data;
nmgmt->u.action.category |= 0x80;
memcpy(nmgmt->da, nmgmt->sa, ETH_ALEN);
memcpy(nmgmt->sa, rx->sdata->vif.addr, ETH_ALEN);
memset(nskb->cb, 0, sizeof(nskb->cb));
if (rx->sdata->vif.type == NL80211_IFTYPE_P2P_DEVICE) {
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(nskb);
info->flags = IEEE80211_TX_CTL_TX_OFFCHAN |
IEEE80211_TX_INTFL_OFFCHAN_TX_OK |
IEEE80211_TX_CTL_NO_CCK_RATE;
if (ieee80211_hw_check(&local->hw, QUEUE_CONTROL))
info->hw_queue =
local->hw.offchannel_tx_hw_queue;
}
__ieee80211_tx_skb_tid_band(rx->sdata, nskb, 7,
status->band);
}
dev_kfree_skb(rx->skb);
return RX_QUEUED;
}
static ieee80211_rx_result debug_noinline
ieee80211_rx_h_mgmt(struct ieee80211_rx_data *rx)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct ieee80211_mgmt *mgmt = (void *)rx->skb->data;
__le16 stype;
stype = mgmt->frame_control & cpu_to_le16(IEEE80211_FCTL_STYPE);
if (!ieee80211_vif_is_mesh(&sdata->vif) &&
sdata->vif.type != NL80211_IFTYPE_ADHOC &&
sdata->vif.type != NL80211_IFTYPE_OCB &&
sdata->vif.type != NL80211_IFTYPE_STATION)
return RX_DROP_MONITOR;
switch (stype) {
case cpu_to_le16(IEEE80211_STYPE_AUTH):
case cpu_to_le16(IEEE80211_STYPE_BEACON):
case cpu_to_le16(IEEE80211_STYPE_PROBE_RESP):
/* process for all: mesh, mlme, ibss */
break;
case cpu_to_le16(IEEE80211_STYPE_ASSOC_RESP):
case cpu_to_le16(IEEE80211_STYPE_REASSOC_RESP):
case cpu_to_le16(IEEE80211_STYPE_DEAUTH):
case cpu_to_le16(IEEE80211_STYPE_DISASSOC):
if (is_multicast_ether_addr(mgmt->da) &&
!is_broadcast_ether_addr(mgmt->da))
return RX_DROP_MONITOR;
/* process only for station */
if (sdata->vif.type != NL80211_IFTYPE_STATION)
return RX_DROP_MONITOR;
break;
case cpu_to_le16(IEEE80211_STYPE_PROBE_REQ):
/* process only for ibss and mesh */
if (sdata->vif.type != NL80211_IFTYPE_ADHOC &&
sdata->vif.type != NL80211_IFTYPE_MESH_POINT)
return RX_DROP_MONITOR;
break;
default:
return RX_DROP_MONITOR;
}
/* queue up frame and kick off work to process it */
rx->skb->pkt_type = IEEE80211_SDATA_QUEUE_TYPE_FRAME;
skb_queue_tail(&sdata->skb_queue, rx->skb);
ieee80211_queue_work(&rx->local->hw, &sdata->work);
if (rx->sta)
rx->sta->rx_stats.packets++;
return RX_QUEUED;
}
static void ieee80211_rx_cooked_monitor(struct ieee80211_rx_data *rx,
struct ieee80211_rate *rate)
{
struct ieee80211_sub_if_data *sdata;
struct ieee80211_local *local = rx->local;
struct sk_buff *skb = rx->skb, *skb2;
struct net_device *prev_dev = NULL;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
int needed_headroom;
/*
* If cooked monitor has been processed already, then
* don't do it again. If not, set the flag.
*/
if (rx->flags & IEEE80211_RX_CMNTR)
goto out_free_skb;
rx->flags |= IEEE80211_RX_CMNTR;
/* If there are no cooked monitor interfaces, just free the SKB */
if (!local->cooked_mntrs)
goto out_free_skb;
/* vendor data is long removed here */
status->flag &= ~RX_FLAG_RADIOTAP_VENDOR_DATA;
/* room for the radiotap header based on driver features */
needed_headroom = ieee80211_rx_radiotap_hdrlen(local, status, skb);
if (skb_headroom(skb) < needed_headroom &&
pskb_expand_head(skb, needed_headroom, 0, GFP_ATOMIC))
goto out_free_skb;
/* prepend radiotap information */
ieee80211_add_rx_radiotap_header(local, skb, rate, needed_headroom,
false);
skb_set_mac_header(skb, 0);
skb->ip_summed = CHECKSUM_UNNECESSARY;
skb->pkt_type = PACKET_OTHERHOST;
skb->protocol = htons(ETH_P_802_2);
list_for_each_entry_rcu(sdata, &local->interfaces, list) {
if (!ieee80211_sdata_running(sdata))
continue;
if (sdata->vif.type != NL80211_IFTYPE_MONITOR ||
!(sdata->u.mntr_flags & MONITOR_FLAG_COOK_FRAMES))
continue;
if (prev_dev) {
skb2 = skb_clone(skb, GFP_ATOMIC);
if (skb2) {
skb2->dev = prev_dev;
netif_receive_skb(skb2);
}
}
prev_dev = sdata->dev;
ieee80211_rx_stats(sdata->dev, skb->len);
}
if (prev_dev) {
skb->dev = prev_dev;
netif_receive_skb(skb);
return;
}
out_free_skb:
dev_kfree_skb(skb);
}
static void ieee80211_rx_handlers_result(struct ieee80211_rx_data *rx,
ieee80211_rx_result res)
{
switch (res) {
case RX_DROP_MONITOR:
I802_DEBUG_INC(rx->sdata->local->rx_handlers_drop);
if (rx->sta)
rx->sta->rx_stats.dropped++;
/* fall through */
case RX_CONTINUE: {
struct ieee80211_rate *rate = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_rx_status *status;
status = IEEE80211_SKB_RXCB((rx->skb));
sband = rx->local->hw.wiphy->bands[status->band];
if (!(status->flag & RX_FLAG_HT) &&
!(status->flag & RX_FLAG_VHT))
rate = &sband->bitrates[status->rate_idx];
ieee80211_rx_cooked_monitor(rx, rate);
break;
}
case RX_DROP_UNUSABLE:
I802_DEBUG_INC(rx->sdata->local->rx_handlers_drop);
if (rx->sta)
rx->sta->rx_stats.dropped++;
dev_kfree_skb(rx->skb);
break;
case RX_QUEUED:
I802_DEBUG_INC(rx->sdata->local->rx_handlers_queued);
break;
}
}
static void ieee80211_rx_handlers(struct ieee80211_rx_data *rx,
struct sk_buff_head *frames)
{
ieee80211_rx_result res = RX_DROP_MONITOR;
struct sk_buff *skb;
#define CALL_RXH(rxh) \
do { \
res = rxh(rx); \
if (res != RX_CONTINUE) \
goto rxh_next; \
} while (0);
/* Lock here to avoid hitting all of the data used in the RX
* path (e.g. key data, station data, ...) concurrently when
* a frame is released from the reorder buffer due to timeout
* from the timer, potentially concurrently with RX from the
* driver.
*/
spin_lock_bh(&rx->local->rx_path_lock);
while ((skb = __skb_dequeue(frames))) {
/*
* all the other fields are valid across frames
* that belong to an aMPDU since they are on the
* same TID from the same station
*/
rx->skb = skb;
CALL_RXH(ieee80211_rx_h_check_more_data)
CALL_RXH(ieee80211_rx_h_uapsd_and_pspoll)
CALL_RXH(ieee80211_rx_h_sta_process)
CALL_RXH(ieee80211_rx_h_decrypt)
CALL_RXH(ieee80211_rx_h_defragment)
CALL_RXH(ieee80211_rx_h_michael_mic_verify)
/* must be after MMIC verify so header is counted in MPDU mic */
#ifdef CONFIG_MAC80211_MESH
if (ieee80211_vif_is_mesh(&rx->sdata->vif))
CALL_RXH(ieee80211_rx_h_mesh_fwding);
#endif
CALL_RXH(ieee80211_rx_h_amsdu)
CALL_RXH(ieee80211_rx_h_data)
/* special treatment -- needs the queue */
res = ieee80211_rx_h_ctrl(rx, frames);
if (res != RX_CONTINUE)
goto rxh_next;
CALL_RXH(ieee80211_rx_h_mgmt_check)
CALL_RXH(ieee80211_rx_h_action)
CALL_RXH(ieee80211_rx_h_userspace_mgmt)
CALL_RXH(ieee80211_rx_h_action_return)
CALL_RXH(ieee80211_rx_h_mgmt)
rxh_next:
ieee80211_rx_handlers_result(rx, res);
#undef CALL_RXH
}
spin_unlock_bh(&rx->local->rx_path_lock);
}
static void ieee80211_invoke_rx_handlers(struct ieee80211_rx_data *rx)
{
struct sk_buff_head reorder_release;
ieee80211_rx_result res = RX_DROP_MONITOR;
__skb_queue_head_init(&reorder_release);
#define CALL_RXH(rxh) \
do { \
res = rxh(rx); \
if (res != RX_CONTINUE) \
goto rxh_next; \
} while (0);
CALL_RXH(ieee80211_rx_h_check_dup)
CALL_RXH(ieee80211_rx_h_check)
ieee80211_rx_reorder_ampdu(rx, &reorder_release);
ieee80211_rx_handlers(rx, &reorder_release);
return;
rxh_next:
ieee80211_rx_handlers_result(rx, res);
#undef CALL_RXH
}
/*
* This function makes calls into the RX path, therefore
* it has to be invoked under RCU read lock.
*/
void ieee80211_release_reorder_timeout(struct sta_info *sta, int tid)
{
struct sk_buff_head frames;
struct ieee80211_rx_data rx = {
.sta = sta,
.sdata = sta->sdata,
.local = sta->local,
/* This is OK -- must be QoS data frame */
.security_idx = tid,
.seqno_idx = tid,
.napi = NULL, /* must be NULL to not have races */
};
struct tid_ampdu_rx *tid_agg_rx;
tid_agg_rx = rcu_dereference(sta->ampdu_mlme.tid_rx[tid]);
if (!tid_agg_rx)
return;
__skb_queue_head_init(&frames);
spin_lock(&tid_agg_rx->reorder_lock);
ieee80211_sta_reorder_release(sta->sdata, tid_agg_rx, &frames);
spin_unlock(&tid_agg_rx->reorder_lock);
if (!skb_queue_empty(&frames)) {
struct ieee80211_event event = {
.type = BA_FRAME_TIMEOUT,
.u.ba.tid = tid,
.u.ba.sta = &sta->sta,
};
drv_event_callback(rx.local, rx.sdata, &event);
}
ieee80211_rx_handlers(&rx, &frames);
}
/* main receive path */
static bool ieee80211_accept_frame(struct ieee80211_rx_data *rx)
{
struct ieee80211_sub_if_data *sdata = rx->sdata;
struct sk_buff *skb = rx->skb;
struct ieee80211_hdr *hdr = (void *)skb->data;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
u8 *bssid = ieee80211_get_bssid(hdr, skb->len, sdata->vif.type);
int multicast = is_multicast_ether_addr(hdr->addr1);
switch (sdata->vif.type) {
case NL80211_IFTYPE_STATION:
if (!bssid && !sdata->u.mgd.use_4addr)
return false;
if (multicast)
return true;
return ether_addr_equal(sdata->vif.addr, hdr->addr1);
case NL80211_IFTYPE_ADHOC:
if (!bssid)
return false;
if (ether_addr_equal(sdata->vif.addr, hdr->addr2) ||
ether_addr_equal(sdata->u.ibss.bssid, hdr->addr2))
return false;
if (ieee80211_is_beacon(hdr->frame_control))
return true;
if (!ieee80211_bssid_match(bssid, sdata->u.ibss.bssid))
return false;
if (!multicast &&
!ether_addr_equal(sdata->vif.addr, hdr->addr1))
return false;
if (!rx->sta) {
int rate_idx;
if (status->flag & (RX_FLAG_HT | RX_FLAG_VHT))
rate_idx = 0; /* TODO: HT/VHT rates */
else
rate_idx = status->rate_idx;
ieee80211_ibss_rx_no_sta(sdata, bssid, hdr->addr2,
BIT(rate_idx));
}
return true;
case NL80211_IFTYPE_OCB:
if (!bssid)
return false;
if (!ieee80211_is_data_present(hdr->frame_control))
return false;
if (!is_broadcast_ether_addr(bssid))
return false;
if (!multicast &&
!ether_addr_equal(sdata->dev->dev_addr, hdr->addr1))
return false;
if (!rx->sta) {
int rate_idx;
if (status->flag & RX_FLAG_HT)
rate_idx = 0; /* TODO: HT rates */
else
rate_idx = status->rate_idx;
ieee80211_ocb_rx_no_sta(sdata, bssid, hdr->addr2,
BIT(rate_idx));
}
return true;
case NL80211_IFTYPE_MESH_POINT:
if (multicast)
return true;
return ether_addr_equal(sdata->vif.addr, hdr->addr1);
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_AP:
if (!bssid)
return ether_addr_equal(sdata->vif.addr, hdr->addr1);
if (!ieee80211_bssid_match(bssid, sdata->vif.addr)) {
/*
* Accept public action frames even when the
* BSSID doesn't match, this is used for P2P
* and location updates. Note that mac80211
* itself never looks at these frames.
*/
if (!multicast &&
!ether_addr_equal(sdata->vif.addr, hdr->addr1))
return false;
if (ieee80211_is_public_action(hdr, skb->len))
return true;
return ieee80211_is_beacon(hdr->frame_control);
}
if (!ieee80211_has_tods(hdr->frame_control)) {
/* ignore data frames to TDLS-peers */
if (ieee80211_is_data(hdr->frame_control))
return false;
/* ignore action frames to TDLS-peers */
if (ieee80211_is_action(hdr->frame_control) &&
!ether_addr_equal(bssid, hdr->addr1))
return false;
}
return true;
case NL80211_IFTYPE_WDS:
if (bssid || !ieee80211_is_data(hdr->frame_control))
return false;
return ether_addr_equal(sdata->u.wds.remote_addr, hdr->addr2);
case NL80211_IFTYPE_P2P_DEVICE:
return ieee80211_is_public_action(hdr, skb->len) ||
ieee80211_is_probe_req(hdr->frame_control) ||
ieee80211_is_probe_resp(hdr->frame_control) ||
ieee80211_is_beacon(hdr->frame_control);
default:
break;
}
WARN_ON_ONCE(1);
return false;
}
/*
* This function returns whether or not the SKB
* was destined for RX processing or not, which,
* if consume is true, is equivalent to whether
* or not the skb was consumed.
*/
static bool ieee80211_prepare_and_rx_handle(struct ieee80211_rx_data *rx,
struct sk_buff *skb, bool consume)
{
struct ieee80211_local *local = rx->local;
struct ieee80211_sub_if_data *sdata = rx->sdata;
rx->skb = skb;
if (!ieee80211_accept_frame(rx))
return false;
if (!consume) {
skb = skb_copy(skb, GFP_ATOMIC);
if (!skb) {
if (net_ratelimit())
wiphy_debug(local->hw.wiphy,
"failed to copy skb for %s\n",
sdata->name);
return true;
}
rx->skb = skb;
}
ieee80211_invoke_rx_handlers(rx);
return true;
}
/*
* This is the actual Rx frames handler. as it belongs to Rx path it must
* be called with rcu_read_lock protection.
*/
static void __ieee80211_rx_handle_packet(struct ieee80211_hw *hw,
struct sk_buff *skb,
struct napi_struct *napi)
{
struct ieee80211_local *local = hw_to_local(hw);
struct ieee80211_sub_if_data *sdata;
struct ieee80211_hdr *hdr;
__le16 fc;
struct ieee80211_rx_data rx;
struct ieee80211_sub_if_data *prev;
struct sta_info *sta, *prev_sta;
struct rhash_head *tmp;
int err = 0;
fc = ((struct ieee80211_hdr *)skb->data)->frame_control;
memset(&rx, 0, sizeof(rx));
rx.skb = skb;
rx.local = local;
rx.napi = napi;
if (ieee80211_is_data(fc) || ieee80211_is_mgmt(fc))
I802_DEBUG_INC(local->dot11ReceivedFragmentCount);
if (ieee80211_is_mgmt(fc)) {
/* drop frame if too short for header */
if (skb->len < ieee80211_hdrlen(fc))
err = -ENOBUFS;
else
err = skb_linearize(skb);
} else {
err = !pskb_may_pull(skb, ieee80211_hdrlen(fc));
}
if (err) {
dev_kfree_skb(skb);
return;
}
hdr = (struct ieee80211_hdr *)skb->data;
ieee80211_parse_qos(&rx);
ieee80211_verify_alignment(&rx);
if (unlikely(ieee80211_is_probe_resp(hdr->frame_control) ||
ieee80211_is_beacon(hdr->frame_control)))
ieee80211_scan_rx(local, skb);
if (ieee80211_is_data(fc)) {
const struct bucket_table *tbl;
prev_sta = NULL;
tbl = rht_dereference_rcu(local->sta_hash.tbl, &local->sta_hash);
for_each_sta_info(local, tbl, hdr->addr2, sta, tmp) {
if (!prev_sta) {
prev_sta = sta;
continue;
}
rx.sta = prev_sta;
rx.sdata = prev_sta->sdata;
ieee80211_prepare_and_rx_handle(&rx, skb, false);
prev_sta = sta;
}
if (prev_sta) {
rx.sta = prev_sta;
rx.sdata = prev_sta->sdata;
if (ieee80211_prepare_and_rx_handle(&rx, skb, true))
return;
goto out;
}
}
prev = NULL;
list_for_each_entry_rcu(sdata, &local->interfaces, list) {
if (!ieee80211_sdata_running(sdata))
continue;
if (sdata->vif.type == NL80211_IFTYPE_MONITOR ||
sdata->vif.type == NL80211_IFTYPE_AP_VLAN)
continue;
/*
* frame is destined for this interface, but if it's
* not also for the previous one we handle that after
* the loop to avoid copying the SKB once too much
*/
if (!prev) {
prev = sdata;
continue;
}
rx.sta = sta_info_get_bss(prev, hdr->addr2);
rx.sdata = prev;
ieee80211_prepare_and_rx_handle(&rx, skb, false);
prev = sdata;
}
if (prev) {
rx.sta = sta_info_get_bss(prev, hdr->addr2);
rx.sdata = prev;
if (ieee80211_prepare_and_rx_handle(&rx, skb, true))
return;
}
out:
dev_kfree_skb(skb);
}
/*
* This is the receive path handler. It is called by a low level driver when an
* 802.11 MPDU is received from the hardware.
*/
void ieee80211_rx_napi(struct ieee80211_hw *hw, struct sk_buff *skb,
struct napi_struct *napi)
{
struct ieee80211_local *local = hw_to_local(hw);
struct ieee80211_rate *rate = NULL;
struct ieee80211_supported_band *sband;
struct ieee80211_rx_status *status = IEEE80211_SKB_RXCB(skb);
WARN_ON_ONCE(softirq_count() == 0);
if (WARN_ON(status->band >= IEEE80211_NUM_BANDS))
goto drop;
sband = local->hw.wiphy->bands[status->band];
if (WARN_ON(!sband))
goto drop;
/*
* If we're suspending, it is possible although not too likely
* that we'd be receiving frames after having already partially
* quiesced the stack. We can't process such frames then since
* that might, for example, cause stations to be added or other
* driver callbacks be invoked.
*/
if (unlikely(local->quiescing || local->suspended))
goto drop;
/* We might be during a HW reconfig, prevent Rx for the same reason */
if (unlikely(local->in_reconfig))
goto drop;
/*
* The same happens when we're not even started,
* but that's worth a warning.
*/
if (WARN_ON(!local->started))
goto drop;
if (likely(!(status->flag & RX_FLAG_FAILED_PLCP_CRC))) {
/*
* Validate the rate, unless a PLCP error means that
* we probably can't have a valid rate here anyway.
*/
if (status->flag & RX_FLAG_HT) {
/*
* rate_idx is MCS index, which can be [0-76]
* as documented on:
*
* http://wireless.kernel.org/en/developers/Documentation/ieee80211/802.11n
*
* Anything else would be some sort of driver or
* hardware error. The driver should catch hardware
* errors.
*/
if (WARN(status->rate_idx > 76,
"Rate marked as an HT rate but passed "
"status->rate_idx is not "
"an MCS index [0-76]: %d (0x%02x)\n",
status->rate_idx,
status->rate_idx))
goto drop;
} else if (status->flag & RX_FLAG_VHT) {
if (WARN_ONCE(status->rate_idx > 9 ||
!status->vht_nss ||
status->vht_nss > 8,
"Rate marked as a VHT rate but data is invalid: MCS: %d, NSS: %d\n",
status->rate_idx, status->vht_nss))
goto drop;
} else {
if (WARN_ON(status->rate_idx >= sband->n_bitrates))
goto drop;
rate = &sband->bitrates[status->rate_idx];
}
}
status->rx_flags = 0;
/*
* key references and virtual interfaces are protected using RCU
* and this requires that we are in a read-side RCU section during
* receive processing
*/
rcu_read_lock();
/*
* Frames with failed FCS/PLCP checksum are not returned,
* all other frames are returned without radiotap header
* if it was previously present.
* Also, frames with less than 16 bytes are dropped.
*/
skb = ieee80211_rx_monitor(local, skb, rate);
if (!skb) {
rcu_read_unlock();
return;
}
ieee80211_tpt_led_trig_rx(local,
((struct ieee80211_hdr *)skb->data)->frame_control,
skb->len);
__ieee80211_rx_handle_packet(hw, skb, napi);
rcu_read_unlock();
return;
drop:
kfree_skb(skb);
}
EXPORT_SYMBOL(ieee80211_rx_napi);
/* This is a version of the rx handler that can be called from hard irq
* context. Post the skb on the queue and schedule the tasklet */
void ieee80211_rx_irqsafe(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct ieee80211_local *local = hw_to_local(hw);
BUILD_BUG_ON(sizeof(struct ieee80211_rx_status) > sizeof(skb->cb));
skb->pkt_type = IEEE80211_RX_MSG;
skb_queue_tail(&local->skb_queue, skb);
tasklet_schedule(&local->tasklet);
}
EXPORT_SYMBOL(ieee80211_rx_irqsafe);
| {
"content_hash": "14091e01f9b4d9419cef137cba4f1827",
"timestamp": "",
"source": "github",
"line_count": 3661,
"max_line_length": 81,
"avg_line_length": 28.318765364654467,
"alnum_prop": 0.6602941885700506,
"repo_name": "KristFoundation/Programs",
"id": "82af407fea7a094db5f08e6426ae670a4cab3729",
"size": "104143",
"binary": false,
"copies": "44",
"ref": "refs/heads/master",
"path": "luaide/net/mac80211/rx.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "10201036"
},
{
"name": "Awk",
"bytes": "30879"
},
{
"name": "C",
"bytes": "539626448"
},
{
"name": "C++",
"bytes": "3413466"
},
{
"name": "Clojure",
"bytes": "1570"
},
{
"name": "Cucumber",
"bytes": "4809"
},
{
"name": "Groff",
"bytes": "46837"
},
{
"name": "Lex",
"bytes": "55541"
},
{
"name": "Lua",
"bytes": "59745"
},
{
"name": "Makefile",
"bytes": "1601043"
},
{
"name": "Objective-C",
"bytes": "521706"
},
{
"name": "Perl",
"bytes": "730609"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "296036"
},
{
"name": "Shell",
"bytes": "357961"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "12797"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "115572"
}
],
"symlink_target": ""
} |
package com.smbtec.xo.orientdb.impl.metadata;
import com.tinkerpop.blueprints.Direction;
/**
*
* @author Lars Martin - [email protected]
* @author Rick-Rainer Ludwig
*
*/
public class CollectionPropertyMetadata {
private final String name;
private final Direction direction;
public CollectionPropertyMetadata(final String name, final Direction direction) {
this.name = name;
this.direction = direction;
}
public String getName() {
return name;
}
public Direction getDirection() {
return direction;
}
}
| {
"content_hash": "1d5871c7eaa4c242d1842655d6aa6302",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 85,
"avg_line_length": 19.5,
"alnum_prop": 0.676923076923077,
"repo_name": "SMB-TEC/xo-orientdb",
"id": "b4771631ce82cf9dd6eb9e0bef5449c10861e960",
"size": "1226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/smbtec/xo/orientdb/impl/metadata/CollectionPropertyMetadata.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "83153"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.