text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
package typeinfo;
//: typeinfo/RegisteredFactories.java
// Registering Class Factories in the base class.
import typeinfo.factory.*;
import java.util.*;
class Part {
public String toString() {
return getClass().getSimpleName();
}
static List<Factory<? extends Part>> partFactories =
new ArrayList<Factory<? extends Part>>();
static {
// Collections.addAll() gives an "unchecked generic
// array creation ... for varargs parameter" warning.
partFactories.add(new FuelFilter.Factory());
partFactories.add(new AirFilter.Factory());
partFactories.add(new CabinAirFilter.Factory());
partFactories.add(new OilFilter.Factory());
partFactories.add(new FanBelt.Factory());
partFactories.add(new PowerSteeringBelt.Factory());
partFactories.add(new GeneratorBelt.Factory());
}
private static Random rand = new Random(47);
public static Part createRandom() {
int n = rand.nextInt(partFactories.size());
return partFactories.get(n).create();
}
}
class Filter extends Part {}
class FuelFilter extends Filter {
// Create a Class Factory for each specific type:
public static class Factory
implements typeinfo.factory.Factory<FuelFilter> {
public FuelFilter create() { return new FuelFilter(); }
}
}
class AirFilter extends Filter {
public static class Factory
implements typeinfo.factory.Factory<AirFilter> {
public AirFilter create() { return new AirFilter(); }
}
}
class CabinAirFilter extends Filter {
public static class Factory
implements typeinfo.factory.Factory<CabinAirFilter> {
public CabinAirFilter create() {
return new CabinAirFilter();
}
}
}
class OilFilter extends Filter {
public static class Factory
implements typeinfo.factory.Factory<OilFilter> {
public OilFilter create() { return new OilFilter(); }
}
}
class Belt extends Part {}
class FanBelt extends Belt {
public static class Factory
implements typeinfo.factory.Factory<FanBelt> {
public FanBelt create() { return new FanBelt(); }
}
}
class GeneratorBelt extends Belt {
public static class Factory
implements typeinfo.factory.Factory<GeneratorBelt> {
public GeneratorBelt create() {
return new GeneratorBelt();
}
}
}
class PowerSteeringBelt extends Belt {
public static class Factory
implements typeinfo.factory.Factory<PowerSteeringBelt> {
public PowerSteeringBelt create() {
return new PowerSteeringBelt();
}
}
}
public class RegisteredFactories {
public static void main(String[] args) {
for(int i = 0; i < 10; i++)
System.out.println(Part.createRandom());
}
} /* Output:
GeneratorBelt
CabinAirFilter
GeneratorBelt
AirFilter
PowerSteeringBelt
CabinAirFilter
FuelFilter
PowerSteeringBelt
PowerSteeringBelt
FuelFilter
*///:~
| {'content_hash': '0609e2cb47e7f4e749b03b92492f3a87', 'timestamp': '', 'source': 'github', 'line_count': 107, 'max_line_length': 59, 'avg_line_length': 26.02803738317757, 'alnum_prop': 0.7235188509874326, 'repo_name': 'Shelley132/java-review', 'id': '18bec198d28f0c0c6977395a707aeb71b475cea6', 'size': '2785', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'thinkinginjava/typeinfo/RegisteredFactories.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '152343'}]} |
<?php
namespace Ent\Widgets;
class TermsList extends \WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
parent::__construct('ent_terms_list', 'Terms List', [
'classname' => 'ent-widget-terms-list',
'description' => 'Taxonomy terms list.',
]);
}
protected function render_terms($terms, $only_root, $hierarchical, $show_count) {
foreach ($terms as $term) {
echo
'<li class="mu-icon-list__entry">',
'<i class="fa fa-tag"></i><a href="', get_term_link($term) ,'">', $term->name ,'</a>';
if ($show_count) {
echo ' (', $term->count ,')';
}
if (!$hierarchical) { echo '</li>'; }
if (!$only_root && count($term->children) != 0) {
if ($hierarchical) { echo '<ul class="mu-icon-list">'; }
$this->render_terms($term->children, $only_root, $hierarchical, $show_count);
if ($hierarchical) { echo '</ul>'; }
}
if ($hierarchical) { echo '</li>'; }
}
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget($args, $instance) {
static $first_dropdown = true;
$term_id_map = [];
$terms_tree = [];
$show_count = empty($instance['count']) ? '0' : '1';
$hierarchical = empty($instance['hierarchical']) ? '0' : '1';
$only_root = empty($instance['only_root']) ? '0' : '1';
$current_taxonomy = $this->get_current_taxonomy($instance);
$terms = get_terms([
'taxonomy' => $current_taxonomy,
'orderby' => 'name',
'hierarchical' => $hierarchical,
]);
// Save ID => OBJECT relation
foreach ($terms as $term) {
$term_id_map[$term->term_id] = $term;
$term->children = [];
}
// Create the actual TREE
foreach ($terms as $term) {
if ($term->parent != 0) {
$term_id_map[$term->parent]->children[] = $term;
} else {
$terms_tree[] = $term;
}
}
echo
'<div class="ent-widget ent-widget-terms-list">',
'<ul class="mu-icon-list">';
$this->render_terms($terms_tree, $only_root, $hierarchical, $show_count);
echo
'</ul>',
'</div>';
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form($instance) {
//Defaults
$instance = wp_parse_args((array) $instance, []);
$count = isset($instance['count']) ? (bool) $instance['count'] : false;
$hierarchical = isset( $instance['hierarchical'] ) ? (bool) $instance['hierarchical'] : false;
$only_root = isset($instance['only_root']) ? (bool) $instance['only_root'] : false;
$current_taxonomy = $this->get_current_taxonomy($instance);
$taxonomies = get_taxonomies(['public' => true], 'object');
$id = $this->get_field_id('taxonomy');
$name = $this->get_field_name('taxonomy');
$input = '<input type="hidden" id="'. $id .'" name="'. $name .'" value="%s" />';
switch (count($taxonomies)) {
// No tag cloud supporting taxonomies found, display error message
case 0:
echo '<p>'. __('The tag cloud will not be displayed since there are no taxonomies that support the tag cloud widget.') .'</p>';
printf($input, '');
break;
// Just a single tag cloud supporting taxonomy found, no need to display options
case 1:
$keys = array_keys($taxonomies);
$taxonomy = reset($keys);
printf($input, esc_attr($taxonomy));
break;
// More than one tag cloud supporting taxonomy found, display options
default:
printf(
'<p><label for="%1$s">%2$s</label>' .
'<select class="widefat" id="%1$s" name="%3$s">',
$id,
__('Taxonomy:'),
$name
);
foreach ($taxonomies as $taxonomy => $tax) {
printf(
'<option value="%s"%s>%s</option>',
esc_attr($taxonomy),
selected($taxonomy, $current_taxonomy, false),
$tax->labels->name
);
}
echo '</select></p>';
}
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('count'); ?>" name="<?php echo $this->get_field_name('count'); ?>"<?php checked($count); ?> />
<label for="<?php echo $this->get_field_id('count'); ?>">Show post counts</label>
<br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('hierarchical'); ?>" name="<?php echo $this->get_field_name('hierarchical'); ?>"<?php checked($hierarchical); ?> />
<label for="<?php echo $this->get_field_id('hierarchical'); ?>">Show hierarchy</label>
<br />
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('only_root'); ?>" name="<?php echo $this->get_field_name('only_root'); ?>"<?php checked($only_root); ?> />
<label for="<?php echo $this->get_field_id('only_root'); ?>">Show only root terms</label>
</p>
<?php
}
protected function get_current_taxonomy($instance) {
if (!empty($instance['taxonomy']) && taxonomy_exists($instance['taxonomy'])) {
return $instance['taxonomy'];
}
return 'category';
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update($new_instance, $instance) {
$instance['count'] = !empty($new_instance['count']) ? 1 : 0;
$instance['hierarchical'] = !empty($new_instance['hierarchical']) ? 1 : 0;
$instance['only_root'] = !empty($new_instance['only_root']) ? 1 : 0;
$instance['taxonomy'] = stripslashes($new_instance['taxonomy']);
return $instance;
}
}
| {'content_hash': '374f5bb8e11f599311579060ac05c48f', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 196, 'avg_line_length': 36.76704545454545, 'alnum_prop': 0.4968320197805594, 'repo_name': 'doup/ent', 'id': '36dd32928a7af1ce2a0bd5addf859a4d50e345c0', 'size': '6471', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Widgets/TermsList.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2610'}, {'name': 'HTML', 'bytes': '8995'}, {'name': 'JavaScript', 'bytes': '3261'}, {'name': 'PHP', 'bytes': '64415'}]} |
"""
django-guardian helper functions.
Functions defined within this module should be considered as django-guardian's
internal functionality. They are **not** guaranteed to be stable - which means
they actual input parameters/output type may change in future releases.
"""
from __future__ import unicode_literals
import os
import logging
from itertools import chain
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.models import AnonymousUser, Group
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.db.models import Model
from django.http import HttpResponseForbidden, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext, TemplateDoesNotExist
from django.utils.http import urlquote
from guardian.compat import get_user_model
from guardian.conf import settings as guardian_settings
from guardian.exceptions import NotUserNorGroup
logger = logging.getLogger(__name__)
abspath = lambda *p: os.path.abspath(os.path.join(*p))
def get_anonymous_user():
"""
Returns ``User`` instance (not ``AnonymousUser``) depending on
``ANONYMOUS_USER_ID`` configuration.
"""
return get_user_model().objects.get(id=guardian_settings.ANONYMOUS_USER_ID)
def get_identity(identity):
"""
Returns (user_obj, None) or (None, group_obj) tuple depending on what is
given. Also accepts AnonymousUser instance but would return ``User``
instead - it is convenient and needed for authorization backend to support
anonymous users.
:param identity: either ``User`` or ``Group`` instance
:raises ``NotUserNorGroup``: if cannot return proper identity instance
**Examples**::
>>> from django.contrib.auth.models import User
>>> user = User.objects.create(username='joe')
>>> get_identity(user)
(<User: joe>, None)
>>> group = Group.objects.create(name='users')
>>> get_identity(group)
(None, <Group: users>)
>>> anon = AnonymousUser()
>>> get_identity(anon)
(<User: AnonymousUser>, None)
>>> get_identity("not instance")
...
NotUserNorGroup: User/AnonymousUser or Group instance is required (got )
"""
if isinstance(identity, AnonymousUser):
identity = get_anonymous_user()
if isinstance(identity, get_user_model()):
return identity, None
elif isinstance(identity, Group):
return None, identity
raise NotUserNorGroup("User/AnonymousUser or Group instance is required "
"(got %s)" % identity)
def get_403_or_None(request, perms, obj=None, login_url=None,
redirect_field_name=None, return_403=False, accept_global_perms=False):
login_url = login_url or settings.LOGIN_URL
redirect_field_name = redirect_field_name or REDIRECT_FIELD_NAME
# Handles both original and with object provided permission check
# as ``obj`` defaults to None
has_permissions = False
# global perms check first (if accept_global_perms)
if accept_global_perms:
has_permissions = all(request.user.has_perm(perm) for perm in perms)
# if still no permission granted, try obj perms
if not has_permissions:
has_permissions = all(request.user.has_perm(perm, obj) for perm in perms)
if not has_permissions:
if return_403:
if guardian_settings.RENDER_403:
try:
response = render_to_response(
guardian_settings.TEMPLATE_403, {},
RequestContext(request))
response.status_code = 403
return response
except TemplateDoesNotExist as e:
if settings.DEBUG:
raise e
elif guardian_settings.RAISE_403:
raise PermissionDenied
return HttpResponseForbidden()
else:
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect("%s?%s=%s" % tup)
def clean_orphan_obj_perms():
"""
Seeks and removes all object permissions entries pointing at non-existing
targets.
Returns number of removed objects.
"""
from guardian.models import UserObjectPermission
from guardian.models import GroupObjectPermission
from django.core.cache import cache
deleted = 0
# TODO: optimise
for perm in chain(UserObjectPermission.objects.all(),
GroupObjectPermission.objects.all()):
if perm.content_object is None:
logger.debug("Removing %s (pk=%d)" % (perm, perm.pk))
perm.delete()
deleted += 1
logger.info("Total removed orphan object permissions instances: %d" %
deleted)
cache.clear()
return deleted
# TODO: should raise error when multiple UserObjectPermission direct relations
# are defined
def get_obj_perms_model(obj, base_cls, generic_cls):
if isinstance(obj, Model):
obj = obj.__class__
ctype = ContentType.objects.get_for_model(obj)
for name in dir(obj):
try:
attr = getattr(obj, name)
except AttributeError:
# this might be thrown if field is a FileField
continue
if hasattr(attr, 'related'):
related = attr.related
model = getattr(related, 'model', None)
if (model and issubclass(model, base_cls) and
model is not generic_cls):
# if model is generic one it would be returned anyway
if not model.objects.is_generic():
# make sure that content_object's content_type is same as
# the one of given obj
fk = model._meta.get_field_by_name('content_object')[0]
if ctype == ContentType.objects.get_for_model(fk.rel.to):
return model
return generic_cls
def get_user_obj_perms_model(obj):
"""
Returns model class that connects given ``obj`` and User class.
"""
from guardian.models import UserObjectPermissionBase
from guardian.models import UserObjectPermission
return get_obj_perms_model(obj, UserObjectPermissionBase, UserObjectPermission)
def get_group_obj_perms_model(obj):
"""
Returns model class that connects given ``obj`` and Group class.
"""
from guardian.models import GroupObjectPermissionBase
from guardian.models import GroupObjectPermission
return get_obj_perms_model(obj, GroupObjectPermissionBase, GroupObjectPermission)
| {'content_hash': 'a45bfddc102474ee5c5cb1069f38a27c', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 85, 'avg_line_length': 35.56382978723404, 'alnum_prop': 0.661681124738259, 'repo_name': 'mobstac/django-guardian', 'id': '0ec855aeb5867752d974ab94222f354ecdebfb7c', 'size': '6686', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'guardian/utils.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'CSS', 'bytes': '13944'}, {'name': 'JavaScript', 'bytes': '498'}, {'name': 'Python', 'bytes': '270252'}, {'name': 'Shell', 'bytes': '3553'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>interimResults property - SpeechRecognition class - polymer_app_layout library - Dart API</title>
<!-- required because all the links are pseudo-absolute -->
<base href="../..">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static-assets/prettify.css">
<link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
<link rel="stylesheet" href="static-assets/styles.css">
<meta name="description" content="API docs for the interimResults property from the SpeechRecognition class, for the Dart programming language.">
<link rel="icon" href="static-assets/favicon.png">
<!-- Do not remove placeholder -->
<!-- Header Placeholder -->
</head>
<body>
<div id="overlay-under-drawer"></div>
<header class="container-fluid" id="title">
<nav class="navbar navbar-fixed-top">
<div class="container">
<button id="sidenav-left-toggle" type="button"> </button>
<ol class="breadcrumbs gt-separated hidden-xs">
<li><a href="index.html">polymer_app_layout_template</a></li>
<li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li>
<li><a href="polymer_app_layout/SpeechRecognition-class.html">SpeechRecognition</a></li>
<li class="self-crumb">interimResults</li>
</ol>
<div class="self-name">interimResults</div>
</div>
</nav>
<div class="container masthead">
<ol class="breadcrumbs gt-separated visible-xs">
<li><a href="index.html">polymer_app_layout_template</a></li>
<li><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></li>
<li><a href="polymer_app_layout/SpeechRecognition-class.html">SpeechRecognition</a></li>
<li class="self-crumb">interimResults</li>
</ol>
<div class="title-description">
<h1 class="title">
<div class="kind">property</div> interimResults
</h1>
<!-- p class="subtitle">
</p -->
</div>
<ul class="subnav">
</ul>
</div>
</header>
<div class="container body">
<div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left">
<h5><a href="index.html">polymer_app_layout_template</a></h5>
<h5><a href="polymer_app_layout/polymer_app_layout-library.html">polymer_app_layout</a></h5>
<h5><a href="polymer_app_layout/SpeechRecognition-class.html">SpeechRecognition</a></h5>
<ol>
<li class="section-title"><a href="polymer_app_layout/SpeechRecognition-class.html#constants">Constants</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/audioEndEvent.html">audioEndEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/audioStartEvent.html">audioStartEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/endEvent.html">endEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/errorEvent.html">errorEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/noMatchEvent.html">noMatchEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/resultEvent.html">resultEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/soundEndEvent.html">soundEndEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/soundStartEvent.html">soundStartEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/speechEndEvent.html">speechEndEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/speechStartEvent.html">speechStartEvent</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/startEvent.html">startEvent</a></li>
<li class="section-title"><a href="polymer_app_layout/SpeechRecognition-class.html#static-properties">Static properties</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/supported.html">supported</a></li>
<li class="section-title"><a href="polymer_app_layout/SpeechRecognition-class.html#instance-properties">Properties</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/continuous.html">continuous</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/grammars.html">grammars</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/interimResults.html">interimResults</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/lang.html">lang</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/maxAlternatives.html">maxAlternatives</a>
</li>
<li>on
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onAudioEnd.html">onAudioEnd</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onAudioStart.html">onAudioStart</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onEnd.html">onEnd</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onError.html">onError</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onNoMatch.html">onNoMatch</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onResult.html">onResult</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onSoundEnd.html">onSoundEnd</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onSoundStart.html">onSoundStart</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onSpeechEnd.html">onSpeechEnd</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onSpeechStart.html">onSpeechStart</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/onStart.html">onStart</a>
</li>
<li class="section-title"><a href="polymer_app_layout/SpeechRecognition-class.html#constructors">Constructors</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/SpeechRecognition.html">SpeechRecognition</a></li>
<li class="section-title"><a href="polymer_app_layout/SpeechRecognition-class.html#methods">Methods</a></li>
<li><a href="polymer_app_layout/SpeechRecognition/abort.html">abort</a>
</li>
<li>addEventListener
</li>
<li>dispatchEvent
</li>
<li>removeEventListener
</li>
<li><a href="polymer_app_layout/SpeechRecognition/start.html">start</a>
</li>
<li><a href="polymer_app_layout/SpeechRecognition/stop.html">stop</a>
</li>
</ol>
</div><!--/.sidebar-offcanvas-->
<div class="col-xs-12 col-sm-9 col-md-6 main-content">
<section class="multi-line-signature">
<span class="returntype">bool</span>
<span class="name ">interimResults</span>
<div class="readable-writable">
read / write
</div>
</section>
<section class="desc markdown">
<p class="no-docs">Not documented.</p>
</section>
</div> <!-- /.main-content -->
</div> <!-- container -->
<footer>
<div class="container-fluid">
<div class="container">
<p class="text-center">
<span class="no-break">
polymer_app_layout_template 0.1.0 api docs
</span>
•
<span class="copyright no-break">
<a href="https://www.dartlang.org">
<img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16">
</a>
</span>
•
<span class="copyright no-break">
<a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a>
</span>
</p>
</div>
</div>
</footer>
<script src="static-assets/prettify.js"></script>
<script src="static-assets/script.js"></script>
<!-- Do not remove placeholder -->
<!-- Footer Placeholder -->
</body>
</html>
| {'content_hash': 'f5e632a5f066889d748de59b3cd9dd09', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 149, 'avg_line_length': 42.72631578947368, 'alnum_prop': 0.6415373244641537, 'repo_name': 'lejard-h/polymer_app_layout_templates', 'id': 'ee6363f86479849c6217b8f68cf5d7b7735d716a', 'size': '8118', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/api/polymer_app_layout/SpeechRecognition/interimResults.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '2381'}, {'name': 'Dart', 'bytes': '25778'}, {'name': 'HTML', 'bytes': '17680'}]} |
.class public Landroid/animation/RectEvaluator;
.super Ljava/lang/Object;
.source "RectEvaluator.java"
# interfaces
.implements Landroid/animation/TypeEvaluator;
# annotations
.annotation system Ldalvik/annotation/Signature;
value = {
"Ljava/lang/Object;",
"Landroid/animation/TypeEvaluator",
"<",
"Landroid/graphics/Rect;",
">;"
}
.end annotation
# instance fields
.field private mRect:Landroid/graphics/Rect;
# direct methods
.method public constructor <init>()V
.locals 0
.prologue
.line 37
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 38
return-void
.end method
.method public constructor <init>(Landroid/graphics/Rect;)V
.locals 0
.param p1, "reuseRect" # Landroid/graphics/Rect;
.prologue
.line 50
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 51
iput-object p1, p0, Landroid/animation/RectEvaluator;->mRect:Landroid/graphics/Rect;
.line 52
return-void
.end method
# virtual methods
.method public evaluate(FLandroid/graphics/Rect;Landroid/graphics/Rect;)Landroid/graphics/Rect;
.locals 7
.param p1, "fraction" # F
.param p2, "startValue" # Landroid/graphics/Rect;
.param p3, "endValue" # Landroid/graphics/Rect;
.prologue
.line 73
iget v4, p2, Landroid/graphics/Rect;->left:I
iget v5, p3, Landroid/graphics/Rect;->left:I
iget v6, p2, Landroid/graphics/Rect;->left:I
sub-int/2addr v5, v6
int-to-float v5, v5
mul-float/2addr v5, p1
float-to-int v5, v5
add-int v1, v4, v5
.line 74
.local v1, "left":I
iget v4, p2, Landroid/graphics/Rect;->top:I
iget v5, p3, Landroid/graphics/Rect;->top:I
iget v6, p2, Landroid/graphics/Rect;->top:I
sub-int/2addr v5, v6
int-to-float v5, v5
mul-float/2addr v5, p1
float-to-int v5, v5
add-int v3, v4, v5
.line 75
.local v3, "top":I
iget v4, p2, Landroid/graphics/Rect;->right:I
iget v5, p3, Landroid/graphics/Rect;->right:I
iget v6, p2, Landroid/graphics/Rect;->right:I
sub-int/2addr v5, v6
int-to-float v5, v5
mul-float/2addr v5, p1
float-to-int v5, v5
add-int v2, v4, v5
.line 76
.local v2, "right":I
iget v4, p2, Landroid/graphics/Rect;->bottom:I
iget v5, p3, Landroid/graphics/Rect;->bottom:I
iget v6, p2, Landroid/graphics/Rect;->bottom:I
sub-int/2addr v5, v6
int-to-float v5, v5
mul-float/2addr v5, p1
float-to-int v5, v5
add-int v0, v4, v5
.line 77
.local v0, "bottom":I
iget-object v4, p0, Landroid/animation/RectEvaluator;->mRect:Landroid/graphics/Rect;
if-nez v4, :cond_0
.line 78
new-instance v4, Landroid/graphics/Rect;
invoke-direct {v4, v1, v3, v2, v0}, Landroid/graphics/Rect;-><init>(IIII)V
.line 81
:goto_0
return-object v4
.line 80
:cond_0
iget-object v4, p0, Landroid/animation/RectEvaluator;->mRect:Landroid/graphics/Rect;
invoke-virtual {v4, v1, v3, v2, v0}, Landroid/graphics/Rect;->set(IIII)V
.line 81
iget-object v4, p0, Landroid/animation/RectEvaluator;->mRect:Landroid/graphics/Rect;
goto :goto_0
.end method
.method public bridge synthetic evaluate(FLjava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
.locals 1
.param p1, "x0" # F
.param p2, "x1" # Ljava/lang/Object;
.param p3, "x2" # Ljava/lang/Object;
.prologue
.line 23
check-cast p2, Landroid/graphics/Rect;
.end local p2 # "x1":Ljava/lang/Object;
check-cast p3, Landroid/graphics/Rect;
.end local p3 # "x2":Ljava/lang/Object;
invoke-virtual {p0, p1, p2, p3}, Landroid/animation/RectEvaluator;->evaluate(FLandroid/graphics/Rect;Landroid/graphics/Rect;)Landroid/graphics/Rect;
move-result-object v0
return-object v0
.end method
| {'content_hash': 'ea1b99ccc7bec75d73292876084d0edc', 'timestamp': '', 'source': 'github', 'line_count': 178, 'max_line_length': 152, 'avg_line_length': 21.707865168539325, 'alnum_prop': 0.6485507246376812, 'repo_name': 'hexiaoshuai/Flyme_device_ZTE_A1', 'id': '13ca925c1ec5505b347182dfa3d9bf39ab28e0e6', 'size': '3864', 'binary': False, 'copies': '2', 'ref': 'refs/heads/C880AV1.0.0B06', 'path': 'framework.jar.out/smali_classes2/android/animation/RectEvaluator.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '1500'}, {'name': 'HTML', 'bytes': '10195'}, {'name': 'Makefile', 'bytes': '11258'}, {'name': 'Python', 'bytes': '924'}, {'name': 'Shell', 'bytes': '2734'}, {'name': 'Smali', 'bytes': '234274633'}]} |
//CHECKSTYLE:FileLength:OFF
package org.pentaho.di.ui.trans.steps.script;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.TreeEditor;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceAdapter;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.mozilla.javascript.CompilerEnvirons;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContextFactory;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.JavaScriptException;
import org.mozilla.javascript.NodeTransformer;
import org.mozilla.javascript.Parser;
import org.mozilla.javascript.Script;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.ast.ScriptNode;
import org.mozilla.javascript.tools.ToolErrorReporter;
import org.pentaho.di.compatibility.Value;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Props;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.plugins.PluginRegistry;
import org.pentaho.di.core.plugins.StepPluginType;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMeta;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.BaseStepMeta;
import org.pentaho.di.trans.step.StepDialogInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.rowgenerator.RowGeneratorMeta;
import org.pentaho.di.trans.steps.script.ScriptAddedFunctions;
import org.pentaho.di.trans.steps.script.ScriptDummy;
import org.pentaho.di.trans.steps.script.ScriptMeta;
import org.pentaho.di.trans.steps.script.ScriptValuesScript;
import org.pentaho.di.ui.core.dialog.EnterTextDialog;
import org.pentaho.di.ui.core.dialog.ErrorDialog;
import org.pentaho.di.ui.core.dialog.PreviewRowsDialog;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.core.widget.ColumnInfo;
import org.pentaho.di.ui.core.widget.StyledTextComp;
import org.pentaho.di.ui.core.widget.TableView;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
public class ScriptDialog extends BaseStepDialog implements StepDialogInterface {
private static Class<?> PKG = ScriptMeta.class; // for i18n purposes, needed by Translator2!!
private static final String[] YES_NO_COMBO = new String[] {
BaseMessages.getString( PKG, "System.Combo.No" ), BaseMessages.getString( PKG, "System.Combo.Yes" ) };
private ModifyListener lsMod;
private SashForm wSash;
private FormData fdSash;
private Composite wTop, wBottom;
private FormData fdTop, fdBottom;
private Label wlScript;
private FormData fdlScript, fdScript;
private Label wSeparator;
private FormData fdSeparator;
private Label wlFields;
private TableView wFields;
private FormData fdlFields, fdFields;
private Label wlPosition;
private FormData fdlPosition;
private Text wlHelpLabel;
private Button wVars, wTest;
private Listener lsVars, lsTest;
// private Button wHelp;
private Label wlScriptFunctions;
private FormData fdlScriptFunctions;
private Tree wTree;
private TreeItem wTreeScriptsItem;
private TreeItem wTreeClassesitem;
private FormData fdlTree;
private Listener lsTree;
// private Listener lsHelp;
private FormData fdHelpLabel;
private Image imageActiveScript = null;
private Image imageInactiveScript = null;
private Image imageActiveStartScript = null;
private Image imageActiveEndScript = null;
private Image imageInputFields = null;
private Image imageOutputFields = null;
private Image imageArrowOrange = null;
private Image imageArrowGreen = null;
private Image imageUnderGreen = null;
private CTabFolder folder;
private Menu cMenu;
private Menu tMenu;
// Suport for Rename Tree
private TreeItem[] lastItem;
private TreeEditor editor;
private static final int DELETE_ITEM = 0;
private static final int ADD_ITEM = 1;
private static final int RENAME_ITEM = 2;
private static final int SET_ACTIVE_ITEM = 3;
private static final int ADD_COPY = 2;
private static final int ADD_BLANK = 1;
private static final int ADD_DEFAULT = 0;
private String strActiveScript;
private String strActiveStartScript;
private String strActiveEndScript;
private static String[] jsFunctionList = ScriptAddedFunctions.jsFunctionList;
public static final int SKIP_TRANSFORMATION = 1;
private static final int ABORT_TRANSFORMATION = -1;
private static final int ERROR_TRANSFORMATION = -2;
private static final int CONTINUE_TRANSFORMATION = 0;
private ScriptMeta input;
private ScriptHelp scVHelp;
private TreeItem iteminput;
private TreeItem itemoutput;
private static GUIResource guiresource = GUIResource.getInstance();
private TreeItem itemWaitFieldsIn, itemWaitFieldsOut;
private RowMetaInterface rowPrevStepFields;
private RowGeneratorMeta genMeta;
public ScriptDialog( Shell parent, Object in, TransMeta transMeta, String sname ) {
super( parent, (BaseStepMeta) in, transMeta, sname );
input = (ScriptMeta) in;
genMeta = null;
try {
// ImageLoader xl = new ImageLoader();
imageUnderGreen = guiresource.getImage( "ui/images/underGreen.png" );
imageArrowGreen = guiresource.getImage( "ui/images/arrowGreen.png" );
imageArrowOrange = guiresource.getImage( "ui/images/arrowOrange.png" );
imageInputFields = guiresource.getImage( "ui/images/inSmall.png" );
imageOutputFields = guiresource.getImage( "ui/images/outSmall.png" );
imageActiveScript = guiresource.getImage( "ui/images/faScript.png" );
imageInactiveScript = guiresource.getImage( "ui/images/fScript.png" );
imageActiveStartScript = guiresource.getImage( "ui/images/sScript.png" );
imageActiveEndScript = guiresource.getImage( "ui/images/eScript.png" );
} catch ( Exception e ) {
imageActiveScript = guiresource.getImageEmpty16x16();
imageInactiveScript = guiresource.getImageEmpty16x16();
imageActiveStartScript = guiresource.getImageEmpty16x16();
imageActiveEndScript = guiresource.getImageEmpty16x16();
imageInputFields = guiresource.getImageEmpty16x16();
imageOutputFields = guiresource.getImageEmpty16x16();
imageArrowOrange = guiresource.getImageEmpty16x16();
imageArrowGreen = guiresource.getImageEmpty16x16();
imageUnderGreen = guiresource.getImageEmpty16x16();
}
try {
scVHelp = new ScriptHelp( "jsFunctionHelp.xml" );
} catch ( Exception e ) {
new ErrorDialog(
shell, "Unexpected error", "There was an unexpected error reading the javascript functions help", e );
}
}
public String open() {
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell( parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MAX | SWT.MIN );
props.setLook( shell );
setShellImage( shell, input );
lsMod = new ModifyListener() {
public void modifyText( ModifyEvent e ) {
input.setChanged();
}
};
changed = input.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout( formLayout );
shell.setText( BaseMessages.getString( PKG, "ScriptDialog.Shell.Title" ) );
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Filename line
wlStepname = new Label( shell, SWT.RIGHT );
wlStepname.setText( BaseMessages.getString( PKG, "ScriptDialog.Stepname.Label" ) );
props.setLook( wlStepname );
fdlStepname = new FormData();
fdlStepname.left = new FormAttachment( 0, 0 );
fdlStepname.right = new FormAttachment( middle, -margin );
fdlStepname.top = new FormAttachment( 0, margin );
wlStepname.setLayoutData( fdlStepname );
wStepname = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
wStepname.setText( stepname );
props.setLook( wStepname );
wStepname.addModifyListener( lsMod );
fdStepname = new FormData();
fdStepname.left = new FormAttachment( middle, 0 );
fdStepname.top = new FormAttachment( 0, margin );
fdStepname.right = new FormAttachment( 100, 0 );
wStepname.setLayoutData( fdStepname );
wSash = new SashForm( shell, SWT.VERTICAL );
// Top sash form
//
wTop = new Composite( wSash, SWT.NONE );
props.setLook( wTop );
FormLayout topLayout = new FormLayout();
topLayout.marginWidth = Const.FORM_MARGIN;
topLayout.marginHeight = Const.FORM_MARGIN;
wTop.setLayout( topLayout );
// Script line
wlScriptFunctions = new Label( wTop, SWT.NONE );
wlScriptFunctions.setText( BaseMessages.getString( PKG, "ScriptDialog.JavascriptFunctions.Label" ) );
props.setLook( wlScriptFunctions );
fdlScriptFunctions = new FormData();
fdlScriptFunctions.left = new FormAttachment( 0, 0 );
fdlScriptFunctions.top = new FormAttachment( 0, 0 );
wlScriptFunctions.setLayoutData( fdlScriptFunctions );
// Tree View Test
wTree = new Tree( wTop, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL );
props.setLook( wTree );
fdlTree = new FormData();
fdlTree.left = new FormAttachment( 0, 0 );
fdlTree.top = new FormAttachment( wlScriptFunctions, margin );
fdlTree.right = new FormAttachment( 20, 0 );
fdlTree.bottom = new FormAttachment( 100, -margin );
wTree.setLayoutData( fdlTree );
// Script line
wlScript = new Label( wTop, SWT.NONE );
wlScript.setText( BaseMessages.getString( PKG, "ScriptDialog.Javascript.Label" ) );
props.setLook( wlScript );
fdlScript = new FormData();
fdlScript.left = new FormAttachment( wTree, margin );
fdlScript.top = new FormAttachment( 0, 0 );
wlScript.setLayoutData( fdlScript );
folder = new CTabFolder( wTop, SWT.BORDER | SWT.RESIZE );
folder.setSimple( false );
folder.setUnselectedImageVisible( true );
folder.setUnselectedCloseVisible( true );
fdScript = new FormData();
fdScript.left = new FormAttachment( wTree, margin );
fdScript.top = new FormAttachment( wlScript, margin );
fdScript.right = new FormAttachment( 100, -5 );
fdScript.bottom = new FormAttachment( 100, -50 );
folder.setLayoutData( fdScript );
wlPosition = new Label( wTop, SWT.NONE );
wlPosition.setText( BaseMessages.getString( PKG, "ScriptDialog.Position.Label" ) );
props.setLook( wlPosition );
fdlPosition = new FormData();
fdlPosition.left = new FormAttachment( wTree, margin );
fdlPosition.right = new FormAttachment( 30, 0 );
fdlPosition.top = new FormAttachment( folder, margin );
wlPosition.setLayoutData( fdlPosition );
wlHelpLabel = new Text( wTop, SWT.V_SCROLL | SWT.LEFT );
wlHelpLabel.setEditable( false );
wlHelpLabel.setText( "Hallo" );
props.setLook( wlHelpLabel );
fdHelpLabel = new FormData();
fdHelpLabel.left = new FormAttachment( wlPosition, margin );
fdHelpLabel.top = new FormAttachment( folder, margin );
fdHelpLabel.right = new FormAttachment( 100, -5 );
fdHelpLabel.bottom = new FormAttachment( 100, 0 );
wlHelpLabel.setLayoutData( fdHelpLabel );
wlHelpLabel.setVisible( false );
fdTop = new FormData();
fdTop.left = new FormAttachment( 0, 0 );
fdTop.top = new FormAttachment( 0, 0 );
fdTop.right = new FormAttachment( 100, 0 );
fdTop.bottom = new FormAttachment( 100, 0 );
wTop.setLayoutData( fdTop );
wBottom = new Composite( wSash, SWT.NONE );
props.setLook( wBottom );
FormLayout bottomLayout = new FormLayout();
bottomLayout.marginWidth = Const.FORM_MARGIN;
bottomLayout.marginHeight = Const.FORM_MARGIN;
wBottom.setLayout( bottomLayout );
wSeparator = new Label( wBottom, SWT.SEPARATOR | SWT.HORIZONTAL );
fdSeparator = new FormData();
fdSeparator.left = new FormAttachment( 0, 0 );
fdSeparator.right = new FormAttachment( 100, 0 );
fdSeparator.top = new FormAttachment( 0, -margin + 2 );
wSeparator.setLayoutData( fdSeparator );
wlFields = new Label( wBottom, SWT.NONE );
wlFields.setText( BaseMessages.getString( PKG, "ScriptDialog.Fields.Label" ) );
props.setLook( wlFields );
fdlFields = new FormData();
fdlFields.left = new FormAttachment( 0, 0 );
fdlFields.top = new FormAttachment( wSeparator, 0 );
wlFields.setLayoutData( fdlFields );
final int FieldsRows = input.getFieldname().length;
ColumnInfo[] colinf =
new ColumnInfo[] {
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.Filename" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.RenameTo" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.Type" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
ValueMeta.getTypes() ),
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.Length" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.Precision" ), ColumnInfo.COLUMN_TYPE_TEXT,
false ),
new ColumnInfo(
BaseMessages.getString( PKG, "ScriptDialog.ColumnInfo.Replace" ), ColumnInfo.COLUMN_TYPE_CCOMBO,
YES_NO_COMBO ), };
wFields =
new TableView(
transMeta, wBottom, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI, colinf, FieldsRows, lsMod, props );
fdFields = new FormData();
fdFields.left = new FormAttachment( 0, 0 );
fdFields.top = new FormAttachment( wlFields, margin );
fdFields.right = new FormAttachment( 100, 0 );
fdFields.bottom = new FormAttachment( 100, 0 );
wFields.setLayoutData( fdFields );
fdBottom = new FormData();
fdBottom.left = new FormAttachment( 0, 0 );
fdBottom.top = new FormAttachment( 0, 0 );
fdBottom.right = new FormAttachment( 100, 0 );
fdBottom.bottom = new FormAttachment( 100, 0 );
wBottom.setLayoutData( fdBottom );
fdSash = new FormData();
fdSash.left = new FormAttachment( 0, 0 );
fdSash.top = new FormAttachment( wStepname, 0 );
fdSash.right = new FormAttachment( 100, 0 );
fdSash.bottom = new FormAttachment( 100, -50 );
wSash.setLayoutData( fdSash );
wSash.setWeights( new int[] { 75, 25 } );
wOK = new Button( shell, SWT.PUSH );
wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
wVars = new Button( shell, SWT.PUSH );
wVars.setText( BaseMessages.getString( PKG, "ScriptDialog.GetVariables.Button" ) );
wTest = new Button( shell, SWT.PUSH );
wTest.setText( BaseMessages.getString( PKG, "ScriptDialog.TestScript.Button" ) );
wCancel = new Button( shell, SWT.PUSH );
wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );
setButtonPositions( new Button[] { wOK, wCancel, wVars, wTest }, margin, null );
// Add listeners
lsCancel = new Listener() {
public void handleEvent( Event e ) {
cancel();
}
};
// lsGet = new Listener() { public void handleEvent(Event e) { get(); } };
lsTest = new Listener() {
public void handleEvent( Event e ) {
newTest();
}
};
lsVars = new Listener() {
public void handleEvent( Event e ) {
test( true, true );
}
};
lsOK = new Listener() {
public void handleEvent( Event e ) {
ok();
}
};
lsTree = new Listener() {
public void handleEvent( Event e ) {
treeDblClick( e );
}
};
// lsHelp = new Listener(){public void handleEvent(Event e){ wlHelpLabel.setVisible(true); }};
wCancel.addListener( SWT.Selection, lsCancel );
// wGet.addListener (SWT.Selection, lsGet );
wTest.addListener( SWT.Selection, lsTest );
wVars.addListener( SWT.Selection, lsVars );
wOK.addListener( SWT.Selection, lsOK );
wTree.addListener( SWT.MouseDoubleClick, lsTree );
lsDef = new SelectionAdapter() {
public void widgetDefaultSelected( SelectionEvent e ) {
ok();
}
};
wStepname.addSelectionListener( lsDef );
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener( new ShellAdapter() {
public void shellClosed( ShellEvent e ) {
if ( !cancel() ) {
e.doit = false;
}
}
} );
folder.addCTabFolder2Listener( new CTabFolder2Adapter() {
public void close( CTabFolderEvent event ) {
CTabItem cItem = (CTabItem) event.item;
event.doit = false;
if ( cItem != null && folder.getItemCount() > 1 ) {
MessageBox messageBox = new MessageBox( shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES );
messageBox.setText( BaseMessages.getString( PKG, "ScriptDialog.DeleteItem.Label" ) );
messageBox.setMessage( BaseMessages.getString( PKG, "ScriptDialog.ConfirmDeleteItem.Label", cItem
.getText() ) );
switch ( messageBox.open() ) {
case SWT.YES:
modifyScriptTree( cItem, DELETE_ITEM );
event.doit = true;
break;
default:
break;
}
}
}
} );
cMenu = new Menu( shell, SWT.POP_UP );
buildingFolderMenu();
tMenu = new Menu( shell, SWT.POP_UP );
buildingTreeMenu();
// Adding the Default Transform Scripts Item to the Tree
wTreeScriptsItem = new TreeItem( wTree, SWT.NULL );
wTreeScriptsItem.setImage( guiresource.getImageBol() );
wTreeScriptsItem.setText( BaseMessages.getString( PKG, "ScriptDialog.TransformScript.Label" ) );
// Set the shell size, based upon previous time...
setSize();
getData();
// Adding the Rest (Functions, InputItems, etc.) to the Tree
buildSpecialFunctionsTree();
// Input Fields
iteminput = new TreeItem( wTree, SWT.NULL );
iteminput.setImage( imageInputFields );
iteminput.setText( BaseMessages.getString( PKG, "ScriptDialog.InputFields.Label" ) );
// Output Fields
itemoutput = new TreeItem( wTree, SWT.NULL );
itemoutput.setImage( imageOutputFields );
itemoutput.setText( BaseMessages.getString( PKG, "ScriptDialog.OutputFields.Label" ) );
// Display waiting message for input
itemWaitFieldsIn = new TreeItem( iteminput, SWT.NULL );
itemWaitFieldsIn.setText( BaseMessages.getString( PKG, "ScriptDialog.GettingFields.Label" ) );
itemWaitFieldsIn.setForeground( guiresource.getColorDirectory() );
iteminput.setExpanded( true );
// Display waiting message for output
itemWaitFieldsOut = new TreeItem( itemoutput, SWT.NULL );
itemWaitFieldsOut.setText( BaseMessages.getString( PKG, "ScriptDialog.GettingFields.Label" ) );
itemWaitFieldsOut.setForeground( guiresource.getColorDirectory() );
itemoutput.setExpanded( true );
//
// Search the fields in the background
//
final Runnable runnable = new Runnable() {
public void run() {
StepMeta stepMeta = transMeta.findStep( stepname );
if ( stepMeta != null ) {
try {
rowPrevStepFields = transMeta.getPrevStepFields( stepMeta );
if ( rowPrevStepFields != null ) {
setInputOutputFields();
} else {
// Can not get fields...end of wait message
iteminput.removeAll();
itemoutput.removeAll();
}
} catch ( KettleException e ) {
logError( BaseMessages.getString( PKG, "System.Dialog.GetFieldsFailed.Message" ) );
}
}
}
};
new Thread( runnable ).start();
// rebuildInputFieldsTree();
// buildOutputFieldsTree();
buildAddClassesListTree();
addRenameTowTreeScriptItems();
input.setChanged( changed );
// Create the drag source on the tree
DragSource ds = new DragSource( wTree, DND.DROP_MOVE );
ds.setTransfer( new Transfer[] { TextTransfer.getInstance() } );
ds.addDragListener( new DragSourceAdapter() {
public void dragStart( DragSourceEvent event ) {
TreeItem item = wTree.getSelection()[0];
// Qualifikation where the Drag Request Comes from
if ( item != null && item.getParentItem() != null ) {
if ( item.getParentItem().equals( wTreeScriptsItem ) ) {
event.doit = false;
} else if ( !item.getData().equals( "Function" ) ) {
String strInsert = (String) item.getData();
if ( strInsert.equals( "jsFunction" ) ) {
event.doit = true;
} else {
event.doit = false;
}
} else {
event.doit = false;
}
} else {
event.doit = false;
}
}
public void dragSetData( DragSourceEvent event ) {
// Set the data to be the first selected item's text
event.data = wTree.getSelection()[0].getText();
}
} );
shell.open();
while ( !shell.isDisposed() ) {
if ( !display.readAndDispatch() ) {
display.sleep();
}
}
return stepname;
}
private void setActiveCtab( String strName ) {
if ( strName.length() == 0 ) {
folder.setSelection( 0 );
} else {
folder.setSelection( getCTabPosition( strName ) );
}
}
private void addCtab( String cScriptName, String strScript, int iType ) {
CTabItem item = new CTabItem( folder, SWT.CLOSE );
switch ( iType ) {
case ADD_DEFAULT:
item.setText( cScriptName );
break;
default:
item.setText( getNextName( cScriptName ) );
break;
}
StyledTextComp wScript =
new StyledTextComp( transMeta, item.getParent(), SWT.MULTI | SWT.LEFT | SWT.H_SCROLL | SWT.V_SCROLL, item
.getText(), false );
if ( ( strScript != null ) && strScript.length() > 0 ) {
wScript.setText( strScript );
} else {
wScript.setText( BaseMessages.getString( PKG, "ScriptDialog.ScriptHere.Label" ) + Const.CR + Const.CR );
}
item.setImage( imageInactiveScript );
props.setLook( wScript, Props.WIDGET_STYLE_FIXED );
wScript.addKeyListener( new KeyAdapter() {
public void keyPressed( KeyEvent e ) {
setPosition();
}
public void keyReleased( KeyEvent e ) {
setPosition();
}
} );
wScript.addFocusListener( new FocusAdapter() {
public void focusGained( FocusEvent e ) {
setPosition();
}
public void focusLost( FocusEvent e ) {
setPosition();
}
} );
wScript.addMouseListener( new MouseAdapter() {
public void mouseDoubleClick( MouseEvent e ) {
setPosition();
}
public void mouseDown( MouseEvent e ) {
setPosition();
}
public void mouseUp( MouseEvent e ) {
setPosition();
}
} );
wScript.addModifyListener( lsMod );
// Text Higlighting
wScript.addLineStyleListener( new ScriptHighlight( ScriptAddedFunctions.jsFunctionList ) );
item.setControl( wScript );
// Adding new Item to Tree
modifyScriptTree( item, ADD_ITEM );
}
private void modifyScriptTree( CTabItem ctabitem, int iModType ) {
switch ( iModType ) {
case DELETE_ITEM:
TreeItem dItem = getTreeItemByName( ctabitem.getText() );
if ( dItem != null ) {
dItem.dispose();
input.setChanged();
}
break;
case ADD_ITEM:
TreeItem item = new TreeItem( wTreeScriptsItem, SWT.NULL );
item.setImage( imageActiveScript );
item.setText( ctabitem.getText() );
input.setChanged();
break;
case RENAME_ITEM:
input.setChanged();
break;
case SET_ACTIVE_ITEM:
input.setChanged();
break;
default:
break;
}
}
private TreeItem getTreeItemByName( String strTabName ) {
TreeItem[] tItems = wTreeScriptsItem.getItems();
for ( int i = 0; i < tItems.length; i++ ) {
if ( tItems[i].getText().equals( strTabName ) ) {
return tItems[i];
}
}
return null;
}
private int getCTabPosition( String strTabName ) {
CTabItem[] cItems = folder.getItems();
for ( int i = 0; i < cItems.length; i++ ) {
if ( cItems[i].getText().equals( strTabName ) ) {
return i;
}
}
return -1;
}
private CTabItem getCTabItemByName( String strTabName ) {
CTabItem[] cItems = folder.getItems();
for ( int i = 0; i < cItems.length; i++ ) {
if ( cItems[i].getText().equals( strTabName ) ) {
return cItems[i];
}
}
return null;
}
private void modifyCTabItem( TreeItem tItem, int iModType, String strOption ) {
switch ( iModType ) {
case DELETE_ITEM:
CTabItem dItem = folder.getItem( getCTabPosition( tItem.getText() ) );
if ( dItem != null ) {
dItem.dispose();
input.setChanged();
}
break;
case RENAME_ITEM:
CTabItem rItem = folder.getItem( getCTabPosition( tItem.getText() ) );
if ( rItem != null ) {
rItem.setText( strOption );
input.setChanged();
if ( rItem.getImage().equals( imageActiveScript ) ) {
strActiveScript = strOption;
} else if ( rItem.getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = strOption;
} else if ( rItem.getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = strOption;
}
}
break;
case SET_ACTIVE_ITEM:
CTabItem aItem = folder.getItem( getCTabPosition( tItem.getText() ) );
if ( aItem != null ) {
input.setChanged();
strActiveScript = tItem.getText();
for ( int i = 0; i < folder.getItemCount(); i++ ) {
if ( folder.getItem( i ).equals( aItem ) ) {
aItem.setImage( imageActiveScript );
} else {
folder.getItem( i ).setImage( imageInactiveScript );
}
}
}
break;
default:
break;
}
}
private StyledTextComp getStyledTextComp() {
CTabItem item = folder.getSelection();
if ( item.getControl().isDisposed() ) {
return null;
} else {
return (StyledTextComp) item.getControl();
}
}
private StyledTextComp getStyledTextComp( CTabItem item ) {
return (StyledTextComp) item.getControl();
}
/*
* private void setStyledTextComp(String strText){ CTabItem item = folder.getSelection();
* ((StyledTextComp)item.getControl()).setText(strText); }
*
* private void setStyledTextComp(String strText, CTabItem item){
* ((StyledTextComp)item.getControl()).setText(strText); }
*/
private String getNextName( String strActualName ) {
String strRC = "";
if ( strActualName.length() == 0 ) {
strActualName = "Item";
}
int i = 0;
strRC = strActualName + "_" + i;
while ( getCTabItemByName( strRC ) != null ) {
i++;
strRC = strActualName + "_" + i;
}
return strRC;
}
public void setPosition() {
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
int linenr = wScript.getLineAtOffset( wScript.getCaretOffset() ) + 1;
int posnr = wScript.getCaretOffset();
// Go back from position to last CR: how many positions?
int colnr = 0;
while ( posnr > 0 && scr.charAt( posnr - 1 ) != '\n' && scr.charAt( posnr - 1 ) != '\r' ) {
posnr--;
colnr++;
}
wlPosition.setText( BaseMessages.getString( PKG, "ScriptDialog.Position.Label2" ) + linenr + ", " + colnr );
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData() {
for ( int i = 0; i < input.getFieldname().length; i++ ) {
if ( input.getFieldname()[i] != null && input.getFieldname()[i].length() > 0 ) {
TableItem item = wFields.table.getItem( i );
item.setText( 1, input.getFieldname()[i] );
if ( input.getRename()[i] != null && !input.getFieldname()[i].equals( input.getRename()[i] ) ) {
item.setText( 2, input.getRename()[i] );
}
item.setText( 3, ValueMeta.getTypeDesc( input.getType()[i] ) );
if ( input.getLength()[i] >= 0 ) {
item.setText( 4, "" + input.getLength()[i] );
}
if ( input.getPrecision()[i] >= 0 ) {
item.setText( 5, "" + input.getPrecision()[i] );
}
item.setText( 6, input.getReplace()[i] ? YES_NO_COMBO[1] : YES_NO_COMBO[0] );
}
}
org.pentaho.di.trans.steps.script.ScriptValuesScript[] jsScripts = input.getJSScripts();
if ( jsScripts.length > 0 ) {
for ( int i = 0; i < jsScripts.length; i++ ) {
if ( jsScripts[i].isTransformScript() ) {
strActiveScript = jsScripts[i].getScriptName();
} else if ( jsScripts[i].isStartScript() ) {
strActiveStartScript = jsScripts[i].getScriptName();
} else if ( jsScripts[i].isEndScript() ) {
strActiveEndScript = jsScripts[i].getScriptName();
}
addCtab( jsScripts[i].getScriptName(), jsScripts[i].getScript(), ADD_DEFAULT );
}
} else {
addCtab( "", "", ADD_DEFAULT );
}
setActiveCtab( strActiveScript );
refresh();
wFields.setRowNums();
wFields.optWidth( true );
wStepname.selectAll();
wStepname.setFocus();
}
// Setting default active Script
private void refresh() {
// CTabItem item = getCTabItemByName(strActiveScript);
for ( int i = 0; i < folder.getItemCount(); i++ ) {
CTabItem item = folder.getItem( i );
if ( item.getText().equals( strActiveScript ) ) {
item.setImage( imageActiveScript );
} else if ( item.getText().equals( strActiveStartScript ) ) {
item.setImage( imageActiveStartScript );
} else if ( item.getText().equals( strActiveEndScript ) ) {
item.setImage( imageActiveEndScript );
} else {
item.setImage( imageInactiveScript );
}
}
// modifyScriptTree(null, SET_ACTIVE_ITEM);
}
private void refreshScripts() {
CTabItem[] cTabs = folder.getItems();
for ( int i = 0; i < cTabs.length; i++ ) {
if ( cTabs[i].getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = cTabs[i].getText();
} else if ( cTabs[i].getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = cTabs[i].getText();
}
}
}
private boolean cancel() {
if ( input.hasChanged() ) {
MessageBox box = new MessageBox( shell, SWT.YES | SWT.NO | SWT.APPLICATION_MODAL );
box.setText( BaseMessages.getString( PKG, "ScriptDialog.WarningDialogChanged.Title" ) );
box.setMessage( BaseMessages.getString( PKG, "ScriptDialog.WarningDialogChanged.Message", Const.CR ) );
int answer = box.open();
if ( answer == SWT.NO ) {
return false;
}
}
stepname = null;
input.setChanged( changed );
dispose();
return true;
}
private void getInfo( ScriptMeta meta ) {
int nrfields = wFields.nrNonEmpty();
meta.allocate( nrfields );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < nrfields; i++ ) {
TableItem item = wFields.getNonEmpty( i );
meta.getFieldname()[i] = item.getText( 1 );
meta.getRename()[i] = item.getText( 2 );
if ( meta.getRename()[i] == null
|| meta.getRename()[i].length() == 0 || meta.getRename()[i].equalsIgnoreCase( meta.getFieldname()[i] ) ) {
meta.getRename()[i] = meta.getFieldname()[i];
}
meta.getType()[i] = ValueMeta.getType( item.getText( 3 ) );
String slen = item.getText( 4 );
String sprc = item.getText( 5 );
meta.getLength()[i] = Const.toInt( slen, -1 );
meta.getPrecision()[i] = Const.toInt( sprc, -1 );
meta.getReplace()[i] = YES_NO_COMBO[1].equalsIgnoreCase( item.getText( 6 ) );
}
// input.setActiveJSScript(strActiveScript);
CTabItem[] cTabs = folder.getItems();
if ( cTabs.length > 0 ) {
ScriptValuesScript[] jsScripts = new ScriptValuesScript[cTabs.length];
for ( int i = 0; i < cTabs.length; i++ ) {
ScriptValuesScript jsScript =
new ScriptValuesScript( ScriptValuesScript.NORMAL_SCRIPT, cTabs[i].getText(), getStyledTextComp(
cTabs[i] ).getText() );
if ( cTabs[i].getImage().equals( imageActiveScript ) ) {
jsScript.setScriptType( ScriptValuesScript.TRANSFORM_SCRIPT );
} else if ( cTabs[i].getImage().equals( imageActiveStartScript ) ) {
jsScript.setScriptType( ScriptValuesScript.START_SCRIPT );
} else if ( cTabs[i].getImage().equals( imageActiveEndScript ) ) {
jsScript.setScriptType( ScriptValuesScript.END_SCRIPT );
}
jsScripts[i] = jsScript;
}
meta.setJSScripts( jsScripts );
}
}
private void ok() {
if ( Const.isEmpty( wStepname.getText() ) ) {
return;
}
stepname = wStepname.getText(); // return value
boolean bInputOK = false;
// Check if Active Script has set, otherwise Ask
if ( getCTabItemByName( strActiveScript ) == null ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.CANCEL | SWT.ICON_ERROR );
mb.setMessage( BaseMessages.getString( PKG, "ScriptDialog.NoActiveScriptSet" ) );
mb.setText( BaseMessages.getString( PKG, "ScriptDialog.ERROR.Label" ) );
switch ( mb.open() ) {
case SWT.OK:
strActiveScript = folder.getItem( 0 ).getText();
refresh();
bInputOK = true;
break;
case SWT.CANCEL:
bInputOK = false;
break;
default:
break;
}
} else {
bInputOK = true;
}
if ( bInputOK ) {
getInfo( input );
dispose();
}
}
public boolean test() {
return test( false, false );
}
private boolean newTest() {
PluginRegistry registry = PluginRegistry.getInstance();
String scriptStepName = wStepname.getText();
try {
// What fields are coming into the step?
//
RowMetaInterface rowMeta = transMeta.getPrevStepFields( stepname ).clone();
if ( rowMeta != null ) {
// Create a new RowGenerator step to generate rows for the test data...
// Only create a new instance the first time to help the user.
// Otherwise he/she has to key in the same test data all the time
//
if ( genMeta == null ) {
genMeta = new RowGeneratorMeta();
genMeta.setRowLimit( "10" );
genMeta.allocate( rowMeta.size() );
//CHECKSTYLE:Indentation:OFF
for ( int i = 0; i < rowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta( i );
if ( valueMeta.isStorageBinaryString() ) {
valueMeta.setStorageType( ValueMetaInterface.STORAGE_TYPE_NORMAL );
}
genMeta.getFieldName()[i] = valueMeta.getName();
genMeta.getFieldType()[i] = valueMeta.getTypeDesc();
genMeta.getFieldLength()[i] = valueMeta.getLength();
genMeta.getFieldPrecision()[i] = valueMeta.getPrecision();
genMeta.getCurrency()[i] = valueMeta.getCurrencySymbol();
genMeta.getDecimal()[i] = valueMeta.getDecimalSymbol();
genMeta.getGroup()[i] = valueMeta.getGroupingSymbol();
String string = null;
switch ( valueMeta.getType() ) {
case ValueMetaInterface.TYPE_DATE:
genMeta.getFieldFormat()[i] = "yyyy/MM/dd HH:mm:ss";
valueMeta.setConversionMask( genMeta.getFieldFormat()[i] );
string = valueMeta.getString( new Date() );
break;
case ValueMetaInterface.TYPE_STRING:
string = "test value test value";
break;
case ValueMetaInterface.TYPE_INTEGER:
genMeta.getFieldFormat()[i] = "#";
valueMeta.setConversionMask( genMeta.getFieldFormat()[i] );
string = valueMeta.getString( Long.valueOf( 0L ) );
break;
case ValueMetaInterface.TYPE_NUMBER:
genMeta.getFieldFormat()[i] = "#.#";
valueMeta.setConversionMask( genMeta.getFieldFormat()[i] );
string = valueMeta.getString( Double.valueOf( 0.0D ) );
break;
case ValueMetaInterface.TYPE_BIGNUMBER:
genMeta.getFieldFormat()[i] = "#.#";
valueMeta.setConversionMask( genMeta.getFieldFormat()[i] );
string = valueMeta.getString( BigDecimal.ZERO );
break;
case ValueMetaInterface.TYPE_BOOLEAN:
string = valueMeta.getString( Boolean.TRUE );
break;
case ValueMetaInterface.TYPE_BINARY:
string = valueMeta.getString( new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, } );
break;
default:
break;
}
genMeta.getValue()[i] = string;
}
}
StepMeta genStep =
new StepMeta( registry.getPluginId( StepPluginType.class, genMeta ), "## TEST DATA ##", genMeta );
genStep.setLocation( 50, 50 );
// Now create a JavaScript step with the information in this dialog
//
ScriptMeta scriptMeta = new ScriptMeta();
getInfo( scriptMeta );
StepMeta scriptStep =
new StepMeta( registry.getPluginId( StepPluginType.class, scriptMeta ), Const.NVL(
scriptStepName, "## SCRIPT ##" ), scriptMeta );
scriptStepName = scriptStep.getName();
scriptStep.setLocation( 150, 50 );
// Create a hop between both steps...
//
TransHopMeta hop = new TransHopMeta( genStep, scriptStep );
// Generate a new test transformation...
//
TransMeta transMeta = new TransMeta();
transMeta.setName( wStepname.getText() + " - PREVIEW" );
transMeta.addStep( genStep );
transMeta.addStep( scriptStep );
transMeta.addTransHop( hop );
// OK, now we ask the user to edit this dialog...
//
if ( Spoon.getInstance().editStep( transMeta, genStep ) != null ) {
// Now run this transformation and grab the results...
//
TransPreviewProgressDialog progressDialog =
new TransPreviewProgressDialog(
shell, transMeta, new String[] { scriptStepName, }, new int[] { Const.toInt( genMeta
.getRowLimit(), 10 ), } );
progressDialog.open();
Trans trans = progressDialog.getTrans();
String loggingText = progressDialog.getLoggingText();
if ( !progressDialog.isCancelled() ) {
if ( trans.getResult() != null && trans.getResult().getNrErrors() > 0 ) {
EnterTextDialog etd =
new EnterTextDialog(
shell, BaseMessages.getString( PKG, "System.Dialog.PreviewError.Title" ), BaseMessages
.getString( PKG, "System.Dialog.PreviewError.Message" ), loggingText, true );
etd.setReadOnly();
etd.open();
}
}
RowMetaInterface previewRowsMeta = progressDialog.getPreviewRowsMeta( wStepname.getText() );
List<Object[]> previewRows = progressDialog.getPreviewRows( wStepname.getText() );
if ( previewRowsMeta != null && previewRows != null && previewRows.size() > 0 ) {
PreviewRowsDialog prd =
new PreviewRowsDialog(
shell, transMeta, SWT.NONE, wStepname.getText(), previewRowsMeta, previewRows, loggingText );
prd.open();
}
}
return true;
} else {
throw new KettleException( BaseMessages.getString( PKG, "ScriptDialog.Exception.CouldNotGetFields" ) );
}
} catch ( Exception e ) {
new ErrorDialog( shell, BaseMessages.getString( PKG, "ScriptDialog.TestFailed.DialogTitle" ), BaseMessages
.getString( PKG, "ScriptDialog.TestFailed.DialogMessage" ), e );
return false;
}
}
private boolean test( boolean getvars, boolean popup ) {
boolean retval = true;
StyledTextComp wScript = getStyledTextComp();
String scr = wScript.getText();
KettleException testException = null;
Context jscx;
Scriptable jsscope;
// Script jsscript;
// Making Refresh to get Active Script State
refreshScripts();
jscx = ContextFactory.getGlobal().enterContext();
jscx.setOptimizationLevel( -1 );
jsscope = jscx.initStandardObjects( null, false );
// Adding the existing Scripts to the Context
for ( int i = 0; i < folder.getItemCount(); i++ ) {
StyledTextComp sItem = getStyledTextComp( folder.getItem( i ) );
Scriptable jsR = Context.toObject( sItem.getText(), jsscope );
jsscope.put( folder.getItem( i ).getText(), jsscope, jsR );
}
// Adding the Name of the Transformation to the Context
jsscope.put( "_TransformationName_", jsscope, this.stepname );
try {
RowMetaInterface rowMeta = transMeta.getPrevStepFields( stepname );
if ( rowMeta != null ) {
ScriptDummy dummyStep = new ScriptDummy( rowMeta, transMeta.getStepFields( stepname ) );
Scriptable jsvalue = Context.toObject( dummyStep, jsscope );
jsscope.put( "_step_", jsscope, jsvalue );
// Modification for Additional Script parsing
try {
if ( input.getAddClasses() != null ) {
for ( int i = 0; i < input.getAddClasses().length; i++ ) {
Object jsOut = Context.javaToJS( input.getAddClasses()[i].getAddObject(), jsscope );
ScriptableObject.putProperty( jsscope, input.getAddClasses()[i].getJSName(), jsOut );
}
}
} catch ( Exception e ) {
testException =
new KettleException( BaseMessages.getString( PKG, "ScriptDialog.CouldNotAddToContext", e.toString() ) );
retval = false;
}
// Adding some default JavaScriptFunctions to the System
try {
Context.javaToJS( ScriptAddedFunctions.class, jsscope );
( (ScriptableObject) jsscope ).defineFunctionProperties(
jsFunctionList, ScriptAddedFunctions.class, ScriptableObject.DONTENUM );
} catch ( Exception ex ) {
testException =
new KettleException( BaseMessages.getString( PKG, "ScriptDialog.CouldNotAddDefaultFunctions", ex
.toString() ) );
retval = false;
}
// Adding some Constants to the JavaScript
try {
jsscope.put( "SKIP_TRANSFORMATION", jsscope, Integer.valueOf( SKIP_TRANSFORMATION ) );
jsscope.put( "ABORT_TRANSFORMATION", jsscope, Integer.valueOf( ABORT_TRANSFORMATION ) );
jsscope.put( "ERROR_TRANSFORMATION", jsscope, Integer.valueOf( ERROR_TRANSFORMATION ) );
jsscope.put( "CONTINUE_TRANSFORMATION", jsscope, Integer.valueOf( CONTINUE_TRANSFORMATION ) );
} catch ( Exception ex ) {
testException =
new KettleException( BaseMessages.getString(
PKG, "ScriptDialog.CouldNotAddTransformationConstants", ex.toString() ) );
retval = false;
}
try {
Object[] row = new Object[rowMeta.size()];
Scriptable jsRowMeta = Context.toObject( rowMeta, jsscope );
jsscope.put( "rowMeta", jsscope, jsRowMeta );
for ( int i = 0; i < rowMeta.size(); i++ ) {
ValueMetaInterface valueMeta = rowMeta.getValueMeta( i );
Object valueData = null;
// Set date and string values to something to simulate real thing
//
if ( valueMeta.isDate() ) {
valueData = new Date();
}
if ( valueMeta.isString() ) {
valueData = "test value test value test value test value test "
+ "value test value test value test value test value test value";
}
if ( valueMeta.isInteger() ) {
valueData = Long.valueOf( 0L );
}
if ( valueMeta.isNumber() ) {
valueData = new Double( 0.0 );
}
if ( valueMeta.isBigNumber() ) {
valueData = BigDecimal.ZERO;
}
if ( valueMeta.isBoolean() ) {
valueData = Boolean.TRUE;
}
if ( valueMeta.isBinary() ) {
valueData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };
}
if ( valueMeta.isStorageBinaryString() ) {
valueMeta.setStorageType( ValueMetaInterface.STORAGE_TYPE_NORMAL );
}
row[i] = valueData;
Scriptable jsarg = Context.toObject( valueData, jsscope );
jsscope.put( valueMeta.getName(), jsscope, jsarg );
}
// OK, for these input values, we're going to allow the user to edit the default values...
// We are displaying a
// 2)
// Add support for Value class (new Value())
Scriptable jsval = Context.toObject( Value.class, jsscope );
jsscope.put( "Value", jsscope, jsval );
// Add the old style row object for compatibility reasons...
//
Scriptable jsRow = Context.toObject( row, jsscope );
jsscope.put( "row", jsscope, jsRow );
} catch ( Exception ev ) {
testException =
new KettleException( BaseMessages.getString( PKG, "ScriptDialog.CouldNotAddInputFields", ev
.toString() ) );
retval = false;
}
try {
// Checking for StartScript
if ( strActiveStartScript != null
&& !folder.getSelection().getText().equals( strActiveStartScript )
&& strActiveStartScript.length() > 0 ) {
String strStartScript =
getStyledTextComp( folder.getItem( getCTabPosition( strActiveStartScript ) ) ).getText();
/* Object startScript = */jscx.evaluateString( jsscope, strStartScript, "trans_Start", 1, null );
}
} catch ( Exception e ) {
testException =
new KettleException( BaseMessages.getString( PKG, "ScriptDialog.CouldProcessStartScript", e
.toString() ) );
retval = false;
}
try {
Script evalScript = jscx.compileString( scr, "script", 1, null );
evalScript.exec( jscx, jsscope );
// Object tranScript = jscx.evaluateString(jsscope, scr, "script", 1, null);
if ( getvars ) {
ScriptNode tree = parseVariables( jscx, jsscope, scr, "script", 1, null );
for ( int i = 0; i < tree.getParamAndVarCount(); i++ ) {
String varname = tree.getParamOrVarName( i );
if ( !varname.equalsIgnoreCase( "row" ) && !varname.equalsIgnoreCase( "trans_Status" ) ) {
int type = ValueMetaInterface.TYPE_STRING;
int length = -1, precision = -1;
Object result = jsscope.get( varname, jsscope );
if ( result != null ) {
String classname = result.getClass().getName();
if ( classname.equalsIgnoreCase( "java.lang.Byte" ) ) {
// MAX = 127
type = ValueMetaInterface.TYPE_INTEGER;
length = 3;
precision = 0;
} else if ( classname.equalsIgnoreCase( "java.lang.Integer" ) ) {
// MAX = 2147483647
type = ValueMetaInterface.TYPE_INTEGER;
length = 9;
precision = 0;
} else if ( classname.equalsIgnoreCase( "java.lang.Long" ) ) {
// MAX = 9223372036854775807
type = ValueMetaInterface.TYPE_INTEGER;
length = 18;
precision = 0;
} else if ( classname.equalsIgnoreCase( "java.lang.Double" ) ) {
type = ValueMetaInterface.TYPE_NUMBER;
length = 16;
precision = 2;
} else if ( classname.equalsIgnoreCase( "org.mozilla.javascript.NativeDate" )
|| classname.equalsIgnoreCase( "java.util.Date" ) ) {
type = ValueMetaInterface.TYPE_DATE;
} else if ( classname.equalsIgnoreCase( "java.lang.Boolean" ) ) {
type = ValueMetaInterface.TYPE_BOOLEAN;
}
}
TableItem ti = new TableItem( wFields.table, SWT.NONE );
ti.setText( 1, varname );
ti.setText( 2, "" );
ti.setText( 3, ValueMeta.getTypeDesc( type ) );
ti.setText( 4, length >= 0 ? ( "" + length ) : "" );
ti.setText( 5, precision >= 0 ? ( "" + precision ) : "" );
// If the variable name exists in the input, suggest to replace the value
//
ti.setText( 6, ( rowMeta.indexOfValue( varname ) >= 0 ) ? YES_NO_COMBO[1] : YES_NO_COMBO[0] );
}
}
wFields.removeEmptyRows();
wFields.setRowNums();
wFields.optWidth( true );
}
// End Script!
} catch ( EvaluatorException e ) {
String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
String message = BaseMessages.getString( PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position );
testException = new KettleException( message, e );
retval = false;
} catch ( JavaScriptException e ) {
String position = "(" + e.lineNumber() + ":" + e.columnNumber() + ")";
String message = BaseMessages.getString( PKG, "ScriptDialog.Exception.CouldNotExecuteScript", position );
testException = new KettleException( message, e );
retval = false;
} catch ( Exception e ) {
testException =
new KettleException(
BaseMessages.getString( PKG, "ScriptDialog.Exception.CouldNotExecuteScript2" ), e );
retval = false;
}
} else {
testException =
new KettleException( BaseMessages.getString( PKG, "ScriptDialog.Exception.CouldNotGetFields" ) );
retval = false;
}
if ( popup ) {
if ( retval ) {
if ( !getvars ) {
MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_INFORMATION );
mb.setMessage( BaseMessages.getString( PKG, "ScriptDialog.ScriptCompilationOK" ) + Const.CR );
mb.setText( "OK" );
mb.open();
}
} else {
new ErrorDialog(
shell, BaseMessages.getString( PKG, "ScriptDialog.TestFailed.DialogTitle" ), BaseMessages.getString(
PKG, "ScriptDialog.TestFailed.DialogMessage" ), testException );
}
}
} catch ( KettleException ke ) {
retval = false;
new ErrorDialog( shell, BaseMessages.getString( PKG, "ScriptDialog.TestFailed.DialogTitle" ), BaseMessages
.getString( PKG, "ScriptDialog.TestFailed.DialogMessage" ), ke );
} finally {
if ( jscx != null ) {
Context.exit();
}
}
return retval;
}
private void buildSpecialFunctionsTree() {
TreeItem item = new TreeItem( wTree, SWT.NULL );
item.setImage( guiresource.getImageBol() );
item.setText( BaseMessages.getString( PKG, "ScriptDialog.TansformConstant.Label" ) );
TreeItem itemT = new TreeItem( item, SWT.NULL );
itemT.setImage( imageArrowGreen );
itemT.setText( "SKIP_TRANSFORMATION" );
itemT.setData( "SKIP_TRANSFORMATION" );
// itemT = new TreeItem(item, SWT.NULL);
// itemT.setText("ABORT_TRANSFORMATION");
// itemT.setData("ABORT_TRANSFORMATION");
itemT = new TreeItem( item, SWT.NULL );
itemT.setImage( imageArrowGreen );
itemT.setText( "ERROR_TRANSFORMATION" );
itemT.setData( "ERROR_TRANSFORMATION" );
itemT = new TreeItem( item, SWT.NULL );
itemT.setImage( imageArrowGreen );
itemT.setText( "CONTINUE_TRANSFORMATION" );
itemT.setData( "CONTINUE_TRANSFORMATION" );
item = new TreeItem( wTree, SWT.NULL );
item.setImage( guiresource.getImageBol() );
item.setText( BaseMessages.getString( PKG, "ScriptDialog.TransformFunctions.Label" ) );
String strData = "";
// Adding the Grouping Items to the Tree
TreeItem itemStringFunctionsGroup = new TreeItem( item, SWT.NULL );
itemStringFunctionsGroup.setImage( imageUnderGreen );
itemStringFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.StringFunctions.Label" ) );
itemStringFunctionsGroup.setData( "Function" );
TreeItem itemNumericFunctionsGroup = new TreeItem( item, SWT.NULL );
itemNumericFunctionsGroup.setImage( imageUnderGreen );
itemNumericFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.NumericFunctions.Label" ) );
itemNumericFunctionsGroup.setData( "Function" );
TreeItem itemDateFunctionsGroup = new TreeItem( item, SWT.NULL );
itemDateFunctionsGroup.setImage( imageUnderGreen );
itemDateFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.DateFunctions.Label" ) );
itemDateFunctionsGroup.setData( "Function" );
TreeItem itemLogicFunctionsGroup = new TreeItem( item, SWT.NULL );
itemLogicFunctionsGroup.setImage( imageUnderGreen );
itemLogicFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.LogicFunctions.Label" ) );
itemLogicFunctionsGroup.setData( "Function" );
TreeItem itemSpecialFunctionsGroup = new TreeItem( item, SWT.NULL );
itemSpecialFunctionsGroup.setImage( imageUnderGreen );
itemSpecialFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.SpecialFunctions.Label" ) );
itemSpecialFunctionsGroup.setData( "Function" );
TreeItem itemFileFunctionsGroup = new TreeItem( item, SWT.NULL );
itemFileFunctionsGroup.setImage( imageUnderGreen );
itemFileFunctionsGroup.setText( BaseMessages.getString( PKG, "ScriptDialog.FileFunctions.Label" ) );
itemFileFunctionsGroup.setData( "Function" );
// Loading the Default delivered JScript Functions
// Method[] methods = ScriptValuesAddedFunctions.class.getMethods();
// String strClassType = ScriptValuesAddedFunctions.class.toString();
Hashtable<String, String> hatFunctions = scVHelp.getFunctionList();
Vector<String> v = new Vector<String>( hatFunctions.keySet() );
Collections.sort( v );
for ( String strFunction : v ) {
String strFunctionType = hatFunctions.get( strFunction );
int iFunctionType = Integer.valueOf( strFunctionType ).intValue();
TreeItem itemFunction = null;
switch ( iFunctionType ) {
case ScriptAddedFunctions.STRING_FUNCTION:
itemFunction = new TreeItem( itemStringFunctionsGroup, SWT.NULL );
break;
case ScriptAddedFunctions.NUMERIC_FUNCTION:
itemFunction = new TreeItem( itemNumericFunctionsGroup, SWT.NULL );
break;
case ScriptAddedFunctions.DATE_FUNCTION:
itemFunction = new TreeItem( itemDateFunctionsGroup, SWT.NULL );
break;
case ScriptAddedFunctions.LOGIC_FUNCTION:
itemFunction = new TreeItem( itemLogicFunctionsGroup, SWT.NULL );
break;
case ScriptAddedFunctions.SPECIAL_FUNCTION:
itemFunction = new TreeItem( itemSpecialFunctionsGroup, SWT.NULL );
break;
case ScriptAddedFunctions.FILE_FUNCTION:
itemFunction = new TreeItem( itemFileFunctionsGroup, SWT.NULL );
break;
default:
break;
}
if ( itemFunction != null ) {
itemFunction.setText( strFunction );
itemFunction.setImage( imageArrowGreen );
strData = "jsFunction";
itemFunction.setData( strData );
}
}
}
public boolean TreeItemExist( TreeItem itemToCheck, String strItemName ) {
boolean bRC = false;
if ( itemToCheck.getItemCount() > 0 ) {
TreeItem[] items = itemToCheck.getItems();
for ( int i = 0; i < items.length; i++ ) {
if ( items[i].getText().equals( strItemName ) ) {
return true;
}
}
}
return bRC;
}
private void setInputOutputFields() {
shell.getDisplay().syncExec( new Runnable() {
public void run() {
// fields are got...end of wait message
iteminput.removeAll();
itemoutput.removeAll();
String strItemInToAdd = "";
String strItemToAddOut = "";
// try{
// RowMetaInterface r = transMeta.getPrevStepFields(stepname);
if ( rowPrevStepFields != null ) {
// TreeItem item = new TreeItem(wTree, SWT.NULL);
// item.setText(BaseMessages.getString(PKG, "ScriptDialog.OutputFields.Label"));
// String strItemToAdd="";
for ( int i = 0; i < rowPrevStepFields.size(); i++ ) {
ValueMetaInterface v = rowPrevStepFields.getValueMeta( i );
strItemToAddOut = v.getName() + ".setValue(var)";
strItemInToAdd = v.getName();
TreeItem itemFields = new TreeItem( iteminput, SWT.NULL );
itemFields.setImage( imageArrowOrange );
itemFields.setText( strItemInToAdd );
itemFields.setData( strItemInToAdd );
/*
* switch(v.getType()){ case ValueMetaInterface.TYPE_STRING : case ValueMetaInterface.TYPE_NUMBER : case
* ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_DATE : case
* ValueMetaInterface.TYPE_BOOLEAN: strItemToAdd=v.getName()+".setValue(var)"; break; default:
* strItemToAdd=v.getName(); break; }
*/
itemFields = new TreeItem( itemoutput, SWT.NULL );
itemFields.setImage( imageArrowOrange );
itemFields.setText( strItemToAddOut );
itemFields.setData( strItemToAddOut );
}
}
/*
* }catch(KettleException ke){ new ErrorDialog(shell, BaseMessages.getString(PKG,
* "ScriptDialog.FailedToGetFields.DialogTitle"), BaseMessages.getString(PKG,
* "ScriptDialog.FailedToGetFields.DialogMessage"), ke); }
*/
}
} );
}
/*
* private void rebuildInputFieldsTree(){ try{ String itemName = BaseMessages.getString(PKG,
* "ScriptDialog.InputFields.Label");
*
* RowMetaInterface r = transMeta.getPrevStepFields(stepname); if (r!=null){ TreeItem item = null; for (TreeItem look
* : wTree.getItems()) { if (look.getText().equals(itemName)) { // This is the rebuild part! for (TreeItem child :
* look.getItems()) child.dispose(); // clear the children. item=look; break; } } if (item==null) item = new
* TreeItem(wTree, SWT.NULL); item.setText(itemName); String strItemToAdd=""; for (int i=0;i<r.size();i++){
* ValueMetaInterface v = r.getValueMeta(i); if (wCompatible.getSelection()) { switch(v.getType()){ case
* ValueMetaInterface.TYPE_STRING : strItemToAdd=v.getName()+".getString()"; break; case
* ValueMetaInterface.TYPE_NUMBER : strItemToAdd=v.getName()+".getNumber()"; break; case
* ValueMetaInterface.TYPE_INTEGER: strItemToAdd=v.getName()+".getInteger()"; break; case ValueMetaInterface.TYPE_DATE
* : strItemToAdd=v.getName()+".getDate()"; break; case ValueMetaInterface.TYPE_BOOLEAN:
* strItemToAdd=v.getName()+".getBoolean()"; break; case ValueMetaInterface.TYPE_BIGNUMBER:
* strItemToAdd=v.getName()+".getBigNumber()"; break; case ValueMetaInterface.TYPE_BINARY:
* strItemToAdd=v.getName()+".getBytes()"; break; case ValueMetaInterface.TYPE_SERIALIZABLE:
* strItemToAdd=v.getName()+".getSerializable()"; break; default: strItemToAdd=v.getName(); break; } } else {
* strItemToAdd=v.getName(); } TreeItem itemInputFields = new TreeItem(item, SWT.NULL);
* itemInputFields.setText(strItemToAdd); itemInputFields.setData(strItemToAdd); } } }catch(KettleException ke){ new
* ErrorDialog(shell, BaseMessages.getString(PKG, "ScriptDialog.FailedToGetFields.DialogTitle"),
* BaseMessages.getString(PKG, "ScriptDialog.FailedToGetFields.DialogMessage"), ke); } }
*/
// Adds the Current item to the current Position
private void treeDblClick( Event event ) {
StyledTextComp wScript = getStyledTextComp();
Point point = new Point( event.x, event.y );
TreeItem item = wTree.getItem( point );
// Qualifikation where the Click comes from
if ( item != null && item.getParentItem() != null ) {
if ( item.getParentItem().equals( wTreeScriptsItem ) ) {
setActiveCtab( item.getText() );
} else if ( !item.getData().equals( "Function" ) ) {
int iStart = wScript.getCaretOffset();
int selCount = wScript.getSelectionCount(); // this selection will be replaced by wScript.insert
iStart = iStart - selCount; // when a selection is already there we need to subtract the position
if ( iStart < 0 ) {
iStart = 0; // just safety
}
String strInsert = (String) item.getData();
if ( strInsert.equals( "jsFunction" ) ) {
strInsert = item.getText();
}
wScript.insert( strInsert );
wScript.setSelection( iStart, iStart + strInsert.length() );
}
}
/*
* if (item != null && item.getParentItem()!=null && !item.getData().equals("Function")) { int iStart =
* wScript.getCaretOffset(); String strInsert =(String)item.getData(); if(strInsert.equals("jsFunction")) strInsert
* = (String)item.getText(); wScript.insert(strInsert); wScript.setSelection(iStart,iStart+strInsert.length()); }
*/
}
// Building the Tree for Additional Classes
private void buildAddClassesListTree() {
if ( wTreeClassesitem != null ) {
wTreeClassesitem.dispose();
}
if ( input.getAddClasses() != null ) {
for ( int i = 0; i < input.getAddClasses().length; i++ ) {
// System.out.println(input.getAddClasses().length);
try {
Method[] methods = input.getAddClasses()[i].getAddClass().getMethods();
String strClassType = input.getAddClasses()[i].getAddClass().toString();
String strParams;
wTreeClassesitem = new TreeItem( wTree, SWT.NULL );
wTreeClassesitem.setText( input.getAddClasses()[i].getJSName() );
for ( int j = 0; j < methods.length; j++ ) {
String strDeclaringClass = methods[j].getDeclaringClass().toString();
if ( strClassType.equals( strDeclaringClass ) ) {
TreeItem item2 = new TreeItem( wTreeClassesitem, SWT.NULL );
strParams = buildAddClassFunctionName( methods[j] );
item2.setText( methods[j].getName() + "(" + strParams + ")" );
String strData =
input.getAddClasses()[i].getJSName() + "." + methods[j].getName() + "(" + strParams + ")";
item2.setData( strData );
}
}
} catch ( Exception e ) {
// Ignore errors
}
}
}
}
private String buildAddClassFunctionName( Method metForParams ) {
StringBuilder sbRC = new StringBuilder();
String strRC = "";
Class<?>[] clsParamType = metForParams.getParameterTypes();
String strParam;
for ( int x = 0; x < clsParamType.length; x++ ) {
strParam = clsParamType[x].getName();
if ( strParam.toLowerCase().indexOf( "javascript" ) <= 0 ) {
if ( strParam.toLowerCase().indexOf( "object" ) > 0 ) {
sbRC.append( "var" );
sbRC.append( ", " );
} else if ( strParam.equals( "java.lang.String" ) ) {
sbRC.append( "String" );
sbRC.append( ", " );
} else {
sbRC.append( strParam );
sbRC.append( ", " );
}
}
}
strRC = sbRC.toString();
if ( strRC.length() > 0 ) {
strRC = strRC.substring( 0, sbRC.length() - 2 );
}
return strRC;
}
private void buildingFolderMenu() {
// styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addNewItem = new MenuItem( cMenu, SWT.PUSH );
addNewItem.setText( BaseMessages.getString( PKG, "ScriptDialog.AddNewTab" ) );
addNewItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
addCtab( "", "", ADD_BLANK );
}
} );
MenuItem copyItem = new MenuItem( cMenu, SWT.PUSH );
copyItem.setText( BaseMessages.getString( PKG, "ScriptDialog.AddCopy" ) );
copyItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
CTabItem item = folder.getSelection();
StyledTextComp st = (StyledTextComp) item.getControl();
addCtab( item.getText(), st.getText(), ADD_COPY );
}
} );
new MenuItem( cMenu, SWT.SEPARATOR );
MenuItem setActiveScriptItem = new MenuItem( cMenu, SWT.PUSH );
setActiveScriptItem.setText( BaseMessages.getString( PKG, "ScriptDialog.SetTransformScript" ) );
setActiveScriptItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
CTabItem item = folder.getSelection();
for ( int i = 0; i < folder.getItemCount(); i++ ) {
if ( folder.getItem( i ).equals( item ) ) {
if ( item.getImage().equals( imageActiveScript ) ) {
strActiveScript = "";
} else if ( item.getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = "";
} else if ( item.getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = "";
}
item.setImage( imageActiveScript );
strActiveScript = item.getText();
} else if ( folder.getItem( i ).getImage().equals( imageActiveScript ) ) {
folder.getItem( i ).setImage( imageInactiveScript );
}
}
modifyScriptTree( item, SET_ACTIVE_ITEM );
}
} );
MenuItem setStartScriptItem = new MenuItem( cMenu, SWT.PUSH );
setStartScriptItem.setText( BaseMessages.getString( PKG, "ScriptDialog.SetStartScript" ) );
setStartScriptItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
CTabItem item = folder.getSelection();
for ( int i = 0; i < folder.getItemCount(); i++ ) {
if ( folder.getItem( i ).equals( item ) ) {
if ( item.getImage().equals( imageActiveScript ) ) {
strActiveScript = "";
} else if ( item.getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = "";
} else if ( item.getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = "";
}
item.setImage( imageActiveStartScript );
strActiveStartScript = item.getText();
} else if ( folder.getItem( i ).getImage().equals( imageActiveStartScript ) ) {
folder.getItem( i ).setImage( imageInactiveScript );
}
}
modifyScriptTree( item, SET_ACTIVE_ITEM );
}
} );
MenuItem setEndScriptItem = new MenuItem( cMenu, SWT.PUSH );
setEndScriptItem.setText( BaseMessages.getString( PKG, "ScriptDialog.SetEndScript" ) );
setEndScriptItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
CTabItem item = folder.getSelection();
for ( int i = 0; i < folder.getItemCount(); i++ ) {
if ( folder.getItem( i ).equals( item ) ) {
if ( item.getImage().equals( imageActiveScript ) ) {
strActiveScript = "";
} else if ( item.getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = "";
} else if ( item.getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = "";
}
item.setImage( imageActiveEndScript );
strActiveEndScript = item.getText();
} else if ( folder.getItem( i ).getImage().equals( imageActiveEndScript ) ) {
folder.getItem( i ).setImage( imageInactiveScript );
}
}
modifyScriptTree( item, SET_ACTIVE_ITEM );
}
} );
new MenuItem( cMenu, SWT.SEPARATOR );
MenuItem setRemoveScriptItem = new MenuItem( cMenu, SWT.PUSH );
setRemoveScriptItem.setText( BaseMessages.getString( PKG, "ScriptDialog.RemoveScriptType" ) );
setRemoveScriptItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
CTabItem item = folder.getSelection();
input.setChanged( true );
if ( item.getImage().equals( imageActiveScript ) ) {
strActiveScript = "";
} else if ( item.getImage().equals( imageActiveStartScript ) ) {
strActiveStartScript = "";
} else if ( item.getImage().equals( imageActiveEndScript ) ) {
strActiveEndScript = "";
}
item.setImage( imageInactiveScript );
}
} );
folder.setMenu( cMenu );
}
private void buildingTreeMenu() {
// styledTextPopupmenu = new Menu(, SWT.POP_UP);
MenuItem addDeleteItem = new MenuItem( tMenu, SWT.PUSH );
addDeleteItem.setText( BaseMessages.getString( PKG, "ScriptDialog.Delete.Label" ) );
addDeleteItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
if ( wTree.getSelectionCount() <= 0 ) {
return;
}
TreeItem tItem = wTree.getSelection()[0];
if ( tItem != null ) {
MessageBox messageBox = new MessageBox( shell, SWT.ICON_QUESTION | SWT.NO | SWT.YES );
messageBox.setText( BaseMessages.getString( PKG, "ScriptDialog.DeleteItem.Label" ) );
messageBox.setMessage( BaseMessages.getString( PKG, "ScriptDialog.ConfirmDeleteItem.Label", tItem
.getText() ) );
switch ( messageBox.open() ) {
case SWT.YES:
modifyCTabItem( tItem, DELETE_ITEM, "" );
tItem.dispose();
input.setChanged();
break;
default:
break;
}
}
}
} );
MenuItem renItem = new MenuItem( tMenu, SWT.PUSH );
renItem.setText( BaseMessages.getString( PKG, "ScriptDialog.Rename.Label" ) );
renItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
renameFunction( wTree.getSelection()[0] );
}
} );
new MenuItem( tMenu, SWT.SEPARATOR );
MenuItem helpItem = new MenuItem( tMenu, SWT.PUSH );
helpItem.setText( BaseMessages.getString( PKG, "ScriptDialog.Sample.Label" ) );
helpItem.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event e ) {
String strFunctionName = wTree.getSelection()[0].getText();
String strFunctionNameWithArgs = strFunctionName;
strFunctionName = strFunctionName.substring( 0, strFunctionName.indexOf( '(' ) );
String strHelpTabName = strFunctionName + "_Sample";
if ( getCTabPosition( strHelpTabName ) == -1 ) {
addCtab( strHelpTabName, scVHelp.getSample( strFunctionName, strFunctionNameWithArgs ), 0 );
}
if ( getCTabPosition( strHelpTabName ) != -1 ) {
setActiveCtab( strHelpTabName );
}
}
} );
wTree.addListener( SWT.MouseDown, new Listener() {
public void handleEvent( Event e ) {
if ( wTree.getSelectionCount() <= 0 ) {
return;
}
TreeItem tItem = wTree.getSelection()[0];
if ( tItem != null ) {
TreeItem pItem = tItem.getParentItem();
if ( pItem != null && pItem.equals( wTreeScriptsItem ) ) {
if ( folder.getItemCount() > 1 ) {
tMenu.getItem( 0 ).setEnabled( true );
} else {
tMenu.getItem( 0 ).setEnabled( false );
}
tMenu.getItem( 1 ).setEnabled( true );
tMenu.getItem( 3 ).setEnabled( false );
} else if ( tItem.equals( wTreeClassesitem ) ) {
tMenu.getItem( 0 ).setEnabled( false );
tMenu.getItem( 1 ).setEnabled( false );
tMenu.getItem( 3 ).setEnabled( false );
} else if ( tItem.getData() != null && tItem.getData().equals( "jsFunction" ) ) {
tMenu.getItem( 0 ).setEnabled( false );
tMenu.getItem( 1 ).setEnabled( false );
tMenu.getItem( 3 ).setEnabled( true );
} else {
tMenu.getItem( 0 ).setEnabled( false );
tMenu.getItem( 1 ).setEnabled( false );
tMenu.getItem( 3 ).setEnabled( false );
}
}
}
} );
wTree.setMenu( tMenu );
}
private void addRenameTowTreeScriptItems() {
lastItem = new TreeItem[1];
editor = new TreeEditor( wTree );
wTree.addListener( SWT.Selection, new Listener() {
public void handleEvent( Event event ) {
final TreeItem item = (TreeItem) event.item;
renameFunction( item );
}
} );
}
// This function is for a Windows Like renaming inside the tree
private void renameFunction( TreeItem tItem ) {
final TreeItem item = tItem;
if ( item.getParentItem() != null && item.getParentItem().equals( wTreeScriptsItem ) ) {
if ( item != null && item == lastItem[0] ) {
boolean isCarbon = SWT.getPlatform().equals( "carbon" );
final Composite composite = new Composite( wTree, SWT.NONE );
if ( !isCarbon ) {
composite.setBackground( shell.getDisplay().getSystemColor( SWT.COLOR_BLACK ) );
}
final Text text = new Text( composite, SWT.NONE );
final int inset = isCarbon ? 0 : 1;
composite.addListener( SWT.Resize, new Listener() {
public void handleEvent( Event e ) {
Rectangle rect = composite.getClientArea();
text.setBounds( rect.x + inset, rect.y + inset, rect.width - inset * 2, rect.height - inset * 2 );
}
} );
Listener textListener = new Listener() {
@SuppressWarnings( "fallthrough" )
public void handleEvent( final Event e ) {
switch ( e.type ) {
case SWT.FocusOut:
if ( text.getText().length() > 0 ) {
// Check if the name Exists
if ( getCTabItemByName( text.getText() ) == null ) {
modifyCTabItem( item, RENAME_ITEM, text.getText() );
item.setText( text.getText() );
}
}
composite.dispose();
break;
case SWT.Verify:
String newText = text.getText();
String leftText = newText.substring( 0, e.start );
String rightText = newText.substring( e.end, newText.length() );
GC gc = new GC( text );
Point size = gc.textExtent( leftText + e.text + rightText );
gc.dispose();
size = text.computeSize( size.x, SWT.DEFAULT );
editor.horizontalAlignment = SWT.LEFT;
Rectangle itemRect = item.getBounds(),
rect = wTree.getClientArea();
editor.minimumWidth = Math.max( size.x, itemRect.width ) + inset * 2;
int left = itemRect.x,
right = rect.x + rect.width;
editor.minimumWidth = Math.min( editor.minimumWidth, right - left );
editor.minimumHeight = size.y + inset * 2;
editor.layout();
break;
case SWT.Traverse:
switch ( e.detail ) {
case SWT.TRAVERSE_RETURN:
if ( text.getText().length() > 0 ) {
// Check if the name Exists
if ( getCTabItemByName( text.getText() ) == null ) {
modifyCTabItem( item, RENAME_ITEM, text.getText() );
item.setText( text.getText() );
}
}
case SWT.TRAVERSE_ESCAPE:
composite.dispose();
e.doit = false;
break;
default:
break;
}
break;
default:
break;
}
}
};
text.addListener( SWT.FocusOut, textListener );
text.addListener( SWT.Traverse, textListener );
text.addListener( SWT.Verify, textListener );
editor.setEditor( composite, item );
text.setText( item.getText() );
text.selectAll();
text.setFocus();
}
}
lastItem[0] = item;
}
// This could be useful for further improvements
public static ScriptNode parseVariables( Context cx, Scriptable scope, String source, String sourceName,
int lineno, Object securityDomain ) {
// Interpreter compiler = new Interpreter();
CompilerEnvirons evn = new CompilerEnvirons();
// evn.setLanguageVersion(Context.VERSION_1_5);
evn.setOptimizationLevel( -1 );
evn.setGeneratingSource( true );
evn.setGenerateDebugInfo( true );
ErrorReporter errorReporter = new ToolErrorReporter( false );
Parser p = new Parser( evn, errorReporter );
ScriptNode tree = p.parse( source, "", 0 ); // IOException
new NodeTransformer().transform( tree );
// Script result = (Script)compiler.compile(scope, evn, tree, p.getEncodedSource(),false, null);
return tree;
}
}
| {'content_hash': '1758c4ef6ed4d3116a16fa933e6208d2', 'timestamp': '', 'source': 'github', 'line_count': 2036, 'max_line_length': 120, 'avg_line_length': 39.22838899803536, 'alnum_prop': 0.6209918741939927, 'repo_name': 'stevewillcock/pentaho-kettle', 'id': '3953c3192279beb53a01f3061d3470daeda90365', 'size': '80773', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'ui/src/org/pentaho/di/ui/trans/steps/script/ScriptDialog.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '13802'}, {'name': 'CSS', 'bytes': '20530'}, {'name': 'GAP', 'bytes': '4005'}, {'name': 'HTML', 'bytes': '69511'}, {'name': 'Java', 'bytes': '37658299'}, {'name': 'JavaScript', 'bytes': '16314'}, {'name': 'Shell', 'bytes': '18578'}, {'name': 'XSLT', 'bytes': '5600'}]} |
@implementation User
- (instancetype)initWithJSONDictionary:(NSDictionary *)json
{
// はてなID
NSString *userId;
NSString *userId_ = json[@"id"];
if ([userId_ isKindOfClass:[NSString class]]) {
userId = userId_;
}
// ニックネーム
NSString *name;
NSString *name_ = json[@"name"];
if ([name_ isKindOfClass:[NSString class]]) {
name = name_;
}
// プロフィール画像のURL
NSURL *profileImageURL;
NSString *profileImageUrlString = json[@"profile_image_url"];
if ([profileImageUrlString isKindOfClass:[NSString class]]) {
profileImageURL = [NSURL URLWithString:profileImageUrlString];
}
// ファンの数
NSNumber *followersCount;
NSString *followersCountString = json[@"followers_count"];
if ([followersCountString isKindOfClass:[NSString class]]) {
followersCount = [NSNumber numberWithInt:[followersCountString intValue]];
}
return [self initWithUserId:userId
name:name
profileImageURL:profileImageURL
followersCount:followersCount];
}
- (instancetype)initWithUserId:(NSString *)userId
name:(NSString *)name
profileImageURL:(NSURL *)profileImageURL
followersCount:(NSNumber *)followersCount
{
self = [super init];
if (self) {
_userId = userId;
_name = name;
_profileImageURL = profileImageURL;
_followersCount = followersCount;
}
return self;
}
- (NSString *)description
{
NSMutableString *description = [NSMutableString stringWithFormat:@"<%@: ", NSStringFromClass([self class])];
[description appendFormat:@"self.userId=%@", self.userId];
[description appendFormat:@", self.name=%@", self.name];
[description appendFormat:@", self.profileImageURL=%@", self.profileImageURL];
[description appendFormat:@", self.followersCount=%@", self.followersCount];
[description appendString:@">"];
return description;
}
@end
| {'content_hash': '55226e321900ada0b67f7f1b49756279', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 112, 'avg_line_length': 30.303030303030305, 'alnum_prop': 0.6375, 'repo_name': 'koogawa/HatenaHaiku', 'id': '7084f6e35c25feb85919253704fd5fe3d625fc35', 'size': '2200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'HatenaHaiku/Model/User.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '21575'}, {'name': 'HTML', 'bytes': '722'}, {'name': 'Objective-C', 'bytes': '346432'}, {'name': 'Ruby', 'bytes': '71'}]} |
var manageAirlineTable;
$(document).ready(function() {
manageAirlineTable = $("#manageAirlineTable").DataTable({
'ajax': 'Airline/fetchAirlineData',
'orders': []
});
});
function addAirlineModel()
{
$("#createForm")[0].reset();
//remove textdanger
$(".text-danger").remove();
// remove form-group
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#createForm").unbind('submit').bind('submit', function() {
var form = $(this);
// remove the text-danger
$(".text-danger").remove();
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(), // /converting the form data into array and sending it to server
dataType: 'json',
success:function(response) {
if(response.success === true) {
$(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// hide the modal
$("#addAirline").modal('hide');
// update the manageAirlineTable
manageAirlineTable.ajax.reload(null, false);
} else {
if(response.messages instanceof Object) {
$.each(response.messages, function(index, value) {
var id = $("#"+index);
id
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.after(value);
});
} else {
$(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
}
}
}
});
return false;
});
}
function editAirline(id = null)
{
// alert("What follows is blank: " + id);
if(id) {
$("#editForm")[0].reset();
$('.form-group').removeClass('has-error').removeClass('has-success');
$('.text-danger').remove();
$.ajax({
url: 'index.php/Airline/getSelectedAirlineInfo' + '/' + id,
type: 'post',
dataType: 'json',
success:function(response) {
// alert("What follows is blanks: " + response.CnCode);
$("#editAPCode").val(response.APCode);
$("#editAPName").val(response.APName);
$("#editAPCity").val(response.APCity);
$("#editForm").unbind('submit').bind('submit', function() {
var form = $(this);
$.ajax({
url: form.attr('action') + '/' + id,
type: 'post',
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success === true) {
$(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// hide the modal
$("#editAirlineModal").modal('hide');
// update the manageAirlineTable
manageAirlineTable.ajax.reload(null, false);
} else {
$('.text-danger').remove()
if(response.messages instanceof Object) {
$.each(response.messages, function(index, value) {
var id = $("#"+index);
id
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.after(value);
});
} else {
$(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
}
}
} // /succes
}); // /ajax
return false;
});
}
});
}
else {
alert('error');
}
}
function removeAirline(id = null)
{
// alert("What follows is blank: " + id);
if(id) {
// alert("What follows is blank: " + id);
$("#removeAirlineBtn").unbind('click').bind('click', function() {
$.ajax({
url: 'index.php/Airline/remove' + '/' + id,
type: 'post',
dataType: 'json',
success:function(response) {
// alert("What follows is blank: " + id);
if(response.success === true) {
$(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// hide the modal
$("#removeAirlineModal").modal('hide');
// update the manageAirlineTable
manageAirlineTable.ajax.reload(null, false);
} else {
$('.text-danger').remove()
if(response.messages instanceof Object) {
$.each(response.messages, function(index, value) {
var id = $("#"+index);
id
.closest('.form-group')
.removeClass('has-error')
.removeClass('has-success')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.after(value);
});
} else {
$(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
}
}
} // /succes
}); // /ajax
});
}
}
| {'content_hash': '706eb3b4dd12f109e931189b07b5081f', 'timestamp': '', 'source': 'github', 'line_count': 199, 'max_line_length': 137, 'avg_line_length': 30.90954773869347, 'alnum_prop': 0.5782799544789465, 'repo_name': 'JohnHHancock/FMS', 'id': 'b9548a94478ee943c3effcf4e4f85c7c2926069b', 'size': '6170', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/js/airline.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '479'}, {'name': 'CSS', 'bytes': '1510'}, {'name': 'HTML', 'bytes': '5502'}, {'name': 'JavaScript', 'bytes': '181590'}, {'name': 'PHP', 'bytes': '1863767'}]} |
package com.saintdan.framework.servlet;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.tomcat.util.http.fileupload.IOUtils;
/**
* Multiple reader for {@link HttpServletRequest}.
*
* @author <a href="http://github.com/saintdan">Liao Yifan</a>
* @date 20/10/2017
* @since JDK1.8
*/
public class RequestWrapper extends HttpServletRequestWrapper {
private ByteArrayOutputStream cachedBytes;
public RequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (cachedBytes == null) {
cacheInputStream();
}
return new CachedServletInputStream();
}
@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
private void cacheInputStream() throws IOException {
/* Cache the inputstream in order to read it multiple times. For
* convenience, I use apache.commons IOUtils
*/
cachedBytes = new ByteArrayOutputStream();
IOUtils.copy(super.getInputStream(), cachedBytes);
}
/* An inputstream which reads the cached request body */
public class CachedServletInputStream extends ServletInputStream {
private ByteArrayInputStream byteArrayInputStream;
public CachedServletInputStream() {
/* create a new input stream from the cached request body */
byteArrayInputStream = new ByteArrayInputStream(cachedBytes.toByteArray());
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
@Override
public boolean isFinished() {
return byteArrayInputStream.available() == 0;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener listener) {
throw new RuntimeException("Not implemented");
}
}
}
| {'content_hash': 'af0b2403945a90221d3eca03658957db', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 81, 'avg_line_length': 27.37037037037037, 'alnum_prop': 0.7356788452864231, 'repo_name': 'saintdan/spring-microservices-boilerplate', 'id': '38cdbbd072ab97f78fc1377ba00b07754ac830ff', 'size': '2217', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/saintdan/framework/servlet/RequestWrapper.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '216'}, {'name': 'Java', 'bytes': '232679'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_05) on Thu Dec 11 10:42:57 EST 2014 -->
<title>M-Index</title>
<meta name="date" content="2014-12-11">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<script type="text/javascript" src="../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="M-Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-11.html">Prev Letter</a></li>
<li><a href="index-13.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-12.html" target="_top">Frames</a></li>
<li><a href="index-12.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">K</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> <a name="I:M">
<!-- -->
</a>
<h2 class="title">M</h2>
<dl>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/JSON/JSONParser.html#makeHttpRequest-java.lang.String-java.lang.String-java.util.List-">makeHttpRequest(String, String, List<NameValuePair>)</a></span> - Method in class com.compsci408.rxcore.JSON.<a href="../com/compsci408/rxcore/JSON/JSONParser.html" title="class in com.compsci408.rxcore.JSON">JSONParser</a></dt>
<dd>
<div class="block">Function for making HTTP Post and Get
requests and return the <code>JSONObject</code>
which results from the request.</div>
</dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mAlarmTone">mAlarmTone</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/Constants.html#MED_DOSE_DESCR">MED_DOSE_DESCR</a></span> - Static variable in class com.compsci408.rxcore.<a href="../com/compsci408/rxcore/Constants.html" title="class in com.compsci408.rxcore">Constants</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/Constants.html#MED_DOSE_QUANT">MED_DOSE_QUANT</a></span> - Static variable in class com.compsci408.rxcore.<a href="../com/compsci408/rxcore/Constants.html" title="class in com.compsci408.rxcore">Constants</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/Constants.html#MED_ID">MED_ID</a></span> - Static variable in class com.compsci408.rxcore.<a href="../com/compsci408/rxcore/Constants.html" title="class in com.compsci408.rxcore">Constants</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/Constants.html#MED_NAME">MED_NAME</a></span> - Static variable in class com.compsci408.rxcore.<a href="../com/compsci408/rxcore/Constants.html" title="class in com.compsci408.rxcore">Constants</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/Constants.html#MED_NICKNAME">MED_NICKNAME</a></span> - Static variable in class com.compsci408.rxcore.<a href="../com/compsci408/rxcore/Constants.html" title="class in com.compsci408.rxcore">Constants</a></dt>
<dd> </dd>
<dt><a href="../com/compsci408/rxcore/datatypes/Medication.html" title="class in com.compsci408.rxcore.datatypes"><span class="typeNameLink">Medication</span></a> - Class in <a href="../com/compsci408/rxcore/datatypes/package-summary.html">com.compsci408.rxcore.datatypes</a></dt>
<dd>
<div class="block">Class describing the attributes of a
medication object.</div>
</dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/datatypes/Medication.html#Medication--">Medication()</a></span> - Constructor for class com.compsci408.rxcore.datatypes.<a href="../com/compsci408/rxcore/datatypes/Medication.html" title="class in com.compsci408.rxcore.datatypes">Medication</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mId">mId</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mIsEnabled">mIsEnabled</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mName">mName</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mTimeHour">mTimeHour</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="../com/compsci408/rxcore/alarms/Alarm.html#mTimeMinute">mTimeMinute</a></span> - Variable in class com.compsci408.rxcore.alarms.<a href="../com/compsci408/rxcore/alarms/Alarm.html" title="class in com.compsci408.rxcore.alarms">Alarm</a></dt>
<dd> </dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">B</a> <a href="index-3.html">C</a> <a href="index-4.html">D</a> <a href="index-5.html">E</a> <a href="index-6.html">F</a> <a href="index-7.html">G</a> <a href="index-8.html">I</a> <a href="index-9.html">J</a> <a href="index-10.html">K</a> <a href="index-11.html">L</a> <a href="index-12.html">M</a> <a href="index-13.html">O</a> <a href="index-14.html">P</a> <a href="index-15.html">R</a> <a href="index-16.html">S</a> <a href="index-17.html">T</a> <a href="index-18.html">U</a> <a href="index-19.html">V</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-11.html">Prev Letter</a></li>
<li><a href="index-13.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-12.html" target="_top">Frames</a></li>
<li><a href="index-12.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {'content_hash': 'c78058c803fca736ff6e7ae7c06f8983', 'timestamp': '', 'source': 'github', 'line_count': 162, 'max_line_length': 700, 'avg_line_length': 58.370370370370374, 'alnum_prop': 0.6750211505922166, 'repo_name': 'duke-compsci408-fall2014/GlassRx', 'id': '0eb4c9ef7167a8e724c6b2620f313cf118325402', 'size': '9456', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'RxCore/doc/index-files/index-12.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1'}, {'name': 'C++', 'bytes': '1'}, {'name': 'CSS', 'bytes': '52380'}, {'name': 'Java', 'bytes': '310827'}, {'name': 'JavaScript', 'bytes': '3368'}]} |
package io.tracee.binding.jaxws;
import io.tracee.TraceeBackend;
import io.tracee.TraceeConstants;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
abstract class AbstractTraceeHandler implements SOAPHandler<SOAPMessageContext> {
protected final TraceeBackend traceeBackend;
private static final Set<QName> HANDLED_HEADERS = Collections.unmodifiableSet(
new HashSet<QName>(Collections.singleton(TraceeConstants.SOAP_HEADER_QNAME)));
public AbstractTraceeHandler(TraceeBackend traceeBackend) {
this.traceeBackend = traceeBackend;
}
@Override
public final boolean handleMessage(final SOAPMessageContext context) {
if (this.isOutgoing(context)) {
this.handleOutgoing(context);
} else {
this.handleIncoming(context);
}
return true;
}
private boolean isOutgoing(MessageContext messageContext) {
Object outboundBoolean = messageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
return outboundBoolean != null && (Boolean) outboundBoolean;
}
@Override
public void close(MessageContext context) {}
protected abstract void handleIncoming(SOAPMessageContext context);
protected abstract void handleOutgoing(SOAPMessageContext context);
@Override
public Set<QName> getHeaders() {
return HANDLED_HEADERS;
}
SOAPHeader getOrCreateHeader(final SOAPMessage message) throws SOAPException {
SOAPHeader header = message.getSOAPHeader();
if (header == null) {
header = message.getSOAPPart().getEnvelope().addHeader();
}
return header;
}
}
| {'content_hash': 'fb49b80305914bf73042fecf6bdceef7', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 88, 'avg_line_length': 29.919354838709676, 'alnum_prop': 0.769811320754717, 'repo_name': 'hypery2k/tracee', 'id': '4bca487f415bcdc4dcaae33298a42b33dd5f645f', 'size': '1855', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'binding/jaxws/src/main/java/io/tracee/binding/jaxws/AbstractTraceeHandler.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '373167'}]} |
package com.weisong.soa.core.zk.config;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import com.weisong.soa.core.zk.ZkClient;
import com.weisong.soa.core.zk.bootstrap.BootstrapZkClient;
@Configuration
public class ZkPropertyJavaConfig {
final static private String PROPERTY_FILES_PATH = "property.files.path";
static private String[] locations = new String[] {
"classpath*:/properties/*.properties"
, "file:/etc/override.properties"
};
static private BootstrapZkClient bootstrapZkClient;
@Bean
static public BootstrapZkClient bootstrapZkClient() throws Exception {
if(bootstrapZkClient == null) {
bootstrapZkClient = new BootstrapZkClient();
}
return bootstrapZkClient;
}
@Bean
static public ZkPropertyPlaceholderConfigurer propertyPlaceholderConfigurer() throws Exception {
ZkClient zkClient = bootstrapZkClient();
ZkPropertyPlaceholderConfigurer c = new ZkPropertyPlaceholderConfigurer(zkClient);
c.setIgnoreResourceNotFound(true);
c.setIgnoreUnresolvablePlaceholders(true);
String path = System.getProperty(PROPERTY_FILES_PATH);
if(path != null) {
locations[0] = locations[0].replace("/properties/", "/" + path + "/");
}
c.setLocations(createResources(locations));
return c;
}
static private Resource[] createResources(String... locations) throws Exception {
List<Resource> resources = new LinkedList<>();
for(String loc : locations) {
Resource[] temp = new PathMatchingResourcePatternResolver().getResources(loc);
resources.addAll(Arrays.asList(temp));
}
return resources.toArray(new Resource[resources.size()]);
}
}
| {'content_hash': '6ee0124120632923a005293a1030d838', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 100, 'avg_line_length': 34.389830508474574, 'alnum_prop': 0.7111877772301627, 'repo_name': 'weisong44/weisong-soa', 'id': '1395fff0c21b365068c0ab9c82ff6f4b0a2b176f', 'size': '2029', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'weisong-soa-core-zk/src/main/java/com/weisong/soa/core/zk/config/ZkPropertyJavaConfig.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '2215'}, {'name': 'CSS', 'bytes': '19'}, {'name': 'HTML', 'bytes': '45'}, {'name': 'Java', 'bytes': '564317'}, {'name': 'Shell', 'bytes': '166'}]} |
package traffic_class // TrafficClass
import "github.com/antlr/antlr4/runtime/Go/antlr"
// BaseTrafficClassListener is a complete listener for a parse tree produced by TrafficClassParser.
type BaseTrafficClassListener struct{}
var _ TrafficClassListener = &BaseTrafficClassListener{}
// VisitTerminal is called when a terminal node is visited.
func (s *BaseTrafficClassListener) VisitTerminal(node antlr.TerminalNode) {}
// VisitErrorNode is called when an error node is visited.
func (s *BaseTrafficClassListener) VisitErrorNode(node antlr.ErrorNode) {}
// EnterEveryRule is called when any rule is entered.
func (s *BaseTrafficClassListener) EnterEveryRule(ctx antlr.ParserRuleContext) {}
// ExitEveryRule is called when any rule is exited.
func (s *BaseTrafficClassListener) ExitEveryRule(ctx antlr.ParserRuleContext) {}
// EnterMatchSrc is called when production matchSrc is entered.
func (s *BaseTrafficClassListener) EnterMatchSrc(ctx *MatchSrcContext) {}
// ExitMatchSrc is called when production matchSrc is exited.
func (s *BaseTrafficClassListener) ExitMatchSrc(ctx *MatchSrcContext) {}
// EnterMatchDst is called when production matchDst is entered.
func (s *BaseTrafficClassListener) EnterMatchDst(ctx *MatchDstContext) {}
// ExitMatchDst is called when production matchDst is exited.
func (s *BaseTrafficClassListener) ExitMatchDst(ctx *MatchDstContext) {}
// EnterMatchDSCP is called when production matchDSCP is entered.
func (s *BaseTrafficClassListener) EnterMatchDSCP(ctx *MatchDSCPContext) {}
// ExitMatchDSCP is called when production matchDSCP is exited.
func (s *BaseTrafficClassListener) ExitMatchDSCP(ctx *MatchDSCPContext) {}
// EnterMatchTOS is called when production matchTOS is entered.
func (s *BaseTrafficClassListener) EnterMatchTOS(ctx *MatchTOSContext) {}
// ExitMatchTOS is called when production matchTOS is exited.
func (s *BaseTrafficClassListener) ExitMatchTOS(ctx *MatchTOSContext) {}
// EnterMatchProtocol is called when production matchProtocol is entered.
func (s *BaseTrafficClassListener) EnterMatchProtocol(ctx *MatchProtocolContext) {}
// ExitMatchProtocol is called when production matchProtocol is exited.
func (s *BaseTrafficClassListener) ExitMatchProtocol(ctx *MatchProtocolContext) {}
// EnterMatchSrcPort is called when production matchSrcPort is entered.
func (s *BaseTrafficClassListener) EnterMatchSrcPort(ctx *MatchSrcPortContext) {}
// ExitMatchSrcPort is called when production matchSrcPort is exited.
func (s *BaseTrafficClassListener) ExitMatchSrcPort(ctx *MatchSrcPortContext) {}
// EnterMatchSrcPortRange is called when production matchSrcPortRange is entered.
func (s *BaseTrafficClassListener) EnterMatchSrcPortRange(ctx *MatchSrcPortRangeContext) {}
// ExitMatchSrcPortRange is called when production matchSrcPortRange is exited.
func (s *BaseTrafficClassListener) ExitMatchSrcPortRange(ctx *MatchSrcPortRangeContext) {}
// EnterMatchDstPort is called when production matchDstPort is entered.
func (s *BaseTrafficClassListener) EnterMatchDstPort(ctx *MatchDstPortContext) {}
// ExitMatchDstPort is called when production matchDstPort is exited.
func (s *BaseTrafficClassListener) ExitMatchDstPort(ctx *MatchDstPortContext) {}
// EnterMatchDstPortRange is called when production matchDstPortRange is entered.
func (s *BaseTrafficClassListener) EnterMatchDstPortRange(ctx *MatchDstPortRangeContext) {}
// ExitMatchDstPortRange is called when production matchDstPortRange is exited.
func (s *BaseTrafficClassListener) ExitMatchDstPortRange(ctx *MatchDstPortRangeContext) {}
// EnterCondCls is called when production condCls is entered.
func (s *BaseTrafficClassListener) EnterCondCls(ctx *CondClsContext) {}
// ExitCondCls is called when production condCls is exited.
func (s *BaseTrafficClassListener) ExitCondCls(ctx *CondClsContext) {}
// EnterCondAny is called when production condAny is entered.
func (s *BaseTrafficClassListener) EnterCondAny(ctx *CondAnyContext) {}
// ExitCondAny is called when production condAny is exited.
func (s *BaseTrafficClassListener) ExitCondAny(ctx *CondAnyContext) {}
// EnterCondAll is called when production condAll is entered.
func (s *BaseTrafficClassListener) EnterCondAll(ctx *CondAllContext) {}
// ExitCondAll is called when production condAll is exited.
func (s *BaseTrafficClassListener) ExitCondAll(ctx *CondAllContext) {}
// EnterCondNot is called when production condNot is entered.
func (s *BaseTrafficClassListener) EnterCondNot(ctx *CondNotContext) {}
// ExitCondNot is called when production condNot is exited.
func (s *BaseTrafficClassListener) ExitCondNot(ctx *CondNotContext) {}
// EnterCondBool is called when production condBool is entered.
func (s *BaseTrafficClassListener) EnterCondBool(ctx *CondBoolContext) {}
// ExitCondBool is called when production condBool is exited.
func (s *BaseTrafficClassListener) ExitCondBool(ctx *CondBoolContext) {}
// EnterCondIPv4 is called when production condIPv4 is entered.
func (s *BaseTrafficClassListener) EnterCondIPv4(ctx *CondIPv4Context) {}
// ExitCondIPv4 is called when production condIPv4 is exited.
func (s *BaseTrafficClassListener) ExitCondIPv4(ctx *CondIPv4Context) {}
// EnterCondPort is called when production condPort is entered.
func (s *BaseTrafficClassListener) EnterCondPort(ctx *CondPortContext) {}
// ExitCondPort is called when production condPort is exited.
func (s *BaseTrafficClassListener) ExitCondPort(ctx *CondPortContext) {}
// EnterCond is called when production cond is entered.
func (s *BaseTrafficClassListener) EnterCond(ctx *CondContext) {}
// ExitCond is called when production cond is exited.
func (s *BaseTrafficClassListener) ExitCond(ctx *CondContext) {}
// EnterTrafficClass is called when production trafficClass is entered.
func (s *BaseTrafficClassListener) EnterTrafficClass(ctx *TrafficClassContext) {}
// ExitTrafficClass is called when production trafficClass is exited.
func (s *BaseTrafficClassListener) ExitTrafficClass(ctx *TrafficClassContext) {}
| {'content_hash': '9a41545651e5bd0ca81c11b9ff01aa36', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 99, 'avg_line_length': 47.275590551181104, 'alnum_prop': 0.8114590273151232, 'repo_name': 'netsec-ethz/scion', 'id': '4efc81b5159120364a0047cc5d84d1db866487c9', 'size': '6046', 'binary': False, 'copies': '2', 'ref': 'refs/heads/scionlab', 'path': 'antlr/traffic_class/trafficclass_base_listener.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '2254'}, {'name': 'Dockerfile', 'bytes': '195'}, {'name': 'Go', 'bytes': '11481996'}, {'name': 'Lua', 'bytes': '37214'}, {'name': 'Makefile', 'bytes': '1803'}, {'name': 'Python', 'bytes': '182730'}, {'name': 'Ruby', 'bytes': '262'}, {'name': 'Shell', 'bytes': '94920'}, {'name': 'Starlark', 'bytes': '466716'}]} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/bg"
>
<include
layout="@layout/common_title"
android:focusable="true"
/>
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
| {'content_hash': 'ca813017c715f9a7a5aface6362be0f7', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 72, 'avg_line_length': 27.45, 'alnum_prop': 0.6375227686703097, 'repo_name': 'gjy3035/lookingforseats-nwpu', 'id': '3210d63f2ac21cf97b28756c4cb9e9a6b30a33e7', 'size': '549', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'res/layout/activity_lost.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '194432'}]} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UrdfToUnity.Urdf.Models.Links.Visuals;
using UrdfToUnity.Urdf.Models.Attributes;
namespace UrdfToUnityTest.Urdf.Models.Links.Visuals
{
[TestClass]
public class ColorTest
{
[TestMethod]
public void ConstructColorNoAlpha()
{
RgbAttribute rgb = new RgbAttribute(255, 255, 255);
Color colour = new Color(rgb);
Assert.AreEqual(rgb, colour.Rgb);
Assert.AreEqual(1d, colour.Alpha);
}
[TestMethod]
public void ConstructColorWithAlpha()
{
double alpha = 0.5;
RgbAttribute rgb = new RgbAttribute(255, 255, 255);
Color colour = new Color(rgb, alpha);
Assert.AreEqual(rgb, colour.Rgb);
Assert.AreEqual(alpha, colour.Alpha);
// Test bounds [0,1]
colour = new Color(rgb, 0d);
colour = new Color(rgb, 1d);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructColorNullRgb()
{
Color colour = new Color(null);
}
[TestMethod]
public void ConstructColorInvalidAlpha()
{
int testCount = 0;
int exceptionCount = 0;
RgbAttribute rgb = new RgbAttribute(0, 0, 0);
double[] alphaTestValues = new double[] { -1, -0.0001, 1.00000001, 2 };
for (int i = 0; i < alphaTestValues.Length; i++)
{
testCount++;
try
{
Color colour = new Color(rgb, alphaTestValues[i]);
}
catch (ArgumentException)
{
exceptionCount++;
}
}
Assert.AreEqual(testCount, exceptionCount);
}
[TestMethod]
public void ToStringColor()
{
Assert.AreEqual("<color rgb=\"0 0 0\" alpha=\"0\"/>", new Color(new RgbAttribute(0, 0, 0), 0).ToString());
Assert.AreEqual("<color rgb=\"64 128 255\" alpha=\"0.5\"/>", new Color(new RgbAttribute(64, 128, 255), 0.5).ToString());
}
[TestMethod]
public void EqualsAndHash()
{
Color colour = new Color(new RgbAttribute(1, 2, 3));
Color same = new Color(new RgbAttribute(1, 2, 3), 1);
Color diff = new Color(new RgbAttribute(3, 2, 1));
Assert.IsTrue(colour.Equals(colour));
Assert.IsFalse(colour.Equals(null));
Assert.IsTrue(colour.Equals(same));
Assert.IsTrue(same.Equals(colour));
Assert.IsFalse(colour.Equals(diff));
Assert.AreEqual(colour.GetHashCode(), same.GetHashCode());
Assert.AreNotEqual(colour.GetHashCode(), diff.GetHashCode());
}
}
}
| {'content_hash': '25ba87efb0c31bba7a6a41b6946e3d2a', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 132, 'avg_line_length': 32.21111111111111, 'alnum_prop': 0.5394963780614005, 'repo_name': 'MangoMangoDevelopment/neptune', 'id': 'c5eb5c714059f3db4edc64b72ade73f95511e6f2', 'size': '2901', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/urdf/UrdfToUnityTest/Urdf/Models/Links/Visuals/ColorTest.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Awk', 'bytes': '640'}, {'name': 'Batchfile', 'bytes': '118'}, {'name': 'C', 'bytes': '80165'}, {'name': 'C#', 'bytes': '692379'}, {'name': 'C++', 'bytes': '1997489'}, {'name': 'CMake', 'bytes': '327588'}, {'name': 'EmberScript', 'bytes': '44956'}, {'name': 'GLSL', 'bytes': '9781'}, {'name': 'HTML', 'bytes': '12555'}, {'name': 'Makefile', 'bytes': '25846'}, {'name': 'Objective-C', 'bytes': '11275'}, {'name': 'Python', 'bytes': '4265203'}, {'name': 'Shell', 'bytes': '31793'}]} |
import { Component } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SprkPromoMediaDirective } from './sprk-promo-media.directive';
@Component({
selector: 'sprk-test',
template: `
<img sprkPromoMedia idString="test" />
<img sprkPromoMedia isFlag="true" />
`,
})
class TestComponent {}
describe('Spark Promo Media Directive', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let element0: HTMLElement;
let element1: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SprkPromoMediaDirective, TestComponent],
}).compileComponents();
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
element0 = fixture.nativeElement.querySelector('img');
element1 = fixture.nativeElement.querySelectorAll('img')[1];
}));
it('should create itself', () => {
expect(component).toBeTruthy();
});
it('should have the correct base class', () => {
expect(element0.classList.contains('sprk-c-Promo__image')).toBe(true);
expect(element1.classList.contains('sprk-c-Promo__image')).toBe(true);
});
it('should apply correct idString value to data-id', () => {
expect(element0.getAttribute('data-id') === 'test').toBe(true);
});
it('should apply correct class if isFlag is true', () => {
expect(element1.classList.contains('sprk-c-Promo__image--flag')).toBe(true);
});
it('should not apply flag media class if isFlag is false', () => {
expect(element0.classList.contains('sprk-c-Promo__image--flag')).toBe(
false,
);
});
it('should not apply data-id when idString is not set', () => {
expect(element1.getAttribute('data-id')).toBe(null);
});
});
| {'content_hash': '544c7db740ade458c46179c2bed34d54', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 80, 'avg_line_length': 31.152542372881356, 'alnum_prop': 0.6730141458106638, 'repo_name': 'sparkdesignsystem/spark-design-system', 'id': 'bcdaf62f4dc20fe5dcd4b51406fd0288952d26f4', 'size': '1838', 'binary': False, 'copies': '1', 'ref': 'refs/heads/staging', 'path': 'angular/projects/spark-angular/src/lib/components/sprk-promo/directives/sprk-promo-media/sprk-promo-media.directive.spec.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2975'}, {'name': 'JavaScript', 'bytes': '1750014'}, {'name': 'SCSS', 'bytes': '252142'}, {'name': 'Swift', 'bytes': '67467'}, {'name': 'TypeScript', 'bytes': '1283216'}]} |
/*
Include declarations.
*/
#include "magick/studio.h"
#include "magick/blob.h"
#include "magick/blob-private.h"
#include "magick/cache.h"
#include "magick/colorspace.h"
#include "magick/exception.h"
#include "magick/exception-private.h"
#include "magick/image.h"
#include "magick/image-private.h"
#include "magick/list.h"
#include "magick/magick.h"
#include "magick/memory_.h"
#include "magick/monitor.h"
#include "magick/monitor-private.h"
#include "magick/quantum-private.h"
#include "magick/static.h"
#include "magick/string_.h"
#include "magick/module.h"
/*
Forward declarations.
*/
static MagickBooleanType
WriteMGKImage(const ImageInfo *,Image *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% I s M G K %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% IsMGK() returns MagickTrue if the image format type, identified by the
% magick string, is MGK.
%
% The format of the IsMGK method is:
%
% MagickBooleanType IsMGK(const unsigned char *magick,const size_t length)
%
% A description of each parameter follows:
%
% o magick: This string is generally the first few bytes of an image file
% or blob.
%
% o length: Specifies the length of the magick string.
%
*/
static MagickBooleanType IsMGK(const unsigned char *magick,const size_t length)
{
if (length < 7)
return(MagickFalse);
if (LocaleNCompare((char *) magick,"id=mgk",7) == 0)
return(MagickTrue);
return(MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e a d M G K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ReadMGKImage() reads a MGK image file and returns it. It allocates
% the memory necessary for the new Image structure and returns a pointer to
% the new image.
%
% The format of the ReadMGKImage method is:
%
% Image *ReadMGKImage(const ImageInfo *image_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *ReadMGKImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
char
buffer[MaxTextExtent];
Image
*image;
MagickBooleanType
status;
register ssize_t
x;
register PixelPacket
*q;
register unsigned char
*p;
ssize_t
count,
y;
size_t
columns,
rows;
unsigned char
*pixels;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
image=AcquireImage(image_info);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MGK image.
*/
(void) ReadBlobString(image,buffer); /* read magic number */
if (IsMGK(buffer,7) == MagickFalse)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
(void) ReadBlobString(image,buffer);
count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows);
if (count <= 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
do
{
/*
Initialize image structure.
*/
image->columns=columns;
image->rows=rows;
image->depth=8;
if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0))
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Convert MGK raster image to pixel packets.
*/
if (SetImageExtent(image,0,0) == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
3UL*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (y=0; y < (ssize_t) image->rows; y++)
{
count=(ssize_t) ReadBlob(image,(size_t) (3*image->columns),pixels);
if (count != (ssize_t) (3*image->columns))
ThrowReaderException(CorruptImageError,"UnableToReadImageData");
p=pixels;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (PixelPacket *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
q->red=ScaleCharToQuantum(*p++);
q->green=ScaleCharToQuantum(*p++);
q->blue=ScaleCharToQuantum(*p++);
q++;
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if ((image->previous == (Image *) NULL) &&
(SetImageProgress(image,LoadImageTag,y,image->rows) == MagickFalse))
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
*buffer='\0';
(void) ReadBlobString(image,buffer);
count=(ssize_t) sscanf(buffer,"%lu %lu\n",&columns,&rows);
if (count > 0)
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
if (image->progress_monitor != (MagickProgressMonitor) NULL)
{
status=SetImageProgress(image,LoadImageTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
} while (count > 0);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% R e g i s t e r M G K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% RegisterMGKImage() adds attributes for the MGK image format to
% the list of supported formats. The attributes include the image format
% tag, a method to read and/or write the format, whether the format
% supports the saving of more than one frame to the same file or blob,
% whether the format supports native in-memory I/O, and a brief
% description of the format.
%
% The format of the RegisterMGKImage method is:
%
% size_t RegisterMGKImage(void)
%
*/
ModuleExport size_t RegisterMGKImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("MGK");
entry->decoder=(DecodeImageHandler *) ReadMGKImage;
entry->encoder=(EncodeImageHandler *) WriteMGKImage;
entry->magick=(IsImageFormatHandler *) IsMGK;
entry->description=ConstantString("MGK");
entry->module=ConstantString("MGK");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% U n r e g i s t e r M G K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% UnregisterMGKImage() removes format registrations made by the
% MGK module from the list of supported formats.
%
% The format of the UnregisterMGKImage method is:
%
% UnregisterMGKImage(void)
%
*/
ModuleExport void UnregisterMGKImage(void)
{
(void) UnregisterMagickInfo("MGK");
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% W r i t e M G K I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% WriteMGKImage() writes an image to a file in red, green, and blue
% MGK rasterfile format.
%
% The format of the WriteMGKImage method is:
%
% MagickBooleanType WriteMGKImage(const ImageInfo *image_info,
% Image *image)
%
% A description of each parameter follows.
%
% o image_info: the image info.
%
% o image: The image.
%
*/
static MagickBooleanType WriteMGKImage(const ImageInfo *image_info,
Image *image)
{
char
buffer[MaxTextExtent];
MagickBooleanType
status;
MagickOffsetType
scene;
register const PixelPacket
*p;
register ssize_t
x;
register unsigned char
*q;
ssize_t
y;
unsigned char
*pixels;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception);
if (status == MagickFalse)
return(status);
scene=0;
do
{
/*
Allocate memory for pixels.
*/
if (image->colorspace != RGBColorspace)
(void) SetImageColorspace(image,RGBColorspace);
pixels=(unsigned char *) AcquireQuantumMemory((size_t) image->columns,
3UL*sizeof(*pixels));
if (pixels == (unsigned char *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
/*
Initialize raster file header.
*/
(void) WriteBlobString(image,"id=mgk\n");
(void) FormatMagickString(buffer,MaxTextExtent,"%lu %lu\n",image->columns,
image->rows);
(void) WriteBlobString(image,buffer);
for (y=0; y < (ssize_t) image->rows; y++)
{
p=AcquireImagePixels(image,0,y,image->columns,1,&image->exception);
if (p == (const PixelPacket *) NULL)
break;
q=pixels;
for (x=0; x < (ssize_t) image->columns; x++)
{
*q++=ScaleQuantumToChar(GetRedSample(p));
*q++=ScaleQuantumToChar(GetGreenSample(p));
*q++=ScaleQuantumToChar(GetBlueSample(p));
p++;
}
(void) WriteBlob(image,(size_t) (q-pixels),pixels);
if ((image->previous == (Image *) NULL) &&
(SetImageProgress(image,SaveImageTag,y,image->rows) == MagickFalse))
break;
}
pixels=(unsigned char *) RelinquishMagickMemory(pixels);
if (GetNextImageInList(image) == (Image *) NULL)
break;
image=SyncNextImageInList(image);
status=SetImageProgress(image,SaveImagesTag,scene,
GetImageListLength(image));
if (status == MagickFalse)
break;
scene++;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(MagickTrue);
}
| {'content_hash': 'fcf05323b4132393903bf9d1a1c4a2cf', 'timestamp': '', 'source': 'github', 'line_count': 421, 'max_line_length': 79, 'avg_line_length': 32.090261282660336, 'alnum_prop': 0.4834937083641747, 'repo_name': 'mikesplain/imagemagick', 'id': '11754c007f1cde246fdedd39c6b19f6d60cfe1b9', 'size': '16159', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'www/source/mgk.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '15217768'}, {'name': 'C++', 'bytes': '659432'}, {'name': 'Perl', 'bytes': '218559'}, {'name': 'Shell', 'bytes': '373860'}]} |
# Building the SDK for Use in the Browser
This section explains how you can create your own build of the AWS SDK for
JavaScript. If you are working with the SDK outside of an environment that
enforces CORS in your browser and want access to the full gamut of services
provided by the **AWS SDK for JavaScript**, it is possible to build a custom
copy of the SDK locally by cloning the repository and running the same build
tools used to generate the default hosted version of the SDK. This chapter
outlines the steps to build the SDK on your own with extra services and API
versions.
## Setting Up
In order to build the SDK, you first need to clone the Git repository containing
the SDK source. These instructions assume you have [Git](http://git-scm.org) and
a version of [Node.js](http://nodejs.org) installed on your machine.
First, clone the repository from GitHub and cd into the directory:
```bash
git clone git://github.com/aws/aws-sdk-js
cd aws-sdk-js
```
After you have cloned the repository, you need to download the dependency modules
for both the SDK and build tool:
```bash
npm install --production && cd dist-tools && npm install --production && cd ..
```
You should now be able to build a packaged version of the SDK.
## Building
The builder tool is found in `dist-tools/browser-builder.js`. You can run
this script by typing:
```bash
node dist-tools/browser-builder.js > aws-sdk.js
```
This will build to the file `aws-sdk.js`. By default this package includes
only the services documented in the {file:browser-services.md Working With Services}
chapter. Building custom services is discussed later in this chapter. Note
also that by default, this file is uncompressed.
### Minifying Output
The builder tool can also compress output. To do this, set the `MINIFY`
environment variable like so:
```bash
MINIFY=1 node dist-tools/browser-builder.js > aws-sdk.js
```
### Building Specific Services and API Versions
#### Selecting Services to Build
When building via the builder tool, you can select which services you want to
build into the SDK. To select services, specify the names of the services
delimited by commas as arguments to the tool on the command-line. For example,
to build only Amazon S3 and Amazon EC2, use the following command:
```bash
node dist-tools/browser-builder.js s3,ec2 > aws-sdk-s3-ec2.js
```
#### Selecting API Versions
You can also select specific API versions of services when building
by suffixing the version name after the service identifier. For example, to
build both API versions of Amazon DynamoDB, you could use the following
command:
```bash
node dist-tools/browser-builder.js dynamodb-2011-12-05,dynamodb-2012-08-10
```
Available service identifiers and API versions can be found by looking at the
file list in https://github.com/aws/aws-sdk-js/tree/master/lib/services/api
#### Building All Services
Finally, you can build **all services** (and API versions) by passing "all"
as a command-line argument:
```bash
node dist-tools/browser-builder.js all > aws-sdk-full.js
```
## The Build Server
The `dist-tools` directory also comes with a utility server that can bundle
and serve the SDK over HTTP. To launch the server, type:
```bash
node dist-tools/server.js
```
You can then access a bundled version of the SDK by hitting either:
```no-highlight
http://localhost:8080/aws-sdk.js
```
or
```no-highlight
http://localhost:8080/aws-sdk.min.js
```
For the uncompressed or compressed versions.
### Loading Specific Services
The build server can also bundle custom services by accepting a query string
to the respecitve bundle URLs with the services and API versions to be used.
The syntax for this is the same as the builder tool syntax on the command-line,
but you can also use a conventional query string syntax. An example to load
the DynamoDB 2011-12-05 API version and latest S3 service would look like:
```no-highlight
http://localhost:8080/aws-sdk.min.js?dynamodb=2011-12-05&s3
```
| {'content_hash': '510619fc62d8c483468c9bcb4d83d712', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 84, 'avg_line_length': 32.29133858267716, 'alnum_prop': 0.7405510851011948, 'repo_name': 'brucewar/poem', 'id': 'ec7176d1041615f6093e2f9dbad07a8db66a7758', 'size': '4144', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Infrastructure/BackEnd/node_modules/aliyun-sdk/doc-src/guide/browser-building.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '72407'}, {'name': 'Shell', 'bytes': '1516'}]} |
a website placeholder
| {'content_hash': '0578720af94cf1180f8dda5d0a39c02b', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 21, 'avg_line_length': 22.0, 'alnum_prop': 0.8636363636363636, 'repo_name': 'clanker/clanker.github.io', 'id': '299d93329ad943a70a6ccb11e6626125dd7341ef', 'size': '42', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7090'}, {'name': 'HTML', 'bytes': '3985'}, {'name': 'JavaScript', 'bytes': '536'}]} |
namespace chrono {
/// @addtogroup chrono_functions
/// @{
/// Constant acceleration function:
///
/// h = height, amount of displacement
/// end = duration of motion,
/// av = fraction of 1st acceleration end (0..1)
/// aw = fraction of 2nd acceleration start (0..1) , with aw>av;
class ChApi ChFunction_ConstAcc : public ChFunction {
private:
double h;
double av;
double aw;
double end;
public:
ChFunction_ConstAcc() : h(1), av(0.5), aw(0.5), end(1) {}
ChFunction_ConstAcc(double m_h, double m_av, double m_aw, double m_end);
ChFunction_ConstAcc(const ChFunction_ConstAcc& other);
~ChFunction_ConstAcc() {}
/// "Virtual" copy constructor (covariant return type).
virtual ChFunction_ConstAcc* Clone() const override { return new ChFunction_ConstAcc(*this); }
virtual FunctionType Get_Type() const override { return FUNCT_CONSTACC; }
virtual double Get_y(double x) const override;
virtual double Get_y_dx(double x) const override;
virtual double Get_y_dxdx(double x) const override;
void Set_end(double m_end) {
if (m_end < 0)
m_end = 0;
end = m_end;
}
void Set_av(double m_av) {
if (m_av < 0)
m_av = 0;
if (m_av > 1)
m_av = 1;
av = m_av;
if (av > aw)
av = aw;
}
void Set_aw(double m_aw) {
if (m_aw < 0)
m_aw = 0;
if (m_aw > 1)
m_aw = 1;
aw = m_aw;
if (aw < av)
aw = av;
}
void Set_h(double m_h) { h = m_h; }
void Set_avw(double m_av, double m_aw) {
av = 0;
aw = 1;
Set_av(m_av);
Set_aw(m_aw);
}
double Get_end() const { return end; }
double Get_av() const { return av; }
double Get_aw() const { return aw; }
double Get_h() const { return h; }
virtual double Get_Ca_pos() const override;
virtual double Get_Ca_neg() const override;
virtual double Get_Cv() const override;
virtual void Estimate_x_range(double& xmin, double& xmax) const override {
xmin = 0.0;
xmax = end;
}
/// Method to allow serialization of transient data to archives.
virtual void ArchiveOUT(ChArchiveOut& marchive) override;
/// Method to allow de-serialization of transient data from archives.
virtual void ArchiveIN(ChArchiveIn& marchive) override;
};
/// @} chrono_functions
CH_CLASS_VERSION(ChFunction_ConstAcc, 0)
} // end namespace chrono
#endif
| {'content_hash': '25412b4147514e0b24babbda0257f007', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 98, 'avg_line_length': 27.010752688172044, 'alnum_prop': 0.5851910828025477, 'repo_name': 'projectchrono/chrono', 'id': 'f24f254a2ac4a33ce6411dfdd3cf1b40750168e8', 'size': '3221', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'src/chrono/motion_functions/ChFunction_ConstAcc.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '7614'}, {'name': 'C', 'bytes': '2409870'}, {'name': 'C++', 'bytes': '26511084'}, {'name': 'CMake', 'bytes': '645492'}, {'name': 'CSS', 'bytes': '170326'}, {'name': 'Cuda', 'bytes': '1226094'}, {'name': 'Dockerfile', 'bytes': '3279'}, {'name': 'GLSL', 'bytes': '4925'}, {'name': 'HTML', 'bytes': '7922'}, {'name': 'Inno Setup', 'bytes': '24125'}, {'name': 'JavaScript', 'bytes': '4731'}, {'name': 'Lex', 'bytes': '3433'}, {'name': 'Lua', 'bytes': '651'}, {'name': 'POV-Ray SDL', 'bytes': '25421'}, {'name': 'PowerShell', 'bytes': '142'}, {'name': 'Python', 'bytes': '645743'}, {'name': 'SWIG', 'bytes': '317316'}, {'name': 'Shell', 'bytes': '4827'}]} |
using System;
using System.Collections.Generic;
using System.Xml;
namespace Sharp.Xmpp.Extensions.Dataforms {
/// <summary>
/// Represents a field that is intended to be invisible to the form-submitting
/// entity, and is returned with the form.
/// </summary>
/// <remarks>
/// Hidden fields should not be shown to the user but just be submitted with
/// the form, much like a hidden field in an HTML form.
/// </remarks>
public class HiddenField : DataField {
/// <summary>
/// The values of the field.
/// </summary>
XmlCollection<string> values;
/// <summary>
/// Gets an enumerable collection of values set on the field.
/// </summary>
public new ICollection<string> Values {
get {
return values;
}
}
/// <summary>
/// Initializes a new instance of the HiddenField class for use in a
/// requesting dataform.
/// </summary>
/// <param name="name">The name of the field.</param>
/// <param name="required">Determines whether the field is required or
/// optional.</param>
/// <param name="label">A human-readable name for the field.</param>
/// <param name="description">A natural-language description of the field,
/// intended for presentation in a user-agent.</param>
/// <param name="values">The default values of the field.</param>
/// <exception cref="ArgumentNullException">The name parameter is
/// null.</exception>
public HiddenField(string name, bool required = false, string label = null,
string description = null, params string[] values)
: base(DataFieldType.Hidden, name, required, label, description) {
this.values = new XmlCollection<string>(element, "value", elem => elem.InnerText);
if (values != null) {
foreach (string s in values) {
if (s == null)
continue;
this.values.Add(s);
}
}
}
/// <summary>
/// Initializes a new instance of the HiddenField class for use in a
/// submitting dataform.
/// </summary>
/// <param name="name">The name of the field.</param>
/// <param name="values">The values of the field.</param>
/// <exception cref="ArgumentNullException">The name parameter is
/// null.</exception>
public HiddenField(string name, params string[] values)
: this(name, false, null, null, values) {
}
/// <summary>
/// Initializes a new instance of the HiddenField class from the specified
/// XML element.
/// </summary>
/// <param name="element">The XML 'field' element to initialize the instance
/// with.</param>
/// <exception cref="ArgumentNullException">The element parameter is
/// null.</exception>
/// <exception cref="ArgumentException">The specified XML element is not a
/// valid data-field element, or the element is not a data-field of type
/// 'hidden'.</exception>
internal HiddenField(XmlElement element)
: base(element) {
AssertType(DataFieldType.Hidden);
}
}
} | {'content_hash': 'edd06395d1eb51e9ebd2742f4a425a3e', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 86, 'avg_line_length': 35.21951219512195, 'alnum_prop': 0.671398891966759, 'repo_name': 'rmoorman/Sharp.Xmpp', 'id': '0d19752990eab3843f1fc03ab1ca3413f8d5dc56', 'size': '2890', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Extensions/XEP-0004/Dataforms/HiddenField.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '765739'}]} |
using System;
using System.Text;
using System.Security.Permissions;
using System.Runtime.Serialization;
using OpenADK.Library;
using OpenADK.Library.Global;
namespace OpenADK.Library.au.Common{
/// <summary>An OtherCodeList</summary>
/// <remarks>
///
/// <para>Author: Generated by adkgen</para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.0</para>
/// </remarks>
[Serializable]
public class OtherCodeList : SifKeyedList<OtherCode>
{
/// <summary>
/// Creates an instance of an OtherCodeList
/// </summary>
public OtherCodeList() : base ( CommonDTD.OTHERCODELIST ){}
/// <summary>
/// Constructor that accepts values for all mandatory fields
/// </summary>
///<param name="otherCode">A state/province code, local code, other code or a text string
/// that crosswalks to or serves as a translation of an associated Code
/// element.</param>
///
public OtherCodeList( OtherCode otherCode ) : base( CommonDTD.OTHERCODELIST )
{
this.SafeAddChild( CommonDTD.OTHERCODELIST_OTHERCODE, otherCode );
}
/// <summary>
/// Constructor used by the .Net Serialization formatter
/// </summary>
[SecurityPermission( SecurityAction.Demand, SerializationFormatter=true )]
protected OtherCodeList( SerializationInfo info, StreamingContext context ) : base( info, context ) {}
///<summary>Adds the value of the <c><OtherCode></c> element.</summary>
/// <param name="Codeset">Describes the OtherCode element content as either a
/// state/province code, a local code, other code, or text string.</param>
/// <param name="Value">Gets or sets the content value of the &lt;OtherCode&gt; element</param>
///<remarks>
/// <para>This form of <c>setOtherCode</c> is provided as a convenience method
/// that is functionally equivalent to the method <c>AddOtherCode</c></para>
/// <para>Version: 2.6</para>
/// <para>Since: 2.0</para>
/// </remarks>
public void AddOtherCode( Codeset Codeset, string Value ) {
AddChild( CommonDTD.OTHERCODELIST_OTHERCODE, new OtherCode( Codeset, Value ) );
}
}}
| {'content_hash': '609efa843d57e8fd09869ad52b30ca0b', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 104, 'avg_line_length': 36.19642857142857, 'alnum_prop': 0.715836211149482, 'repo_name': 'open-adk/OpenADK-csharp', 'id': '4513ddd86f05aec6e2e82d3888bbc7e0510eeb64', 'size': '2190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/au/sdo/Common/OtherCodeList.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '16903092'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '9853da23ce579e27be5ef0ea227de296', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'c62927474e16a45d842b3e6ae37775508ed08b6b', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia torralbasii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
import React from 'react';
import ReactDOM from 'react-dom/server';
import path from 'path';
import Html from '../../src/helpers/Html';
// import { Provider } from 'react-redux';
// import { createMemoryHistory } from 'history';
// import { StaticRouter } from 'react-router';
// import { syncHistoryWithStore } from 'react-router-redux';
// import createStore from '../../src/redux/createStore';
// import APIClient from '../../src/helpers/APIClient';
// import Html from '../../src/helpers/Html';
// import App from '../../src/containers/App';
// import routes from '../../src/routes';
const serverRouteMidlleware = () => (req, res, next) => {
// const filename = path.resolve('../../dist/', 'index.html');
// res.send(`<!doctype html>${ ReactDOM.renderToString(<Html />) }`);
// const memoryHistory = createMemoryHistory();
// const client = new APIClient(req);
// const store = createStore(history, client);
// const history = syncHistoryWithStore(memoryHistory, store);
// const context = {};
// const component = (
// <Provider store={store} key="provider" >
// <StaticRouter history={history} location={req.url} context={context}>
// <App>
// { routes(store) }
// </App>
// </StaticRouter>
// </Provider>
// );
// if (context.url) {
// res.writeHead(302, {
// Location: context.url
// });
// } else {
// res.send(`<!doctype html>${ ReactDOM.renderToString(<Html store={store} component={component} />) }`);
// }
res.end();
}
export default serverRouteMidlleware;
| {'content_hash': 'fe55914400cacef920451048dd4679ac', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 107, 'avg_line_length': 32.40425531914894, 'alnum_prop': 0.6382140512147079, 'repo_name': 'WCCrazyCoder/react-redux-web-application', 'id': '3df96c5791565f24e876acd523522d8211d89d81', 'size': '1523', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/middleware/serverRouteMiddleware.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '88'}, {'name': 'HTML', 'bytes': '247'}, {'name': 'JavaScript', 'bytes': '18385'}]} |
package com.taobao.tddl.qatest.matrix.join;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;
import com.taobao.tddl.qatest.BaseMatrixTestCase;
import com.taobao.tddl.qatest.BaseTestCase;
import com.taobao.tddl.qatest.ExecuteTableName;
import com.taobao.tddl.qatest.util.EclipseParameterized;
/**
* inner left right 三种不同join类型
*
* @author zhuoxue
* @since 5.0.1
*/
@RunWith(EclipseParameterized.class)
public class JoinAndTest extends BaseMatrixTestCase {
String[] columnParam = { "host_id", "host_name", "hostgroup_id", "hostgroup_name" };
String[] joinType = { "inner", "left", "right" };
String[] innerJoin = { "inner" };
String[] leftJoin = { "left" };
String sql = null;
String hint = "";
@Parameters(name = "{index}:table0={0},table1={1},table2={2},table3={3},table4={4}")
public static List<String[]> prepareDate() {
return Arrays.asList(ExecuteTableName.hostinfoHostgoupStudentModuleinfoModulehostTable(dbType));
}
public JoinAndTest(String monitor_host_infoTableName, String monitor_hostgroup_infoTableName,
String studentTableName, String monitor_module_infoTableName, String monitor_module_hostTableName)
throws Exception{
BaseTestCase.host_info = monitor_host_infoTableName;
BaseTestCase.hostgroup_info = monitor_hostgroup_infoTableName;
BaseTestCase.studentTableName = studentTableName;
BaseTestCase.module_info = monitor_module_infoTableName;
BaseTestCase.module_host = monitor_module_hostTableName;
initData();
}
public void initData() throws Exception {
//
hostinfoPrepare(0, 100);
hostgroupInfoPrepare(50, 200);
module_infoPrepare(0, 40);
module_hostPrepare(1, 80);
studentPrepare(65, 80);
}
@After
public void destory() throws Exception {
psConRcRsClose(rc, rs);
}
/**
* 两表join on后面带and连接
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void AndTest() throws Exception {
for (int i = 0; i < joinType.length; i++) {
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id and "
+ host_info + ".host_id=52 where " + hostgroup_info + ".hostgroup_id=52";
if (!host_info.contains("oneGroup_oneAtom")) sql = hint + sql;
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
/**
* 两表join 条件为针对num类型的过滤
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void AndNumFiledTest() throws Exception {
for (int i = 0; i < innerJoin.length; i++) {
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id where "
+ host_info + ".host_id=52";
// if (!host_info.contains("oneGroup_oneAtom"))
// sql = hint+sql;
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id where "
+ host_info + ".host_id>80";
// if (!host_info.contains("oneGroup_oneAtom"))
// sql = hint+sql;
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
/**
* 两表join 条件为针对String类型的过滤
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void StringFieldTest() throws Exception {
for (int i = 0; i < innerJoin.length; i++) {
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id"
+ " where " + host_info + ".host_name='hostname90'";
if (!host_info.contains("oneGroup_oneAtom")) sql = hint + sql;
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
/**
* 三表join 条件中有and 和 or
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void ThreeTableWithAndWithOr() throws Exception {
for (int i = 0; i < joinType.length; i++) {
sql = "SELECT * from " + host_info + " a " + joinType[i] + " JOIN " + host_info
+ " b ON a.host_id=b.host_id " + joinType[i] + " JOIN " + host_info
+ " c ON b.host_id=c.host_id and b.host_id=1 and c.host_id=1 where a.host_id=1";
if (!host_info.contains("oneGroup_oneAtom")) sql = hint + sql;
String[] columnParam = { "host_id", "host_name" };
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
/**
* 两表join 条件中为带and的过滤 and两边为不同的字段
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void AndAndTest() throws Exception {
for (int i = 0; i < innerJoin.length; i++) {
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id where "
+ host_info + ".host_name='hostname80' and " + hostgroup_info + ".hostgroup_name='hostgroupname80'";
if (!host_info.contains("oneGroup_oneAtom")) sql = hint + sql;
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
/**
* 两表join 条件中为带and的过滤 and两边为相同的字段
*
* @author zhuoxue
* @since 5.0.1
*/
@Test
public void AndAndSameFiledTest() throws Exception {
for (int i = 0; i < innerJoin.length; i++) {
sql = "select " + host_info + ".host_id," + "" + host_info + ".host_name," + host_info + ".hostgroup_id,"
+ hostgroup_info + ".hostgroup_name " + "from " + hostgroup_info + " " + joinType[i] + " join "
+ host_info + " " + "on " + host_info + ".hostgroup_id=" + hostgroup_info + ".hostgroup_id where "
+ hostgroup_info + ".hostgroup_id>20 and " + hostgroup_info + ".hostgroup_id<80";
if (!host_info.contains("oneGroup_oneAtom")) {
sql = hint + sql;
}
selectContentSameAssert(sql, columnParam, Collections.EMPTY_LIST);
}
}
}
| {'content_hash': '005e1c9c96b422fe63980ac5cc685690', 'timestamp': '', 'source': 'github', 'line_count': 182, 'max_line_length': 138, 'avg_line_length': 41.98351648351648, 'alnum_prop': 0.5534615887972778, 'repo_name': 'xloye/tddl5', 'id': 'e39427c569acb1ba1aba688e59d4ef7113773c14', 'size': '7801', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tddl-qatest/src/test/java/com/taobao/tddl/qatest/matrix/join/JoinAndTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2238'}, {'name': 'CSS', 'bytes': '23992'}, {'name': 'Java', 'bytes': '9099464'}, {'name': 'JavaScript', 'bytes': '140331'}, {'name': 'Shell', 'bytes': '10381'}]} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
</head>
<body onload="prettyPrint();">
<pre class="prettyprint lang-js">
<div id="cls-Ext.FlashProxy"></div>/**
* @class Ext.FlashProxy
* @singleton
*/
Ext.FlashEventProxy = {
onEvent : function(id, e){
var fp = Ext.getCmp(id);
if(fp){
fp.onFlashEvent(e);
}else{
arguments.callee.defer(10, this, [id, e]);
}
}
};</pre>
</body>
</html> | {'content_hash': '0321ca0b0a7a7362b1ea0fca8b4421ba', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 87, 'avg_line_length': 28.24, 'alnum_prop': 0.5906515580736544, 'repo_name': 'DeepLit/WHG', 'id': '3aa682d8a2bfb42b3e91efc4f69d343eed2ac98e', 'size': '831', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'root/static/js/ext/docs/source/EventProxy.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1196605'}, {'name': 'Erlang', 'bytes': '903'}, {'name': 'JavaScript', 'bytes': '25870737'}, {'name': 'PHP', 'bytes': '527568'}, {'name': 'Perl', 'bytes': '165888'}, {'name': 'Perl6', 'bytes': '1291'}, {'name': 'Ruby', 'bytes': '11908'}, {'name': 'Shell', 'bytes': '4443'}]} |
package org.sample;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;
/**
* Application object for your web application.
* If you want to run this application without deploying, run the Start class.
*
* @see org.sample.Start#main(String[])
*/
public class WicketApplication extends WebApplication
{
/**
* @see org.apache.wicket.Application#getHomePage()
*/
@Override
public Class<? extends WebPage> getHomePage()
{
return HomePage.class;
}
/**
* @see org.apache.wicket.Application#init()
*/
@Override
public void init()
{
super.init();
// add your configuration here
}
}
| {'content_hash': '1299736dcb54c832fc4cea59ef59667a', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 78, 'avg_line_length': 19.87878787878788, 'alnum_prop': 0.711890243902439, 'repo_name': 'MadasamySankarapandian/select2-bug-quickstart', 'id': '1d46b5305cbfb2048f1ea7d88ce53484c0ca34c2', 'size': '656', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/sample/WicketApplication.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1312'}, {'name': 'Java', 'bytes': '8173'}]} |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>ActiveRecord::ConnectionAdapters::PostgreSQLColumn::Cast</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../../css/github.css" type="text/css" media="screen" />
<script src="../../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.1.8</span><br />
<h1>
<span class="type">Module</span>
ActiveRecord::ConnectionAdapters::PostgreSQLColumn::Cast
</h1>
<ul class="files">
<li><a href="../../../../files/__/__/__/__/usr/local/share/gems/gems/activerecord-4_1_8/lib/active_record/connection_adapters/postgresql/cast_rb.html">/usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>A</dt>
<dd>
<ul>
<li>
<a href="#method-i-array_to_string">array_to_string</a>
</li>
</ul>
</dd>
<dt>C</dt>
<dd>
<ul>
<li>
<a href="#method-i-cidr_to_string">cidr_to_string</a>
</li>
</ul>
</dd>
<dt>H</dt>
<dd>
<ul>
<li>
<a href="#method-i-hstore_to_string">hstore_to_string</a>
</li>
</ul>
</dd>
<dt>J</dt>
<dd>
<ul>
<li>
<a href="#method-i-json_to_string">json_to_string</a>
</li>
</ul>
</dd>
<dt>P</dt>
<dd>
<ul>
<li>
<a href="#method-i-point_to_string">point_to_string</a>
</li>
</ul>
</dd>
<dt>R</dt>
<dd>
<ul>
<li>
<a href="#method-i-range_to_string">range_to_string</a>
</li>
</ul>
</dd>
<dt>S</dt>
<dd>
<ul>
<li>
<a href="#method-i-string_to_array">string_to_array</a>,
</li>
<li>
<a href="#method-i-string_to_bit">string_to_bit</a>,
</li>
<li>
<a href="#method-i-string_to_cidr">string_to_cidr</a>,
</li>
<li>
<a href="#method-i-string_to_hstore">string_to_hstore</a>,
</li>
<li>
<a href="#method-i-string_to_json">string_to_json</a>,
</li>
<li>
<a href="#method-i-string_to_point">string_to_point</a>,
</li>
<li>
<a href="#method-i-string_to_time">string_to_time</a>
</li>
</ul>
</dd>
</dl>
<!-- Section constants -->
<div class="sectiontitle">Constants</div>
<table border='0' cellpadding='5'>
<tr valign='top'>
<td class="attr-name">HstorePair</td>
<td>=</td>
<td class="attr-value">begin
quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/
unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/
/(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/
end</td>
</tr>
<tr valign='top'>
<td> </td>
<td colspan="2" class="attr-desc"></td>
</tr>
<tr valign='top'>
<td class="attr-name">ARRAY_ESCAPE</td>
<td>=</td>
<td class="attr-value">"\\" * 2 * 2</td>
</tr>
<tr valign='top'>
<td> </td>
<td colspan="2" class="attr-desc"></td>
</tr>
</table>
<!-- Methods -->
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-array_to_string">
<b>array_to_string</b>(value, column, adapter)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-array_to_string" name="method-i-array_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-array_to_string_source')" id="l_method-i-array_to_string_source">show</a>
</p>
<div id="method-i-array_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 70</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">array_to_string</span>(<span class="ruby-identifier">value</span>, <span class="ruby-identifier">column</span>, <span class="ruby-identifier">adapter</span>)
<span class="ruby-identifier">casted_values</span> = <span class="ruby-identifier">value</span>.<span class="ruby-identifier">map</span> <span class="ruby-keyword">do</span> <span class="ruby-operator">|</span><span class="ruby-identifier">val</span><span class="ruby-operator">|</span>
<span class="ruby-keyword">if</span> <span class="ruby-constant">String</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">val</span>
<span class="ruby-keyword">if</span> <span class="ruby-identifier">val</span> <span class="ruby-operator">==</span> <span class="ruby-string">"NULL"</span>
<span class="ruby-node">"\"#{val}\""</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">quote_and_escape</span>(<span class="ruby-identifier">adapter</span>.<span class="ruby-identifier">type_cast</span>(<span class="ruby-identifier">val</span>, <span class="ruby-identifier">column</span>, <span class="ruby-keyword">true</span>))
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">adapter</span>.<span class="ruby-identifier">type_cast</span>(<span class="ruby-identifier">val</span>, <span class="ruby-identifier">column</span>, <span class="ruby-keyword">true</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span>
<span class="ruby-node">"{#{casted_values.join(',')}}"</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-cidr_to_string">
<b>cidr_to_string</b>(object)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-cidr_to_string" name="method-i-cidr_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-cidr_to_string_source')" id="l_method-i-cidr_to_string_source">show</a>
</p>
<div id="method-i-cidr_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 113</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">cidr_to_string</span>(<span class="ruby-identifier">object</span>)
<span class="ruby-keyword">if</span> <span class="ruby-constant">IPAddr</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">object</span>
<span class="ruby-node">"#{object.to_s}/#{object.instance_variable_get(:@mask_addr).to_s(2).count('1')}"</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">object</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-hstore_to_string">
<b>hstore_to_string</b>(object, array_member = false)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-hstore_to_string" name="method-i-hstore_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-hstore_to_string_source')" id="l_method-i-hstore_to_string_source">show</a>
</p>
<div id="method-i-hstore_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 38</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">hstore_to_string</span>(<span class="ruby-identifier">object</span>, <span class="ruby-identifier">array_member</span> = <span class="ruby-keyword">false</span>)
<span class="ruby-keyword">if</span> <span class="ruby-constant">Hash</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">object</span>
<span class="ruby-identifier">string</span> = <span class="ruby-identifier">object</span>.<span class="ruby-identifier">map</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">k</span>, <span class="ruby-identifier">v</span><span class="ruby-operator">|</span> <span class="ruby-node">"#{escape_hstore(k)}=>#{escape_hstore(v)}"</span> }.<span class="ruby-identifier">join</span>(<span class="ruby-string">','</span>)
<span class="ruby-identifier">string</span> = <span class="ruby-identifier">escape_hstore</span>(<span class="ruby-identifier">string</span>) <span class="ruby-keyword">if</span> <span class="ruby-identifier">array_member</span>
<span class="ruby-identifier">string</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">object</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-json_to_string">
<b>json_to_string</b>(object)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-json_to_string" name="method-i-json_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-json_to_string_source')" id="l_method-i-json_to_string_source">show</a>
</p>
<div id="method-i-json_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 62</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">json_to_string</span>(<span class="ruby-identifier">object</span>)
<span class="ruby-keyword">if</span> <span class="ruby-constant">Hash</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">object</span> <span class="ruby-operator">||</span> <span class="ruby-constant">Array</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">object</span>
<span class="ruby-constant">ActiveSupport</span><span class="ruby-operator">::</span><span class="ruby-constant">JSON</span>.<span class="ruby-identifier">encode</span>(<span class="ruby-identifier">object</span>)
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">object</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-point_to_string">
<b>point_to_string</b>(point)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-point_to_string" name="method-i-point_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-point_to_string_source')" id="l_method-i-point_to_string_source">show</a>
</p>
<div id="method-i-point_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 5</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">point_to_string</span>(<span class="ruby-identifier">point</span>)
<span class="ruby-node">"(#{point[0]},#{point[1]})"</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-range_to_string">
<b>range_to_string</b>(object)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-range_to_string" name="method-i-range_to_string" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-range_to_string_source')" id="l_method-i-range_to_string_source">show</a>
</p>
<div id="method-i-range_to_string_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 85</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">range_to_string</span>(<span class="ruby-identifier">object</span>)
<span class="ruby-identifier">from</span> = <span class="ruby-identifier">object</span>.<span class="ruby-identifier">begin</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:infinite?</span>) <span class="ruby-operator">&&</span> <span class="ruby-identifier">object</span>.<span class="ruby-identifier">begin</span>.<span class="ruby-identifier">infinite?</span> <span class="ruby-operator">?</span> <span class="ruby-string">''</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">object</span>.<span class="ruby-identifier">begin</span>
<span class="ruby-identifier">to</span> = <span class="ruby-identifier">object</span>.<span class="ruby-identifier">end</span>.<span class="ruby-identifier">respond_to?</span>(<span class="ruby-value">:infinite?</span>) <span class="ruby-operator">&&</span> <span class="ruby-identifier">object</span>.<span class="ruby-identifier">end</span>.<span class="ruby-identifier">infinite?</span> <span class="ruby-operator">?</span> <span class="ruby-string">''</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">object</span>.<span class="ruby-identifier">end</span>
<span class="ruby-node">"[#{from},#{to}#{object.exclude_end? ? ')' : ']'}"</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_array">
<b>string_to_array</b>(string, oid)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_array" name="method-i-string_to_array" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_array_source')" id="l_method-i-string_to_array_source">show</a>
</p>
<div id="method-i-string_to_array_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 121</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_array</span>(<span class="ruby-identifier">string</span>, <span class="ruby-identifier">oid</span>)
<span class="ruby-identifier">parse_pg_array</span>(<span class="ruby-identifier">string</span>).<span class="ruby-identifier">map</span> {<span class="ruby-operator">|</span><span class="ruby-identifier">val</span><span class="ruby-operator">|</span> <span class="ruby-identifier">type_cast_array</span>(<span class="ruby-identifier">oid</span>, <span class="ruby-identifier">val</span>)}
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_bit">
<b>string_to_bit</b>(value)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_bit" name="method-i-string_to_bit" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_bit_source')" id="l_method-i-string_to_bit_source">show</a>
</p>
<div id="method-i-string_to_bit_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 29</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_bit</span>(<span class="ruby-identifier">value</span>)
<span class="ruby-keyword">case</span> <span class="ruby-identifier">value</span>
<span class="ruby-keyword">when</span> <span class="ruby-regexp">/^0x/i</span>
<span class="ruby-identifier">value</span>[<span class="ruby-number">2</span><span class="ruby-operator">..</span><span class="ruby-number">-1</span>].<span class="ruby-identifier">hex</span>.<span class="ruby-identifier">to_s</span>(<span class="ruby-number">2</span>) <span class="ruby-comment"># Hexadecimal notation</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">value</span> <span class="ruby-comment"># Bit-string notation</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_cidr">
<b>string_to_cidr</b>(string)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_cidr" name="method-i-string_to_cidr" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_cidr_source')" id="l_method-i-string_to_cidr_source">show</a>
</p>
<div id="method-i-string_to_cidr_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 99</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_cidr</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">if</span> <span class="ruby-identifier">string</span>.<span class="ruby-identifier">nil?</span>
<span class="ruby-keyword">nil</span>
<span class="ruby-keyword">elsif</span> <span class="ruby-constant">String</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">string</span>
<span class="ruby-keyword">begin</span>
<span class="ruby-constant">IPAddr</span>.<span class="ruby-identifier">new</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">rescue</span> <span class="ruby-constant">ArgumentError</span>
<span class="ruby-keyword">nil</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">string</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_hstore">
<b>string_to_hstore</b>(string)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_hstore" name="method-i-string_to_hstore" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_hstore_source')" id="l_method-i-string_to_hstore_source">show</a>
</p>
<div id="method-i-string_to_hstore_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 48</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_hstore</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">if</span> <span class="ruby-identifier">string</span>.<span class="ruby-identifier">nil?</span>
<span class="ruby-keyword">nil</span>
<span class="ruby-keyword">elsif</span> <span class="ruby-constant">String</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">string</span>
<span class="ruby-constant">Hash</span>[<span class="ruby-identifier">string</span>.<span class="ruby-identifier">scan</span>(<span class="ruby-constant">HstorePair</span>).<span class="ruby-identifier">map</span> { <span class="ruby-operator">|</span><span class="ruby-identifier">k</span>, <span class="ruby-identifier">v</span><span class="ruby-operator">|</span>
<span class="ruby-identifier">v</span> = <span class="ruby-identifier">v</span>.<span class="ruby-identifier">upcase</span> <span class="ruby-operator">==</span> <span class="ruby-string">'NULL'</span> <span class="ruby-operator">?</span> <span class="ruby-keyword">nil</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">v</span>.<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/\A"(.*)"\Z/m</span>,<span class="ruby-string">'\1'</span>).<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/\(.)/</span>, <span class="ruby-string">'\1'</span>)
<span class="ruby-identifier">k</span> = <span class="ruby-identifier">k</span>.<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/\A"(.*)"\Z/m</span>,<span class="ruby-string">'\1'</span>).<span class="ruby-identifier">gsub</span>(<span class="ruby-regexp">/\(.)/</span>, <span class="ruby-string">'\1'</span>)
[<span class="ruby-identifier">k</span>, <span class="ruby-identifier">v</span>]
}]
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">string</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_json">
<b>string_to_json</b>(string)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_json" name="method-i-string_to_json" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_json_source')" id="l_method-i-string_to_json_source">show</a>
</p>
<div id="method-i-string_to_json_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 91</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_json</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">if</span> <span class="ruby-constant">String</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">string</span>
<span class="ruby-constant">ActiveSupport</span><span class="ruby-operator">::</span><span class="ruby-constant">JSON</span>.<span class="ruby-identifier">decode</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">else</span>
<span class="ruby-identifier">string</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_point">
<b>string_to_point</b>(string)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_point" name="method-i-string_to_point" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_point_source')" id="l_method-i-string_to_point_source">show</a>
</p>
<div id="method-i-string_to_point_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 9</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_point</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">if</span> <span class="ruby-identifier">string</span>[<span class="ruby-number">0</span>] <span class="ruby-operator">==</span> <span class="ruby-string">'('</span> <span class="ruby-operator">&&</span> <span class="ruby-identifier">string</span>[<span class="ruby-number">-1</span>] <span class="ruby-operator">==</span> <span class="ruby-string">')'</span>
<span class="ruby-identifier">string</span> = <span class="ruby-identifier">string</span>[<span class="ruby-number">1</span><span class="ruby-operator">...</span><span class="ruby-number">-1</span>]
<span class="ruby-keyword">end</span>
<span class="ruby-identifier">string</span>.<span class="ruby-identifier">split</span>(<span class="ruby-string">','</span>).<span class="ruby-identifier">map</span>{ <span class="ruby-operator">|</span><span class="ruby-identifier">v</span><span class="ruby-operator">|</span> <span class="ruby-constant">Float</span>(<span class="ruby-identifier">v</span>) }
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="method-i-string_to_time">
<b>string_to_time</b>(string)
<a href="../../../../classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html#method-i-string_to_time" name="method-i-string_to_time" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('method-i-string_to_time_source')" id="l_method-i-string_to_time_source">show</a>
</p>
<div id="method-i-string_to_time_source" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/share/gems/gems/activerecord-4.1.8/lib/active_record/connection_adapters/postgresql/cast.rb, line 16</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">string_to_time</span>(<span class="ruby-identifier">string</span>)
<span class="ruby-keyword">return</span> <span class="ruby-identifier">string</span> <span class="ruby-keyword">unless</span> <span class="ruby-constant">String</span> <span class="ruby-operator">===</span> <span class="ruby-identifier">string</span>
<span class="ruby-keyword">case</span> <span class="ruby-identifier">string</span>
<span class="ruby-keyword">when</span> <span class="ruby-string">'infinity'</span>; <span class="ruby-constant">Float</span><span class="ruby-operator">::</span><span class="ruby-constant">INFINITY</span>
<span class="ruby-keyword">when</span> <span class="ruby-string">'-infinity'</span>; <span class="ruby-operator">-</span><span class="ruby-constant">Float</span><span class="ruby-operator">::</span><span class="ruby-constant">INFINITY</span>
<span class="ruby-keyword">when</span> <span class="ruby-regexp">/ BC$/</span>
<span class="ruby-keyword">super</span>(<span class="ruby-string">"-"</span> <span class="ruby-operator">+</span> <span class="ruby-identifier">string</span>.<span class="ruby-identifier">sub</span>(<span class="ruby-regexp">/ BC$/</span>, <span class="ruby-string">""</span>))
<span class="ruby-keyword">else</span>
<span class="ruby-keyword">super</span>
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | {'content_hash': 'a6d000ed22b08ff63f92856676941db5', 'timestamp': '', 'source': 'github', 'line_count': 777, 'max_line_length': 642, 'avg_line_length': 45.32818532818533, 'alnum_prop': 0.5445485519591141, 'repo_name': 'mojo1643/Dalal_v2', 'id': 'f04ecea384363da34a9b67e5b363db955fefe3bb', 'size': '35220', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'doc/api/classes/ActiveRecord/ConnectionAdapters/PostgreSQLColumn/Cast.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '363591'}, {'name': 'CoffeeScript', 'bytes': '211'}, {'name': 'HTML', 'bytes': '210461'}, {'name': 'JavaScript', 'bytes': '8037'}, {'name': 'Ruby', 'bytes': '177800'}, {'name': 'Shell', 'bytes': '219'}]} |
<!DOCTYPE html>
<html class="">
<head>
<title>Renault test project</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="../../css/style.css?1510508419440" media="all" />
<link rel="stylesheet" href="../../css/pattern-scaffolding.css?1510508419440" media="all" />
<!-- Begin Pattern Lab (Required for Pattern Lab to run properly) -->
<!-- never cache patterns -->
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
<link rel="stylesheet" href="../../styleguide/css/styleguide.min.css?1510508419440" media="all">
<link rel="stylesheet" href="../../styleguide/css/prism-typeahead.min.css?1510508419440" media="all" />
<!-- End Pattern Lab -->
</head>
<body class="">
<section class="m-obj-media">
<div class="m-obj-media__img">
<img class="a-cmp-media-w320" src="https://dummyimage.com/320x262/7e7e7e/000000.png" alt="" />
<div class="a-cmp-image-description a-cmp-image-description--bottom-left-position utl-txt-uppercase utl-pos-absolute">Lorem ipsum</div>
</div>
<div class="m-obj-media__txt a-cmp-media-w320">
<h6 class="a-cmp-heading--6">Solutrans - Le salon International des solutions de transport routier arrive à Lyon en 2017</h6>
<p class="a-cmp-paragraph a-cmp-paragraph--default m-obj-media__paragraph">Cras luctus hendrerit neque lacinia scelerisque. Integer nulla turpis, mattis at libero et, vehicula congue augue.</p>
</div>
</section>
<!--DO NOT REMOVE-->
<script type="text/json" id="sg-pattern-data-footer" class="sg-pattern-data">
{
"cssEnabled": false,
"patternLineageExists": true,
"patternLineages": [{
"lineagePattern": "atoms-img-320x262",
"lineagePath": "../../patterns/00-atoms-04-images-44-img-320x262\\00-atoms-04-images-44-img-320x262.rendered.html"
}],
"lineage": [{
"lineagePattern": "atoms-img-320x262",
"lineagePath": "../../patterns/00-atoms-04-images-44-img-320x262\\00-atoms-04-images-44-img-320x262.rendered.html"
}],
"patternLineageRExists": true,
"patternLineagesR": [{
"lineagePattern": "organisms-article-cote-business",
"lineagePath": "../../patterns/02-organisms-02-home-page-07-article-cote-business\\02-organisms-02-home-page-07-article-cote-business.rendered.html"
}],
"lineageR": [{
"lineagePattern": "organisms-article-cote-business",
"lineagePath": "../../patterns/02-organisms-02-home-page-07-article-cote-business\\02-organisms-02-home-page-07-article-cote-business.rendered.html"
}],
"patternLineageEExists": true,
"patternDesc": "",
"patternBreadcrumb": {
"patternType": "molecules",
"patternSubtype": "media-cote-business"
},
"patternExtension": "mustache",
"patternName": "Media Cote Business Img 320x262 2nd",
"patternPartial": "molecules-media-cote-business-img-320x262-2nd",
"patternState": "",
"patternEngineName": "mustache",
"extraOutput": {}
}
</script>
<script>
var scriptLoader = {
run: function(js, cb, target) {
var s = document.getElementById(target + '-' + cb);
for (var i = 0; i < js.length; i++) {
var src = (typeof js[i] != 'string') ? js[i].src : js[i];
var c = document.createElement('script');
c.src = '../../' + src + '?' + cb;
if (typeof js[i] != 'string') {
if (js[i].dep !== undefined) {
c.onload = function(dep, cb, target) {
return function() {
scriptLoader.run(dep, cb, target);
}
}(js[i].dep, cb, target);
}
}
s.parentNode.insertBefore(c, s);
}
}
}
</script>
<script id="pl-js-polyfill-insert-1510508419440">
(function() {
if (self != top) {
var cb = '1510508419440';
var js = [];
if (typeof document !== 'undefined' && !('classList' in document.documentElement)) {
js.push('styleguide/bower_components/classList.min.js');
}
scriptLoader.run(js, cb, 'pl-js-polyfill-insert');
}
})();
</script>
<script id="pl-js-insert-1510508419440">
(function() {
if (self != top) {
var cb = '1510508419440';
var js = [{
'src': 'styleguide/bower_components/jwerty.min.js',
'dep': ['styleguide/js/patternlab-pattern.min.js']
}];
scriptLoader.run(js, cb, 'pl-js-insert');
}
})();
</script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script type="text/javascript" src="../../js/slick.js"></script>
<script type="text/javascript" src="../../js/global-variables.js"></script>
<script type="text/javascript" src="../../js/main.js"></script>
<script type="text/javascript" src="../../js/sticky-faq.js"></script>
<script type="text/javascript" src="../../js/sticky.js"></script>
</body>
</html> | {'content_hash': 'f6567d8aef5f0b7808754a362d865864', 'timestamp': '', 'source': 'github', 'line_count': 143, 'max_line_length': 201, 'avg_line_length': 38.96503496503497, 'alnum_prop': 0.6101938262742282, 'repo_name': 'giga0/renault_task', 'id': '600613676f13ca161517e2c3f1491e6ed7868da0', 'size': '5720', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/patterns/01-molecules-08-media-cote-business-05-media-cote-business-img-320x262-2nd/01-molecules-08-media-cote-business-05-media-cote-business-img-320x262-2nd.rendered.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '582439'}, {'name': 'HTML', 'bytes': '7727081'}, {'name': 'JavaScript', 'bytes': '334757'}]} |
module DropletKit
class DatabaseEvictionPolicyMapping
include Kartograph::DSL
kartograph do
mapping DatabaseEvictionPolicy
property :eviction_policy, scopes: %i[read update]
end
end
end
| {'content_hash': '7de1321cb68a965dd3594f0528dad73f', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 56, 'avg_line_length': 19.636363636363637, 'alnum_prop': 0.7361111111111112, 'repo_name': 'digitalocean/droplet_kit', 'id': 'a84b174eee675d182051b4fe6ac1e2839076a39c', 'size': '247', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'lib/droplet_kit/mappings/database_eviction_policy_mapping.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '313808'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '6657b16081e9a548fb300db596021f27', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '0d0c66738d2009013faf718c54d1d2a87db12615', 'size': '183', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Galium/Galium lasiocarpum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
<document>
<sentences>
<sentence id="1">
<tokens>
<token id="1">
<word>I</word>
<lemma>I</lemma>
<CharacterOffsetBegin>0</CharacterOffsetBegin>
<CharacterOffsetEnd>1</CharacterOffsetEnd>
<POS>PRP</POS>
</token>
<token id="2">
<word>'m</word>
<lemma>be</lemma>
<CharacterOffsetBegin>1</CharacterOffsetBegin>
<CharacterOffsetEnd>3</CharacterOffsetEnd>
<POS>VBP</POS>
</token>
<token id="3">
<word>giving</word>
<lemma>give</lemma>
<CharacterOffsetBegin>4</CharacterOffsetBegin>
<CharacterOffsetEnd>10</CharacterOffsetEnd>
<POS>VBG</POS>
</token>
<token id="4">
<word>away</word>
<lemma>away</lemma>
<CharacterOffsetBegin>11</CharacterOffsetBegin>
<CharacterOffsetEnd>15</CharacterOffsetEnd>
<POS>RP</POS>
</token>
<token id="5">
<word>the</word>
<lemma>the</lemma>
<CharacterOffsetBegin>16</CharacterOffsetBegin>
<CharacterOffsetEnd>19</CharacterOffsetEnd>
<POS>DT</POS>
</token>
<token id="6">
<word>old</word>
<lemma>old</lemma>
<CharacterOffsetBegin>20</CharacterOffsetBegin>
<CharacterOffsetEnd>23</CharacterOffsetEnd>
<POS>JJ</POS>
</token>
<token id="7">
<word>family</word>
<lemma>family</lemma>
<CharacterOffsetBegin>24</CharacterOffsetBegin>
<CharacterOffsetEnd>30</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="8">
<word>computer</word>
<lemma>computer</lemma>
<CharacterOffsetBegin>31</CharacterOffsetBegin>
<CharacterOffsetEnd>39</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="9">
<word>to</word>
<lemma>to</lemma>
<CharacterOffsetBegin>40</CharacterOffsetBegin>
<CharacterOffsetEnd>42</CharacterOffsetEnd>
<POS>TO</POS>
</token>
<token id="10">
<word>a</word>
<lemma>a</lemma>
<CharacterOffsetBegin>43</CharacterOffsetBegin>
<CharacterOffsetEnd>44</CharacterOffsetEnd>
<POS>DT</POS>
</token>
<token id="11">
<word>friend</word>
<lemma>friend</lemma>
<CharacterOffsetBegin>45</CharacterOffsetBegin>
<CharacterOffsetEnd>51</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="12">
<word>.</word>
<lemma>.</lemma>
<CharacterOffsetBegin>51</CharacterOffsetBegin>
<CharacterOffsetEnd>52</CharacterOffsetEnd>
<POS>.</POS>
</token>
</tokens>
<parse>(ROOT (S (NP (PRP I)) (VP (VBP 'm) (VP (VBG giving) (PRT (RP away)) (NP (DT the) (JJ old) (NN family) (NN computer)) (PP (TO to) (NP (DT a) (NN friend))))) (. .))) </parse>
<dependencies type="basic-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">giving</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">giving</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">giving</governor>
<dependent idx="2">'m</dependent>
</dep>
<dep type="prt">
<governor idx="3">giving</governor>
<dependent idx="4">away</dependent>
</dep>
<dep type="det">
<governor idx="8">computer</governor>
<dependent idx="5">the</dependent>
</dep>
<dep type="amod">
<governor idx="8">computer</governor>
<dependent idx="6">old</dependent>
</dep>
<dep type="nn">
<governor idx="8">computer</governor>
<dependent idx="7">family</dependent>
</dep>
<dep type="dobj">
<governor idx="3">giving</governor>
<dependent idx="8">computer</dependent>
</dep>
<dep type="prep">
<governor idx="3">giving</governor>
<dependent idx="9">to</dependent>
</dep>
<dep type="det">
<governor idx="11">friend</governor>
<dependent idx="10">a</dependent>
</dep>
<dep type="pobj">
<governor idx="9">to</governor>
<dependent idx="11">friend</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">giving</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">giving</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">giving</governor>
<dependent idx="2">'m</dependent>
</dep>
<dep type="prt">
<governor idx="3">giving</governor>
<dependent idx="4">away</dependent>
</dep>
<dep type="det">
<governor idx="8">computer</governor>
<dependent idx="5">the</dependent>
</dep>
<dep type="amod">
<governor idx="8">computer</governor>
<dependent idx="6">old</dependent>
</dep>
<dep type="nn">
<governor idx="8">computer</governor>
<dependent idx="7">family</dependent>
</dep>
<dep type="dobj">
<governor idx="3">giving</governor>
<dependent idx="8">computer</dependent>
</dep>
<dep type="det">
<governor idx="11">friend</governor>
<dependent idx="10">a</dependent>
</dep>
<dep type="prep_to">
<governor idx="3">giving</governor>
<dependent idx="11">friend</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-ccprocessed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">giving</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">giving</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">giving</governor>
<dependent idx="2">'m</dependent>
</dep>
<dep type="prt">
<governor idx="3">giving</governor>
<dependent idx="4">away</dependent>
</dep>
<dep type="det">
<governor idx="8">computer</governor>
<dependent idx="5">the</dependent>
</dep>
<dep type="amod">
<governor idx="8">computer</governor>
<dependent idx="6">old</dependent>
</dep>
<dep type="nn">
<governor idx="8">computer</governor>
<dependent idx="7">family</dependent>
</dep>
<dep type="dobj">
<governor idx="3">giving</governor>
<dependent idx="8">computer</dependent>
</dep>
<dep type="det">
<governor idx="11">friend</governor>
<dependent idx="10">a</dependent>
</dep>
<dep type="prep_to">
<governor idx="3">giving</governor>
<dependent idx="11">friend</dependent>
</dep>
</dependencies>
</sentence>
<sentence id="2">
<tokens>
<token id="1">
<word>I</word>
<lemma>I</lemma>
<CharacterOffsetBegin>53</CharacterOffsetBegin>
<CharacterOffsetEnd>54</CharacterOffsetEnd>
<POS>PRP</POS>
</token>
<token id="2">
<word>was</word>
<lemma>be</lemma>
<CharacterOffsetBegin>55</CharacterOffsetBegin>
<CharacterOffsetEnd>58</CharacterOffsetEnd>
<POS>VBD</POS>
</token>
<token id="3">
<word>wanting</word>
<lemma>want</lemma>
<CharacterOffsetBegin>59</CharacterOffsetBegin>
<CharacterOffsetEnd>66</CharacterOffsetEnd>
<POS>VBG</POS>
</token>
<token id="4">
<word>to</word>
<lemma>to</lemma>
<CharacterOffsetBegin>67</CharacterOffsetBegin>
<CharacterOffsetEnd>69</CharacterOffsetEnd>
<POS>TO</POS>
</token>
<token id="5">
<word>know</word>
<lemma>know</lemma>
<CharacterOffsetBegin>70</CharacterOffsetBegin>
<CharacterOffsetEnd>74</CharacterOffsetEnd>
<POS>VB</POS>
</token>
<token id="6">
<word>if</word>
<lemma>if</lemma>
<CharacterOffsetBegin>75</CharacterOffsetBegin>
<CharacterOffsetEnd>77</CharacterOffsetEnd>
<POS>IN</POS>
</token>
<token id="7">
<word>,</word>
<lemma>,</lemma>
<CharacterOffsetBegin>77</CharacterOffsetBegin>
<CharacterOffsetEnd>78</CharacterOffsetEnd>
<POS>,</POS>
</token>
<token id="8">
<word>after</word>
<lemma>after</lemma>
<CharacterOffsetBegin>79</CharacterOffsetBegin>
<CharacterOffsetEnd>84</CharacterOffsetEnd>
<POS>IN</POS>
</token>
<token id="9">
<word>I</word>
<lemma>I</lemma>
<CharacterOffsetBegin>85</CharacterOffsetBegin>
<CharacterOffsetEnd>86</CharacterOffsetEnd>
<POS>PRP</POS>
</token>
<token id="10">
<word>'ve</word>
<lemma>have</lemma>
<CharacterOffsetBegin>86</CharacterOffsetBegin>
<CharacterOffsetEnd>89</CharacterOffsetEnd>
<POS>VBP</POS>
</token>
<token id="11">
<word>deleted</word>
<lemma>delete</lemma>
<CharacterOffsetBegin>90</CharacterOffsetBegin>
<CharacterOffsetEnd>97</CharacterOffsetEnd>
<POS>VBN</POS>
</token>
<token id="12">
<word>the</word>
<lemma>the</lemma>
<CharacterOffsetBegin>98</CharacterOffsetBegin>
<CharacterOffsetEnd>101</CharacterOffsetEnd>
<POS>DT</POS>
</token>
<token id="13">
<word>history</word>
<lemma>history</lemma>
<CharacterOffsetBegin>102</CharacterOffsetBegin>
<CharacterOffsetEnd>109</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="14">
<word>from</word>
<lemma>from</lemma>
<CharacterOffsetBegin>110</CharacterOffsetBegin>
<CharacterOffsetEnd>114</CharacterOffsetEnd>
<POS>IN</POS>
</token>
<token id="15">
<word>Internet</word>
<lemma>Internet</lemma>
<CharacterOffsetBegin>115</CharacterOffsetBegin>
<CharacterOffsetEnd>123</CharacterOffsetEnd>
<POS>NNP</POS>
</token>
<token id="16">
<word>Options</word>
<lemma>Options</lemma>
<CharacterOffsetBegin>124</CharacterOffsetBegin>
<CharacterOffsetEnd>131</CharacterOffsetEnd>
<POS>NNPS</POS>
</token>
<token id="17">
<word>or</word>
<lemma>or</lemma>
<CharacterOffsetBegin>132</CharacterOffsetBegin>
<CharacterOffsetEnd>134</CharacterOffsetEnd>
<POS>CC</POS>
</token>
<token id="18">
<word>Properties</word>
<lemma>Properties</lemma>
<CharacterOffsetBegin>135</CharacterOffsetBegin>
<CharacterOffsetEnd>145</CharacterOffsetEnd>
<POS>NNPS</POS>
</token>
<token id="19">
<word>can</word>
<lemma>can</lemma>
<CharacterOffsetBegin>146</CharacterOffsetBegin>
<CharacterOffsetEnd>149</CharacterOffsetEnd>
<POS>MD</POS>
</token>
<token id="20">
<word>anyone</word>
<lemma>anyone</lemma>
<CharacterOffsetBegin>150</CharacterOffsetBegin>
<CharacterOffsetEnd>156</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="21">
<word>see</word>
<lemma>see</lemma>
<CharacterOffsetBegin>157</CharacterOffsetBegin>
<CharacterOffsetEnd>160</CharacterOffsetEnd>
<POS>VB</POS>
</token>
<token id="22">
<word>what</word>
<lemma>what</lemma>
<CharacterOffsetBegin>161</CharacterOffsetBegin>
<CharacterOffsetEnd>165</CharacterOffsetEnd>
<POS>WP</POS>
</token>
<token id="23">
<word>our</word>
<lemma>we</lemma>
<CharacterOffsetBegin>166</CharacterOffsetBegin>
<CharacterOffsetEnd>169</CharacterOffsetEnd>
<POS>PRP$</POS>
</token>
<token id="24">
<word>family</word>
<lemma>family</lemma>
<CharacterOffsetBegin>170</CharacterOffsetBegin>
<CharacterOffsetEnd>176</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="25">
<word>has</word>
<lemma>have</lemma>
<CharacterOffsetBegin>177</CharacterOffsetBegin>
<CharacterOffsetEnd>180</CharacterOffsetEnd>
<POS>VBZ</POS>
</token>
<token id="26">
<word>looked</word>
<lemma>look</lemma>
<CharacterOffsetBegin>181</CharacterOffsetBegin>
<CharacterOffsetEnd>187</CharacterOffsetEnd>
<POS>VBN</POS>
</token>
<token id="27">
<word>up</word>
<lemma>up</lemma>
<CharacterOffsetBegin>188</CharacterOffsetBegin>
<CharacterOffsetEnd>190</CharacterOffsetEnd>
<POS>RP</POS>
</token>
<token id="28">
<word>?</word>
<lemma>?</lemma>
<CharacterOffsetBegin>190</CharacterOffsetBegin>
<CharacterOffsetEnd>191</CharacterOffsetEnd>
<POS>.</POS>
</token>
</tokens>
<parse>(ROOT (S (NP (PRP I)) (VP (VBD was) (VP (VBG wanting) (S (VP (TO to) (VP (VB know) (SBAR (IN if) (, ,) (S (SBAR (IN after) (S (NP (PRP I)) (VP (VBP 've) (VP (VBN deleted) (NP (DT the) (NN history)) (PP (IN from) (NP (NNP Internet))))))) (NP (NNPS Options) (CC or) (NNPS Properties)) (VP (MD can) (NP (NN anyone)) (S (VP (VB see) (SBAR (WHNP (WP what)) (S (NP (PRP$ our) (NN family)) (VP (VBZ has) (VP (VBN looked) (PRT (RP up)))))))))))))))) (. ?))) </parse>
<dependencies type="basic-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">wanting</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">wanting</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">wanting</governor>
<dependent idx="2">was</dependent>
</dep>
<dep type="aux">
<governor idx="5">know</governor>
<dependent idx="4">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="3">wanting</governor>
<dependent idx="5">know</dependent>
</dep>
<dep type="mark">
<governor idx="19">can</governor>
<dependent idx="6">if</dependent>
</dep>
<dep type="mark">
<governor idx="11">deleted</governor>
<dependent idx="8">after</dependent>
</dep>
<dep type="nsubj">
<governor idx="11">deleted</governor>
<dependent idx="9">I</dependent>
</dep>
<dep type="aux">
<governor idx="11">deleted</governor>
<dependent idx="10">'ve</dependent>
</dep>
<dep type="advcl">
<governor idx="19">can</governor>
<dependent idx="11">deleted</dependent>
</dep>
<dep type="det">
<governor idx="13">history</governor>
<dependent idx="12">the</dependent>
</dep>
<dep type="dobj">
<governor idx="11">deleted</governor>
<dependent idx="13">history</dependent>
</dep>
<dep type="prep">
<governor idx="11">deleted</governor>
<dependent idx="14">from</dependent>
</dep>
<dep type="pobj">
<governor idx="14">from</governor>
<dependent idx="15">Internet</dependent>
</dep>
<dep type="nsubj">
<governor idx="19">can</governor>
<dependent idx="16">Options</dependent>
</dep>
<dep type="cc">
<governor idx="16">Options</governor>
<dependent idx="17">or</dependent>
</dep>
<dep type="conj">
<governor idx="16">Options</governor>
<dependent idx="18">Properties</dependent>
</dep>
<dep type="advcl">
<governor idx="5">know</governor>
<dependent idx="19">can</dependent>
</dep>
<dep type="dobj">
<governor idx="19">can</governor>
<dependent idx="20">anyone</dependent>
</dep>
<dep type="dep">
<governor idx="19">can</governor>
<dependent idx="21">see</dependent>
</dep>
<dep type="dobj">
<governor idx="26">looked</governor>
<dependent idx="22">what</dependent>
</dep>
<dep type="poss">
<governor idx="24">family</governor>
<dependent idx="23">our</dependent>
</dep>
<dep type="nsubj">
<governor idx="26">looked</governor>
<dependent idx="24">family</dependent>
</dep>
<dep type="aux">
<governor idx="26">looked</governor>
<dependent idx="25">has</dependent>
</dep>
<dep type="ccomp">
<governor idx="21">see</governor>
<dependent idx="26">looked</dependent>
</dep>
<dep type="prt">
<governor idx="26">looked</governor>
<dependent idx="27">up</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">wanting</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">wanting</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">wanting</governor>
<dependent idx="2">was</dependent>
</dep>
<dep type="aux">
<governor idx="5">know</governor>
<dependent idx="4">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="3">wanting</governor>
<dependent idx="5">know</dependent>
</dep>
<dep type="mark">
<governor idx="19">can</governor>
<dependent idx="6">if</dependent>
</dep>
<dep type="mark">
<governor idx="11">deleted</governor>
<dependent idx="8">after</dependent>
</dep>
<dep type="nsubj">
<governor idx="11">deleted</governor>
<dependent idx="9">I</dependent>
</dep>
<dep type="aux">
<governor idx="11">deleted</governor>
<dependent idx="10">'ve</dependent>
</dep>
<dep type="advcl">
<governor idx="19">can</governor>
<dependent idx="11">deleted</dependent>
</dep>
<dep type="det">
<governor idx="13">history</governor>
<dependent idx="12">the</dependent>
</dep>
<dep type="dobj">
<governor idx="11">deleted</governor>
<dependent idx="13">history</dependent>
</dep>
<dep type="prep_from">
<governor idx="11">deleted</governor>
<dependent idx="15">Internet</dependent>
</dep>
<dep type="nsubj">
<governor idx="19">can</governor>
<dependent idx="16">Options</dependent>
</dep>
<dep type="conj_or">
<governor idx="16">Options</governor>
<dependent idx="18">Properties</dependent>
</dep>
<dep type="advcl">
<governor idx="5">know</governor>
<dependent idx="19">can</dependent>
</dep>
<dep type="dobj">
<governor idx="19">can</governor>
<dependent idx="20">anyone</dependent>
</dep>
<dep type="dep">
<governor idx="19">can</governor>
<dependent idx="21">see</dependent>
</dep>
<dep type="dobj">
<governor idx="26">looked</governor>
<dependent idx="22">what</dependent>
</dep>
<dep type="poss">
<governor idx="24">family</governor>
<dependent idx="23">our</dependent>
</dep>
<dep type="nsubj">
<governor idx="26">looked</governor>
<dependent idx="24">family</dependent>
</dep>
<dep type="aux">
<governor idx="26">looked</governor>
<dependent idx="25">has</dependent>
</dep>
<dep type="ccomp">
<governor idx="21">see</governor>
<dependent idx="26">looked</dependent>
</dep>
<dep type="prt">
<governor idx="26">looked</governor>
<dependent idx="27">up</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-ccprocessed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="3">wanting</dependent>
</dep>
<dep type="nsubj">
<governor idx="3">wanting</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="3">wanting</governor>
<dependent idx="2">was</dependent>
</dep>
<dep type="aux">
<governor idx="5">know</governor>
<dependent idx="4">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="3">wanting</governor>
<dependent idx="5">know</dependent>
</dep>
<dep type="mark">
<governor idx="19">can</governor>
<dependent idx="6">if</dependent>
</dep>
<dep type="mark">
<governor idx="11">deleted</governor>
<dependent idx="8">after</dependent>
</dep>
<dep type="nsubj">
<governor idx="11">deleted</governor>
<dependent idx="9">I</dependent>
</dep>
<dep type="aux">
<governor idx="11">deleted</governor>
<dependent idx="10">'ve</dependent>
</dep>
<dep type="advcl">
<governor idx="19">can</governor>
<dependent idx="11">deleted</dependent>
</dep>
<dep type="det">
<governor idx="13">history</governor>
<dependent idx="12">the</dependent>
</dep>
<dep type="dobj">
<governor idx="11">deleted</governor>
<dependent idx="13">history</dependent>
</dep>
<dep type="prep_from">
<governor idx="11">deleted</governor>
<dependent idx="15">Internet</dependent>
</dep>
<dep type="nsubj">
<governor idx="19">can</governor>
<dependent idx="16">Options</dependent>
</dep>
<dep type="conj_or">
<governor idx="16">Options</governor>
<dependent idx="18">Properties</dependent>
</dep>
<dep type="nsubj">
<governor idx="19">can</governor>
<dependent idx="18">Properties</dependent>
</dep>
<dep type="advcl">
<governor idx="5">know</governor>
<dependent idx="19">can</dependent>
</dep>
<dep type="dobj">
<governor idx="19">can</governor>
<dependent idx="20">anyone</dependent>
</dep>
<dep type="dep">
<governor idx="19">can</governor>
<dependent idx="21">see</dependent>
</dep>
<dep type="dobj">
<governor idx="26">looked</governor>
<dependent idx="22">what</dependent>
</dep>
<dep type="poss">
<governor idx="24">family</governor>
<dependent idx="23">our</dependent>
</dep>
<dep type="nsubj">
<governor idx="26">looked</governor>
<dependent idx="24">family</dependent>
</dep>
<dep type="aux">
<governor idx="26">looked</governor>
<dependent idx="25">has</dependent>
</dep>
<dep type="ccomp">
<governor idx="21">see</governor>
<dependent idx="26">looked</dependent>
</dep>
<dep type="prt">
<governor idx="26">looked</governor>
<dependent idx="27">up</dependent>
</dep>
</dependencies>
</sentence>
<sentence id="3">
<tokens>
<token id="1">
<word>I</word>
<lemma>I</lemma>
<CharacterOffsetBegin>192</CharacterOffsetBegin>
<CharacterOffsetEnd>193</CharacterOffsetEnd>
<POS>PRP</POS>
</token>
<token id="2">
<word>want</word>
<lemma>want</lemma>
<CharacterOffsetBegin>194</CharacterOffsetBegin>
<CharacterOffsetEnd>198</CharacterOffsetEnd>
<POS>VBP</POS>
</token>
<token id="3">
<word>to</word>
<lemma>to</lemma>
<CharacterOffsetBegin>199</CharacterOffsetBegin>
<CharacterOffsetEnd>201</CharacterOffsetEnd>
<POS>TO</POS>
</token>
<token id="4">
<word>keep</word>
<lemma>keep</lemma>
<CharacterOffsetBegin>202</CharacterOffsetBegin>
<CharacterOffsetEnd>206</CharacterOffsetEnd>
<POS>VB</POS>
</token>
<token id="5">
<word>our</word>
<lemma>we</lemma>
<CharacterOffsetBegin>207</CharacterOffsetBegin>
<CharacterOffsetEnd>210</CharacterOffsetEnd>
<POS>PRP$</POS>
</token>
<token id="6">
<word>family</word>
<lemma>family</lemma>
<CharacterOffsetBegin>211</CharacterOffsetBegin>
<CharacterOffsetEnd>217</CharacterOffsetEnd>
<POS>NN</POS>
</token>
<token id="7">
<word>histories</word>
<lemma>history</lemma>
<CharacterOffsetBegin>218</CharacterOffsetBegin>
<CharacterOffsetEnd>227</CharacterOffsetEnd>
<POS>NNS</POS>
</token>
<token id="8">
<word>completely</word>
<lemma>completely</lemma>
<CharacterOffsetBegin>228</CharacterOffsetBegin>
<CharacterOffsetEnd>238</CharacterOffsetEnd>
<POS>RB</POS>
</token>
<token id="9">
<word>private</word>
<lemma>private</lemma>
<CharacterOffsetBegin>239</CharacterOffsetBegin>
<CharacterOffsetEnd>246</CharacterOffsetEnd>
<POS>JJ</POS>
</token>
<token id="10">
<word>.</word>
<lemma>.</lemma>
<CharacterOffsetBegin>246</CharacterOffsetBegin>
<CharacterOffsetEnd>247</CharacterOffsetEnd>
<POS>.</POS>
</token>
</tokens>
<parse>(ROOT (S (NP (PRP I)) (VP (VBP want) (S (VP (TO to) (VP (VB keep) (S (NP (PRP$ our) (NN family) (NNS histories)) (ADJP (RB completely) (JJ private))))))) (. .))) </parse>
<dependencies type="basic-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="2">want</dependent>
</dep>
<dep type="nsubj">
<governor idx="2">want</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="4">keep</governor>
<dependent idx="3">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="2">want</governor>
<dependent idx="4">keep</dependent>
</dep>
<dep type="poss">
<governor idx="7">histories</governor>
<dependent idx="5">our</dependent>
</dep>
<dep type="nn">
<governor idx="7">histories</governor>
<dependent idx="6">family</dependent>
</dep>
<dep type="nsubj">
<governor idx="9">private</governor>
<dependent idx="7">histories</dependent>
</dep>
<dep type="advmod">
<governor idx="9">private</governor>
<dependent idx="8">completely</dependent>
</dep>
<dep type="xcomp">
<governor idx="4">keep</governor>
<dependent idx="9">private</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="2">want</dependent>
</dep>
<dep type="nsubj">
<governor idx="2">want</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="4">keep</governor>
<dependent idx="3">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="2">want</governor>
<dependent idx="4">keep</dependent>
</dep>
<dep type="poss">
<governor idx="7">histories</governor>
<dependent idx="5">our</dependent>
</dep>
<dep type="nn">
<governor idx="7">histories</governor>
<dependent idx="6">family</dependent>
</dep>
<dep type="nsubj">
<governor idx="9">private</governor>
<dependent idx="7">histories</dependent>
</dep>
<dep type="advmod">
<governor idx="9">private</governor>
<dependent idx="8">completely</dependent>
</dep>
<dep type="xcomp">
<governor idx="4">keep</governor>
<dependent idx="9">private</dependent>
</dep>
</dependencies>
<dependencies type="collapsed-ccprocessed-dependencies">
<dep type="root">
<governor idx="0">ROOT</governor>
<dependent idx="2">want</dependent>
</dep>
<dep type="nsubj">
<governor idx="2">want</governor>
<dependent idx="1">I</dependent>
</dep>
<dep type="aux">
<governor idx="4">keep</governor>
<dependent idx="3">to</dependent>
</dep>
<dep type="xcomp">
<governor idx="2">want</governor>
<dependent idx="4">keep</dependent>
</dep>
<dep type="poss">
<governor idx="7">histories</governor>
<dependent idx="5">our</dependent>
</dep>
<dep type="nn">
<governor idx="7">histories</governor>
<dependent idx="6">family</dependent>
</dep>
<dep type="nsubj">
<governor idx="9">private</governor>
<dependent idx="7">histories</dependent>
</dep>
<dep type="advmod">
<governor idx="9">private</governor>
<dependent idx="8">completely</dependent>
</dep>
<dep type="xcomp">
<governor idx="4">keep</governor>
<dependent idx="9">private</dependent>
</dep>
</dependencies>
</sentence>
</sentences>
</document>
</root>
| {'content_hash': '7c4d25a8f50bc73f9acced46a8551042', 'timestamp': '', 'source': 'github', 'line_count': 923, 'max_line_length': 473, 'avg_line_length': 37.14842903575298, 'alnum_prop': 0.4798180121325245, 'repo_name': 'osmanbaskaya/semeval14-task3', 'id': 'afd7c6ed67ff45d29b156fc1a5b8d59521c6c338', 'size': '34288', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'run/corenlp-paragraph2sentence.train/262.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '22682'}, {'name': 'Scala', 'bytes': '1451'}, {'name': 'Shell', 'bytes': '532'}, {'name': 'TeX', 'bytes': '215954'}]} |
package org.mp4parser.test.boxes.iso14496.part30;
import com.googlecode.mp4parser.boxes.BoxRoundtripTest;
import org.junit.runners.Parameterized;
import org.mp4parser.ParsableBox;
import org.mp4parser.boxes.iso14496.part30.WebVTTConfigurationBox;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
public class WebVTTConfigurationBoxTest extends BoxRoundtripTest {
public WebVTTConfigurationBoxTest(ParsableBox parsableBoxUnderTest, Map.Entry<String, Object>... properties) {
super(parsableBoxUnderTest, properties);
}
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Collections.singletonList(
new Object[]{new WebVTTConfigurationBox(),
new Map.Entry[]{
new E("config", "1234 \n ljhsdjkshdj \n\n")}
});
}
} | {'content_hash': '1454815def1cfaf620c225b21a3afd88', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 114, 'avg_line_length': 29.933333333333334, 'alnum_prop': 0.6959910913140311, 'repo_name': 'sannies/mp4parser', 'id': '35c661108375d420e3298546e6818e6b03977821', 'size': '898', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'isoparser/src/test/java/org/mp4parser/test/boxes/iso14496/part30/WebVTTConfigurationBoxTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1849395'}]} |
package org.ebayopensource.turmeric.runtime.common.impl.internal.monitoring;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import org.ebayopensource.turmeric.runtime.common.exceptions.ServiceException;
import org.ebayopensource.turmeric.runtime.common.impl.internal.pipeline.BaseMessageContextImpl;
import org.ebayopensource.turmeric.runtime.common.impl.utils.LogManager;
import org.ebayopensource.turmeric.runtime.common.monitoring.MetricCategory;
import org.ebayopensource.turmeric.runtime.common.monitoring.MetricClassifier;
import org.ebayopensource.turmeric.runtime.common.monitoring.MetricDef;
import org.ebayopensource.turmeric.runtime.common.monitoring.MetricId;
import org.ebayopensource.turmeric.runtime.common.monitoring.MetricsCollector;
import org.ebayopensource.turmeric.runtime.common.monitoring.MonitoringLevel;
import org.ebayopensource.turmeric.runtime.common.monitoring.value.BaseMetricValue;
import org.ebayopensource.turmeric.runtime.common.monitoring.value.MetricComponentType;
import org.ebayopensource.turmeric.runtime.common.monitoring.value.MetricComponentValue;
import org.ebayopensource.turmeric.runtime.common.monitoring.value.MetricValue;
import org.ebayopensource.turmeric.runtime.common.monitoring.value.MetricValueAggregator;
import org.ebayopensource.turmeric.runtime.common.pipeline.MessageContext;
import org.ebayopensource.turmeric.runtime.common.pipeline.MessageContextAccessor;
import org.ebayopensource.turmeric.runtime.common.types.SOAConstants;
import org.ebayopensource.turmeric.runtime.common.types.SOAHeaders;
/**
* @author wdeng, ichernyshev
*/
final class MetricValueAggregatorImpl extends BaseMetricValue implements MetricValueAggregator {
private static final String METRIC_CLASSIFIER_PROP = "org.ebayopensource.turmeric.runtime.MetricClassifier";
private static final MetricClassifier UNKNOWN_CLASSIFIER = new MetricClassifier("Unknown", "Unknown", "Unknown");
/*
* By default, we will use the Usecase, DC based classifier. However, user can
* specify a custom classifier, by providing a factory for the MetricValue.
*/
private final MetricDef m_metricDef;
private final boolean m_isNormalLevel;
private final MetricsCollector m_collector;
private HashMap<MetricClassifier, MetricValue> m_valueByClassifier;
private MetricValue m_firstValue;
public static MetricValueAggregatorImpl create(MetricId id,
MetricDef metricDef, MetricsCollector collector)
{
if (metricDef == null || id == null) {
throw new NullPointerException();
}
MetricValue sampleValue = metricDef.getValueFactory().create(id);
List<MetricComponentType> types = sampleValue.getAllComponentsTypes();
return new MetricValueAggregatorImpl(id, types, metricDef, collector);
}
private MetricValueAggregatorImpl(MetricId id, List<MetricComponentType> types,
MetricDef metricDef, MetricsCollector collector)
{
super(id, types);
m_metricDef = metricDef;
m_isNormalLevel = (metricDef.getLevel() == MonitoringLevel.NORMAL);
m_collector = collector;
m_valueByClassifier = new HashMap<MetricClassifier,MetricValue>();
}
public final boolean isEnabled() {
if (m_isNormalLevel) {
return true;
}
MonitoringLevel effectiveLevel = m_collector.getMonitoringLevel(getMetricId().getAdminName());
return effectiveLevel.ordinal() >= m_metricDef.getLevel().ordinal();
}
public MetricDef getMetricDef() {
return m_metricDef;
}
public MetricCategory getCategory() {
return m_metricDef.getCategory();
}
public MonitoringLevel getLevel() {
return m_metricDef.getLevel();
}
@Override
public synchronized MetricValue deepCopy(boolean isReadOnly) {
MetricValueAggregatorImpl result = (MetricValueAggregatorImpl)super.deepCopy(isReadOnly);
HashMap<MetricClassifier,MetricValue> valuesSrc = m_valueByClassifier;
HashMap<MetricClassifier,MetricValue> valuesDst =
new HashMap<MetricClassifier,MetricValue>(valuesSrc.size());
for (Map.Entry<MetricClassifier,MetricValue> e: valuesSrc.entrySet()) {
MetricValue value2 = e.getValue().deepCopy(isReadOnly);
valuesDst.put(e.getKey(), value2);
}
result.m_valueByClassifier = valuesDst;
return result;
}
@Override
public synchronized void addOtherValue(MetricValue other, boolean isPositive) {
checkUpdateable();
MetricValueAggregatorImpl other2 = (MetricValueAggregatorImpl)other;
HashMap<MetricClassifier,MetricValue> otherValues = other2.m_valueByClassifier;
for (Map.Entry<MetricClassifier,MetricValue> e: m_valueByClassifier.entrySet()) {
MetricClassifier classifier = e.getKey();
BaseMetricValue newValue = (BaseMetricValue)e.getValue();
MetricValue otherValue = otherValues.get(classifier);
if (otherValue != null) {
newValue.addOtherValue(otherValue, isPositive);
}
}
}
public MetricValue getTotalValue() {
BaseMetricValue result = null;
for (MetricValue value: m_valueByClassifier.values()) {
if (result != null) {
result.addOtherValue(value, true);
} else {
if (m_valueByClassifier.size() == 1) {
return value.deepCopy(true);
}
// there is more than 1 object, we will call add,
// so no need to create a copy here
result = (BaseMetricValue)value.deepCopy(false);
}
}
if (result != null) {
return result.deepCopy(true);
}
return null;
}
@Override
public MetricComponentValue[] getValues() {
throw new UnsupportedOperationException("MetricValueAggregatorImpl does not support getValues call");
}
public Collection<MetricClassifier> getClassifiers() {
// no need to synchronize as people are handed out copies only
return m_valueByClassifier.keySet();
}
public MetricValue getValue(MetricClassifier classifier) {
return m_valueByClassifier.get(classifier);
}
@Override
public void update(MetricValue value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext();
update(classifier, value);
}
@Override
public void update(int value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext();
update(classifier, value);
}
@Override
public void update(long value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext();
update(classifier, value);
}
@Override
public void update(float value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext();
update(classifier, value);
}
@Override
public void update(double value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext();
update(classifier, value);
}
public void update(MessageContext ctx, MetricValue value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext(ctx);
update(classifier, value);
}
public void update(MessageContext ctx, int value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext(ctx);
update(classifier, value);
}
public void update(MessageContext ctx, long value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext(ctx);
update(classifier, value);
}
public void update(MessageContext ctx, float value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext(ctx);
update(classifier, value);
}
public void update(MessageContext ctx, double value) {
if (! isEnabled()) return;
MetricClassifier classifier = getClassifierFromContext(ctx);
update(classifier, value);
}
private synchronized void update(MetricClassifier classifier, MetricValue newValue) {
checkUpdateable();
MetricValue classifiedValue = getMetricValueForClassifier(classifier);
classifiedValue.update(newValue);
}
private synchronized void update(MetricClassifier classifier, int value) {
checkUpdateable();
MetricValue classifiedValue = getMetricValueForClassifier(classifier);
classifiedValue.update(value);
}
private synchronized void update(MetricClassifier classifier, long value) {
checkUpdateable();
MetricValue classifiedValue = getMetricValueForClassifier(classifier);
classifiedValue.update(value);
}
private synchronized void update(MetricClassifier classifier, float value) {
checkUpdateable();
MetricValue classifiedValue = getMetricValueForClassifier(classifier);
classifiedValue.update(value);
}
private synchronized void update(MetricClassifier classifier, double value) {
checkUpdateable();
MetricValue classifiedValue = getMetricValueForClassifier(classifier);
classifiedValue.update(value);
}
/**
* Resets the values, to be called by Ops manually
*/
public synchronized void reset() {
checkUpdateable();
m_valueByClassifier.clear();
}
private MetricValue getMetricValueForClassifier(MetricClassifier classifier) {
MetricValue value = m_valueByClassifier.get(classifier);
if (value == null) {
value = m_metricDef.getValueFactory().create(getMetricId());
if (value == null) {
throw new NullPointerException();
}
if (m_firstValue != null) {
if (m_firstValue.getClass() != value.getClass()) {
throw new IllegalArgumentException(
m_metricDef.getValueFactory().getClass().getName() +
" returned two different value types: " + value.getClass().getName() +
" and " + m_firstValue.getClass().getName());
}
} else {
m_firstValue = value;
}
m_valueByClassifier.put(classifier, value);
}
return value;
}
private static MetricClassifier getClassifierFromContext() {
BaseMessageContextImpl ctx = (BaseMessageContextImpl)MessageContextAccessor.getContext();
return getClassifierFromContext(ctx);
}
private static MetricClassifier getClassifierFromContext(MessageContext ctx) {
return getClassifierFromContext((BaseMessageContextImpl)ctx);
}
private static MetricClassifier getClassifierFromContext(BaseMessageContextImpl ctx) {
/*
* Look in the MessageContext, find the USECASE_NAME and DC and
* look up in the map m_ClassifierBasedValues and
* update the respective MetricValue.
* The logic is similar for all update methods.
*/
if (ctx == null) {
return UNKNOWN_CLASSIFIER;
}
MetricClassifier result = (MetricClassifier)ctx.getProperty(METRIC_CLASSIFIER_PROP);
try {
String usecase = ctx.getRequestMessage().getTransportHeader(SOAHeaders.USECASE_NAME);
String knownUsecase = result == null ? null : result.getUseCase();
if (knownUsecase != null && !SOAConstants.DEFAULT_USE_CASE.equals(knownUsecase)
&& knownUsecase.equals(usecase)) {
return result;
}
String sourceDc = ctx.getClientAddress().getDataCenter();
String targetDc = ctx.getServiceAddress().getDataCenter();
if (usecase == null) {
usecase = SOAConstants.DEFAULT_USE_CASE;
}
if (targetDc == null) {
targetDc = "Unknown";
}
if (sourceDc == null) {
sourceDc = "Unknown";
}
result = new MetricClassifier(usecase, sourceDc, targetDc);
} catch (ServiceException e) {
LogManager.getInstance(MetricValueAggregatorImpl.class).log(Level.WARNING,
"Unable to build SOA Metrics Classifier: " + e.toString(), e);
result = UNKNOWN_CLASSIFIER;
}
ctx.setSystemProperty(METRIC_CLASSIFIER_PROP, result);
return result;
}
}
| {'content_hash': 'b30ad7611705dca255304981cd066cde', 'timestamp': '', 'source': 'github', 'line_count': 359, 'max_line_length': 114, 'avg_line_length': 31.481894150417826, 'alnum_prop': 0.7619890284905326, 'repo_name': 'vthangathurai/SOA-Runtime', 'id': '65c74301fcdadb4fdde56a8b98b7996e63f29446', 'size': '11752', 'binary': False, 'copies': '2', 'ref': 'refs/heads/soabranch', 'path': 'soa-client/src/main/java/org/ebayopensource/turmeric/runtime/common/impl/internal/monitoring/MetricValueAggregatorImpl.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '8734301'}, {'name': 'Perl', 'bytes': '2788'}, {'name': 'Shell', 'bytes': '621'}]} |
namespace zbs {
namespace unicode {
/// Maximum valid Unicode code point.
constexpr rune max_rune = U'\U0010FFFF';
/// Represents invalid code points.
constexpr rune replacement_char = U'\uFFFD';
/// Maximum ASCII value.
constexpr rune max_ascii = U'\u007F';
/// Maximum Latin-1 value.
constexpr rune max_latin1 = U'\u00FF';
/// Represents a range of 16-bit Unicode code points. The range runs from lo to
/// hi inclusive and has the specified stride.
struct range16 {
uint16 lo;
uint16 hi;
uint16 stride;
};
/// Represents a range of Unicode code points and is used when one or more of
/// the values will not fit in 16 bits. The range runs from lo to hi inclusive
/// and has the specified stride. Lo and hi must always be >= 1<<16.
struct range32 {
uint32 lo;
uint32 hi;
uint32 stride;
};
/// Class defines a set of Unicode code points by listing the ranges of code
/// points within the set. The ranges are listed in two slices to save space: a
/// slice of 16-bit ranges and a slice of 32-bit ranges. The two slices must be
/// in sorted order and non-overlapping. Also, r32 should contain only values
/// >= 0x10000 (1<<16).
struct range_table {
slice<const range16> r16;
slice<const range32> r32;
int latin_offset = 0;
constexpr range_table() = default;
// the reason for this constructor to be explicitly defined is the
// following: C++ seems to lose array size information in some cases,
// the one I care about is this: `range_table r = {array, array, n}`
// doesn't work unfortunately without the constructor below
constexpr range_table(slice<const range16> r16, slice<const range32> r32, int latin_offset):
r16(r16), r32(r32), latin_offset(latin_offset) {}
};
enum case_t {
upper_case,
lower_case,
title_case,
max_case,
};
struct case_range {
uint32 lo;
uint32 hi;
rune delta[max_case];
};
constexpr rune upper_lower = max_rune + 1;
/// Reports whether r is in the specified table of ranges rt.
bool is(const range_table &rt, rune r);
/// Reports whether r is a control character. The C (Other) Unicode category
/// includes more code points such as surrogates; use is(C, r) to test for them.
bool is_control(rune r);
/// Reports whether r is a decimal digit.
bool is_digit(rune r);
/// Reports whether r is defined as a Graphic by Unicode. Such characters
/// include letters, marks, numbers, punctuation, symbols, and spaces, from
/// categories L, M, N, P, S, Zs.
bool is_graphic(rune r);
/// Reports whether r is a letter (category L).
bool is_letter(rune r);
/// Reports whether r is a lower case letter.
bool is_lower(rune r);
/// Reports whether r is a mark character (category M).
bool is_mark(rune r);
/// Reports whether r is a number (category N).
bool is_number(rune r);
/// Reports whether r is a member of one of the ranges in set.
bool is_one_of(slice<const range_table> set, rune r);
/// Reports whether r is defined as printable by libzbs. Such characters
/// include letters, marks, numbers, punctuation, symbols, and the ASCII space
/// character, from categories L, M, N, P, S and the ASCII space character.
/// This categorization is the same as is_graphic except that the only spacing
/// character is ASCII space, U+0020.
bool is_print(rune r);
/// Reports whether r is a Unicode punctuation character (category P).
bool is_punct(rune r);
/// Reports whether r is a space character as defined by Unicode's White Space
/// property; in the Latin-1 space this is: `\t`, `\n`, `\v`, `\f`, `\r`,
/// `U+0020` (SPACE), `U+0085` (NEL), `U+00A0` (NBSP).
bool is_space(rune r);
/// Reports whether r is a symbolic character.
bool is_symbol(rune r);
/// Reports whether r is a title case letter.
bool is_title(rune r);
/// Reports whether r is an upper case letter.
bool is_upper(rune r);
/// Iterates over Unicode code points equivalent under the Unicode-defined
/// simple case folding. Among the code points equivalent to r (including r
/// itself), simple_fold returns the smallest rune >= r if one exists, or else
/// the smallest rune >= 0.
///
/// For example:
///
/// simple_fold(U'A') = U'a'
/// simple_fold(U'a') = U'A'
///
/// simple_fold(U'K') = U'k'
/// simple_fold(U'k') = U'\u212A' (Kelvin symbol, K)
/// simple_fold(U'\u212A') = U'K'
///
/// simple_fold(U'1') = U'1'
rune simple_fold(rune r);
/// Maps r to the specified _case: upper_case, lower_case, or title_case.
rune to(case_t _case, rune r);
/// Maps r to lower case.
rune to_lower(rune r);
/// Maps r to title case.
rune to_title(rune r);
/// Maps r to upper case.
rune to_upper(rune r);
}} // namespace zbs::unicode
#include "_unicode_tables.hh"
| {'content_hash': '425fd068b396384fdf5d62ff614a1443', 'timestamp': '', 'source': 'github', 'line_count': 153, 'max_line_length': 93, 'avg_line_length': 30.254901960784313, 'alnum_prop': 0.6923741628861525, 'repo_name': 'nsf/libzbs', 'id': 'a687810087310e09489c5af1cf5719dbfec42c4a', 'size': '4707', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/zbs/unicode.hh', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '377704'}, {'name': 'Python', 'bytes': '2454'}]} |
require 'spec_helper'
describe GraphQL::Tracing::AppOpticsTracing do
module AppOpticsTest
class Schema < GraphQL::Schema
def self.id_from_object(_object = nil, _type = nil, _context = {})
SecureRandom.uuid
end
class Address < GraphQL::Schema::Object
global_id_field :id
field :street, String
field :number, Integer
end
class Company < GraphQL::Schema::Object
global_id_field :id
field :name, String
field :address, Schema::Address
def address
OpenStruct.new(
id: AppOpticsTest::Schema.id_from_object,
street: 'MyStreetName',
number: 'MyStreetNumber'
)
end
end
class Query < GraphQL::Schema::Object
field :int, Integer, null: false
def int; 1; end
field :company, Company do
argument :id, ID
end
def company(id:)
OpenStruct.new(
id: id,
name: 'MyName')
end
end
query Query
use GraphQL::Tracing::AppOpticsTracing
end
end
before do
load 'spec/support/appoptics.rb'
$appoptics_tracing_spans = []
$appoptics_tracing_kvs = []
$appoptics_tracing_name = nil
AppOpticsAPM::Config[:graphql] = { :enabled => true,
:remove_comments => true,
:sanitize_query => true,
:transaction_name => true
}
end
it 'calls AppOpticsAPM::SDK.trace with names and kvs' do
query = 'query Query { int }'
AppOpticsTest::Schema.execute(query)
assert_equal $appoptics_tracing_name, 'graphql.query.Query'
refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ }
assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size
assert_equal($appoptics_tracing_kvs[0][:Spec], 'graphql')
assert_equal($appoptics_tracing_kvs[0][:InboundQuery], query)
end
it 'uses type + field keys' do
query = <<-QL
query { company(id: 1) # there is a comment here
{ id name address
{ street }
}
}
# and another one here
QL
AppOpticsTest::Schema.execute(query)
assert_equal $appoptics_tracing_name, 'graphql.query.company'
refute $appoptics_tracing_spans.find { |name| name !~ /^graphql\./ }
assert_equal $appoptics_tracing_kvs.compact.size, $appoptics_tracing_spans.compact.size
assert_includes($appoptics_tracing_spans, 'graphql.Query.company')
assert_includes($appoptics_tracing_spans, 'graphql.Company.address')
end
# case: appoptics_apm didn't get required
it 'should not barf, when AppOpticsAPM is undefined' do
Object.send(:remove_const, :AppOpticsAPM)
query = 'query Query { int }'
begin
AppOpticsTest::Schema.execute(query)
rescue StandardError => e
msg = e.message.split("\n").first
flunk "failed: It raised '#{msg}' when AppOpticsAPM is undefined."
end
end
# case: appoptics may have encountered a compile or service key problem
it 'should not barf, when appoptics is present but not loaded' do
AppOpticsAPM.stub(:loaded, false) do
query = 'query Query { int }'
begin
AppOpticsTest::Schema.execute(query)
rescue StandardError => e
msg = e.message.split("\n").first
flunk "failed: It raised '#{msg}' when AppOpticsAPM is not loaded."
end
end
end
# case: using appoptics_apm < 4.12.0, without default graphql configs
it 'creates traces by default when it cannot find configs for graphql' do
AppOpticsAPM::Config.clear
query = 'query Query { int }'
AppOpticsTest::Schema.execute(query)
refute $appoptics_tracing_spans.empty?, 'failed: no traces were created'
end
it 'should not create traces when disabled' do
AppOpticsAPM::Config[:graphql][:enabled] = false
query = 'query Query { int }'
AppOpticsTest::Schema.execute(query)
assert $appoptics_tracing_spans.empty?, 'failed: traces were created'
end
end
| {'content_hash': '07365dac0403f5b9a522dad35bc7546d', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 91, 'avg_line_length': 29.891304347826086, 'alnum_prop': 0.6206060606060606, 'repo_name': 'nevesenin/graphql-ruby', 'id': '9068fd22e73582199dfef92869b676519461b9c8', 'size': '4457', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/graphql/tracing/appoptics_tracing_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '30991'}, {'name': 'JavaScript', 'bytes': '9565'}, {'name': 'Ragel', 'bytes': '9215'}, {'name': 'Ruby', 'bytes': '2404245'}, {'name': 'SCSS', 'bytes': '13574'}, {'name': 'TypeScript', 'bytes': '129560'}, {'name': 'Yacc', 'bytes': '21111'}]} |
<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Class Job
| Picturepark.SDK.V1 API </title>
<meta name="viewport" content="width=device-width">
<meta name="title" content="Class Job
| Picturepark.SDK.V1 API ">
<meta name="generator" content="docfx 2.16.7.0">
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" href="../styles/docfx.vendor.css">
<link rel="stylesheet" href="../styles/docfx.css">
<link rel="stylesheet" href="../styles/main.css">
<meta property="docfx:navrel" content="../toc.html">
<meta property="docfx:tocrel" content="toc.html">
<meta property="docfx:rel" content="../">
</head>
<body data-spy="scroll" data-target="#affix">
<div id="wrapper">
<header>
<nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../index.html">
<img id="logo" class="svg" src="../logo.svg" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="navbar">
<form class="navbar-form navbar-right" role="search" id="search">
<div class="form-group">
<input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
</div>
</form>
</div>
</div>
</nav>
<div class="subnav navbar navbar-default">
<div class="container hide-when-search" id="breadcrumb">
<ul class="breadcrumb">
<li></li>
</ul>
</div>
</div>
</header>
<div role="main" class="container body-content">
<div id="search-results">
<div class="search-list"></div>
<div class="sr-items"></div>
<ul id="pagination"></ul>
</div>
</div>
<div role="main" class="container body-content hide-when-search">
<div class="sidenav hide-when-search">
<a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
<div class="sidetoggle collapse" id="sidetoggle">
<div id="sidetoc"></div>
</div>
</div>
<div class="article row grid-right">
<div class="col-md-10">
<article class="content wrap" id="_content">
<h1 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job">Class Job
</h1>
<div class="markdown level0 summary"></div>
<div class="markdown level0 conceptual"></div>
<div class="inheritance">
<h5>Inheritance</h5>
<div class="level0"><span class="xref">System.Object</span></div>
<div class="level1"><span class="xref">Job</span></div>
</div>
<div class="inheritedMembers">
<h5>Inherited Members</h5>
<div>
<span class="xref">System.Object.ToString()</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object)</span>
</div>
<div>
<span class="xref">System.Object.Equals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span>
</div>
<div>
<span class="xref">System.Object.GetHashCode()</span>
</div>
<div>
<span class="xref">System.Object.GetType()</span>
</div>
<div>
<span class="xref">System.Object.MemberwiseClone()</span>
</div>
</div>
<h6><strong>Namespace</strong>:Picturepark.SDK.V1.ServiceProvider.Contract</h6>
<h6><strong>Assembly</strong>:cs.temp.dll.dll</h6>
<h5 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_syntax">Syntax</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public class Job</code></pre>
</div>
<h3 id="properties">Properties
</h3>
<a id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Id_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Id*"></a>
<h4 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Id" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Id">Id</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string Id { get; set; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td></td>
</tr>
</tbody>
</table>
<a id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Name_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Name*"></a>
<h4 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Name" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Name">Name</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string Name { get; set; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td></td>
</tr>
</tbody>
</table>
<a id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Url_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Url*"></a>
<h4 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_Url" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.Url">Url</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string Url { get; set; }</code></pre>
</div>
<h5 class="propertyValue">Property Value</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td></td>
</tr>
</tbody>
</table>
<h3 id="methods">Methods
</h3>
<a id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_FromJson_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.FromJson*"></a>
<h4 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_FromJson_System_String_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.FromJson(System.String)">FromJson(String)</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public static Job FromJson(string data)</code></pre>
</div>
<h5 class="parameters">Parameters</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td><span class="parametername">data</span></td>
<td></td>
</tr>
</tbody>
</table>
<h5 class="returns">Returns</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a class="xref" href="Picturepark.SDK.V1.ServiceProvider.Contract.Job.html">Job</a></td>
<td></td>
</tr>
</tbody>
</table>
<a id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_ToJson_" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.ToJson*"></a>
<h4 id="Picturepark_SDK_V1_ServiceProvider_Contract_Job_ToJson" data-uid="Picturepark.SDK.V1.ServiceProvider.Contract.Job.ToJson">ToJson()</h4>
<div class="markdown level1 summary"></div>
<div class="markdown level1 conceptual"></div>
<h5 class="decalaration">Declaration</h5>
<div class="codewrapper">
<pre><code class="lang-csharp hljs">public string ToJson()</code></pre>
</div>
<h5 class="returns">Returns</h5>
<table class="table table-bordered table-striped table-condensed">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="xref">System.String</span></td>
<td></td>
</tr>
</tbody>
</table>
</article>
</div>
<div class="hidden-sm col-md-2" role="complementary">
<div class="sideaffix">
<div class="contribution">
<ul class="nav">
</ul>
</div>
<nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
<!-- <p><a class="back-to-top" href="#top">Back to top</a><p> -->
</nav>
</div>
</div>
</div>
</div>
<footer>
<div class="grad-bottom"></div>
<div class="footer">
<div class="container">
<span class="pull-right">
<a href="#top">Back to top</a>
</span>
<span>Copyright © 2015-2017 Microsoft<br>Generated by <strong>DocFX</strong></span>
</div>
</div>
</footer>
</div>
<script type="text/javascript" src="../styles/docfx.vendor.js"></script>
<script type="text/javascript" src="../styles/docfx.js"></script>
<script type="text/javascript" src="../styles/main.js"></script>
</body>
</html>
| {'content_hash': '1ed7e4b7ac06fa83e4264f0887ec1136', 'timestamp': '', 'source': 'github', 'line_count': 301, 'max_line_length': 199, 'avg_line_length': 42.89036544850498, 'alnum_prop': 0.48644461657629745, 'repo_name': 'Picturepark/Picturepark.SDK.DotNet', 'id': '4e4745de77d4270de70cd279883ef2b23332a3b3', 'size': '12913', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/sdk/site/api/Picturepark.SDK.V1.ServiceProvider.Contract.Job.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1481'}, {'name': 'C#', 'bytes': '8219178'}, {'name': 'PostScript', 'bytes': '2927'}, {'name': 'PowerShell', 'bytes': '2869'}]} |
package pod
import (
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/service"
)
type BoundPodFactory interface {
// Make a container object for a given pod, given the machine that the pod is running on.
MakeBoundPod(machine string, pod *api.Pod) (*api.BoundPod, error)
}
type BasicBoundPodFactory struct {
// TODO: this should really point at the API rather than a registry
ServiceRegistry service.Registry
}
func (b *BasicBoundPodFactory) MakeBoundPod(machine string, pod *api.Pod) (*api.BoundPod, error) {
envVars, err := service.GetServiceEnvironmentVariables(api.NewContext(), b.ServiceRegistry, machine)
if err != nil {
return nil, err
}
boundPod := &api.BoundPod{}
if err := api.Scheme.Convert(pod, boundPod); err != nil {
return nil, err
}
for ix, container := range boundPod.Spec.Containers {
boundPod.Spec.Containers[ix].Env = append(container.Env, envVars...)
}
// Make a dummy self link so that references to this bound pod will work.
// TODO: When kubelets get boundPods from apiserver instead of etcd, then
// the selflink should be generated there.
boundPod.SelfLink = "/api/v1beta1/boundPods/" + boundPod.Name
return boundPod, nil
}
| {'content_hash': '413e488cfd8a57db88df797f54e2fa58', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 101, 'avg_line_length': 33.486486486486484, 'alnum_prop': 0.7465698143664246, 'repo_name': 'CrunchyData/dnsbridge', 'id': '0cbbd54c5a241f89c4f9a3f38f8124031dfdae1b', 'size': '1817', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/github.com/GoogleCloudPlatform/kubernetes/pkg/registry/pod/bound_pod_factory.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '18347'}, {'name': 'Assembly', 'bytes': '40104'}, {'name': 'C', 'bytes': '464'}, {'name': 'CSS', 'bytes': '96405'}, {'name': 'Emacs Lisp', 'bytes': '8434'}, {'name': 'Go', 'bytes': '12409671'}, {'name': 'HTML', 'bytes': '389443'}, {'name': 'JavaScript', 'bytes': '90915'}, {'name': 'Makefile', 'bytes': '8048'}, {'name': 'Nginx', 'bytes': '2026'}, {'name': 'PHP', 'bytes': '3948'}, {'name': 'Perl', 'bytes': '84'}, {'name': 'Python', 'bytes': '116686'}, {'name': 'Ruby', 'bytes': '11216'}, {'name': 'Scheme', 'bytes': '1093'}, {'name': 'Shell', 'bytes': '577438'}, {'name': 'VimL', 'bytes': '3376'}]} |
**Approved** | [#runtime/35126](https://github.com/dotnet/runtime/issues/35126#issuecomment-854040319) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=0h0m0s)
The proposed amendments look good. The constructors can always be added later when there's a compelling scenario.
The net approved shape is now
```C#
namespace System.Net.Http.Headers
{
public partial class HttpHeaders
{
public HttpHeadersNonValidated NonValidated { get; }
}
public readonly struct HttpHeadersNonValidated :
IReadOnlyDictionary<string, HeaderStringValues>
{
public int Count { get; }
public bool Contains(string headerName);
public bool TryGetValues(string headerName, out HeaderStringValues values);
public HeaderStringValues this[string headerName];
public Enumerator GetEnumerator();
public readonly struct Enumerator : IEnumerator<KeyValuePair<string, HeaderStringValues>>
{
public bool MoveNext();
public KeyValuePair<string, HeaderStringValues> Current { get; }
public void Dispose();
... // explicitly implemented interface members
}
... // explicitly implemented interface members
}
public readonly struct HeaderStringValues :
IReadOnlyCollection<string>
{
public int Count { get; }
public override string ToString();
public Enumerator GetEnumerator();
public readonly struct Enumerator : IEnumerator<string>
{
public bool MoveNext();
public string Current { get; }
public void Dispose();
... // explicitly implemented interface members
}
... // explicitly implemented interface members
}
}
```
## Do not do math with local DateTime
**NeedsWork** | [#runtime/33764](https://github.com/dotnet/runtime/issues/33764#issuecomment-854046706) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=0h14m3s)
It's unclear what is being proposed here. The examples seem to focus on the interaction with DateTimeKind.Local and DateTimeKind.Utc, not "do[ing] math with local DateTime", as the title suggests.
It's also not clear if this is realistically achievable, since any DateTime that comes in as a method parameter has a DateTimeKind that is not known to the called method (unless something coerced it).
Perhaps an updated title, or more clear examples would help drive a discussion.
## Do not pass Utf8JsonReader by value
**Approved** | [#runtime/33772](https://github.com/dotnet/runtime/issues/33772#issuecomment-854061368) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=0h22m24s)
Severity: Warning
Category: Reliability
* The analyzer, and the messaging, should be more generalized, like "Do not pass mutable value type '{0}' by value."
* We should have a list of well-known problematic types, like Utf8JsonReader, but also support loading other types from config.
* Some types may be able to be identified heuristically, like "ends in Enumerator, is a value type, and is a nested type"
* The list should also include SpinLock
* The analyzer should look for method parameter declarations where the parameter is of one of these types and the parameter mode is not ref or out (either by-value or in/readonly-ref).
* It should also look for these types in "output positions", like property declared types or method returns.
* The fixer should change the parameter to be by ref, and then (as a stretch goal) update calls appropriately (if able).
## Prefer static ReadOnlySpan<byte> properties over static readonly byte[] fields
**Approved** | [#runtime/33780](https://github.com/dotnet/runtime/issues/33780#issuecomment-854077948) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=0h47m22s)
Category: Performance
Level: Info
* The analyzer should look at all static readonly field declarations where the field type is an array of byte/sbyte/bool, the array is initialized with a literal array initializer. (Note that in the future some other types may also be allowed, but that will depend on the presence of a RuntimeFeatures feature)
* Then do a candidate elimination round: Any time that the array was passed to some other method as an array (vs going through AsSpan explicitly or implicitly) then do not report on this field.
* Any remaining fields can be changed to the new pattern.
## Avoid unnecessary string concatenation
**NeedsWork** | [#runtime/33783](https://github.com/dotnet/runtime/issues/33783#issuecomment-854088293) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=1h13m9s)
It's not clear that the resulting code is "better", especially if it inlines a concatenation across conditional statements (duplicated code costs vs performance benefits). There may be room for "StringBuilder would be better here", but they're hard to describe.
Separating out the unconditional (unobserved) concatenation into a distinct analyzer/diagnostic would be less controversial; but the conditional cases are definitely more complicated.
## Override Stream.ReadByte/WriteByte
**Rejected** | [#runtime/33788](https://github.com/dotnet/runtime/issues/33788#issuecomment-854101396) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=1h31m35s)
Knowing to override ReadByte and WriteByte is something that would show up in a performance analysis, and a performance-improvements focus would likely have already highlighted it.
Without usage on a specific Stream-derived type saying that ReadByte/WriteByte were even called, this is too low value considering the already high cost of implementing a Stream "properly", and so doesn't seem justified.
The group got sidetracked by theorizing about a `DelgatingStream : Stream` type and a new intermediate `Stream` type that rewrites everything in terms of fewer protected abstract methods focused on Span/Memory... but that's not really what this issue was about.
## Prefer Span<T>.Clear() over Span<T>.Fill(default)
**Approved** | [#runtime/33813](https://github.com/dotnet/runtime/issues/33813#issuecomment-854102050) | [Video](https://www.youtube.com/watch?v=m8JAKGO8zrI&t=1h54m32s)
Level: Info
Category: Performance
Looks good as proposed.
| {'content_hash': 'eec279e46d89285416883bff788e7720', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 311, 'avg_line_length': 58.55555555555556, 'alnum_prop': 0.7371916508538899, 'repo_name': 'dotnet/apireviews', 'id': '1569f763e9bbbc8527a45b9a297963a6a594e4bd', 'size': '6391', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': '2021/06-03-quick-reviews/README.md', 'mode': '33188', 'license': 'mit', 'language': []} |
#ifndef _CELM_OBJECT_H
#define _CELM_OBJECT_H
#include "elm.h"
#include "Eo.h"
namespace elm {
using namespace v8;
class CElmObject{
private:
static Persistent<FunctionTemplate> tmpl;
protected:
// Evas_Object *eo;
Persistent<Object> jsObject;
Eo *eobj;
/*
struct {
Persistent<Value> animate;
Persistent<Value> click;
Persistent<Value> key_down;
} cb;
struct {
bool isResize;
} cached;
*/
Ecore_Animator *current_animator;
CElmObject();
CElmObject(Local<Object> _jsObject, Eo *_eobj);
virtual ~CElmObject();
void ApplyProperties(Handle<Object> obj);
template <class T>
static Handle<Value> New(const Arguments& args)
{
HandleScope scope;
if (!args.IsConstructCall())
{
args[0]->ToObject()->SetHiddenValue(String::New("type"), T::GetTemplate()->GetFunction());
return args[0];
}
CElmObject *parent = (args[1] == Undefined()) ? NULL :
static_cast<CElmObject *>(args[1]->ToObject()->GetPointerFromInternalField(0));
T *obj = new T(args.This(), parent);
obj->jsObject.MakeWeak(obj, T::Delete);
/*
Local<Array> properties = obj->jsObject->GetPropertyNames();
for (unsigned int i = 0; i < properties->Length(); i++)
{
Local<String> key = properties->Get(i)->ToString();
String::Utf8Value key_utf(key);
printf(" obj_prop: %s\n", *key_utf);
}
*/
return Undefined();
}
static void Delete(Persistent<Value>, void *parameter);
public:
static void Initialize(Handle<Object> target);
Eo *GetEo() const { return eobj; }
Handle<Object> GetJSObject() const { return jsObject; }
virtual void DidRealiseElement(Local<Value>) {}
static Handle<Value> Realise(const Arguments& args);
static Local<Object> Realise(Handle<Value> desc, Handle<Value> parent);
};
Handle<Value> Callback_elements_get(Local<String>, const AccessorInfo &info);
void Callback_elements_set(Local<String>, Local<Value> value, const AccessorInfo &info);
}
#endif
| {'content_hash': '28d9db0974dbda8cef41d7c51b2a6490', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 103, 'avg_line_length': 24.28735632183908, 'alnum_prop': 0.6261239943208708, 'repo_name': 'yakov-g/eo_bindings', 'id': '07124fb3901f5ce8a75725fb9f78d061d15397ac', 'size': '2113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'eo_js/CElmObject.h', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '390127'}, {'name': 'C++', 'bytes': '14085'}, {'name': 'JavaScript', 'bytes': '22908'}, {'name': 'Python', 'bytes': '158282'}]} |
#ifndef OSMIUM_IO_ANY_OUTPUT_HPP
#define OSMIUM_IO_ANY_OUTPUT_HPP
#include <osmium/io/any_compression.hpp> // IWYU pragma: export
#include <osmium/io/opl_output.hpp> // IWYU pragma: export
#include <osmium/io/pbf_output.hpp> // IWYU pragma: export
#include <osmium/io/xml_output.hpp> // IWYU pragma: export
#endif // OSMIUM_IO_ANY_OUTPUT_HPP
| {'content_hash': 'd8f244b9f130a55cb7c28386fb383e5c', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 63, 'avg_line_length': 28.916666666666668, 'alnum_prop': 0.7319884726224783, 'repo_name': 'antoinegiret/osrm-backend', 'id': '9d97d7d932e028f6540807b85a076b4f034b453e', 'size': '1829', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'third_party/osmium/io/any_output.hpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C++', 'bytes': '1127604'}, {'name': 'CMake', 'bytes': '49863'}, {'name': 'Gherkin', 'bytes': '297801'}, {'name': 'Lua', 'bytes': '38366'}, {'name': 'Python', 'bytes': '1514'}, {'name': 'Ruby', 'bytes': '55838'}]} |
/*
* 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 fuzzy.mf;
import org.apache.commons.math3.util.FastMath;
/**
* Generalized Bell-Shaped Membership Function. Equivalent to Matlab
* <a href="http://www.mathworks.com/help/toolbox/fuzzy/gbellmf.html">gbellmf</a>
* function.
*
* @since 0.1
*/
public class GeneralizedBellShapedMembershipFunction implements MembershipFunction<Double> {
private final double a;
private final double b;
private final double c;
public GeneralizedBellShapedMembershipFunction(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
/*
* (non-Javadoc)
* @see fuzzy.mf.MembershipFunction#apply(java.lang.Object)
*/
@Override
public Double apply(Double x) {
return 1/(1+FastMath.pow(FastMath.abs((x-c)/a), 2*b));
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if(obj == null) {
return false;
}
if(obj == this) {
return true;
}
if(!(obj instanceof GeneralizedBellShapedMembershipFunction)) {
return false;
}
final GeneralizedBellShapedMembershipFunction that = (GeneralizedBellShapedMembershipFunction)obj;
return this.a == that.a && this.b == that.b && this.c == that.c;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int hash = "GeneralizedBellShapedMembershipFunction".hashCode();
hash <<= 2;
hash ^= (int)this.a;
hash <<= 2;
hash ^= (int)this.b;
hash <<= 2;
hash ^= (int)this.c;
return hash;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Generalized Bell-Shaped Membership Function ["+a+" "+b+" "+c+"]";
}
} | {'content_hash': '85bfaa9aac96cef8be1e3c55f1915c41', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 100, 'avg_line_length': 26.75862068965517, 'alnum_prop': 0.6649484536082474, 'repo_name': 'tupilabs/nebular', 'id': '8da23b8d62923943a6076d48f78f11f7e16823f9', 'size': '2328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/fuzzy/mf/GeneralizedBellShapedMembershipFunction.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '872084'}, {'name': 'Perl', 'bytes': '1205'}]} |
package des
import (
"crypto/cipher"
"crypto/internal/alias"
"encoding/binary"
"strconv"
)
// The DES block size in bytes.
const BlockSize = 8
type KeySizeError int
func (k KeySizeError) Error() string {
return "crypto/des: invalid key size " + strconv.Itoa(int(k))
}
// desCipher is an instance of DES encryption.
type desCipher struct {
subkeys [16]uint64
}
// NewCipher creates and returns a new cipher.Block.
func NewCipher(key []byte) (cipher.Block, error) {
if len(key) != 8 {
return nil, KeySizeError(len(key))
}
c := new(desCipher)
c.generateSubkeys(key)
return c, nil
}
func (c *desCipher) BlockSize() int { return BlockSize }
func (c *desCipher) Encrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("crypto/des: input not full block")
}
if len(dst) < BlockSize {
panic("crypto/des: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/des: invalid buffer overlap")
}
encryptBlock(c.subkeys[:], dst, src)
}
func (c *desCipher) Decrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("crypto/des: input not full block")
}
if len(dst) < BlockSize {
panic("crypto/des: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/des: invalid buffer overlap")
}
decryptBlock(c.subkeys[:], dst, src)
}
// A tripleDESCipher is an instance of TripleDES encryption.
type tripleDESCipher struct {
cipher1, cipher2, cipher3 desCipher
}
// NewTripleDESCipher creates and returns a new cipher.Block.
func NewTripleDESCipher(key []byte) (cipher.Block, error) {
if len(key) != 24 {
return nil, KeySizeError(len(key))
}
c := new(tripleDESCipher)
c.cipher1.generateSubkeys(key[:8])
c.cipher2.generateSubkeys(key[8:16])
c.cipher3.generateSubkeys(key[16:])
return c, nil
}
func (c *tripleDESCipher) BlockSize() int { return BlockSize }
func (c *tripleDESCipher) Encrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("crypto/des: input not full block")
}
if len(dst) < BlockSize {
panic("crypto/des: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/des: invalid buffer overlap")
}
b := binary.BigEndian.Uint64(src)
b = permuteInitialBlock(b)
left, right := uint32(b>>32), uint32(b)
left = (left << 1) | (left >> 31)
right = (right << 1) | (right >> 31)
for i := 0; i < 8; i++ {
left, right = feistel(left, right, c.cipher1.subkeys[2*i], c.cipher1.subkeys[2*i+1])
}
for i := 0; i < 8; i++ {
right, left = feistel(right, left, c.cipher2.subkeys[15-2*i], c.cipher2.subkeys[15-(2*i+1)])
}
for i := 0; i < 8; i++ {
left, right = feistel(left, right, c.cipher3.subkeys[2*i], c.cipher3.subkeys[2*i+1])
}
left = (left << 31) | (left >> 1)
right = (right << 31) | (right >> 1)
preOutput := (uint64(right) << 32) | uint64(left)
binary.BigEndian.PutUint64(dst, permuteFinalBlock(preOutput))
}
func (c *tripleDESCipher) Decrypt(dst, src []byte) {
if len(src) < BlockSize {
panic("crypto/des: input not full block")
}
if len(dst) < BlockSize {
panic("crypto/des: output not full block")
}
if alias.InexactOverlap(dst[:BlockSize], src[:BlockSize]) {
panic("crypto/des: invalid buffer overlap")
}
b := binary.BigEndian.Uint64(src)
b = permuteInitialBlock(b)
left, right := uint32(b>>32), uint32(b)
left = (left << 1) | (left >> 31)
right = (right << 1) | (right >> 31)
for i := 0; i < 8; i++ {
left, right = feistel(left, right, c.cipher3.subkeys[15-2*i], c.cipher3.subkeys[15-(2*i+1)])
}
for i := 0; i < 8; i++ {
right, left = feistel(right, left, c.cipher2.subkeys[2*i], c.cipher2.subkeys[2*i+1])
}
for i := 0; i < 8; i++ {
left, right = feistel(left, right, c.cipher1.subkeys[15-2*i], c.cipher1.subkeys[15-(2*i+1)])
}
left = (left << 31) | (left >> 1)
right = (right << 31) | (right >> 1)
preOutput := (uint64(right) << 32) | uint64(left)
binary.BigEndian.PutUint64(dst, permuteFinalBlock(preOutput))
}
| {'content_hash': '289a594c91d22c1b502f1200fee63913', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 94, 'avg_line_length': 26.31788079470199, 'alnum_prop': 0.657775541016608, 'repo_name': 'golang/go', 'id': 'ece764f171ad7b71771d73884f4ba341fd2f38f2', 'size': '4134', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/crypto/des/cipher.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2705689'}, {'name': 'Awk', 'bytes': '450'}, {'name': 'Batchfile', 'bytes': '8497'}, {'name': 'C', 'bytes': '127970'}, {'name': 'C++', 'bytes': '917'}, {'name': 'Dockerfile', 'bytes': '2789'}, {'name': 'Fortran', 'bytes': '100'}, {'name': 'Go', 'bytes': '41103717'}, {'name': 'HTML', 'bytes': '2621340'}, {'name': 'JavaScript', 'bytes': '20492'}, {'name': 'Makefile', 'bytes': '748'}, {'name': 'Perl', 'bytes': '31365'}, {'name': 'Python', 'bytes': '15738'}, {'name': 'Shell', 'bytes': '62900'}]} |
/**
* 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. See accompanying LICENSE file.
*/
package org.apache.hadoop.security.authentication.server;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.net.HttpCookie;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.hadoop.security.authentication.client.AuthenticatedURL;
import org.apache.hadoop.security.authentication.client.AuthenticationException;
import org.apache.hadoop.security.authentication.util.Signer;
import org.apache.hadoop.security.authentication.util.SignerSecretProvider;
import org.apache.hadoop.security.authentication.util.StringSignerSecretProviderCreator;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
public class TestAuthenticationFilter {
private static final long TOKEN_VALIDITY_SEC = 1000;
private static final long TOKEN_MAX_INACTIVE_INTERVAL = 1000;
@Test
public void testGetConfiguration() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("");
Mockito.when(config.getInitParameter("a")).thenReturn("A");
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("a")).elements());
Properties props = filter.getConfiguration("", config);
Assert.assertEquals("A", props.getProperty("a"));
config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo");
Mockito.when(config.getInitParameter("foo.a")).thenReturn("A");
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>(Arrays.asList("foo.a")).elements());
props = filter.getConfiguration("foo.", config);
Assert.assertEquals("A", props.getProperty("a"));
}
@Test
public void testInitEmpty() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameterNames()).thenReturn(new Vector<String>().elements());
filter.init(config);
Assert.fail();
} catch (ServletException ex) {
// Expected
Assert.assertEquals("Authentication type must be specified: simple|kerberos|<class>",
ex.getMessage());
} catch (Exception ex) {
Assert.fail();
} finally {
filter.destroy();
}
}
public static class DummyAuthenticationHandler implements AuthenticationHandler {
public static boolean init;
public static boolean managementOperationReturn;
public static boolean destroy;
public static boolean expired;
public static final String TYPE = "dummy";
public static void reset() {
init = false;
destroy = false;
}
@Override
public void init(Properties config) throws ServletException {
init = true;
managementOperationReturn =
config.getProperty("management.operation.return", "true").equals("true");
expired = config.getProperty("expired.token", "false").equals("true");
}
@Override
public boolean managementOperation(AuthenticationToken token,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, AuthenticationException {
if (!managementOperationReturn) {
response.setStatus(HttpServletResponse.SC_ACCEPTED);
}
return managementOperationReturn;
}
@Override
public void destroy() {
destroy = true;
}
@Override
public String getType() {
return TYPE;
}
@Override
public AuthenticationToken authenticate(HttpServletRequest request, HttpServletResponse response)
throws IOException, AuthenticationException {
AuthenticationToken token = null;
String param = request.getParameter("authenticated");
if (param != null && param.equals("true")) {
token = new AuthenticationToken("u", "p", "t");
token.setExpires((expired) ? 0 : System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
} else {
if (request.getHeader("WWW-Authenticate") == null) {
response.setHeader("WWW-Authenticate", "dummyauth");
} else {
throw new AuthenticationException("AUTH FAILED");
}
}
return token;
}
}
@Test
public void testFallbackToRandomSecretProvider() throws Exception {
// minimal configuration & simple auth handler (Pseudo)
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
Mockito.when(config.getInitParameter(
AuthenticationFilter.AUTH_TOKEN_VALIDITY)).thenReturn(
(new Long(TOKEN_VALIDITY_SEC)).toString());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements());
ServletContext context = Mockito.mock(ServletContext.class);
Mockito.when(context.getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE))
.thenReturn(null);
Mockito.when(config.getServletContext()).thenReturn(context);
filter.init(config);
Assert.assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
Assert.assertTrue(filter.isRandomSecret());
Assert.assertFalse(filter.isCustomSignerSecretProvider());
Assert.assertNull(filter.getCookieDomain());
Assert.assertNull(filter.getCookiePath());
Assert.assertEquals(TOKEN_VALIDITY_SEC, filter.getValidity());
} finally {
filter.destroy();
}
}
@Test
public void testInit() throws Exception {
// custom secret as inline
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<>(Arrays.asList(AuthenticationFilter.AUTH_TYPE))
.elements());
ServletContext context = Mockito.mock(ServletContext.class);
Mockito.when(context.getAttribute(
AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)).thenReturn(
new SignerSecretProvider() {
@Override
public void init(Properties config, ServletContext servletContext,
long tokenValidity) {
}
@Override
public byte[] getCurrentSecret() {
return null;
}
@Override
public byte[][] getAllSecrets() {
return null;
}
});
Mockito.when(config.getServletContext()).thenReturn(context);
filter.init(config);
Assert.assertFalse(filter.isRandomSecret());
Assert.assertTrue(filter.isCustomSignerSecretProvider());
} finally {
filter.destroy();
}
// custom secret by file
File testDir = new File(System.getProperty("test.build.data",
"target/test-dir"));
testDir.mkdirs();
String secretValue = "hadoop";
File secretFile = new File(testDir, "http-secret.txt");
Writer writer = new FileWriter(secretFile);
writer.write(secretValue);
writer.close();
filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(
AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
Mockito.when(config.getInitParameter(
AuthenticationFilter.SIGNATURE_SECRET_FILE))
.thenReturn(secretFile.getAbsolutePath());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET_FILE)).elements());
ServletContext context = Mockito.mock(ServletContext.class);
Mockito.when(context.getAttribute(
AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE))
.thenReturn(null);
Mockito.when(config.getServletContext()).thenReturn(context);
filter.init(config);
Assert.assertFalse(filter.isRandomSecret());
Assert.assertFalse(filter.isCustomSignerSecretProvider());
} finally {
filter.destroy();
}
// custom cookie domain and cookie path
filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple");
Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_DOMAIN)).thenReturn(".foo.com");
Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)).thenReturn("/bar");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.COOKIE_DOMAIN,
AuthenticationFilter.COOKIE_PATH)).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
Assert.assertEquals(".foo.com", filter.getCookieDomain());
Assert.assertEquals("/bar", filter.getCookiePath());
} finally {
filter.destroy();
}
// authentication handler lifecycle, and custom impl
DummyAuthenticationHandler.reset();
filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
Assert.assertTrue(DummyAuthenticationHandler.init);
} finally {
filter.destroy();
Assert.assertTrue(DummyAuthenticationHandler.destroy);
}
// kerberos auth handler
filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
ServletContext sc = Mockito.mock(ServletContext.class);
Mockito.when(config.getServletContext()).thenReturn(sc);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("kerberos");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements());
filter.init(config);
} catch (ServletException ex) {
// Expected
} finally {
Assert.assertEquals(KerberosAuthenticationHandler.class, filter.getAuthenticationHandler().getClass());
filter.destroy();
}
}
@Test
public void testInitCaseSensitivity() throws Exception {
// minimal configuration & simple auth handler (Pseudo)
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("SimPle");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TOKEN_VALIDITY)).thenReturn(
(new Long(TOKEN_VALIDITY_SEC)).toString());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
Assert.assertEquals(PseudoAuthenticationHandler.class,
filter.getAuthenticationHandler().getClass());
} finally {
filter.destroy();
}
}
@Test
public void testGetRequestURL() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
Mockito.when(request.getQueryString()).thenReturn("a=A&b=B");
Assert.assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request));
} finally {
filter.destroy();
}
}
@Test
public void testGetToken() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
SignerSecretProvider secretProvider =
getMockedServletContextWithStringSigner(config);
filter.init(config);
AuthenticationToken token = new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
AuthenticationToken newToken = filter.getToken(request);
Assert.assertEquals(token.toString(), newToken.toString());
} finally {
filter.destroy();
}
}
@Test
public void testGetTokenExpired() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
AuthenticationToken token =
new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
token.setExpires(System.currentTimeMillis() - TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
boolean failed = false;
try {
filter.getToken(request);
} catch (AuthenticationException ex) {
Assert.assertEquals("AuthenticationToken expired", ex.getMessage());
failed = true;
} finally {
Assert.assertTrue("token not expired", failed);
}
} finally {
filter.destroy();
}
}
@Test
public void testGetTokenInvalidType() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
AuthenticationToken token = new AuthenticationToken("u", "p", "invalidtype");
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
boolean failed = false;
try {
filter.getToken(request);
} catch (AuthenticationException ex) {
Assert.assertEquals("Invalid AuthenticationToken type", ex.getMessage());
failed = true;
} finally {
Assert.assertTrue("token not invalid type", failed);
}
} finally {
filter.destroy();
}
}
private static SignerSecretProvider getMockedServletContextWithStringSigner(
FilterConfig config) throws Exception {
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET,
"secret");
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
ServletContext context = Mockito.mock(ServletContext.class);
Mockito.when(context.getAttribute(
AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE))
.thenReturn(secretProvider);
Mockito.when(config.getServletContext()).thenReturn(context);
return secretProvider;
}
@Test
public void testDoFilterNotAuthenticated() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = Mockito.mock(FilterChain.class);
Mockito.doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Assert.fail();
return null;
}
}
).when(chain).doFilter(any(), any());
Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true);
filter.doFilter(request, response, chain);
Mockito.verify(response).sendError(
HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
} finally {
filter.destroy();
}
}
private void _testDoFilterAuthentication(boolean withDomainPath,
boolean invalidToken,
boolean expired) throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter("expired.token")).
thenReturn(Boolean.toString(expired));
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE))
.thenReturn(DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter
.AUTH_TOKEN_VALIDITY)).thenReturn(new Long(TOKEN_VALIDITY_SEC).toString());
Mockito.when(config.getInitParameter(AuthenticationFilter
.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(new
Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.AUTH_TOKEN_VALIDITY,
AuthenticationFilter.SIGNATURE_SECRET, "management.operation" +
".return", "expired.token")).elements());
getMockedServletContextWithStringSigner(config);
if (withDomainPath) {
Mockito.when(config.getInitParameter(AuthenticationFilter
.COOKIE_DOMAIN)).thenReturn(".foo.com");
Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH))
.thenReturn("/bar");
Mockito.when(config.getInitParameterNames()).thenReturn(new
Vector<String>(Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.AUTH_TOKEN_VALIDITY,
AuthenticationFilter.SIGNATURE_SECRET,
AuthenticationFilter.COOKIE_DOMAIN, AuthenticationFilter
.COOKIE_PATH, "management.operation.return")).elements());
}
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getParameter("authenticated")).thenReturn("true");
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer
("http://foo:8080/bar"));
Mockito.when(request.getQueryString()).thenReturn("authenticated=true");
if (invalidToken) {
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{new Cookie
(AuthenticatedURL.AUTH_COOKIE, "foo")});
}
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = Mockito.mock(FilterChain.class);
final Map<String, String> cookieMap = new HashMap<String, String>();
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String cookieHeader = (String)invocation.getArguments()[1];
parseCookieMap(cookieHeader, cookieMap);
return null;
}
}).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());
try {
filter.init(config);
filter.doFilter(request, response, chain);
if (expired) {
Mockito.verify(response, Mockito.never()).
addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());
} else {
String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE);
Assert.assertNotNull("cookie missing", v);
Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains
("t=") && v.contains("e=") && v.contains("s="));
Mockito.verify(chain).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String value = signer.verifyAndExtract(v);
AuthenticationToken token = AuthenticationToken.parse(value);
assertThat(token.getExpires(), not(0L));
if (withDomainPath) {
Assert.assertEquals(".foo.com", cookieMap.get("Domain"));
Assert.assertEquals("/bar", cookieMap.get("Path"));
} else {
Assert.assertFalse(cookieMap.containsKey("Domain"));
Assert.assertFalse(cookieMap.containsKey("Path"));
}
}
} finally {
filter.destroy();
}
}
private static void parseCookieMap(String cookieHeader, Map<String,
String> cookieMap) {
List<HttpCookie> cookies = HttpCookie.parse(cookieHeader);
for (HttpCookie cookie : cookies) {
if (AuthenticatedURL.AUTH_COOKIE.equals(cookie.getName())) {
cookieMap.put(cookie.getName(), cookie.getValue());
if (cookie.getPath() != null) {
cookieMap.put("Path", cookie.getPath());
}
if (cookie.getDomain() != null) {
cookieMap.put("Domain", cookie.getDomain());
}
}
}
}
@Test
public void testDoFilterAuthentication() throws Exception {
_testDoFilterAuthentication(false, false, false);
}
@Test
public void testDoFilterAuthenticationImmediateExpiration() throws Exception {
_testDoFilterAuthentication(false, false, true);
}
@Test
public void testDoFilterAuthenticationWithInvalidToken() throws Exception {
_testDoFilterAuthentication(false, true, false);
}
@Test
public void testDoFilterAuthenticationWithDomainPath() throws Exception {
_testDoFilterAuthentication(true, false, false);
}
@Test
public void testDoFilterAuthenticated() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
AuthenticationToken token = new AuthenticationToken("u", "p", "t");
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = Mockito.mock(FilterChain.class);
Mockito.doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
HttpServletRequest request = (HttpServletRequest) args[0];
Assert.assertEquals("u", request.getRemoteUser());
Assert.assertEquals("p", request.getUserPrincipal().getName());
return null;
}
}
).when(chain).doFilter(any(), any());
filter.doFilter(request, response, chain);
} finally {
filter.destroy();
}
}
@Test
public void testDoFilterAuthenticationFailure() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{});
Mockito.when(request.getHeader("WWW-Authenticate")).thenReturn("dummyauth");
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = Mockito.mock(FilterChain.class);
final Map<String, String> cookieMap = new HashMap<String, String>();
Mockito.doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
parseCookieMap((String) args[1], cookieMap);
return null;
}
}
).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());
Mockito.doAnswer(
new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Assert.fail("shouldn't get here");
return null;
}
}
).when(chain).doFilter(any(), any());
filter.doFilter(request, response, chain);
Mockito.verify(response).sendError(
HttpServletResponse.SC_FORBIDDEN, "AUTH FAILED");
Mockito.verify(response, Mockito.never()).setHeader(Mockito.eq("WWW-Authenticate"), Mockito.anyString());
String value = cookieMap.get(AuthenticatedURL.AUTH_COOKIE);
Assert.assertNotNull("cookie missing", value);
Assert.assertEquals("", value);
} finally {
filter.destroy();
}
}
@Test
public void testDoFilterAuthenticatedExpired() throws Exception {
String secret = "secret";
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(
secret);
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
AuthenticationToken token = new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
token.setExpires(System.currentTimeMillis() - TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, secret);
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true);
FilterChain chain = Mockito.mock(FilterChain.class);
verifyUnauthorized(filter, request, response, chain);
} finally {
filter.destroy();
}
}
@Test
public void
testDoFilterAuthenticationAuthorized() throws Exception {
// Both expired period and MaxInActiveInterval are not reached.
long maxInactives = System.currentTimeMillis()
+ TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
boolean authorized = true;
_testDoFilterAuthenticationMaxInactiveInterval(maxInactives,
expires,
authorized);
}
@Test
public void
testDoFilterAuthenticationUnauthorizedExpired() throws Exception {
// Expired period is reached, MaxInActiveInterval is not reached.
long maxInactives = System.currentTimeMillis()
+ TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() - TOKEN_VALIDITY_SEC;
boolean authorized = false;
_testDoFilterAuthenticationMaxInactiveInterval(maxInactives,
expires,
authorized);
}
@Test
public void
testDoFilterAuthenticationUnauthorizedInactived() throws Exception {
// Expired period is not reached, MaxInActiveInterval is reached.
long maxInactives = System.currentTimeMillis()
- TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
boolean authorized = false;
_testDoFilterAuthenticationMaxInactiveInterval(maxInactives,
expires,
authorized);
}
@Test
public void
testDoFilterAuthenticationUnauthorizedInactivedExpired()
throws Exception {
// Both expired period and MaxInActiveInterval is reached.
long maxInactives = System.currentTimeMillis()
- TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() - TOKEN_VALIDITY_SEC;
boolean authorized = false;
_testDoFilterAuthenticationMaxInactiveInterval(maxInactives,
expires,
authorized);
}
@Test
public void testTokenWithValidActivityInterval() throws Exception {
// Provide token containing valid maxInactive value.
// The token is active.
// The server has maxInactiveInterval configured to -1.(disabled)
// The server shall authorize the access, but should not drop a new cookie
long maxInactives = System.currentTimeMillis()
+ TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
maxInactives,
-1,
expires,
true, //authorized
false //newCookie
);
// Provide token containing valid maxInactive value.
// The token is active.
// The server has maxInactiveInterval configured to value
// greater than 0.(enabled)
// The server shall authorize the access and drop a new cookie
// with renewed activity interval
maxInactives = System.currentTimeMillis()
+ TOKEN_MAX_INACTIVE_INTERVAL;
expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
maxInactives,
TOKEN_MAX_INACTIVE_INTERVAL,
expires,
true, //authorized
true //newCookie
);
}
@Test
public void testTokenWithExpiredActivityIntervaln() throws Exception {
// Provide token containing invalid maxInactive value.
// The token is inactive.
// The server has maxInactiveInterval configured to -1.(disabled)
// The server should deny access and expire the token.
long maxInactives = System.currentTimeMillis()
- TOKEN_MAX_INACTIVE_INTERVAL;
long expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
maxInactives,
-1,
expires,
false, //authorized
false //newCookie
);
// Provide token containing invalid maxInactive value.
// The token is inactive.
// The server has maxInactiveInterval configured to value
// greater than 0.(enabled)
// The server should deny access and expire the token.
maxInactives = System.currentTimeMillis()
+ TOKEN_MAX_INACTIVE_INTERVAL;
expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
maxInactives,
-1,
expires,
true, //authorized
false //newCookie
);
}
@Test
public void testTokenWithNoActivityIntervals()
throws Exception {
// Provide token which does not contain maxInactive value.
// The server has maxInactiveInterval configured to -1.
// The server shall authorize the access, but should not drop a new cookie
long expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
-1,
-1,
expires,
true, //authorized
false //newCookie
);
// Provide token which does not contain maxInactive value.
// The server has maxInactiveInterval to some value
// The server shall authorize the access and drop a new cookie
// with renewed activity interval
expires = System.currentTimeMillis() + TOKEN_VALIDITY_SEC;
_testDoFilterAuthenticationMaxInactiveInterval(
-1,
TOKEN_MAX_INACTIVE_INTERVAL,
expires,
true, //authorized
true //newCookie
);
}
private void
_testDoFilterAuthenticationMaxInactiveInterval(long maxInactivesInToken,
long expires,
boolean authorized)
throws Exception {
_testDoFilterAuthenticationMaxInactiveInterval(maxInactivesInToken,
TOKEN_MAX_INACTIVE_INTERVAL, expires, authorized, true);
}
private void
_testDoFilterAuthenticationMaxInactiveInterval(long maxInactivesInToken,
long maxInactivesOnServer,
long expires,
boolean authorized,
boolean newCookie)
throws Exception {
String secret = "secret";
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(
AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(
AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(secret);
Mockito.when(config.getInitParameter(
AuthenticationFilter.AUTH_TOKEN_MAX_INACTIVE_INTERVAL)).thenReturn(
Long.toString(maxInactivesOnServer));
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
AuthenticationFilter.AUTH_TOKEN_MAX_INACTIVE_INTERVAL,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(
new StringBuffer("http://foo:8080/bar"));
AuthenticationToken token = new AuthenticationToken("u", "p",
DummyAuthenticationHandler.TYPE);
token.setMaxInactives(maxInactivesInToken);
token.setExpires(expires);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, secret);
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(response.containsHeader("WWW-Authenticate"))
.thenReturn(true);
FilterChain chain = Mockito.mock(FilterChain.class);
if (authorized) {
verifyAuthorized(filter, request, response, chain, newCookie);
} else {
verifyUnauthorized(filter, request, response, chain);
}
} finally {
filter.destroy();
}
}
private static void verifyAuthorized(AuthenticationFilter filter,
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
boolean newCookie) throws
Exception {
final Map<String, String> cookieMap = new HashMap<>();
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String cookieHeader = (String) invocation.getArguments()[1];
parseCookieMap(cookieHeader, cookieMap);
return null;
}
}).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());
filter.doFilter(request, response, chain);
if (newCookie) {
// a new cookie should be dropped when maxInactiveInterval is enabled
String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE);
Assert.assertNotNull("cookie missing", v);
Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains
("t=") && v.contains("i=") && v.contains("e=")
&& v.contains("s="));
Mockito.verify(chain).doFilter(any(ServletRequest.class),
any(ServletResponse.class));
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String value = signer.verifyAndExtract(v);
AuthenticationToken token = AuthenticationToken.parse(value);
assertThat(token.getMaxInactives(), not(0L));
assertThat(token.getExpires(), not(0L));
Assert.assertFalse("Token is expired.", token.isExpired());
} else {
//make sure that no auth cookie is dropped.
//For unauthorized response, auth cookie is dropped with empty value
Assert.assertTrue("cookie is present",
!cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE));
}
}
private static void verifyUnauthorized(AuthenticationFilter filter,
HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws
IOException,
ServletException {
//For unauthorized response, a cookie is dropped with empty string as value
final Map<String, String> cookieMap = new HashMap<String, String>();
Mockito.doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String cookieHeader = (String) invocation.getArguments()[1];
parseCookieMap(cookieHeader, cookieMap);
return null;
}
}).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString());
filter.doFilter(request, response, chain);
Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse
.SC_UNAUTHORIZED), Mockito.anyString());
Mockito.verify(chain, Mockito.never()).doFilter(
any(ServletRequest.class), any(ServletResponse.class));
Assert.assertTrue("cookie is missing",
cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE));
Assert.assertEquals("", cookieMap.get(AuthenticatedURL.AUTH_COOKIE));
}
@Test
public void testDoFilterAuthenticatedInvalidType() throws Exception {
String secret = "secret";
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(
secret);
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar"));
AuthenticationToken token = new AuthenticationToken("u", "p", "invalidtype");
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, secret);
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true);
FilterChain chain = Mockito.mock(FilterChain.class);
verifyUnauthorized(filter, request, response, chain);
} finally {
filter.destroy();
}
}
@Test
public void testManagementOperation() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("false");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).
thenReturn(DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
"management.operation.return")).elements());
getMockedServletContextWithStringSigner(config);
filter.init(config);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getRequestURL()).
thenReturn(new StringBuffer("http://foo:8080/bar"));
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
FilterChain chain = Mockito.mock(FilterChain.class);
filter.doFilter(request, response, chain);
Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED);
Mockito.verifyNoMoreInteractions(response);
Mockito.reset(request);
Mockito.reset(response);
AuthenticationToken token = new AuthenticationToken("u", "p", "t");
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
SignerSecretProvider secretProvider =
StringSignerSecretProviderCreator.newStringSignerSecretProvider();
Properties secretProviderProps = new Properties();
secretProviderProps.setProperty(
AuthenticationFilter.SIGNATURE_SECRET, "secret");
secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer());
filter.doFilter(request, response, chain);
Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED);
Mockito.verifyNoMoreInteractions(response);
} finally {
filter.destroy();
}
}
}
| {'content_hash': 'd8ef4dfb8a49d0a7160d921e43ab6135', 'timestamp': '', 'source': 'github', 'line_count': 1248, 'max_line_length': 115, 'avg_line_length': 42.75480769230769, 'alnum_prop': 0.6817346977023127, 'repo_name': 'steveloughran/hadoop', 'id': '20c0343f957b770b00987d3bbd69a0cdb11112c1', 'size': '53358', 'binary': False, 'copies': '5', 'ref': 'refs/heads/trunk', 'path': 'hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationFilter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '78591'}, {'name': 'C', 'bytes': '1974547'}, {'name': 'C++', 'bytes': '2861923'}, {'name': 'CMake', 'bytes': '115553'}, {'name': 'CSS', 'bytes': '117128'}, {'name': 'Dockerfile', 'bytes': '7311'}, {'name': 'HTML', 'bytes': '420629'}, {'name': 'Java', 'bytes': '93884754'}, {'name': 'JavaScript', 'bytes': '1245137'}, {'name': 'Python', 'bytes': '23553'}, {'name': 'Shell', 'bytes': '480813'}, {'name': 'TLA', 'bytes': '14997'}, {'name': 'TSQL', 'bytes': '30600'}, {'name': 'TeX', 'bytes': '19322'}, {'name': 'XSLT', 'bytes': '18026'}]} |
&& !defined(BOOST_MPL_PREPROCESSING_MODE) \
&& BOOST_WORKAROUND(BOOST_MSVC, < 1300)
# define BOOST_MPL_CFG_NTTP_BUG
#endif
#endif // BOOST_MPL_AUX_CONFIG_NTTP_HPP_INCLUDED
| {'content_hash': '928a3f0c7b2c8fb16fe83092595e8b4f', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 48, 'avg_line_length': 23.125, 'alnum_prop': 0.6810810810810811, 'repo_name': 'gazzlab/LSL-gazzlab-branch', 'id': 'fca1aa01928ffd454d2e0a94f6642cf8aade84f5', 'size': '1127', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'liblsl/external/lslboost/mpl/aux_/config/nttp.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '63003'}, {'name': 'C++', 'bytes': '53791427'}, {'name': 'Objective-C', 'bytes': '39516'}, {'name': 'Perl', 'bytes': '2051'}, {'name': 'Python', 'bytes': '4119'}, {'name': 'Shell', 'bytes': '2310'}]} |
using Microsoft.AspNetCore.Mvc;
namespace HtmlGenerationWebSite.Areas.Customer.Controllers;
[Area("Customer")]
public class HtmlGeneration_CustomerController : Controller
{
public IActionResult Index(Models.Customer customer)
{
return View("Customer");
}
[HttpGet]
public IActionResult CustomerWithRecords()
{
return View("CustomerWithRecords");
}
public IActionResult CustomerWithRecords(Models.CustomerRecord customer)
{
return View("CustomerWithRecords");
}
}
| {'content_hash': 'a5929c56890507493722b46ccf41d59f', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 76, 'avg_line_length': 23.08695652173913, 'alnum_prop': 0.7137476459510358, 'repo_name': 'aspnet/AspNetCore', 'id': '832a542c23522b9b59eb896b14562be5c2ce691e', 'size': '669', 'binary': False, 'copies': '1', 'ref': 'refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2', 'path': 'src/Mvc/test/WebSites/HtmlGenerationWebSite/Areas/Customer/Controllers/HtmlGeneration_CustomerController.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '109'}, {'name': 'Batchfile', 'bytes': '19526'}, {'name': 'C', 'bytes': '213916'}, {'name': 'C#', 'bytes': '47455169'}, {'name': 'C++', 'bytes': '1900454'}, {'name': 'CMake', 'bytes': '7955'}, {'name': 'CSS', 'bytes': '62326'}, {'name': 'Dockerfile', 'bytes': '3584'}, {'name': 'F#', 'bytes': '7982'}, {'name': 'Groovy', 'bytes': '1529'}, {'name': 'HTML', 'bytes': '1130653'}, {'name': 'Java', 'bytes': '297552'}, {'name': 'JavaScript', 'bytes': '2726829'}, {'name': 'Lua', 'bytes': '4904'}, {'name': 'Makefile', 'bytes': '220'}, {'name': 'Objective-C', 'bytes': '222'}, {'name': 'PowerShell', 'bytes': '241706'}, {'name': 'Python', 'bytes': '19476'}, {'name': 'Roff', 'bytes': '6044'}, {'name': 'Shell', 'bytes': '142293'}, {'name': 'Smalltalk', 'bytes': '3'}, {'name': 'TypeScript', 'bytes': '797435'}]} |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.api.integration.archive;
import com.yahoo.config.provision.TenantName;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.tenant.ArchiveAccess;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/**
* @author freva
* @author andreer
*/
public class MockArchiveService implements ArchiveService {
public Set<ArchiveBucket> archiveBuckets = new HashSet<>();
public Map<TenantName, ArchiveAccess> authorizeAccessByTenantName = new HashMap<>();
@Override
public ArchiveBucket createArchiveBucketFor(ZoneId zoneId) {
return new ArchiveBucket("bucketName", "keyArn");
}
@Override
public void updatePolicies(ZoneId zoneId, Set<ArchiveBucket> buckets, Map<TenantName, ArchiveAccess> authorizeAccessByTenantName) {
this.archiveBuckets = new HashSet<>(buckets);
this.authorizeAccessByTenantName = new HashMap<>(authorizeAccessByTenantName);
}
@Override
public boolean canAddTenantToBucket(ZoneId zoneId, ArchiveBucket bucket) {
return bucket.tenants().size() < 5;
}
@Override
public URI bucketURI(ZoneId zoneId, String bucketName, TenantName tenantName) {
return URI.create(String.format("s3://%s/%s/", bucketName, tenantName.value()));
}
}
| {'content_hash': '872b20885abd2baa3d37cc26907efd56', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 135, 'avg_line_length': 32.95652173913044, 'alnum_prop': 0.7407651715039578, 'repo_name': 'vespa-engine/vespa', 'id': 'a2847439ce7af9c19e9a325052f05c3d0e34bf2b', 'size': '1516', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/archive/MockArchiveService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '8130'}, {'name': 'C', 'bytes': '60315'}, {'name': 'C++', 'bytes': '29580035'}, {'name': 'CMake', 'bytes': '593981'}, {'name': 'Emacs Lisp', 'bytes': '91'}, {'name': 'GAP', 'bytes': '3312'}, {'name': 'Go', 'bytes': '560664'}, {'name': 'HTML', 'bytes': '54520'}, {'name': 'Java', 'bytes': '40814190'}, {'name': 'JavaScript', 'bytes': '73436'}, {'name': 'LLVM', 'bytes': '6152'}, {'name': 'Lex', 'bytes': '11499'}, {'name': 'Makefile', 'bytes': '5553'}, {'name': 'Objective-C', 'bytes': '12369'}, {'name': 'Perl', 'bytes': '23134'}, {'name': 'Python', 'bytes': '52392'}, {'name': 'Roff', 'bytes': '17506'}, {'name': 'Ruby', 'bytes': '10690'}, {'name': 'Shell', 'bytes': '268737'}, {'name': 'Yacc', 'bytes': '14735'}]} |
package com.amazonaws.services.inspector.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/inspector-2016-02-16/ListAssessmentRuns" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListAssessmentRunsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* A list of ARNs that specifies the assessment runs that are returned by the action.
* </p>
*/
private java.util.List<String> assessmentRunArns;
/**
* <p>
* When a response is generated, if there is more data to be listed, this parameter is present in the response and
* contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination request. If there is no
* more data to be listed, this parameter is set to null.
* </p>
*/
private String nextToken;
/**
* <p>
* A list of ARNs that specifies the assessment runs that are returned by the action.
* </p>
*
* @return A list of ARNs that specifies the assessment runs that are returned by the action.
*/
public java.util.List<String> getAssessmentRunArns() {
return assessmentRunArns;
}
/**
* <p>
* A list of ARNs that specifies the assessment runs that are returned by the action.
* </p>
*
* @param assessmentRunArns
* A list of ARNs that specifies the assessment runs that are returned by the action.
*/
public void setAssessmentRunArns(java.util.Collection<String> assessmentRunArns) {
if (assessmentRunArns == null) {
this.assessmentRunArns = null;
return;
}
this.assessmentRunArns = new java.util.ArrayList<String>(assessmentRunArns);
}
/**
* <p>
* A list of ARNs that specifies the assessment runs that are returned by the action.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setAssessmentRunArns(java.util.Collection)} or {@link #withAssessmentRunArns(java.util.Collection)} if
* you want to override the existing values.
* </p>
*
* @param assessmentRunArns
* A list of ARNs that specifies the assessment runs that are returned by the action.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAssessmentRunsResult withAssessmentRunArns(String... assessmentRunArns) {
if (this.assessmentRunArns == null) {
setAssessmentRunArns(new java.util.ArrayList<String>(assessmentRunArns.length));
}
for (String ele : assessmentRunArns) {
this.assessmentRunArns.add(ele);
}
return this;
}
/**
* <p>
* A list of ARNs that specifies the assessment runs that are returned by the action.
* </p>
*
* @param assessmentRunArns
* A list of ARNs that specifies the assessment runs that are returned by the action.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAssessmentRunsResult withAssessmentRunArns(java.util.Collection<String> assessmentRunArns) {
setAssessmentRunArns(assessmentRunArns);
return this;
}
/**
* <p>
* When a response is generated, if there is more data to be listed, this parameter is present in the response and
* contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination request. If there is no
* more data to be listed, this parameter is set to null.
* </p>
*
* @param nextToken
* When a response is generated, if there is more data to be listed, this parameter is present in the
* response and contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination
* request. If there is no more data to be listed, this parameter is set to null.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* When a response is generated, if there is more data to be listed, this parameter is present in the response and
* contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination request. If there is no
* more data to be listed, this parameter is set to null.
* </p>
*
* @return When a response is generated, if there is more data to be listed, this parameter is present in the
* response and contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination
* request. If there is no more data to be listed, this parameter is set to null.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* When a response is generated, if there is more data to be listed, this parameter is present in the response and
* contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination request. If there is no
* more data to be listed, this parameter is set to null.
* </p>
*
* @param nextToken
* When a response is generated, if there is more data to be listed, this parameter is present in the
* response and contains the value to use for the <b>nextToken</b> parameter in a subsequent pagination
* request. If there is no more data to be listed, this parameter is set to null.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListAssessmentRunsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAssessmentRunArns() != null)
sb.append("AssessmentRunArns: ").append(getAssessmentRunArns()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListAssessmentRunsResult == false)
return false;
ListAssessmentRunsResult other = (ListAssessmentRunsResult) obj;
if (other.getAssessmentRunArns() == null ^ this.getAssessmentRunArns() == null)
return false;
if (other.getAssessmentRunArns() != null && other.getAssessmentRunArns().equals(this.getAssessmentRunArns()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAssessmentRunArns() == null) ? 0 : getAssessmentRunArns().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListAssessmentRunsResult clone() {
try {
return (ListAssessmentRunsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
| {'content_hash': 'd1decec773a193469c44134a88749fa2', 'timestamp': '', 'source': 'github', 'line_count': 211, 'max_line_length': 151, 'avg_line_length': 38.29857819905213, 'alnum_prop': 0.6426184878109145, 'repo_name': 'dagnir/aws-sdk-java', 'id': 'c9ebd7e9f2e08e0a68900c7440795b96a61b09a6', 'size': '8661', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-inspector/src/main/java/com/amazonaws/services/inspector/model/ListAssessmentRunsResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '157317'}, {'name': 'Gherkin', 'bytes': '25556'}, {'name': 'Java', 'bytes': '165755153'}, {'name': 'Scilab', 'bytes': '3561'}]} |
package io.vertigo.orchestra.services;
import io.vertigo.core.component.Component;
import io.vertigo.orchestra.services.execution.ProcessExecutor;
import io.vertigo.orchestra.services.log.ProcessLogger;
import io.vertigo.orchestra.services.report.ProcessReport;
import io.vertigo.orchestra.services.schedule.ProcessScheduler;
/**
* Interface (interne) de gestion des executions des processus Orchestra.
*
* @author KleeGroup.
* @version $Id$
*/
public interface OrchestraServices extends Component {
/**
* Executes the processes (scheduled or manual)
* @return the executor
*/
ProcessExecutor getExecutor();
/**
* Only accessible if a plugin has been registered
* @return the report
*/
ProcessReport getReport();
/**
* Only accessible if a plugin has been registered
* @return the processLogger
*/
ProcessLogger getLogger();
/**
* @return the scheduler
*/
ProcessScheduler getScheduler();
}
| {'content_hash': 'ba9fe5d2905c456460c48814fe400bf0', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 73, 'avg_line_length': 23.325, 'alnum_prop': 0.7491961414790996, 'repo_name': 'KleeGroup/vertigo-addons', 'id': 'd960476dce613d1d36b3c10f4cefcb4b56d1acd3', 'size': '1728', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vertigo-orchestra/src/main/java/io/vertigo/orchestra/services/OrchestraServices.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '175395'}]} |
home: true
layout: AEUX
heroImage: AEUX_Panels.png
tagline: UX motion design with the tools you like
actionText: Get started →
actionLink: /guide/
features:
- title: Real layers
details: Build visual design layers in After Effects as editable as possible with shape and text layers. Images will be exported and built as files when needed –even from Figma in the browser.
- title: Grouping/Ungrouping
details: In Ae, a layer exists either in the current comp or somewhere else –which is very different from the grouping in most design apps. It is now possible to group and ungroup precomped layers.
- title: Flexibility
details: AEUX is less as an exporter and more of a portal between design and motion. Transfer what you need instead of organizing hundreds of layers before even setting a keyframe.
footer: Built by <a href="http://battleaxe.co">Adam Plouff</a> and your friends at <a href="https://wearesumux.appspot.com/">Google motion design</a>
---
| {'content_hash': '22eed03391c0e0d40c42482a4f7022fa', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 199, 'avg_line_length': 64.0, 'alnum_prop': 0.778125, 'repo_name': 'google/AEUX', 'id': 'dfcecc78c8726f14fdebd4eec32f7b1398092abb', 'size': '970', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'Documentation/docs/README.md', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7628'}, {'name': 'HTML', 'bytes': '9643'}, {'name': 'JavaScript', 'bytes': '399271'}, {'name': 'TypeScript', 'bytes': '187568'}, {'name': 'Vue', 'bytes': '79953'}]} |
package com.tvd12.ezyfox.mapping.test.jackson;
import com.tvd12.ezyfox.mapping.jackson.EzySimpleJsonMapper;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.testng.annotations.Test;
public class EzySimpleJsonMapperTest {
@Test
public void test() {
EzySimpleJsonMapper mapper = EzySimpleJsonMapper.builder()
.build();
System.out.println(mapper.writeAsString(new A("hello")));
System.out.println(mapper.writeAsString(new B("world")));
}
@Getter
@Setter
@ToString
@AllArgsConstructor
public static class A {
private String name;
}
@Setter
@ToString
@AllArgsConstructor
public static class B {
protected String name;
@SuppressWarnings("unused")
public String getName() {
throw new RuntimeException();
}
}
}
| {'content_hash': '565fa658b5aca6c06171130f1fe51beb', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 66, 'avg_line_length': 23.512820512820515, 'alnum_prop': 0.6663031624863686, 'repo_name': 'youngmonkeys/ezyfox', 'id': '60e076019281ce6477ef8624696d049bf08c2cf5', 'size': '917', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ezyfox-mapping/src/test/java/com/tvd12/ezyfox/mapping/test/jackson/EzySimpleJsonMapperTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '100'}, {'name': 'Java', 'bytes': '2124702'}, {'name': 'Shell', 'bytes': '138'}]} |
using content::NavigationEntry;
class SessionServiceTest : public BrowserWithTestWindowTest,
public content::NotificationObserver {
public:
SessionServiceTest() : window_bounds(0, 1, 2, 3), sync_save_count_(0){}
protected:
virtual void SetUp() {
BrowserWithTestWindowTest::SetUp();
std::string b = base::Int64ToString(base::Time::Now().ToInternalValue());
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
path_ = temp_dir_.path().Append(FILE_PATH_LITERAL("SessionTestDirs"));
ASSERT_TRUE(file_util::CreateDirectory(path_));
path_ = path_.AppendASCII(b);
SessionService* session_service = new SessionService(path_);
helper_.set_service(session_service);
service()->SetWindowType(
window_id, Browser::TYPE_TABBED, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window_id,
window_bounds,
ui::SHOW_STATE_NORMAL);
}
// Upon notification, increment the sync_save_count variable
void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
ASSERT_EQ(type, chrome::NOTIFICATION_SESSION_SERVICE_SAVED);
sync_save_count_++;
}
virtual void TearDown() {
helper_.set_service(NULL);
}
void UpdateNavigation(const SessionID& window_id,
const SessionID& tab_id,
const TabNavigation& navigation,
int index,
bool select) {
scoped_ptr<NavigationEntry> entry(NavigationEntry::Create());
entry->SetURL(navigation.virtual_url());
entry->SetReferrer(navigation.referrer());
entry->SetTitle(navigation.title());
entry->SetContentState(navigation.state());
entry->SetTransitionType(navigation.transition());
entry->SetHasPostData(
navigation.type_mask() & TabNavigation::HAS_POST_DATA);
entry->SetOriginalRequestURL(navigation.original_request_url());
service()->UpdateTabNavigation(window_id, tab_id, index, *entry.get());
if (select)
service()->SetSelectedNavigationIndex(window_id, tab_id, index);
}
void ReadWindows(std::vector<SessionWindow*>* windows) {
// Forces closing the file.
helper_.set_service(NULL);
SessionService* session_service = new SessionService(path_);
helper_.set_service(session_service);
helper_.ReadWindows(windows);
}
// Configures the session service with one window with one tab and a single
// navigation. If |pinned_state| is true or |write_always| is true, the
// pinned state of the tab is updated. The session service is then recreated
// and the pinned state of the read back tab is returned.
bool CreateAndWriteSessionWithOneTab(bool pinned_state, bool write_always) {
SessionID tab_id;
TabNavigation nav1(0, GURL("http://google.com"),
content::Referrer(GURL("http://www.referrer.com"),
WebKit::WebReferrerPolicyDefault),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
if (pinned_state || write_always)
helper_.service()->SetPinnedState(window_id, tab_id, pinned_state);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
EXPECT_EQ(1U, windows->size());
if (HasFatalFailure())
return false;
EXPECT_EQ(1U, windows[0]->tabs.size());
if (HasFatalFailure())
return false;
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
return tab->pinned;
}
SessionService* service() { return helper_.service(); }
SessionBackend* backend() { return helper_.backend(); }
const gfx::Rect window_bounds;
SessionID window_id;
int sync_save_count_;
// Path used in testing.
ScopedTempDir temp_dir_;
FilePath path_;
SessionServiceTestHelper helper_;
};
TEST_F(SessionServiceTest, Basic) {
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
TabNavigation nav1(0, GURL("http://google.com"),
content::Referrer(GURL("http://www.referrer.com"),
WebKit::WebReferrerPolicyDefault),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
nav1.set_original_request_url(GURL("http://original.request.com"));
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_TRUE(window_bounds == windows[0]->bounds);
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(1U, windows[0]->tabs.size());
ASSERT_EQ(Browser::TYPE_TABBED, windows[0]->type);
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
}
// Make sure we persist post entries.
TEST_F(SessionServiceTest, PersistPostData) {
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), std::string(),
content::PAGE_TRANSITION_QUALIFIER_MASK);
nav1.set_type_mask(TabNavigation::HAS_POST_DATA);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
helper_.AssertSingleWindowWithSingleTab(windows.get(), 1);
}
TEST_F(SessionServiceTest, ClosingTabStaysClosed) {
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(tab_id.id(), tab2_id.id());
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window_id, tab2_id, 1, false);
UpdateNavigation(window_id, tab2_id, nav2, 0, true);
service()->TabClosed(window_id, tab2_id, false);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(1U, windows[0]->tabs.size());
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
}
TEST_F(SessionServiceTest, Pruning) {
SessionID tab_id;
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
for (int i = 0; i < 6; ++i) {
TabNavigation& nav = (i % 2) == 0 ? nav1 : nav2;
UpdateNavigation(window_id, tab_id, nav, i, true);
}
service()->TabNavigationPathPrunedFromBack(window_id, tab_id, 3);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(1U, windows[0]->tabs.size());
SessionTab* tab = windows[0]->tabs[0];
// We left the selected index at 5, then pruned. When rereading the
// index should get reset to last valid navigation, which is 2.
helper_.AssertTabEquals(window_id, tab_id, 0, 2, 3, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
helper_.AssertNavigationEquals(nav2, tab->navigations[1]);
helper_.AssertNavigationEquals(nav1, tab->navigations[2]);
}
TEST_F(SessionServiceTest, TwoWindows) {
SessionID window2_id;
SessionID tab1_id;
SessionID tab2_id;
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab1_id, 0, true);
UpdateNavigation(window_id, tab1_id, nav1, 0, true);
const gfx::Rect window2_bounds(3, 4, 5, 6);
service()->SetWindowType(
window2_id, Browser::TYPE_TABBED, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window2_id,
window2_bounds,
ui::SHOW_STATE_MAXIMIZED);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, true);
UpdateNavigation(window2_id, tab2_id, nav2, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(2U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(0, windows[1]->selected_tab_index);
ASSERT_EQ(1U, windows[0]->tabs.size());
ASSERT_EQ(1U, windows[1]->tabs.size());
SessionTab* rt1;
SessionTab* rt2;
if (windows[0]->window_id.id() == window_id.id()) {
ASSERT_EQ(window2_id.id(), windows[1]->window_id.id());
ASSERT_EQ(ui::SHOW_STATE_NORMAL, windows[0]->show_state);
ASSERT_EQ(ui::SHOW_STATE_MAXIMIZED, windows[1]->show_state);
rt1 = windows[0]->tabs[0];
rt2 = windows[1]->tabs[0];
} else {
ASSERT_EQ(window2_id.id(), windows[0]->window_id.id());
ASSERT_EQ(window_id.id(), windows[1]->window_id.id());
ASSERT_EQ(ui::SHOW_STATE_MAXIMIZED, windows[0]->show_state);
ASSERT_EQ(ui::SHOW_STATE_NORMAL, windows[1]->show_state);
rt1 = windows[1]->tabs[0];
rt2 = windows[0]->tabs[0];
}
SessionTab* tab = rt1;
helper_.AssertTabEquals(window_id, tab1_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
tab = rt2;
helper_.AssertTabEquals(window2_id, tab2_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav2, tab->navigations[0]);
}
TEST_F(SessionServiceTest, WindowWithNoTabsGetsPruned) {
SessionID window2_id;
SessionID tab1_id;
SessionID tab2_id;
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab1_id, 0, true);
UpdateNavigation(window_id, tab1_id, nav1, 0, true);
const gfx::Rect window2_bounds(3, 4, 5, 6);
service()->SetWindowType(
window2_id, Browser::TYPE_TABBED, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window2_id,
window2_bounds,
ui::SHOW_STATE_NORMAL);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(1U, windows[0]->tabs.size());
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab1_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
}
TEST_F(SessionServiceTest, ClosingWindowDoesntCloseTabs) {
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(tab_id.id(), tab2_id.id());
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window_id, tab2_id, 1, false);
UpdateNavigation(window_id, tab2_id, nav2, 0, true);
service()->WindowClosing(window_id);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(2U, windows[0]->tabs.size());
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
tab = windows[0]->tabs[1];
helper_.AssertTabEquals(window_id, tab2_id, 1, 0, 1, *tab);
helper_.AssertNavigationEquals(nav2, tab->navigations[0]);
}
TEST_F(SessionServiceTest, WindowCloseCommittedAfterNavigate) {
SessionID window2_id;
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(window2_id.id(), window_id.id());
service()->SetWindowType(
window2_id, Browser::TYPE_TABBED, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window2_id,
window_bounds,
ui::SHOW_STATE_NORMAL);
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, false);
UpdateNavigation(window2_id, tab2_id, nav2, 0, true);
service()->WindowClosing(window2_id);
service()->TabClosed(window2_id, tab2_id, false);
service()->WindowClosed(window2_id);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(1U, windows[0]->tabs.size());
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
}
// Makes sure we don't track popups.
TEST_F(SessionServiceTest, IgnorePopups) {
if (browser_defaults::kRestorePopups)
return; // This test is only applicable if popups aren't restored.
SessionID window2_id;
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(window2_id.id(), window_id.id());
service()->SetWindowType(
window2_id, Browser::TYPE_POPUP, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window2_id,
window_bounds,
ui::SHOW_STATE_NORMAL);
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, false);
UpdateNavigation(window2_id, tab2_id, nav2, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(1U, windows[0]->tabs.size());
SessionTab* tab = windows[0]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
}
// Makes sure we track popups.
TEST_F(SessionServiceTest, RestorePopup) {
if (!browser_defaults::kRestorePopups)
return; // This test is only applicable if popups are restored.
SessionID window2_id;
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(window2_id.id(), window_id.id());
service()->SetWindowType(
window2_id, Browser::TYPE_POPUP, SessionService::TYPE_NORMAL);
service()->SetWindowBounds(window2_id,
window_bounds,
ui::SHOW_STATE_NORMAL);
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, false);
UpdateNavigation(window2_id, tab2_id, nav2, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(2U, windows->size());
int tabbed_index = windows[0]->type == Browser::TYPE_TABBED ?
0 : 1;
int popup_index = tabbed_index == 0 ? 1 : 0;
ASSERT_EQ(0, windows[tabbed_index]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[tabbed_index]->window_id.id());
ASSERT_EQ(1U, windows[tabbed_index]->tabs.size());
SessionTab* tab = windows[tabbed_index]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
ASSERT_EQ(0, windows[popup_index]->selected_tab_index);
ASSERT_EQ(window2_id.id(), windows[popup_index]->window_id.id());
ASSERT_EQ(1U, windows[popup_index]->tabs.size());
tab = windows[popup_index]->tabs[0];
helper_.AssertTabEquals(window2_id, tab2_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav2, tab->navigations[0]);
}
#if defined (USE_AURA)
// Makes sure we track apps. Only applicable on aura.
TEST_F(SessionServiceTest, RestoreApp) {
SessionID window2_id;
SessionID tab_id;
SessionID tab2_id;
ASSERT_NE(window2_id.id(), window_id.id());
service()->SetWindowType(
window2_id, Browser::TYPE_POPUP, SessionService::TYPE_APP);
service()->SetWindowBounds(window2_id,
window_bounds,
ui::SHOW_STATE_NORMAL);
service()->SetWindowAppName(window2_id, "TestApp");
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
TabNavigation nav2(0, GURL("http://google2.com"), content::Referrer(),
ASCIIToUTF16("abcd"), "defg",
content::PAGE_TRANSITION_AUTO_BOOKMARK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.PrepareTabInWindow(window2_id, tab2_id, 0, false);
UpdateNavigation(window2_id, tab2_id, nav2, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(2U, windows->size());
int tabbed_index = windows[0]->type == Browser::TYPE_TABBED ?
0 : 1;
int app_index = tabbed_index == 0 ? 1 : 0;
ASSERT_EQ(0, windows[tabbed_index]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[tabbed_index]->window_id.id());
ASSERT_EQ(1U, windows[tabbed_index]->tabs.size());
SessionTab* tab = windows[tabbed_index]->tabs[0];
helper_.AssertTabEquals(window_id, tab_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav1, tab->navigations[0]);
ASSERT_EQ(0, windows[app_index]->selected_tab_index);
ASSERT_EQ(window2_id.id(), windows[app_index]->window_id.id());
ASSERT_EQ(1U, windows[app_index]->tabs.size());
ASSERT_TRUE(windows[app_index]->type == Browser::TYPE_POPUP);
ASSERT_EQ("TestApp", windows[app_index]->app_name);
tab = windows[app_index]->tabs[0];
helper_.AssertTabEquals(window2_id, tab2_id, 0, 0, 1, *tab);
helper_.AssertNavigationEquals(nav2, tab->navigations[0]);
}
#endif
// Tests pruning from the front.
TEST_F(SessionServiceTest, PruneFromFront) {
const std::string base_url("http://google.com/");
SessionID tab_id;
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
// Add 5 navigations, with the 4th selected.
for (int i = 0; i < 5; ++i) {
TabNavigation nav(0, GURL(base_url + base::IntToString(i)),
content::Referrer(),
ASCIIToUTF16("a"), "b",
content::PAGE_TRANSITION_QUALIFIER_MASK);
UpdateNavigation(window_id, tab_id, nav, i, (i == 3));
}
// Prune the first two navigations from the front.
helper_.service()->TabNavigationPathPrunedFromFront(window_id, tab_id, 2);
// Read back in.
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
ASSERT_EQ(0, windows[0]->selected_tab_index);
ASSERT_EQ(window_id.id(), windows[0]->window_id.id());
ASSERT_EQ(1U, windows[0]->tabs.size());
// There shouldn't be an app id.
EXPECT_TRUE(windows[0]->tabs[0]->extension_app_id.empty());
// We should be left with three navigations, the 2nd selected.
SessionTab* tab = windows[0]->tabs[0];
ASSERT_EQ(1, tab->current_navigation_index);
EXPECT_EQ(3U, tab->navigations.size());
EXPECT_TRUE(GURL(base_url + base::IntToString(2)) ==
tab->navigations[0].virtual_url());
EXPECT_TRUE(GURL(base_url + base::IntToString(3)) ==
tab->navigations[1].virtual_url());
EXPECT_TRUE(GURL(base_url + base::IntToString(4)) ==
tab->navigations[2].virtual_url());
}
// Prunes from front so that we have no entries.
TEST_F(SessionServiceTest, PruneToEmpty) {
const std::string base_url("http://google.com/");
SessionID tab_id;
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
// Add 5 navigations, with the 4th selected.
for (int i = 0; i < 5; ++i) {
TabNavigation nav(0, GURL(base_url + base::IntToString(i)),
content::Referrer(),
ASCIIToUTF16("a"), "b",
content::PAGE_TRANSITION_QUALIFIER_MASK);
UpdateNavigation(window_id, tab_id, nav, i, (i == 3));
}
// Prune the first two navigations from the front.
helper_.service()->TabNavigationPathPrunedFromFront(window_id, tab_id, 5);
// Read back in.
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(0U, windows->size());
}
// Don't set the pinned state and make sure the pinned value is false.
TEST_F(SessionServiceTest, PinnedDefaultsToFalse) {
EXPECT_FALSE(CreateAndWriteSessionWithOneTab(false, false));
}
// Explicitly set the pinned state to false and make sure we get back false.
TEST_F(SessionServiceTest, PinnedFalseWhenSetToFalse) {
EXPECT_FALSE(CreateAndWriteSessionWithOneTab(false, true));
}
// Make sure application extension ids are persisted.
TEST_F(SessionServiceTest, PersistApplicationExtensionID) {
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
std::string app_id("foo");
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("abc"), std::string(),
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
helper_.SetTabExtensionAppID(window_id, tab_id, app_id);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
helper_.AssertSingleWindowWithSingleTab(windows.get(), 1);
EXPECT_TRUE(app_id == windows[0]->tabs[0]->extension_app_id);
}
// Explicitly set the pinned state to true and make sure we get back true.
TEST_F(SessionServiceTest, PinnedTrue) {
EXPECT_TRUE(CreateAndWriteSessionWithOneTab(true, true));
}
// Test that the notification for SESSION_SERVICE_SAVED is working properly.
TEST_F(SessionServiceTest, SavedSessionNotification) {
content::NotificationRegistrar registrar_;
registrar_.Add(this, chrome::NOTIFICATION_SESSION_SERVICE_SAVED,
content::NotificationService::AllSources());
service()->Save();
EXPECT_EQ(sync_save_count_, 1);
}
// Makes sure a tab closed by a user gesture is not restored.
TEST_F(SessionServiceTest, CloseTabUserGesture) {
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
TabNavigation nav1(0, GURL("http://google.com"),
content::Referrer(GURL("http://www.referrer.com"),
WebKit::WebReferrerPolicyDefault),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
service()->TabClosed(window_id, tab_id, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_TRUE(windows->empty());
}
// Verifies SetWindowBounds maps SHOW_STATE_DEFAULT to SHOW_STATE_NORMAL.
TEST_F(SessionServiceTest, DontPersistDefault) {
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
TabNavigation nav1(0, GURL("http://google.com"),
content::Referrer(GURL("http://www.referrer.com"),
WebKit::WebReferrerPolicyDefault),
ASCIIToUTF16("abc"), "def",
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
service()->SetWindowBounds(window_id,
window_bounds,
ui::SHOW_STATE_DEFAULT);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
ASSERT_EQ(1U, windows->size());
EXPECT_EQ(ui::SHOW_STATE_NORMAL, windows[0]->show_state);
}
TEST_F(SessionServiceTest, RemovePostData) {
helper_.service()->save_post_data_ = false;
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
std::string content_state("dummy_content_state");
// Create a TabNavigation containing content_state and representing a POST
// request.
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("title"), content_state,
content::PAGE_TRANSITION_QUALIFIER_MASK);
nav1.set_type_mask(TabNavigation::HAS_POST_DATA);
// Create a TabNavigation containing content_state and representing a normal
// request.
TabNavigation nav2(0, GURL("http://google.com/nopost"), content::Referrer(),
ASCIIToUTF16("title"), content_state,
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
UpdateNavigation(window_id, tab_id, nav2, 1, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
helper_.AssertSingleWindowWithSingleTab(windows.get(), 2);
// Expected: the HTTP body was removed from the content state of the POST
// navigation but the content state of the normal navigation is intact.
EXPECT_NE(content_state, windows[0]->tabs[0]->navigations[0].state());
helper_.AssertNavigationEquals(nav2, windows[0]->tabs[0]->navigations[1]);
}
TEST_F(SessionServiceTest, KeepPostDataWithoutPasswords) {
helper_.service()->save_post_data_ = true;
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
// Create a content state representing a HTTP body without posted passwords.
WebKit::WebHTTPBody http_body;
http_body.initialize();
const char char_data[] = "data";
http_body.appendData(WebKit::WebData(char_data, sizeof(char_data)-1));
WebKit::WebHistoryItem history_item;
history_item.initialize();
history_item.setHTTPBody(http_body);
std::string content_state = webkit_glue::HistoryItemToString(history_item);
// Create a TabNavigation containing content_state and representing a POST
// request.
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("title"), content_state,
content::PAGE_TRANSITION_QUALIFIER_MASK);
nav1.set_type_mask(TabNavigation::HAS_POST_DATA);
// Create a TabNavigation containing content_state and representing a normal
// request.
TabNavigation nav2(0, GURL("http://google.com/nopost"), content::Referrer(),
ASCIIToUTF16("title"), content_state,
content::PAGE_TRANSITION_QUALIFIER_MASK);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
UpdateNavigation(window_id, tab_id, nav2, 1, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
helper_.AssertSingleWindowWithSingleTab(windows.get(), 2);
// Expected: the content state of both navigations was saved and restored.
helper_.AssertNavigationEquals(nav1, windows[0]->tabs[0]->navigations[0]);
helper_.AssertNavigationEquals(nav2, windows[0]->tabs[0]->navigations[1]);
}
TEST_F(SessionServiceTest, RemovePostDataWithPasswords) {
helper_.service()->save_post_data_ = true;
SessionID tab_id;
ASSERT_NE(window_id.id(), tab_id.id());
// Create a content state representing a HTTP body with posted passwords.
WebKit::WebHTTPBody http_body;
http_body.initialize();
const char char_data[] = "data";
http_body.appendData(WebKit::WebData(char_data, sizeof(char_data)-1));
http_body.setContainsPasswordData(true);
WebKit::WebHistoryItem history_item;
history_item.initialize();
history_item.setHTTPBody(http_body);
std::string content_state = webkit_glue::HistoryItemToString(history_item);
// Create a TabNavigation containing content_state and representing a POST
// request with passwords.
TabNavigation nav1(0, GURL("http://google.com"), content::Referrer(),
ASCIIToUTF16("title"), content_state,
content::PAGE_TRANSITION_QUALIFIER_MASK);
nav1.set_type_mask(TabNavigation::HAS_POST_DATA);
helper_.PrepareTabInWindow(window_id, tab_id, 0, true);
UpdateNavigation(window_id, tab_id, nav1, 0, true);
ScopedVector<SessionWindow> windows;
ReadWindows(&(windows.get()));
helper_.AssertSingleWindowWithSingleTab(windows.get(), 1);
// Expected: the HTTP body was removed from the content state of the POST
// navigation with passwords.
EXPECT_NE(content_state, windows[0]->tabs[0]->navigations[0].state());
}
// This test is only applicable to chromeos.
#if defined(OS_CHROMEOS)
// Verifies migration of tab/window closed works.
TEST_F(SessionServiceTest, CanOpenV1TabClosed) {
FilePath v1_file_path;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &v1_file_path));
// v1_session_file contains a tab closed command with the original id. The
// file was generated from ClosingTabStaysClosed. If we successfully processed
// the file we'll have one tab.
v1_file_path =
v1_file_path.AppendASCII("sessions").AppendASCII("v1_session_file");
FilePath dest_file_path(path_);
dest_file_path = dest_file_path.AppendASCII("Current Session");
// Forces closing the file.
helper_.set_service(NULL);
ASSERT_TRUE(file_util::CopyFile(v1_file_path, dest_file_path));
SessionService* session_service = new SessionService(path_);
helper_.set_service(session_service);
ScopedVector<SessionWindow> windows;
helper_.ReadWindows(&(windows.get()));
ASSERT_EQ(1u, windows.size());
EXPECT_EQ(1u, windows[0]->tabs.size());
}
#endif
| {'content_hash': '445cb88550652b17e7d4cc65cf852c41', 'timestamp': '', 'source': 'github', 'line_count': 851, 'max_line_length': 80, 'avg_line_length': 37.64159811985899, 'alnum_prop': 0.6581337995192458, 'repo_name': 'gx1997/chrome-loongson', 'id': 'fd02b48a817fcc79529d7e7ec91695ab4e170adf', 'size': '33572', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'chrome/browser/sessions/session_service_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Assembly', 'bytes': '1178292'}, {'name': 'C', 'bytes': '74543799'}, {'name': 'C++', 'bytes': '120777816'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Go', 'bytes': '18556'}, {'name': 'Java', 'bytes': '62764'}, {'name': 'JavaScript', 'bytes': '10089209'}, {'name': 'Objective-C', 'bytes': '6954601'}, {'name': 'PHP', 'bytes': '97796'}, {'name': 'Perl', 'bytes': '1047454'}, {'name': 'Python', 'bytes': '6417217'}, {'name': 'R', 'bytes': '524'}, {'name': 'Ruby', 'bytes': '837'}, {'name': 'Shell', 'bytes': '5356327'}, {'name': 'Tcl', 'bytes': '277077'}]} |
namespace PaintsNow {
namespace NsFluteLeaves {
class FluteLeaves : public IScript::Library {
public:
FluteLeaves(IThread& thread);
};
}
}
#endif // __FLUTELEAVES_H__ | {'content_hash': 'e650e8de6b2c564036e53281e472a778', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 47, 'avg_line_length': 16.272727272727273, 'alnum_prop': 0.6871508379888268, 'repo_name': 'paintsnow/paintsnow', 'id': 'ba89af2ee9a9619503b2d89c711603ced81ac63a', 'size': '353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/Utility/FluteLeaves/FluteLeaves.h', 'mode': '33188', 'license': 'mit', 'language': []} |
using AppKit;
namespace Documents
{
[NSApplicationMain, IBObject]
class AppDelegate : INSApplicationDelegate
{
public void applicationDidFinishLaunching(NSNotification notification)
{
}
}
} | {'content_hash': '83acbd36fa1684cdba0b532184d581d0', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 72, 'avg_line_length': 15.428571428571429, 'alnum_prop': 0.7268518518518519, 'repo_name': 'remobjects/ElementsSamples', 'id': '40d7c53789fb00dd8d2037019229043e8b53e597', 'size': '218', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Hydrogene/Toffee/OS X/Documents/AppDelegate.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP.NET', 'bytes': '8446'}, {'name': 'C', 'bytes': '1844'}, {'name': 'C#', 'bytes': '123653'}, {'name': 'CSS', 'bytes': '435'}, {'name': 'GLSL', 'bytes': '1486'}, {'name': 'Go', 'bytes': '513138'}, {'name': 'HTML', 'bytes': '22290'}, {'name': 'Java', 'bytes': '51837'}, {'name': 'Metal', 'bytes': '12625'}, {'name': 'Objective-C', 'bytes': '4470'}, {'name': 'Pascal', 'bytes': '1497534'}, {'name': 'Swift', 'bytes': '76044'}, {'name': 'Visual Basic .NET', 'bytes': '11935'}]} |
$vcenterName = 'vCenter'
$storeName = 'VMStore1'
# vCenter
Connect-VIServer -Server $vcenterName -Credential $cred | Out-Null
# Tintri VMStore
$tsrv = Connect-TintriServer -Server $storeName -Credential $cred -SetDefaultServer
Get-TintriVM | %{
$vm = Get-VM -Id "VirtualMachine-$($_.VMware.Mor)" -ErrorAction SilentlyContinue
$vIOPS = 0
if($vm){
$stats = 'datastore.numberReadAveraged.average','datastore.numberWriteAveraged.average'
$vIOPS = Get-Stat -Entity $vm -Stat $stats -Realtime -MaxSamples 1 -ErrorAction SilentlyContinue |
Measure-Object -Property Value -Sum | Select -ExpandProperty Sum
}
$tStats = Get-TintriVMStat -VM $_ -IncludeRealtimeStats
$tIOPS = $tStats.OperationsReadIops + $tStats.OperationsWriteIops
$_ | Select @{N='Name';E={$_.VMware.Name}},
@{N='vSphere IOPS';E={$vIOPS}},
@{N='VMStore IOPS';E={$tIOPS}}
}
Disconnect-TintriServer -All
Disconnect-VIServer -Server $vcenterName -Confirm:$false
| {'content_hash': 'a8075987b4bff3ab9165fd517ada6477', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 107, 'avg_line_length': 38.30769230769231, 'alnum_prop': 0.6867469879518072, 'repo_name': 'Tintri/webinar-powershell-examples', 'id': '45e43788b4521bc8aa8dad6d7a2e4e7243967f5c', 'size': '2287', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'webinar_2015_07_14/demo3f.ps1', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PowerShell', 'bytes': '42506'}]} |
namespace unvell.ReoGrid
{
public interface IAutoFillSectionEntry
{
object Value { get; }
bool IsSequenceOf(IAutoFillSectionEntry otherEntry);
object GetIterationValue(object baseValue, object incrementPerIteration, int iteration);
object GetIncrementPerIteration(object baseValue, int numberOfEntries);
}
} | {'content_hash': '37f467fc9a924fc190a38d6a97065345', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 92, 'avg_line_length': 22.333333333333332, 'alnum_prop': 0.7731343283582089, 'repo_name': 'unvell/ReoGrid', 'id': '50959869bf5599ecc692255929ca1eeefe020c1f', 'size': '990', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ReoGrid/Core/AutoFillSerial/IAutoFillSectionEntry.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '9720'}, {'name': 'C#', 'bytes': '3424831'}, {'name': 'HTML', 'bytes': '3851'}]} |
import xs from 'xstream'
var stream = xs.periodic(1000)
.filter(i => i % 2 === 0)
.map(i => i * i)
.endWhen(xs.periodic(5000).take(1))
// So far, the stream is idle.
// As soon as it gets its first listener, it starts executing.
stream.addListener({
next: i => console.log(i),
error: err => console.error(err),
complete: () => console.log('completed'),
})
| {'content_hash': '424e725a623a2f7f513e1e260a2e5f53', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 62, 'avg_line_length': 24.733333333333334, 'alnum_prop': 0.6307277628032345, 'repo_name': 'mertnuhoglu/study', 'id': '47ee52c2ca1a94301d08206c838b6fa558acd6b2', 'size': '371', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'js/ex/study_ts/src/problems/p01/ex08.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '1346'}, {'name': 'Batchfile', 'bytes': '2299'}, {'name': 'C', 'bytes': '174'}, {'name': 'CSS', 'bytes': '236474'}, {'name': 'Clojure', 'bytes': '629884'}, {'name': 'Dockerfile', 'bytes': '979'}, {'name': 'Emacs Lisp', 'bytes': '1702'}, {'name': 'HTML', 'bytes': '23846866'}, {'name': 'Java', 'bytes': '69706'}, {'name': 'JavaScript', 'bytes': '11626914'}, {'name': 'Jupyter Notebook', 'bytes': '372344'}, {'name': 'Lua', 'bytes': '31206'}, {'name': 'Mermaid', 'bytes': '55'}, {'name': 'PLpgSQL', 'bytes': '41904'}, {'name': 'Procfile', 'bytes': '293'}, {'name': 'Python', 'bytes': '8861'}, {'name': 'R', 'bytes': '168361'}, {'name': 'Ruby', 'bytes': '453'}, {'name': 'Sass', 'bytes': '1120'}, {'name': 'Scala', 'bytes': '837'}, {'name': 'Shell', 'bytes': '81225'}, {'name': 'TeX', 'bytes': '453'}, {'name': 'TypeScript', 'bytes': '465092'}, {'name': 'Vim Script', 'bytes': '4860'}, {'name': 'sed', 'bytes': '3'}]} |
cd ../..
export PYTHONPATH=.
./bin/pyxie --profile arduino parse examples/while-break/while-break.pyxie
| {'content_hash': '587d929375646ec6b9603e3d65068366', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 74, 'avg_line_length': 26.25, 'alnum_prop': 0.7428571428571429, 'repo_name': 'sparkslabs/pyxie', 'id': '5c9de35e7720cab16a1e083626261fff7c94906b', 'size': '118', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/while-break/parse.sh', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '12956'}, {'name': 'CSS', 'bytes': '6040'}, {'name': 'Makefile', 'bytes': '3135'}, {'name': 'OpenEdge ABL', 'bytes': '451'}, {'name': 'Python', 'bytes': '231765'}, {'name': 'Shell', 'bytes': '393'}]} |
package view;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
* Classe que permet printar dialegs amb un missatge concret i una tipologia concreta.
*/
public class Dialog extends JDialog{
/**
* Metode que printa un dialeg amb missatge informatiu amb la string rebuda.
*/
public static void DialogOK(String message){
//JOptionPane.showMessageDialog(null,message, "Information message", JOptionPane.INFORMATION_MESSAGE);
JOptionPane pane = new JOptionPane(message, JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION);
JDialog dialog = pane.createDialog(new JFrame(), "Information message!");
dialog.setModalityType(JDialog.ModalityType.MODELESS);
dialog.setVisible(true);
}
/**
* Metode que printa un dialeg d'error amb el missatge rebut per referencia.
*/
public static void DialogKO(String message){
JOptionPane pane = new JOptionPane(message, JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
JDialog dialog = pane.createDialog(new JFrame(), "Information message!");
dialog.setModalityType(JDialog.ModalityType.MODELESS);
dialog.setVisible(true);
}
}
| {'content_hash': '8fdf93dd96afc76315f2a635e5ba1d88', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 107, 'avg_line_length': 41.758620689655174, 'alnum_prop': 0.7308009909165979, 'repo_name': 'NuriaValls/MemoTournament.Client', 'id': '1cc6b29c6a090f7fff609aa8afa0c83fb290f75b', 'size': '1211', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/view/Dialog.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '32322'}]} |
/** \file algebra/matrix_identity.h
*
* \brief Symbolic identity matrix.
*
* Contains the class invlib::Matrixidentity which implements a generic,
* symbolic identity matrix which can be used to form algebraic expressions.
*
*/
#ifndef ALGEBRA_MATRIX_IDENTITY_H
#define ALGEBRA_MATRIX_IDENTITY_H
#include <iostream>
#include "invlib/traits.h"
#include "invlib/algebra/matrix.h"
namespace invlib
{
// -------------------- //
// Forward Declarations //
// -------------------- //
template
<
typename T1,
typename T2
>
class MatrixProduct;
template
<
typename T1,
typename T2
>
class MatrixSum;
// --------------------- //
// Class MatrixIdentity //
// --------------------- //
/** \brief Symbolic matrix identity.
*
* A class template representing a (scaled) matrix identity matrix.
*
* \tparam RealType The floating point type used for scalars.
* \tparam MatrixType The underlying MatrixType type that is used.
*
*/
template
<
typename Matrix
>
class MatrixIdentity
{
public:
/*! The basic scalar type. */
using RealType = typename Matrix::RealType;
/*! The basic vector type */
using VectorType = typename Matrix::VectorType;
/*! The basic matrix type. */
using MatrixType = Matrix;
/*! The basic matrix type. */
using ResultType = Matrix;
// ------------------------------- //
// Constructors and Destructors //
// ------------------------------- //
/*! Create true matrix identity (no scaling) */
MatrixIdentity();
/*! Create scaled matrix identity */
MatrixIdentity(RealType c_);
MatrixIdentity(const MatrixIdentity &) = default;
MatrixIdentity(MatrixIdentity &&) = default;
MatrixIdentity & operator=(const MatrixIdentity &) = default;
MatrixIdentity & operator=(MatrixIdentity &&) = default;
/*! Return scaling factor of matrix */
RealType scale() const;
/*! Return diagonal element of the identity matrix. */
RealType diagonal() const;
// --------------------- //
// Nested Evaluation //
// --------------------- //
template <typename T1>
T1 multiply(T1 &&A) const;
template <typename T1>
T1 multiply(const T1 &A) const;
template <typename T1>
T1 solve(T1 &A) const;
template <typename T1>
T1 solve(const T1 &A) const;
void scale(RealType c);
// --------------------- //
// Arrithmetic Operators //
// --------------------- //
template <typename T1>
using Product = MatrixProduct<MatrixIdentity, T1>;
template<typename T1>
Product<T1> operator*(T1 &&A) const;
private:
RealType c;
};
/** \brief Multiplication by a scalar.
*
* Overload of the * operator for multiplication of an algebraic
* expression by a scalar.
*
* \tparam T1 The type of the algebraic expression.
*
* \param c The scaling factor.
* \param B The algebraic expression to be scaled.
* \return A matrix product proxy object with a scaled identity matrix and
* the given algebraic expression as operands.
*/
template
<
typename T1,
typename RealType = typename decay<T1>::RealType,
typename MatrixType = typename decay<T1>::MatrixType,
typename = disable_if< is_same<decay<T1>, MatrixIdentity<MatrixType> > >
>
auto operator*(double c, T1&& B)
-> MatrixProduct<MatrixIdentity<MatrixType>, T1>
{
using I = MatrixIdentity<MatrixType>;
using P = typename I::template Product<T1>;
return P(I(c), B);
}
/** \brief Scale identity matrix.
*
* Overload of the * operator for multiplication of an identity
* matrix by a scalar.
*
* \tparam T1 The underlying matrix type of the identity matrix object.
*
* \param c The scaling factor.
* \param B The identity matrix object to be scaled.
* \return A scaled identity matrix object.
*
*/
template
<
typename T1
>
auto operator*(double c,
const MatrixIdentity<T1>& A)
-> MatrixIdentity<T1>
{
MatrixIdentity<T1> B(A);
B.scale(c);
return B;
}
/** \brief Identity matrix inverse.
*
* Compute the inverse of a (scaled) identity matrix.
*
* \tparam T1 The underlying matrix type of the identity matrix object.
* \param B The identity matrix to be inverted.
* \return The inverted identity matrix object.
*
*/
template
<
typename T1
>
auto inv(const MatrixIdentity<T1> &A)
-> MatrixIdentity<T1>
{
return MatrixIdentity<T1>(1.0 / A.scale());
}
// ---------------------------------------------- //
// Partial Specialization of Matrix Product Class //
// ---------------------------------------------- //
template
<
typename T1,
typename T2
>
class MatrixProduct<MatrixIdentity<T1>, T2>
{
public:
/*! The basic scalar type. */
using RealType = typename decay<T2>::RealType;
/*! The basic vector type */
using VectorType = typename decay<T2>::VectorType;
/*! The basic matrix type. */
using MatrixType = typename decay<T2>::MatrixType;
/*! The type of the result of the expression */
using ResultType = typename decay<T2>::ResultType;
// ------------------------------- //
// Constructors and Destructors //
// ------------------------------- //
MatrixProduct(const MatrixIdentity<T1> & A_, T2 B_ )
: A(A_), B(B_) {}
MatrixProduct(const MatrixProduct &) = default;
MatrixProduct(MatrixProduct &&) = default;
MatrixProduct & operator=(const MatrixProduct &) = default;
MatrixProduct & operator=(MatrixProduct &&) = delete;
~MatrixProduct() = default;
// --------------------- //
// Nested Evaluation //
// --------------------- //
template <typename T3>
auto multiply(const T3 &u) const -> typename T3::ResultType;
MatrixType invert() const;
VectorType solve(const VectorType &v) const;
MatrixType transpose() const;
VectorType diagonal() const;
VectorType row(size_t i) const;
VectorType col(size_t i) const;
// --------------------- //
// Algebraic Operators //
// --------------------- //
template <typename T3>
using NestedProduct = typename decay<T2>::template Product<T3>;
template <typename T3>
using Product = MatrixProduct<MatrixIdentity<T1>, NestedProduct<T3>>;
template <typename T3>
Product<T3> operator*(T3 &&C) const
{
return Product<T3>(A, B * std::forward<T3>(C));
}
template <typename T3>
using Sum = MatrixSum<MatrixProduct , T3>;
template <typename T3>
Sum<T3> operator+(T3 &&C) const
{
return Sum<T3>(*this, C);
}
template <typename T3>
using Difference = MatrixDifference<MatrixProduct , T3>;
template <typename T3>
Difference<T3> operator-(T3 &&C)
{
return Difference<T3>(*this, C);
}
operator ResultType() const;
private:
MatrixIdentity<T1> A;
T2 B;
};
#include "matrix_identity.cpp"
} // namespace invlib
#endif // ALGEBRA_MATRIX_IDENTITY_H
| {'content_hash': 'f4ff30f705beab77f94c30d90cf59b0c', 'timestamp': '', 'source': 'github', 'line_count': 288, 'max_line_length': 76, 'avg_line_length': 23.84027777777778, 'alnum_prop': 0.6099621322458492, 'repo_name': 'simonpf/invlib', 'id': '02d0ff2dafc7ae04ae45e724f0ab3842ff1cbe16', 'size': '6866', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/invlib/algebra/matrix_identity.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '921'}, {'name': 'C++', 'bytes': '903317'}, {'name': 'CMake', 'bytes': '18411'}, {'name': 'Cuda', 'bytes': '1060'}, {'name': 'Python', 'bytes': '35212'}]} |
package com.roysmond.loafer.api;
import org.springframework.boot.Banner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cache.annotation.EnableCaching;
/**
* Created by w on 2017/4/24.
*/
@EnableCaching
@SpringBootApplication
public class LoaferApplication {
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "true");
new SpringApplicationBuilder()
.sources(LoaferApplication.class)
.bannerMode(Banner.Mode.CONSOLE)
.run(args);
}
}
| {'content_hash': '5015082a5c4c0d4479bdf9f5354c6638', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 70, 'avg_line_length': 27.958333333333332, 'alnum_prop': 0.7213114754098361, 'repo_name': 'Roysmond/loafer', 'id': '4e0dc45374318629d158ed37954ea51ece4cbc85', 'size': '671', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'loafer-api/src/main/java/com.roysmond.loafer.api/LoaferApplication.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3818'}, {'name': 'HTML', 'bytes': '44011'}, {'name': 'Java', 'bytes': '61736'}, {'name': 'JavaScript', 'bytes': '1996'}, {'name': 'TypeScript', 'bytes': '32115'}]} |
import mongoose from 'mongoose';
import { SetSchema } from './set';
const Schema = mongoose.Schema;
export const ExerciseSchema = new Schema({
title: { type: 'String', required: true },
cuid: { type: 'String', required: true },
workoutCUID: { type: 'String', required: true },
sets: [SetSchema],
});
export const ExerciseModel = mongoose.model('Exercise', ExerciseSchema);
| {'content_hash': 'f2c625875773da6ac777f4e7cc0b47c9', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 72, 'avg_line_length': 31.916666666666668, 'alnum_prop': 0.6919060052219321, 'repo_name': 'Danielbook/liftinglog', 'id': '014836d4bc1141ead7f97d12e7b0e37adbd8ce55', 'size': '383', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/models/exercise.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1365'}, {'name': 'HTML', 'bytes': '1998'}, {'name': 'JavaScript', 'bytes': '87802'}]} |
using System;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
namespace Azure.ResourceManager.Sql
{
/// <summary> Deletes a private endpoint connection with a given name. </summary>
public partial class PrivateEndpointConnectionsDeleteOperation : Operation<Response>, IOperationSource<Response>
{
private readonly ArmOperationHelpers<Response> _operation;
internal PrivateEndpointConnectionsDeleteOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response)
{
_operation = new ArmOperationHelpers<Response>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.Location, "PrivateEndpointConnectionsDeleteOperation");
}
/// <inheritdoc />
public override string Id => _operation.Id;
/// <inheritdoc />
public override Response Value => _operation.Value;
/// <inheritdoc />
public override bool HasCompleted => _operation.HasCompleted;
/// <inheritdoc />
public override bool HasValue => _operation.HasValue;
/// <inheritdoc />
public override Response GetRawResponse() => _operation.GetRawResponse();
/// <inheritdoc />
public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response<Response>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken);
/// <inheritdoc />
public override ValueTask<Response<Response>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken);
Response IOperationSource<Response>.CreateResult(Response response, CancellationToken cancellationToken)
{
return response;
}
async ValueTask<Response> IOperationSource<Response>.CreateResultAsync(Response response, CancellationToken cancellationToken)
{
return await new ValueTask<Response>(response).ConfigureAwait(false);
}
}
}
| {'content_hash': 'f308be4f506136fd7ee7a06f89af4e04', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 223, 'avg_line_length': 45.45454545454545, 'alnum_prop': 0.7248, 'repo_name': 'markcowl/azure-sdk-for-net', 'id': 'de0a01d621b477575d9d4feb29193280d223424b', 'size': '2638', 'binary': False, 'copies': '3', 'ref': 'refs/heads/ext-resource', 'path': 'sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/PrivateEndpointConnectionsDeleteOperation.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '13482080'}, {'name': 'PowerShell', 'bytes': '3408'}]} |
/*
* 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.
*/
package junit;
/**
*
* @author LukeMcNemee
*/
public class Kalkulacka2 implements KalkulackaInterface {
@Override
public double soucet(double x, double y) {
for (int i = 1; i < y; i++) {
x++;
}
return x;
}
@Override
public double rozdil(double x, double y) {
while(x >= y){
x = x - 1;
}
return x;
}
@Override
public double soucin(double x, double y) {
for (int i = 1; i < y; i++) {
x *= x;
}
return x;
}
@Override
public double podil(double x, double y) {
if(y == 0) throw new IllegalArgumentException("division by zero");
return (int) x/y;
}
}
| {'content_hash': '9dee2802790f4affaf3c999afda30bf5', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 79, 'avg_line_length': 21.162790697674417, 'alnum_prop': 0.5417582417582417, 'repo_name': 'LukeMcNemee/java', 'id': 'ddfd89e842f67816be5a39dc93a359c7aa695fbc', 'size': '910', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '11/jUnit/src/junit/Kalkulacka2.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '71066'}, {'name': 'Java', 'bytes': '182949'}]} |
require "utils"
require 'capistrano/configuration/roles'
require 'capistrano/server_definition'
class ConfigurationRolesTest < Test::Unit::TestCase
class MockConfig
attr_reader :original_initialize_called
def initialize
@original_initialize_called = true
end
include Capistrano::Configuration::Roles
end
def setup
@config = MockConfig.new
end
def test_initialize_should_initialize_roles_collection
assert @config.original_initialize_called
assert @config.roles.empty?
end
def test_roles_for_host_with_one_role
@config.role :app, "app1.capistrano.test"
@config.role :not_app, "not-app.capistrano.test"
app_server = @config.roles[:app].servers.first
assert @config.role_names_for_host(app_server)==[ :app ]
end
def test_roles_for_host_with_multiple_roles
@config.server "www.capistrano.test", :db, :worker
db_server = @config.roles[:db].servers.first
assert_equal @config.role_names_for_host(db_server).map(&:to_s).sort, [ 'db', 'worker' ]
end
def test_role_should_allow_empty_list
@config.role :app
assert @config.roles.keys.include?(:app)
assert @config.roles[:app].empty?
end
def test_role_with_one_argument_should_add_to_roles_collection
@config.role :app, "app1.capistrano.test"
assert_equal [:app], @config.roles.keys
assert_role_equals %w(app1.capistrano.test)
end
def test_role_block_returning_single_string_is_added_to_roles_collection
@config.role :app do
'app1.capistrano.test'
end
assert_role_equals %w(app1.capistrano.test)
end
def test_role_with_multiple_arguments_should_add_each_to_roles_collection
@config.role :app, "app1.capistrano.test", "app2.capistrano.test"
assert_equal [:app], @config.roles.keys
assert_role_equals %w(app1.capistrano.test app2.capistrano.test)
end
def test_role_with_block_and_strings_should_add_both_to_roles_collection
@config.role :app, 'app1.capistrano.test' do
'app2.capistrano.test'
end
assert_role_equals %w(app1.capistrano.test app2.capistrano.test)
end
def test_role_block_returning_array_should_add_each_to_roles_collection
@config.role :app do
['app1.capistrano.test', 'app2.capistrano.test']
end
assert_role_equals %w(app1.capistrano.test app2.capistrano.test)
end
def test_role_with_options_should_apply_options_to_each_argument
@config.role :app, "app1.capistrano.test", "app2.capistrano.test", :extra => :value
@config.roles[:app].each do |server|
assert_equal({:extra => :value}, server.options)
end
end
def test_role_with_options_should_apply_options_to_block_results
@config.role :app, :extra => :value do
['app1.capistrano.test', 'app2.capistrano.test']
end
@config.roles[:app].each do |server|
assert_equal({:extra => :value}, server.options)
end
end
def test_options_should_apply_only_to_this_argument_set
@config.role :app, 'app1.capistrano.test', 'app2.capistrano.test' do
['app3.capistrano.test', 'app4.capistrano.test']
end
@config.role :app, 'app5.capistrano.test', 'app6.capistrano.test', :extra => :value do
['app7.capistrano.test', 'app8.capistrano.test']
end
@config.role :app, 'app9.capistrano.test'
option_hosts = ['app5.capistrano.test', 'app6.capistrano.test', 'app7.capistrano.test', 'app8.capistrano.test']
@config.roles[:app].each do |server|
if (option_hosts.include? server.host)
assert_equal({:extra => :value}, server.options)
else
assert_not_equal({:extra => :value}, server.options)
end
end
end
# Here, the source should be more readable than the method name
def test_role_block_returns_options_hash_is_merged_with_role_options_argument
@config.role :app, :first => :one, :second => :two do
['app1.capistrano.test', 'app2.capistrano.test', {:second => :please, :third => :three}]
end
@config.roles[:app].each do |server|
assert_equal({:first => :one, :second => :please, :third => :three}, server.options)
end
end
def test_role_block_can_override_role_options_argument
@config.role :app, :value => :wrong do
Capistrano::ServerDefinition.new('app.capistrano.test')
end
@config.roles[:app].servers
@config.roles[:app].servers.each do |server|
assert_not_equal({:value => :wrong}, server.options)
end
end
def test_role_block_can_return_nil
@config.role :app do
nil
end
assert_role_equals ([])
end
def test_role_block_can_return_empty_array
@config.role :app do
[]
end
assert_role_equals ([])
end
def test_role_definitions_via_server_should_associate_server_with_roles
@config.server "www.capistrano.test", :web, :app
assert_equal %w(www.capistrano.test), @config.roles[:app].map { |s| s.host }
assert_equal %w(www.capistrano.test), @config.roles[:web].map { |s| s.host }
end
private
def assert_role_equals(list)
assert_equal list, @config.roles[:app].map { |s| s.host }
end
end
| {'content_hash': '5beef03cf76f4165d30a920f07a9bd79', 'timestamp': '', 'source': 'github', 'line_count': 157, 'max_line_length': 115, 'avg_line_length': 32.22929936305732, 'alnum_prop': 0.6800395256916996, 'repo_name': 'piousbox/microsites2-cities', 'id': '14de756a2caca2718fe0ac3c8bd4f8a70db93baa', 'size': '5060', 'binary': False, 'copies': '1', 'ref': 'refs/heads/cities2', 'path': 'vendor/ruby/1.9.1/gems/capistrano-2.15.4/test/configuration/roles_test.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '34286'}, {'name': 'JavaScript', 'bytes': '32921'}, {'name': 'Ruby', 'bytes': '153682'}, {'name': 'Shell', 'bytes': '1616'}]} |
require File.dirname(__FILE__) + '/../test_helper'
class TrackerTaskTest < Test::Unit::TestCase
def test_belongs_to_tracker
pt = tasks(:tracker_task1)
assert_equal pt.class.to_s, 'TrackerTask'
assert_not_nil pt.tracker
assert pt.tracker.class.to_s == 'Tracker'
end
def test_create
assert_difference('TrackerTask.count', 1) do
create
end
end
def test_create_needs_tracker_id
t = nil
assert_no_difference('TrackerTask.count') do
t = create(:tracker_id => nil)
end
assert t.errors.on(:tracker_id)
end
protected
def create(options = {})
TrackerTask.create({
:tracker_id => 2,
:name => "New Task",
}.merge(options))
end
end
| {'content_hash': 'bf4f9f19298d02b8459b5585f4cf558a', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 50, 'avg_line_length': 19.97222222222222, 'alnum_prop': 0.6300417246175244, 'repo_name': 'dimus/tuskit', 'id': '0eafeda841f514e253cbd0eb261a1671c173c074', 'size': '719', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/unit/tracker_task_test.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '140481'}, {'name': 'JavaScript', 'bytes': '250905'}, {'name': 'Ruby', 'bytes': '257059'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_77) on Mon May 23 19:37:09 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Uses of Package org.apache.lucene.codecs.blockterms (Lucene 6.0.1 API)</title>
<meta name="date" content="2016-05-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.apache.lucene.codecs.blockterms (Lucene 6.0.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/lucene/codecs/blockterms/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.apache.lucene.codecs.blockterms" class="title">Uses of Package<br>org.apache.lucene.codecs.blockterms</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/lucene/codecs/blockterms/package-summary.html">org.apache.lucene.codecs.blockterms</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.lucene.codecs.blockterms">org.apache.lucene.codecs.blockterms</a></td>
<td class="colLast">
<div class="block">Pluggable term index / block terms dictionary implementations.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.apache.lucene.codecs.blockterms">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../org/apache/lucene/codecs/blockterms/package-summary.html">org.apache.lucene.codecs.blockterms</a> used by <a href="../../../../../org/apache/lucene/codecs/blockterms/package-summary.html">org.apache.lucene.codecs.blockterms</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/lucene/codecs/blockterms/class-use/TermsIndexReaderBase.html#org.apache.lucene.codecs.blockterms">TermsIndexReaderBase</a>
<div class="block"><a href="../../../../../org/apache/lucene/codecs/blockterms/BlockTermsReader.html" title="class in org.apache.lucene.codecs.blockterms"><code>BlockTermsReader</code></a> interacts with an instance of this class
to manage its terms index.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../org/apache/lucene/codecs/blockterms/class-use/TermsIndexReaderBase.FieldIndexEnum.html#org.apache.lucene.codecs.blockterms">TermsIndexReaderBase.FieldIndexEnum</a>
<div class="block">Similar to TermsEnum, except, the only "metadata" it
reports for a given indexed term is the long fileOffset
into the main terms dictionary file.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/lucene/codecs/blockterms/class-use/TermsIndexWriterBase.html#org.apache.lucene.codecs.blockterms">TermsIndexWriterBase</a>
<div class="block">Base class for terms index implementations to plug
into <a href="../../../../../org/apache/lucene/codecs/blockterms/BlockTermsWriter.html" title="class in org.apache.lucene.codecs.blockterms"><code>BlockTermsWriter</code></a>.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../org/apache/lucene/codecs/blockterms/class-use/TermsIndexWriterBase.FieldWriter.html#org.apache.lucene.codecs.blockterms">TermsIndexWriterBase.FieldWriter</a>
<div class="block">Terms index API for a single field.</div>
</td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../org/apache/lucene/codecs/blockterms/class-use/VariableGapTermsIndexWriter.IndexTermSelector.html#org.apache.lucene.codecs.blockterms">VariableGapTermsIndexWriter.IndexTermSelector</a>
<div class="block">Hook for selecting which terms should be placed in the terms index.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/lucene/codecs/blockterms/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| {'content_hash': '4142538121e1bea2c114e4c8b9fe7d82', 'timestamp': '', 'source': 'github', 'line_count': 201, 'max_line_length': 328, 'avg_line_length': 40.44776119402985, 'alnum_prop': 0.6463714637146372, 'repo_name': 'YorkUIRLab/irlab', 'id': '291128f1d7e786a7ccc28f308e397211c7f91109', 'size': '8130', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/lucene-6.0.1/docs/codecs/org/apache/lucene/codecs/blockterms/package-use.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '433499'}, {'name': 'Gnuplot', 'bytes': '2444'}, {'name': 'HTML', 'bytes': '95820812'}, {'name': 'Java', 'bytes': '303195'}, {'name': 'JavaScript', 'bytes': '33538'}]} |
package org.javaee7.servlet.programmatic.login;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Arun Gupta
*/
@WebServlet(urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String password = request.getParameter("password");
if (user != null && password != null) {
request.login(user, password);
}
userDetails(out, request);
}
private void userDetails(PrintWriter out, HttpServletRequest request) {
out.println("isUserInRole?" + request.isUserInRole("g1"));
out.println("getRemoteUser?" + request.getRemoteUser());
out.println("getUserPrincipal?" + request.getUserPrincipal());
out.println("getAuthType?" + request.getAuthType());
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| {'content_hash': 'ed9f85da722d73629d85ad53453c2593', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 123, 'avg_line_length': 34.03488372093023, 'alnum_prop': 0.6750939528527502, 'repo_name': 'ftomassetti/JavaIncrementalParser', 'id': '673d44fd6451656d8b6a30540150e9f46725a11e', 'size': '2927', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/resources/javaee7-samples/servlet/security-programmatic/src/main/java/org/javaee7/servlet/programmatic/login/LoginServlet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '45351'}, {'name': 'Groovy', 'bytes': '4889'}, {'name': 'Java', 'bytes': '2084352'}, {'name': 'JavaScript', 'bytes': '103909'}, {'name': 'Scala', 'bytes': '75554'}, {'name': 'TypeScript', 'bytes': '583'}]} |
FROM fnichol/uhttpd
copy . /www/
| {'content_hash': '14de84c60f8c3bc3f2d0abace8c13cde', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 19, 'avg_line_length': 11.333333333333334, 'alnum_prop': 0.7058823529411765, 'repo_name': 'ZackMattor/2d-playground', 'id': 'ecf57513b78ebf4717a2d0114905d7c4809b6f16', 'size': '34', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Dockerfile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '6541'}, {'name': 'JavaScript', 'bytes': '21601'}]} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
namespace CordovaWP8_3._3._02
{
public partial class App : Application
{
/// <summary>
/// Provides easy access to the root frame of the Phone Application.
/// </summary>
/// <returns>The root frame of the Phone Application.</returns>
public PhoneApplicationFrame RootFrame { get; private set; }
/// <summary>
/// Constructor for the Application object.
/// </summary>
public App()
{
// Global handler for uncaught exceptions.
UnhandledException += Application_UnhandledException;
// Show graphics profiling information while debugging.
if (System.Diagnostics.Debugger.IsAttached)
{
// Display the current frame rate counters.
//Application.Current.Host.Settings.EnableFrameRateCounter = true;
// Show the areas of the app that are being redrawn in each frame.
//Application.Current.Host.Settings.EnableRedrawRegions = true;
// Enable non-production analysis visualization mode,
// which shows areas of a page that are being GPU accelerated with a colored overlay.
//Application.Current.Host.Settings.EnableCacheVisualization = true;
}
// Standard Silverlight initialization
InitializeComponent();
// Phone-specific initialization
InitializePhoneApplication();
}
// Code to execute when the application is launching (eg, from Start)
// This code will not execute when the application is reactivated
private void Application_Launching(object sender, LaunchingEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// Avoid screen locks while debugging.
PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
}
}
// Code to execute when the application is activated (brought to foreground)
// This code will not execute when the application is first launched
private void Application_Activated(object sender, ActivatedEventArgs e)
{
}
// Code to execute when the application is deactivated (sent to background)
// This code will not execute when the application is closing
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
}
// Code to execute when the application is closing (eg, user hit Back)
// This code will not execute when the application is deactivated
private void Application_Closing(object sender, ClosingEventArgs e)
{
}
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
// Code to execute on Unhandled Exceptions
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
#region Phone application initialization
// Avoid double-initialization
private bool phoneApplicationInitialized = false;
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
}
// Do not add any additional code to this method
private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
RootVisual = RootFrame;
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
#endregion
}
}
| {'content_hash': '7a90e868ba8bbd7042419e34a2384eea', 'timestamp': '', 'source': 'github', 'line_count': 142, 'max_line_length': 108, 'avg_line_length': 37.014084507042256, 'alnum_prop': 0.6381278538812786, 'repo_name': 'SYMBIO/cordova-plugin-background-download', 'id': '3da15d7407f8ec9f6b48d62f2c434d2659499625', 'size': '6032', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'prototypes/wp8/CordovaWP8_3.3.02/App.xaml.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2088'}, {'name': 'C#', 'bytes': '126832'}, {'name': 'CSS', 'bytes': '7670'}, {'name': 'HTML', 'bytes': '4755'}, {'name': 'Java', 'bytes': '16305'}, {'name': 'JavaScript', 'bytes': '20096'}, {'name': 'Objective-C', 'bytes': '6717'}]} |
<script>
window.etoolsSearchableDropdown = window.etoolsSearchableDropdown || {};
/** @polymerBehavior etoolsSearchableDropdown.SplitLabelBehavior */
etoolsSearchableDropdown.SplitLabelBehavior = { // eslint-disable-line no-undef
getPrimaryLabel: function(label) {
return label? label.slice(0, label.indexOf('|')) : '';
},
getSecondaryLabel: function(label) {
return label ? label.slice(label.indexOf('|')+1) : '';
}
};
</script>
| {'content_hash': '8b4e930da8db471d6c6b91509a98b4b2', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 81, 'avg_line_length': 38.833333333333336, 'alnum_prop': 0.6888412017167382, 'repo_name': 'unicef-polymer/etools-searchable-multiselection-menu', 'id': 'dbc47f9f35823a234e49d4662a3ed7ab6c1a5674', 'size': '466', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'behaviors/split-label-behavior.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '96992'}]} |
$(".button-collapse").sideNav();
// Initialize collapsible (uncomment the line below if you use the dropdown variation)
//$('.collapsible').collapsible();
| {'content_hash': 'df9989b222e21f148cd5b353db21e283', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 86, 'avg_line_length': 51.666666666666664, 'alnum_prop': 0.7290322580645161, 'repo_name': 'RucaLove/YogaBuddy', 'id': 'f1ff303da242eb16724a83e26027501af5bcfa90', 'size': '185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'RUCA/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '15810'}, {'name': 'HTML', 'bytes': '93675'}, {'name': 'JavaScript', 'bytes': '57945'}]} |
package net.dean.jraw.models;
import com.fasterxml.jackson.databind.JsonNode;
/**
* A simple key-value read-only store for account preferences. A list of keys can be found
* <a href="https://www.reddit.com/dev/api#GET_api_v1_me_prefs">here</a> and values can be retrieved with
* {@link #data(String, Class)}.
*/
public final class AccountPreferences extends JsonModel {
/** Instantiates a new AccountPreferences */
public AccountPreferences(JsonNode dataNode) {
super(dataNode);
}
}
| {'content_hash': 'f437cabd638102bbeb6c3b27a743bfb5', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 105, 'avg_line_length': 33.93333333333333, 'alnum_prop': 0.7190569744597249, 'repo_name': 'ccrama/JRAW', 'id': '25d3aef9a7c87bbf02b6e5da321f0717d434cae3', 'size': '509', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/java/net/dean/jraw/models/AccountPreferences.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '681180'}, {'name': 'Python', 'bytes': '2686'}, {'name': 'Shell', 'bytes': '2136'}]} |
layout: quote
category: quote
title: "NYTimes: The Year in Pictures 2017"
date: 2017-12-28
tags: [2017, reflection, photography, nytimes]
author: Andrew Dai
quote:
title: The Year in Pictures 2017
author: Amanda Hess, NYTimes
source: "https://www.nytimes.com/interactive/2017/12/19/sunday-review/2017-year-in-pictures.html"
date: 2017-12-19
text: "And still, photography holds the power to clarify… It’s a cliché to remark, at the end of the year, that the time has moved quickly and slowly all at once. But one of the dark powers of our devices is to bend time, to suck us into the screen and spit us out seemingly months later. It can sometimes feel as if the only thing that exists is the one that’s being talked about online right now. To study these photographs is to be perpetually surprised at what has just happened: The last mass shooting before the last mass shooting before the last mass shooting; the hurricane before the flood before the fires. It seems impossible, looking back at a photograph from President Trump’s inauguration, that Barack Obama was actually president of the United States earlier this year."
---
| {'content_hash': '3a818c746ff62560a5f9a9941930eb45', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 794, 'avg_line_length': 88.3076923076923, 'alnum_prop': 0.7804878048780488, 'repo_name': 'BunsenMcDubbs/bunsenmcdubbs.github.io', 'id': 'f5b38d77e6d0520ae8c01525d4408aa4bb88fc41', 'size': '1159', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_posts/2017-12-28-nytimes-year-in-pictures.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '11336'}, {'name': 'HTML', 'bytes': '23305'}, {'name': 'JavaScript', 'bytes': '1674'}]} |
package sdjournal
import (
"os"
"testing"
"time"
"github.com/coreos/go-systemd/journal"
)
func TestJournalFollow(t *testing.T) {
r, err := NewJournalReader(JournalReaderConfig{
Since: time.Duration(-15) * time.Second,
Matches: []Match{
{
Field: SD_JOURNAL_FIELD_SYSTEMD_UNIT,
Value: "NetworkManager.service",
},
},
})
if err != nil {
t.Fatalf("Error opening journal: %s", err)
}
if r == nil {
t.Fatal("Got a nil reader")
}
defer r.Close()
// start writing some test entries
done := make(chan struct{}, 1)
defer close(done)
go func() {
for {
select {
case <-done:
return
default:
if err = journal.Print(journal.PriInfo, "test message %s", time.Now()); err != nil {
t.Fatalf("Error writing to journal: %s", err)
}
time.Sleep(time.Second)
}
}
}()
// and follow the reader synchronously
timeout := time.Duration(5) * time.Second
if err = r.Follow(time.After(timeout), os.Stdout); err != ErrExpired {
t.Fatalf("Error during follow: %s", err)
}
}
| {'content_hash': 'aec419e3c27cda0da2625f7b49fcb858', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 88, 'avg_line_length': 18.78181818181818, 'alnum_prop': 0.6263310745401742, 'repo_name': 'mikkeloscar/go-systemd', 'id': 'ad6cd0edb074464bc4c130814a08d39f42b1ec32', 'size': '1654', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sdjournal/journal_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '147689'}, {'name': 'Shell', 'bytes': '1590'}]} |
<?php
namespace Google\Service\Directory;
class DirectoryChromeosdevicesCommandResult extends \Google\Model
{
/**
* @var string
*/
public $errorMessage;
/**
* @var string
*/
public $executeTime;
/**
* @var string
*/
public $result;
/**
* @param string
*/
public function setErrorMessage($errorMessage)
{
$this->errorMessage = $errorMessage;
}
/**
* @return string
*/
public function getErrorMessage()
{
return $this->errorMessage;
}
/**
* @param string
*/
public function setExecuteTime($executeTime)
{
$this->executeTime = $executeTime;
}
/**
* @return string
*/
public function getExecuteTime()
{
return $this->executeTime;
}
/**
* @param string
*/
public function setResult($result)
{
$this->result = $result;
}
/**
* @return string
*/
public function getResult()
{
return $this->result;
}
}
// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DirectoryChromeosdevicesCommandResult::class, 'Google_Service_Directory_DirectoryChromeosdevicesCommandResult');
| {'content_hash': '1c57f706f58112dbebf6277bef2be1c3', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 124, 'avg_line_length': 17.348484848484848, 'alnum_prop': 0.6393013100436681, 'repo_name': 'googleapis/google-api-php-client-services', 'id': 'd3e0149b5a5dc34e811f703d44d31d03b37bd227', 'size': '1735', 'binary': False, 'copies': '6', 'ref': 'refs/heads/main', 'path': 'src/Directory/DirectoryChromeosdevicesCommandResult.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'PHP', 'bytes': '55414116'}, {'name': 'Python', 'bytes': '427325'}, {'name': 'Shell', 'bytes': '787'}]} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_listen_socket_54b.cpp
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__new.label.xml
Template File: sources-sinks-54b.tmpl.cpp
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with new [] and check the size of the memory to be allocated
* BadSink : Allocate memory with new [], but incorrectly check the size of the memory to be allocated
* Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING L"hello"
namespace CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_listen_socket_54
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_c(size_t data);
void badSink_b(size_t data)
{
badSink_c(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(size_t data);
void goodG2BSink_b(size_t data)
{
goodG2BSink_c(data);
}
/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink_c(size_t data);
void goodB2GSink_b(size_t data)
{
goodB2GSink_c(data);
}
#endif /* OMITGOOD */
} /* close namespace */
| {'content_hash': '90118a3f8893816ccac687aa44ce37b5', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 157, 'avg_line_length': 24.710843373493976, 'alnum_prop': 0.7001462701121404, 'repo_name': 'maurer/tiamat', 'id': '3c4013918b7f004b60bb44b2213304e13c642a40', 'size': '2051', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s02/CWE789_Uncontrolled_Mem_Alloc__new_wchar_t_listen_socket_54b.cpp', 'mode': '33188', 'license': 'mit', 'language': []} |
Ext.define('Rendering.controller.Home', {
extend: 'Rendering.controller.Base',
/**
* Action for home route /.
* Activates the first tab
*/
index: function() {
Ext.getCmp('viewport').child('tabpanel').setActiveTab(0);
}
}); | {'content_hash': 'f26382c757e088fa03d3d04eab075c86', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 64, 'avg_line_length': 24.09090909090909, 'alnum_prop': 0.5849056603773585, 'repo_name': 'angie/Ext.ux.Router', 'id': 'afea5c23cc51f031ade437f46d5d74f7ca505544', 'size': '265', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'examples/rendering/app/controller/Home.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9052'}, {'name': 'HTML', 'bytes': '25478'}, {'name': 'JavaScript', 'bytes': '10174595'}]} |
package com.syk.dao;
import weibo4j.model.Status;
public interface StatusDao extends BaseDao<Status> {
}
| {'content_hash': 'cc942fd498dfb6c326d1d9fc48d5bdef', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 52, 'avg_line_length': 18.833333333333332, 'alnum_prop': 0.7433628318584071, 'repo_name': 'SongYuanKun/sjpc', 'id': 'c532ba7dc1f34d9e30c9829b226bff6ff5e439fd', 'size': '113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sjpc-dao/src/main/java/com/syk/dao/StatusDao.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '377043'}, {'name': 'Groff', 'bytes': '103341'}, {'name': 'HTML', 'bytes': '2599'}, {'name': 'Java', 'bytes': '839248'}, {'name': 'JavaScript', 'bytes': '1480733'}]} |
if [[ "$OSTYPE" == "darwin"* ]]; then
# Mac OSX
result=:$(brew ls coreutils)
if [ -z "$result" ]; then
'Error: coreutils is not installed.'
exit 1
fi
TOP_DIR=$(greadlink -f `dirname "$0"` | grep -o '.*/oshinko-cli')
else
TOP_DIR=$(readlink -f `dirname "$0"` | grep -o '.*/oshinko-cli')
fi
. $TOP_DIR/sparkimage.sh
PROJECT='github.com/radanalyticsio/oshinko-cli'
function usage {
echo "usage: release.sh VERSION"
echo ""
echo "VERSION -- should be set to the git tag being built, for example v0.6.1"
echo ""
echo "Builds release zip/tarball containing a versioned oshinko binary for each supported platform."
echo "Meant to be run from the oshinko-cli root directory."
echo "Output is in the _release directory."
echo "Installs gox cross-compiler on the current GOPATH"
}
while getopts h option; do
case $option in
h)
usage
exit 0
;;
esac
done
shift $((OPTIND-1))
if [ "$#" -ne 1 ]; then
usage
exit 1
fi
go get github.com/mitchellh/gox
$GOPATH/bin/gox "-output=_release/{{.Dir}}_{{.OS}}_{{.Arch}}/{{.Dir}}" "-osarch=darwin/amd64 linux/386 linux/amd64" -tags standard -ldflags "-X $PROJECT/version.gitTag=$1 -X $PROJECT/version.appName=oshinko -X $PROJECT/version.sparkImage=$SPARK_IMAGE" ./cmd/oshinko
cd _release
zip oshinko_$1_macosx.zip oshinko_darwin_amd64/oshinko
tar -cvzf oshinko_$1_linux_386.tar.gz oshinko_linux_386
tar -cvzf oshinko_$1_linux_amd64.tar.gz oshinko_linux_amd64
| {'content_hash': 'cf29a6bb671ebdee43038501e597633a', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 265, 'avg_line_length': 31.653061224489797, 'alnum_prop': 0.6370083816892328, 'repo_name': 'radanalyticsio/oshinko-cli', 'id': '07446cc49053cc3cb6c31e38c09c6551db745643', 'size': '1563', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scripts/release.sh', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'Dockerfile', 'bytes': '422'}, {'name': 'Go', 'bytes': '442529'}, {'name': 'Makefile', 'bytes': '869'}, {'name': 'Python', 'bytes': '2181'}, {'name': 'Shell', 'bytes': '237203'}]} |
import _plotly_utils.basevalidators
class RoughnessValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="roughness", parent_name="volume.lighting", **kwargs
):
super(RoughnessValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "calc"),
max=kwargs.pop("max", 1),
min=kwargs.pop("min", 0),
**kwargs,
)
| {'content_hash': 'a62788bf10520ba02ff7565677d33a05', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 78, 'avg_line_length': 33.4, 'alnum_prop': 0.5828343313373253, 'repo_name': 'plotly/plotly.py', 'id': 'de256c18588e61b1ee45d5fe38aec9a5cd4dc025', 'size': '501', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/python/plotly/plotly/validators/volume/lighting/_roughness.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '545'}, {'name': 'JavaScript', 'bytes': '2074'}, {'name': 'PostScript', 'bytes': '565328'}, {'name': 'Python', 'bytes': '31506317'}, {'name': 'TypeScript', 'bytes': '71337'}]} |
karma-inject-html-preprocessor
==============================
Karma plugin to inject raw HTML (including scripts, styles, etc) directly into the test runner page
| {'content_hash': '459a785a691ffc850f273a2b2a26c060', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 99, 'avg_line_length': 40.75, 'alnum_prop': 0.656441717791411, 'repo_name': 'scottrippey/karma-inject-html-preprocessor', 'id': '92e02728bbc62c83bd8cc8d08f72d32ba27cb706', 'size': '163', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1315'}]} |
@interface UIAWindow : UIAElement
{
}
- (id)elements;
- (_Bool)_windowShouldAcceptAXElement:(id)arg1;
- (id)_uiaContentArea;
- (id)contentArea;
@end
| {'content_hash': 'e362b232a2f9c1d1591c0a44e6e9fc50', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 47, 'avg_line_length': 13.818181818181818, 'alnum_prop': 0.7039473684210527, 'repo_name': 'joemasilotti/UIAutomation', 'id': '8a55e240a5f1c2448abe3d551f8cf33fb773ad27', 'size': '328', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Headers/UIAWindow.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '940'}, {'name': 'Objective-C', 'bytes': '52176'}, {'name': 'Ruby', 'bytes': '535'}]} |
/*
* ecs
*
* ECS Open API
*
*/
package model
import (
"encoding/json"
"strings"
)
// Response Object
type ShowServerRemoteConsoleResponse struct {
RemoteConsole *ServerRemoteConsole `json:"remote_console,omitempty"`
}
func (o ShowServerRemoteConsoleResponse) String() string {
data, _ := json.Marshal(o)
return strings.Join([]string{"ShowServerRemoteConsoleResponse", string(data)}, " ")
}
| {'content_hash': '00cf5858bf4ae56e97d14e1541c60e2f', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 84, 'avg_line_length': 16.875, 'alnum_prop': 0.7185185185185186, 'repo_name': 'bskiba/autoscaler', 'id': 'ca847eaa14f2f781ca1ce48125e33d71f8bab77f', 'size': '405', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cluster-autoscaler/cloudprovider/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/model/model_show_server_remote_console_response.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '5549'}, {'name': 'Go', 'bytes': '3983049'}, {'name': 'Makefile', 'bytes': '10184'}, {'name': 'Python', 'bytes': '20302'}, {'name': 'Shell', 'bytes': '45631'}]} |
class SitePage < ActiveRecord::Base
belongs_to :site
belongs_to :page, class_name: "Content::Page"
end
| {'content_hash': 'f137d07e8f2fd5f15342eb05991f1bf6', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 47, 'avg_line_length': 26.75, 'alnum_prop': 0.7289719626168224, 'repo_name': 'builtbybuffalo/buffalo_pages', 'id': 'd9eac21c78d2b87dd87ebc40b0f43d9018043702', 'size': '107', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/site_page.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '29876'}, {'name': 'Ruby', 'bytes': '48302'}, {'name': 'Shell', 'bytes': '131'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Consistent Swift Style :: TrozWare</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<meta name="description" content=" Why is important to style your code? How do you decide on a style? Is there a way to enforce this style automatically? "/>
<meta name="keywords" content="[Swift Apple macOS iOS Apple Watch]"/>
<meta name="robots" content="noodp"/>
<link rel="canonical" href="https://troz.net/post/2018/swiftlint/" />
<link rel="stylesheet" href="https://troz.net/assets/style.css">
<link rel="stylesheet" href="https://troz.net/style.css">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://troz.net/img/apple-touch-icon-144-precomposed.png">
<link rel="shortcut icon" href="https://troz.net/img/favicon.png">
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Consistent Swift Style :: TrozWare — " />
<meta name="twitter:description" content=" Why is important to style your code? How do you decide on a style? Is there a way to enforce this style automatically? " />
<meta name="twitter:site" content="https://troz.net/" />
<meta name="twitter:creator" content="" />
<meta name="twitter:image" content="">
<meta property="og:locale" content="en" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Consistent Swift Style :: TrozWare — ">
<meta property="og:description" content=" Why is important to style your code? How do you decide on a style? Is there a way to enforce this style automatically? " />
<meta property="og:url" content="https://troz.net/post/2018/swiftlint/" />
<meta property="og:site_name" content="Consistent Swift Style" />
<meta property="og:image" content="">
<meta property="og:image:width" content="2048">
<meta property="og:image:height" content="1024">
<meta property="article:published_time" content="2018-03-31 09:35:21 +1000 AEST" />
</head>
<body class="dark-theme">
<div class="container">
<header class="header">
<span class="header__inner">
<a href="https://troz.net/" class="logo" style="text-decoration: none;">
<span class="logo__mark"><svg xmlns="http://www.w3.org/2000/svg" class="greater-icon" width="44" height="44" viewBox="0 0 44 44">
<polyline fill="none" stroke="#000" stroke-width="2" points="15 8 29.729 22.382 15 35.367"/>
</svg>
</span>
<span class="logo__text">TrozWare</span>
<span class="logo__cursor" style="width: 2px"></span>
</a>
<span class="header__right">
<nav class="menu">
<ul class="menu__inner menu__inner--desktop">
<li><a href="/">Home</a></li>
<li><a href="/apps/">Apps</a></li>
<li><a href="/post/">Archives</a></li>
<li><a href="/tags/">Tags</a></li>
<li><a href="/contact/">Contact</a></li>
</ul>
<ul class="menu__inner menu__inner--mobile">
<li><a href="/">Home</a></li>
<li><a href="/apps/">Apps</a></li>
<li><a href="/post/">Archives</a></li>
<li><a href="/tags/">Tags</a></li>
<li><a href="/contact/">Contact</a></li>
</ul>
</nav>
<span class="menu-trigger">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</svg>
</span>
<span class="theme-toggle">
<svg class="theme-toggler" width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M22 41C32.4934 41 41 32.4934 41 22C41 11.5066 32.4934 3 22
3C11.5066 3 3 11.5066 3 22C3 32.4934 11.5066 41 22 41ZM7 22C7
13.7157 13.7157 7 22 7V37C13.7157 37 7 30.2843 7 22Z"/>
</svg>
</span>
</span>
</span>
</header>
<div class="content">
<div class="post">
<h2 class="post-title"><a href="https://troz.net/post/2018/swiftlint/">Consistent Swift Style</a></h2>
<div class="post-meta">
<span class="post-date">
31 Mar 2018
</span>
<span class="more-meta">- 1917 words, </span>
<span class="more-meta"> 9 minute read</span>
</div>
<span class="post-tags">
#<a href="https://troz.net/tags/swift">swift</a>
#<a href="https://troz.net/tags/swiftlint">swiftlint</a>
#<a href="https://troz.net/tags/lint">lint</a>
#<a href="https://troz.net/tags/style">style</a>
</span>
<div class="post-content">
<ul>
<li>Why is important to style your code?</li>
<li>How do you decide on a style?</li>
<li>Is there a way to enforce this style automatically?</li>
</ul>
<h2 id="what-is-style-in-swift">What is style in Swift?</h2>
<p>Style applies to writing in any programming language and refers to the way you structure your code.</p>
<p>For example, how to you arrange braces?</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-swift" data-lang="swift"><span style="color:#66d9ef">if</span> theValue <span style="color:#f92672"><</span> <span style="color:#ae81ff">10</span> {
<span style="color:#75715e">// do one thing</span>
} <span style="color:#66d9ef">else</span> {
<span style="color:#75715e">// do the other thing</span>
}
</code></pre></div><p>or</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-swift" data-lang="swift"><span style="color:#66d9ef">if</span> theValue <span style="color:#f92672"><</span> <span style="color:#ae81ff">10</span>
{
<span style="color:#75715e">// do one thing</span>
}
<span style="color:#66d9ef">else</span>
{
<span style="color:#75715e">// do the other thing</span>
}
</code></pre></div><p>or anything in between?</p>
<p>Do you use camelCase or snake_case?</p>
<p>Do you always start class names with an uppercase letter?</p>
<p>And of course there is the Great Debate: tabs or spaces? And how many?</p>
<h2 id="why-is-important-to-style-your-code">Why is important to style your code?</h2>
<p>You only write code once, but you & others will read it many times.</p>
<p>As I tell students, in six months time some poor sucker is going to have to read this code, and worse still, that poor sucker might be you, so make it readable.</p>
<p>There is a cognitive load involved in reading code but you can lighten that load by using consistent patterns that your brain can recognise quickly without having to re-analyse them each time.</p>
<h2 id="how-do-you-decide-on-a-style">How do you decide on a style?</h2>
<p>Do a search online for <a href="https://encrypted.google.com/search?hl=en&q=Swift%20style%20guide">Swift style guide</a> and you will get numerous results, although you do have to dodge the sites dedicated to Taylor Swift’s dress sense! I like the <a href="https://github.com/raywenderlich/swift-style-guide">Ray Wenderlich guide</a> although its emphasis is on styles that read well in print and in web pages. The <a href="https://github.com/linkedin/swift-style-guide">LinkedIn guide</a> is also good. <a href="https://github.com/github/swift-style-guide">GitHub</a> also has a style guide but it hasn’t been updated recently. However it contains some good general advice.</p>
<p>But in the end, you have to decide your own style. The important thing then is to be consistent. I don’t care whether you use camelCase or snake_case, tabs or spaces, but if you use a mixture your code will be harder to read, so pick a style and stick to it.</p>
<h2 id="is-there-a-way-to-enforce-this-style-automatically">Is there a way to enforce this style automatically?</h2>
<p>This is where <a href="https://github.com/realm/SwiftLint">SwiftLint</a> comes into the picture. SwiftLint is a tool that can check your code and look for style violations. While it comes with a default set of rules, you can configure these rules to suit your own style.</p>
<h3 id="installing-and-running-swiftlint">Installing and Running SwiftLint</h3>
<p>To install SwiftLint, I recommend using <a href="https://brew.sh">HomeBrew</a>. Once you have HomeBrew installed, open Terminal and type <code>brew install swiftlint</code>. You can update it any time using <code>brew upgrade swiftlint</code>.</p>
<p>You can run SwiftLint directly from the Terminal. <code>cd</code> to the folder containing your Xcode project and type <code>swiftlint</code>. For a brand new iOS project, you will probably get a result similar to this:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-text" data-lang="text">Linting Swift files in current working directory
Linting 'ViewController.swift' (1/2)
Linting 'AppDelegate.swift' (2/2)
ViewController.swift:23: warning: Vertical Whitespace Violation: Limit vertical whitespace to a single empty line. Currently 2. (vertical_whitespace)
ViewController.swift:25: warning: Trailing Newline Violation: Files should have a single trailing newline. (trailing_newline)
AppDelegate.swift:16: warning: Vertical Whitespace Violation: Limit vertical whitespace to a single empty line. Currently 2. (vertical_whitespace)
AppDelegate.swift:44: warning: Vertical Whitespace Violation: Limit vertical whitespace to a single empty line. Currently 2. (vertical_whitespace)
AppDelegate.swift:46: warning: Trailing Newline Violation: Files should have a single trailing newline. (trailing_newline)
AppDelegate.swift:17: warning: Line Length Violation: Line should be 120 characters or less: currently 144 characters (line_length)
AppDelegate.swift:23: error: Line Length Violation: Line should be 120 characters or less: currently 285 characters (line_length)
AppDelegate.swift:24: warning: Line Length Violation: Line should be 120 characters or less: currently 159 characters (line_length)
AppDelegate.swift:28: error: Line Length Violation: Line should be 120 characters or less: currently 218 characters (line_length)
AppDelegate.swift:29: warning: Line Length Violation: Line should be 120 characters or less: currently 141 characters (line_length)
AppDelegate.swift:33: warning: Line Length Violation: Line should be 120 characters or less: currently 155 characters (line_length)
AppDelegate.swift:37: warning: Line Length Violation: Line should be 120 characters or less: currently 194 characters (line_length)
AppDelegate.swift:41: warning: Line Length Violation: Line should be 120 characters or less: currently 128 characters (line_length)
Done linting! Found 13 violations, 2 serious in 2 files.
</code></pre></div><p><em>I have removed the full path that will be listed for each file just to make this fit better.</em></p>
<p>These reports show the file and line number, whether this is an error or a warning, a description of the error and the name of the SwiftLint rule that caused the warning or error.</p>
<p>You could now go through and fix each of these but there are 2 solutions to make things easier:
Try entering this in the Terminal window: <code>swiftlint autocorrect</code>.</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-text" data-lang="text">Correcting Swift files in current working directory
Correcting 'ViewController.swift' (1/2)
Correcting 'AppDelegate.swift' (2/2)
ViewController.swift:22:1 Corrected Vertical Whitespace
ViewController.swift:23 Corrected Trailing Newline
AppDelegate.swift:15:1 Corrected Vertical Whitespace
AppDelegate.swift:43:1 Corrected Vertical Whitespace
AppDelegate.swift:43 Corrected Trailing Newline
Done correcting 2 files!
</code></pre></div><p>And now if you run <code>swiftlint</code> again you will only get <code>Done linting! Found 8 violations, 2 serious in 2 files.</code> and all the remaining issues are for <code>Line Length Violation</code> This shows that autocorrect cannot fix everything and while it is good on spacing, it has trouble with more complex issues. But it is still worth doing as it can do a lot of the tedious fixes that creep into Xcode projects.</p>
<h3 id="incorporating-swiftlint-into-xcode">Incorporating SwiftLint into Xcode</h3>
<p>The next thing to do to make your life easier is to add SwiftLint to your Xcode project so that it can run automatically whenever you do a build.</p>
<p>Open your project in Xcode and select the project itself at the top of the Navigator on the left. Select the target for the main app and click the Build Phases tab along the top. Click the + button at the top left of the existing build phases and choose ‘New Run Script Phase’. Expand the newly added phase and paste in the following script:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash"><span style="color:#66d9ef">if</span> which swiftlint >/dev/null; <span style="color:#66d9ef">then</span>
swiftlint autocorrect
swiftlint
<span style="color:#66d9ef">else</span>
echo <span style="color:#e6db74">"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint"</span>
<span style="color:#66d9ef">fi</span>
</code></pre></div><p>Your Xcode window should look something like this:</p>
<p><a href="/images/SwiftLineRunScript.png"><img src="/images/SwiftLineRunScript.png" alt="SwiftLint Run Script phase"></a></p>
<p>If you think this looks like it is running SwiftLint twice, you are correct. The first time through it corrects what it can and the second pass reports all remaining issues. This is still faster than manually correcting the easy stuff. So now you will see any violations in the Xcode issue navigator when you do a build and you can click the entry to go directly to the code.</p>
<p><img src="/images/IssuesNavigator.png" alt="SwiftLint errors & warnings in Xcode issues navigator"></p>
<h3 id="configuring-swiftlint">Configuring SwiftLint</h3>
<p>Now you are all set to SwiftLint all your code, but how do you decide what styles SwiftLint should enforce? Go back to Terminal, make the Terminal window as wide as possible and run <code>swiftlint rules</code> which will return a table like this (click to see full-sized image):</p>
<p><a href="/images/swiftlint_rules.png"><img src="/images/swiftlint_rules.png" alt="SwiftLint Rules"></a></p>
<p>For details on what each rule does, check out the entries in <a href="https://github.com/realm/SwiftLint/blob/master/Rules.md">Rules.md</a></p>
<p>As an example, look at the rules for line_length:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-text" data-lang="text">+------------------------------------------+--------+-------------+------------------------+-------------+---------------------+
| identifier | opt-in | correctable | enabled in your config | kind | configuration |
+------------------------------------------+--------+-------------+------------------------+-------------+---------------------+
| line_length | no | no | yes | metrics | warning: 120, er... |
+------------------------------------------+--------+-------------+------------------------+-------------+---------------------+
</code></pre></div><p>And by making my Terminal window full width, I can see the configuration column contains <code>warning: 120, error: 200, ignores urls: false, ignores function declarations: false, ignores comments: false</code>.</p>
<ul>
<li>The rule name (identifier) is line_length - this is what appears in the issue navigator or Terminal.</li>
<li>It is not an opt-in rule, meaning that it is enabled by default.</li>
<li>It is not correctable by autocorrect.</li>
<li>It is enabled in this configuration.</li>
<li>And then comes the configuration:
<ul>
<li>a line of more than 120 characters will generate a warning</li>
<li>a line with more than 200 characters will generate an error and stop the build</li>
<li>this rule will not ignore URLs, function declarations or comments</li>
</ul>
</li>
</ul>
<p>To set your own configurations, you need to create a <code>.swiftlint.yml</code> file in the same folder as your Xcode project. The leading period makes the file invisible, so you will need to create and edit it using Terminal.</p>
<p>In the Terminal, <code>cd</code> to the folder containing your Xcode project file and run <code>touch .swiftlint.yml</code> to create the invisible file. You can edit the file in Terminal using <code>nano</code>, <code>vim</code> or whatever you prefer, but you can also open it in any text editor. I prefer to use Atom so I open the file by running this command: <code>atom .swiftlint.yml</code>.</p>
<p>The SwiftLint ReadMe has a section about <a href="https://github.com/realm/SwiftLint#configuration">configuration</a> which shows the format and the various general headings you can use, as well as how to configure an individual rule.</p>
<p>Here is my .swiftlint.yml file:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-yml" data-lang="yml"><span style="color:#66d9ef">disabled_rules</span>: <span style="color:#75715e"># rule identifiers to exclude from running</span>
<span style="color:#66d9ef">included</span>: <span style="color:#75715e"># paths to include during linting. `--path` is ignored if present. takes precendence over `excluded`.</span>
<span style="color:#66d9ef">excluded</span>: <span style="color:#75715e"># paths to ignore during linting. overridden by `included`.</span>
- Carthage
- Pods
<span style="color:#66d9ef">opt_in_rules</span>:
- closure_end_indentation
- closure_spacing
- contains_over_first_not_nil
- empty_count
- explicit_init
- fatal_error_message
- force_unwrapping
- literal_expression_end_indentation
- multiline_arguments
- multiline_parameters
- operator_usage_whitespace
- overridden_super_call
- private_outlet
- prohibited_super_call
- trailing_closure
- unneeded_parentheses_in_closure_argument
<span style="color:#66d9ef">function_body_length</span>:
- <span style="color:#ae81ff">60</span> <span style="color:#75715e"># warning</span>
- <span style="color:#ae81ff">100</span> <span style="color:#75715e"># error</span>
<span style="color:#66d9ef">line_length</span>:
- <span style="color:#ae81ff">150</span> <span style="color:#75715e"># warning</span>
- <span style="color:#ae81ff">200</span> <span style="color:#75715e"># error</span>
<span style="color:#66d9ef">cyclomatic_complexity</span>:
<span style="color:#66d9ef">ignores_case_statements</span>: <span style="color:#66d9ef">true</span>
</code></pre></div><ul>
<li>No rules are disabled by default.</li>
<li><code>included</code> is blank which means it checks every folder…</li>
<li>… except for the ones listed in the <code>excluded</code> section.</li>
<li><code>opt-in-rules</code>: I went through the list of rules with <code>opt-in</code> equal to <code>yes</code> and enabled all I thought useful.</li>
<li><code>function_body_length</code> - the default warning length is 40 but I allow myself 60 as that fits on my screen so I can always see the entire function without scrolling.</li>
<li><code>line_length</code> - with a bigger screen, I lengthen both the warning and error lengths.</li>
<li><code>cyclomatic_complexity</code> checks for functions that are getting so complex that the compiler might run into trouble. I have this on with the default warning & error limits, but I set it to ignore <code>case</code> statements as they can often trigger this without really being too complex.</li>
</ul>
<p>Now that my .swiftlint.yml file is edited, doing a build uses those settings and for a new iOS project, I am now down to 2 errors and 3 warnings, all due to long lines in AppDelegate.swift.</p>
<p>The other main way to configure SwiftLint is by disabling specific rules in my code.</p>
<p>As an example, I have an <code>enum</code> for direction:</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-swift" data-lang="swift"><span style="color:#66d9ef">enum</span> <span style="color:#a6e22e">Direction</span> {
<span style="color:#66d9ef">case</span> up, down, <span style="color:#66d9ef">left</span>, <span style="color:#66d9ef">right</span>
}
</code></pre></div><p>When I build this, SwiftLint gives a warning:
<code>Identifier Name Violation: Enum element name should be between 3 and 40 characters long: 'up' (identifier_name)</code></p>
<p>This tells me that <code>up</code> is too short a word to use as an identifier according to the <code>identifier_name</code> rule. In this case, <code>up</code> is the obvious identifier to use, so I want SwiftLint to let it pass. But I don’t want to check my configuration file, because I want it to catch other short identifier names.</p>
<p>The solution is to add this comment to my code, before the <code>case</code> line:</p>
<p><code>// swiftlint:disable next identifier_name</code></p>
<p>This tells SwiftLint to ignore the next <code>identifier_name</code> warning or error it sees and now my code builds without error.</p>
<p>Rules can also be disabled or enabled by file. Check out the <a href="https://github.com/realm/SwiftLint#disable-rules-in-code">Disable rules in code</a> section of the SwiftLint ReadMe for more details.</p>
<h2 id="what-are-the-benefits">What are the benefits?</h2>
<p>For me, SwiftLint enforces a number of good habits:</p>
<ul>
<li>Files are kept relatively short.</li>
<li>Functions are always small enough to fit on a single screen.</li>
<li>Variable names & function names cannot be too short and non-descriptive.</li>
<li>Braces, indentation and white-space are always consistent.</li>
</ul>
<p>And sometimes the warnings make me think of a better way to do things.</p>
</div>
<div class="pagination">
<div class="pagination__title">
<span class="pagination__title-h">Read other posts</span>
<hr />
</div>
<div class="pagination__buttons">
<a class="btn next" href="https://troz.net/post/2018/app-updates/">← App Updates</a>
<a class="btn previous" href="https://troz.net/post/2018/icon-builder-5/">Icon Builder 5 →</a>
</div>
</div>
</div>
</div>
<link rel="stylesheet" href="/css/footer.css" />
<footer class="footer">
<div class="footer__inner">
<div class="social_footer">
<a id="email-Link" class="mailtoui" href="mailto:[email protected]"
><img src="/icons/envelope.svg"
/></a>
<a href="https://stackoverflow.com/users/1082632"
><img src="/icons/stack-overflow.svg"
/></a>
<a href="https://twitter.com/trozware"><img src="/icons/twitter.svg"/></a>
<a href="https://github.com/trozware"><img src="/icons/github.svg"/></a>
<a href="https://troz.net/index.xml"><img src="/icons/rss.svg"/></a>
<a href="https://troz.net/feed.json"><img src="/icons/json.png"/></a>
<a href="https://dev.to/trozware">
<img src="https://d2fltix0v2e0sb.cloudfront.net/dev-badge.svg"
alt="TrozWare's DEV Profile"
style="height: 37px; margin-top: -3px" height="40" width="40">
</a>
</div>
</div>
<div class="footer__inner">
<div class="copyright">
<span>© 2012 - 2020 Sarah Reichelt</span>
<span
><a href="http://gohugo.io">Hugo</a> theme created by
<a href="https://twitter.com/panr">panr</a> 2018</span
>
</div>
</div>
</footer>
<script src="/assets/main.js"></script>
<script src="/assets/prism.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mailtoui@latest/dist/mailtoui-min.js"></script>
<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
<script src="/quicklink.js"></script>
<script>
window.addEventListener('load', () => {
quicklink()
})
</script>
</div>
</body>
</html>
| {'content_hash': '87650c8702c133d4c12dc03a29860775', 'timestamp': '', 'source': 'github', 'line_count': 423, 'max_line_length': 697, 'avg_line_length': 58.314420803782504, 'alnum_prop': 0.6907203956703287, 'repo_name': 'trozware/trozware.github.io', 'id': '6e0031dee3afebccf9c6706f16de3a67052fd6d0', 'size': '24676', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/post/2018/swiftlint/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '72654'}, {'name': 'HTML', 'bytes': '1323960'}]} |
/**
* Created by shalomeir on 15. 3. 16..
*/
'use strict';
var DomControl = {
isChildNodeOf: function(target, parentIds) {
// returns boolean whether target is child of a list of ids
// parentIds can be a string or an array of ids
if (typeof parentIds === 'string') {
parentIds = [parentIds];
}
// if this node is not the one we want, move up the dom tree
while (target !== null && parentIds.indexOf(target.id) < 0) {
target = target.parentNode;
}
// at this point we have found our containing div or we are out of parent nodes
return (target !== null && parentIds.indexOf(target.id) >= 0);
}
};
module.exports = DomControl;
| {'content_hash': '869ac79663160efc574c21924a28e108', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 83, 'avg_line_length': 27.36, 'alnum_prop': 0.6359649122807017, 'repo_name': 'tfink419/southeast-fl-jews', 'id': '8d0dd26fa841cee0131647bacd1f33f9bbb92398', 'size': '684', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'webapp/client/scripts/utils/DomControl.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '51151'}, {'name': 'HTML', 'bytes': '10480'}, {'name': 'JavaScript', 'bytes': '2479725'}, {'name': 'Python', 'bytes': '50569'}, {'name': 'Shell', 'bytes': '86'}]} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: BayesianProbitRegressor.proto
#ifndef PROTOBUF_BayesianProbitRegressor_2eproto__INCLUDED
#define PROTOBUF_BayesianProbitRegressor_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3003000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3003000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata_lite.h>
#include <google/protobuf/message_lite.h>
#include <google/protobuf/repeated_field.h> // IWYU pragma: export
#include <google/protobuf/extension_set.h> // IWYU pragma: export
// @@protoc_insertion_point(includes)
namespace CoreML {
namespace Specification {
class BayesianProbitRegressor;
class BayesianProbitRegressorDefaultTypeInternal;
extern BayesianProbitRegressorDefaultTypeInternal _BayesianProbitRegressor_default_instance_;
class BayesianProbitRegressor_FeatureValueWeight;
class BayesianProbitRegressor_FeatureValueWeightDefaultTypeInternal;
extern BayesianProbitRegressor_FeatureValueWeightDefaultTypeInternal _BayesianProbitRegressor_FeatureValueWeight_default_instance_;
class BayesianProbitRegressor_FeatureWeight;
class BayesianProbitRegressor_FeatureWeightDefaultTypeInternal;
extern BayesianProbitRegressor_FeatureWeightDefaultTypeInternal _BayesianProbitRegressor_FeatureWeight_default_instance_;
class BayesianProbitRegressor_Gaussian;
class BayesianProbitRegressor_GaussianDefaultTypeInternal;
extern BayesianProbitRegressor_GaussianDefaultTypeInternal _BayesianProbitRegressor_Gaussian_default_instance_;
} // namespace Specification
} // namespace CoreML
namespace CoreML {
namespace Specification {
namespace protobuf_BayesianProbitRegressor_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
static const ::google::protobuf::internal::ParseTableField entries[];
static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
static const ::google::protobuf::internal::ParseTable schema[];
static const ::google::protobuf::uint32 offsets[];
static void InitDefaultsImpl();
static void Shutdown();
};
void AddDescriptors();
void InitDefaults();
} // namespace protobuf_BayesianProbitRegressor_2eproto
// ===================================================================
class BayesianProbitRegressor_Gaussian : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.BayesianProbitRegressor.Gaussian) */ {
public:
BayesianProbitRegressor_Gaussian();
virtual ~BayesianProbitRegressor_Gaussian();
BayesianProbitRegressor_Gaussian(const BayesianProbitRegressor_Gaussian& from);
inline BayesianProbitRegressor_Gaussian& operator=(const BayesianProbitRegressor_Gaussian& from) {
CopyFrom(from);
return *this;
}
static const BayesianProbitRegressor_Gaussian& default_instance();
static inline const BayesianProbitRegressor_Gaussian* internal_default_instance() {
return reinterpret_cast<const BayesianProbitRegressor_Gaussian*>(
&_BayesianProbitRegressor_Gaussian_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
0;
void Swap(BayesianProbitRegressor_Gaussian* other);
// implements Message ----------------------------------------------
inline BayesianProbitRegressor_Gaussian* New() const PROTOBUF_FINAL { return New(NULL); }
BayesianProbitRegressor_Gaussian* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const BayesianProbitRegressor_Gaussian& from);
void MergeFrom(const BayesianProbitRegressor_Gaussian& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BayesianProbitRegressor_Gaussian* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// double mean = 1;
void clear_mean();
static const int kMeanFieldNumber = 1;
double mean() const;
void set_mean(double value);
// double precision = 2;
void clear_precision();
static const int kPrecisionFieldNumber = 2;
double precision() const;
void set_precision(double value);
// @@protoc_insertion_point(class_scope:CoreML.Specification.BayesianProbitRegressor.Gaussian)
private:
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
double mean_;
double precision_;
mutable int _cached_size_;
friend struct protobuf_BayesianProbitRegressor_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class BayesianProbitRegressor_FeatureValueWeight : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight) */ {
public:
BayesianProbitRegressor_FeatureValueWeight();
virtual ~BayesianProbitRegressor_FeatureValueWeight();
BayesianProbitRegressor_FeatureValueWeight(const BayesianProbitRegressor_FeatureValueWeight& from);
inline BayesianProbitRegressor_FeatureValueWeight& operator=(const BayesianProbitRegressor_FeatureValueWeight& from) {
CopyFrom(from);
return *this;
}
static const BayesianProbitRegressor_FeatureValueWeight& default_instance();
static inline const BayesianProbitRegressor_FeatureValueWeight* internal_default_instance() {
return reinterpret_cast<const BayesianProbitRegressor_FeatureValueWeight*>(
&_BayesianProbitRegressor_FeatureValueWeight_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
1;
void Swap(BayesianProbitRegressor_FeatureValueWeight* other);
// implements Message ----------------------------------------------
inline BayesianProbitRegressor_FeatureValueWeight* New() const PROTOBUF_FINAL { return New(NULL); }
BayesianProbitRegressor_FeatureValueWeight* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const BayesianProbitRegressor_FeatureValueWeight& from);
void MergeFrom(const BayesianProbitRegressor_FeatureValueWeight& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BayesianProbitRegressor_FeatureValueWeight* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// .CoreML.Specification.BayesianProbitRegressor.Gaussian featureWeight = 2;
bool has_featureweight() const;
void clear_featureweight();
static const int kFeatureWeightFieldNumber = 2;
const ::CoreML::Specification::BayesianProbitRegressor_Gaussian& featureweight() const;
::CoreML::Specification::BayesianProbitRegressor_Gaussian* mutable_featureweight();
::CoreML::Specification::BayesianProbitRegressor_Gaussian* release_featureweight();
void set_allocated_featureweight(::CoreML::Specification::BayesianProbitRegressor_Gaussian* featureweight);
// uint32 featureValue = 1;
void clear_featurevalue();
static const int kFeatureValueFieldNumber = 1;
::google::protobuf::uint32 featurevalue() const;
void set_featurevalue(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight)
private:
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::CoreML::Specification::BayesianProbitRegressor_Gaussian* featureweight_;
::google::protobuf::uint32 featurevalue_;
mutable int _cached_size_;
friend struct protobuf_BayesianProbitRegressor_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class BayesianProbitRegressor_FeatureWeight : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.BayesianProbitRegressor.FeatureWeight) */ {
public:
BayesianProbitRegressor_FeatureWeight();
virtual ~BayesianProbitRegressor_FeatureWeight();
BayesianProbitRegressor_FeatureWeight(const BayesianProbitRegressor_FeatureWeight& from);
inline BayesianProbitRegressor_FeatureWeight& operator=(const BayesianProbitRegressor_FeatureWeight& from) {
CopyFrom(from);
return *this;
}
static const BayesianProbitRegressor_FeatureWeight& default_instance();
static inline const BayesianProbitRegressor_FeatureWeight* internal_default_instance() {
return reinterpret_cast<const BayesianProbitRegressor_FeatureWeight*>(
&_BayesianProbitRegressor_FeatureWeight_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
2;
void Swap(BayesianProbitRegressor_FeatureWeight* other);
// implements Message ----------------------------------------------
inline BayesianProbitRegressor_FeatureWeight* New() const PROTOBUF_FINAL { return New(NULL); }
BayesianProbitRegressor_FeatureWeight* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const BayesianProbitRegressor_FeatureWeight& from);
void MergeFrom(const BayesianProbitRegressor_FeatureWeight& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BayesianProbitRegressor_FeatureWeight* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// repeated .CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight weights = 2;
int weights_size() const;
void clear_weights();
static const int kWeightsFieldNumber = 2;
const ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight& weights(int index) const;
::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight* mutable_weights(int index);
::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight* add_weights();
::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight >*
mutable_weights();
const ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight >&
weights() const;
// uint32 featureId = 1;
void clear_featureid();
static const int kFeatureIdFieldNumber = 1;
::google::protobuf::uint32 featureid() const;
void set_featureid(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:CoreML.Specification.BayesianProbitRegressor.FeatureWeight)
private:
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight > weights_;
::google::protobuf::uint32 featureid_;
mutable int _cached_size_;
friend struct protobuf_BayesianProbitRegressor_2eproto::TableStruct;
};
// -------------------------------------------------------------------
class BayesianProbitRegressor : public ::google::protobuf::MessageLite /* @@protoc_insertion_point(class_definition:CoreML.Specification.BayesianProbitRegressor) */ {
public:
BayesianProbitRegressor();
virtual ~BayesianProbitRegressor();
BayesianProbitRegressor(const BayesianProbitRegressor& from);
inline BayesianProbitRegressor& operator=(const BayesianProbitRegressor& from) {
CopyFrom(from);
return *this;
}
static const BayesianProbitRegressor& default_instance();
static inline const BayesianProbitRegressor* internal_default_instance() {
return reinterpret_cast<const BayesianProbitRegressor*>(
&_BayesianProbitRegressor_default_instance_);
}
static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
3;
void Swap(BayesianProbitRegressor* other);
// implements Message ----------------------------------------------
inline BayesianProbitRegressor* New() const PROTOBUF_FINAL { return New(NULL); }
BayesianProbitRegressor* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
void CheckTypeAndMergeFrom(const ::google::protobuf::MessageLite& from)
PROTOBUF_FINAL;
void CopyFrom(const BayesianProbitRegressor& from);
void MergeFrom(const BayesianProbitRegressor& from);
void Clear() PROTOBUF_FINAL;
bool IsInitialized() const PROTOBUF_FINAL;
size_t ByteSizeLong() const PROTOBUF_FINAL;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
void DiscardUnknownFields();
int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(BayesianProbitRegressor* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return NULL;
}
inline void* MaybeArenaPtr() const {
return NULL;
}
public:
::std::string GetTypeName() const PROTOBUF_FINAL;
// nested types ----------------------------------------------------
typedef BayesianProbitRegressor_Gaussian Gaussian;
typedef BayesianProbitRegressor_FeatureValueWeight FeatureValueWeight;
typedef BayesianProbitRegressor_FeatureWeight FeatureWeight;
// accessors -------------------------------------------------------
// repeated .CoreML.Specification.BayesianProbitRegressor.FeatureWeight features = 3;
int features_size() const;
void clear_features();
static const int kFeaturesFieldNumber = 3;
const ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight& features(int index) const;
::CoreML::Specification::BayesianProbitRegressor_FeatureWeight* mutable_features(int index);
::CoreML::Specification::BayesianProbitRegressor_FeatureWeight* add_features();
::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight >*
mutable_features();
const ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight >&
features() const;
// string regressionInputFeatureName = 10;
void clear_regressioninputfeaturename();
static const int kRegressionInputFeatureNameFieldNumber = 10;
const ::std::string& regressioninputfeaturename() const;
void set_regressioninputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_regressioninputfeaturename(::std::string&& value);
#endif
void set_regressioninputfeaturename(const char* value);
void set_regressioninputfeaturename(const char* value, size_t size);
::std::string* mutable_regressioninputfeaturename();
::std::string* release_regressioninputfeaturename();
void set_allocated_regressioninputfeaturename(::std::string* regressioninputfeaturename);
// string optimismInputFeatureName = 11;
void clear_optimisminputfeaturename();
static const int kOptimismInputFeatureNameFieldNumber = 11;
const ::std::string& optimisminputfeaturename() const;
void set_optimisminputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_optimisminputfeaturename(::std::string&& value);
#endif
void set_optimisminputfeaturename(const char* value);
void set_optimisminputfeaturename(const char* value, size_t size);
::std::string* mutable_optimisminputfeaturename();
::std::string* release_optimisminputfeaturename();
void set_allocated_optimisminputfeaturename(::std::string* optimisminputfeaturename);
// string samplingScaleInputFeatureName = 12;
void clear_samplingscaleinputfeaturename();
static const int kSamplingScaleInputFeatureNameFieldNumber = 12;
const ::std::string& samplingscaleinputfeaturename() const;
void set_samplingscaleinputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_samplingscaleinputfeaturename(::std::string&& value);
#endif
void set_samplingscaleinputfeaturename(const char* value);
void set_samplingscaleinputfeaturename(const char* value, size_t size);
::std::string* mutable_samplingscaleinputfeaturename();
::std::string* release_samplingscaleinputfeaturename();
void set_allocated_samplingscaleinputfeaturename(::std::string* samplingscaleinputfeaturename);
// string samplingTruncationInputFeatureName = 13;
void clear_samplingtruncationinputfeaturename();
static const int kSamplingTruncationInputFeatureNameFieldNumber = 13;
const ::std::string& samplingtruncationinputfeaturename() const;
void set_samplingtruncationinputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_samplingtruncationinputfeaturename(::std::string&& value);
#endif
void set_samplingtruncationinputfeaturename(const char* value);
void set_samplingtruncationinputfeaturename(const char* value, size_t size);
::std::string* mutable_samplingtruncationinputfeaturename();
::std::string* release_samplingtruncationinputfeaturename();
void set_allocated_samplingtruncationinputfeaturename(::std::string* samplingtruncationinputfeaturename);
// string meanOutputFeatureName = 20;
void clear_meanoutputfeaturename();
static const int kMeanOutputFeatureNameFieldNumber = 20;
const ::std::string& meanoutputfeaturename() const;
void set_meanoutputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_meanoutputfeaturename(::std::string&& value);
#endif
void set_meanoutputfeaturename(const char* value);
void set_meanoutputfeaturename(const char* value, size_t size);
::std::string* mutable_meanoutputfeaturename();
::std::string* release_meanoutputfeaturename();
void set_allocated_meanoutputfeaturename(::std::string* meanoutputfeaturename);
// string varianceOutputFeatureName = 21;
void clear_varianceoutputfeaturename();
static const int kVarianceOutputFeatureNameFieldNumber = 21;
const ::std::string& varianceoutputfeaturename() const;
void set_varianceoutputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_varianceoutputfeaturename(::std::string&& value);
#endif
void set_varianceoutputfeaturename(const char* value);
void set_varianceoutputfeaturename(const char* value, size_t size);
::std::string* mutable_varianceoutputfeaturename();
::std::string* release_varianceoutputfeaturename();
void set_allocated_varianceoutputfeaturename(::std::string* varianceoutputfeaturename);
// string pessimisticProbabilityOutputFeatureName = 22;
void clear_pessimisticprobabilityoutputfeaturename();
static const int kPessimisticProbabilityOutputFeatureNameFieldNumber = 22;
const ::std::string& pessimisticprobabilityoutputfeaturename() const;
void set_pessimisticprobabilityoutputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_pessimisticprobabilityoutputfeaturename(::std::string&& value);
#endif
void set_pessimisticprobabilityoutputfeaturename(const char* value);
void set_pessimisticprobabilityoutputfeaturename(const char* value, size_t size);
::std::string* mutable_pessimisticprobabilityoutputfeaturename();
::std::string* release_pessimisticprobabilityoutputfeaturename();
void set_allocated_pessimisticprobabilityoutputfeaturename(::std::string* pessimisticprobabilityoutputfeaturename);
// string sampledProbabilityOutputFeatureName = 23;
void clear_sampledprobabilityoutputfeaturename();
static const int kSampledProbabilityOutputFeatureNameFieldNumber = 23;
const ::std::string& sampledprobabilityoutputfeaturename() const;
void set_sampledprobabilityoutputfeaturename(const ::std::string& value);
#if LANG_CXX11
void set_sampledprobabilityoutputfeaturename(::std::string&& value);
#endif
void set_sampledprobabilityoutputfeaturename(const char* value);
void set_sampledprobabilityoutputfeaturename(const char* value, size_t size);
::std::string* mutable_sampledprobabilityoutputfeaturename();
::std::string* release_sampledprobabilityoutputfeaturename();
void set_allocated_sampledprobabilityoutputfeaturename(::std::string* sampledprobabilityoutputfeaturename);
// .CoreML.Specification.BayesianProbitRegressor.Gaussian bias = 2;
bool has_bias() const;
void clear_bias();
static const int kBiasFieldNumber = 2;
const ::CoreML::Specification::BayesianProbitRegressor_Gaussian& bias() const;
::CoreML::Specification::BayesianProbitRegressor_Gaussian* mutable_bias();
::CoreML::Specification::BayesianProbitRegressor_Gaussian* release_bias();
void set_allocated_bias(::CoreML::Specification::BayesianProbitRegressor_Gaussian* bias);
// uint32 numberOfFeatures = 1;
void clear_numberoffeatures();
static const int kNumberOfFeaturesFieldNumber = 1;
::google::protobuf::uint32 numberoffeatures() const;
void set_numberoffeatures(::google::protobuf::uint32 value);
// @@protoc_insertion_point(class_scope:CoreML.Specification.BayesianProbitRegressor)
private:
::google::protobuf::internal::InternalMetadataWithArenaLite _internal_metadata_;
::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight > features_;
::google::protobuf::internal::ArenaStringPtr regressioninputfeaturename_;
::google::protobuf::internal::ArenaStringPtr optimisminputfeaturename_;
::google::protobuf::internal::ArenaStringPtr samplingscaleinputfeaturename_;
::google::protobuf::internal::ArenaStringPtr samplingtruncationinputfeaturename_;
::google::protobuf::internal::ArenaStringPtr meanoutputfeaturename_;
::google::protobuf::internal::ArenaStringPtr varianceoutputfeaturename_;
::google::protobuf::internal::ArenaStringPtr pessimisticprobabilityoutputfeaturename_;
::google::protobuf::internal::ArenaStringPtr sampledprobabilityoutputfeaturename_;
::CoreML::Specification::BayesianProbitRegressor_Gaussian* bias_;
::google::protobuf::uint32 numberoffeatures_;
mutable int _cached_size_;
friend struct protobuf_BayesianProbitRegressor_2eproto::TableStruct;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// BayesianProbitRegressor_Gaussian
// double mean = 1;
inline void BayesianProbitRegressor_Gaussian::clear_mean() {
mean_ = 0;
}
inline double BayesianProbitRegressor_Gaussian::mean() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.Gaussian.mean)
return mean_;
}
inline void BayesianProbitRegressor_Gaussian::set_mean(double value) {
mean_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.Gaussian.mean)
}
// double precision = 2;
inline void BayesianProbitRegressor_Gaussian::clear_precision() {
precision_ = 0;
}
inline double BayesianProbitRegressor_Gaussian::precision() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.Gaussian.precision)
return precision_;
}
inline void BayesianProbitRegressor_Gaussian::set_precision(double value) {
precision_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.Gaussian.precision)
}
// -------------------------------------------------------------------
// BayesianProbitRegressor_FeatureValueWeight
// uint32 featureValue = 1;
inline void BayesianProbitRegressor_FeatureValueWeight::clear_featurevalue() {
featurevalue_ = 0u;
}
inline ::google::protobuf::uint32 BayesianProbitRegressor_FeatureValueWeight::featurevalue() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureValue)
return featurevalue_;
}
inline void BayesianProbitRegressor_FeatureValueWeight::set_featurevalue(::google::protobuf::uint32 value) {
featurevalue_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureValue)
}
// .CoreML.Specification.BayesianProbitRegressor.Gaussian featureWeight = 2;
inline bool BayesianProbitRegressor_FeatureValueWeight::has_featureweight() const {
return this != internal_default_instance() && featureweight_ != NULL;
}
inline void BayesianProbitRegressor_FeatureValueWeight::clear_featureweight() {
if (GetArenaNoVirtual() == NULL && featureweight_ != NULL) delete featureweight_;
featureweight_ = NULL;
}
inline const ::CoreML::Specification::BayesianProbitRegressor_Gaussian& BayesianProbitRegressor_FeatureValueWeight::featureweight() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureWeight)
return featureweight_ != NULL ? *featureweight_
: *::CoreML::Specification::BayesianProbitRegressor_Gaussian::internal_default_instance();
}
inline ::CoreML::Specification::BayesianProbitRegressor_Gaussian* BayesianProbitRegressor_FeatureValueWeight::mutable_featureweight() {
if (featureweight_ == NULL) {
featureweight_ = new ::CoreML::Specification::BayesianProbitRegressor_Gaussian;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureWeight)
return featureweight_;
}
inline ::CoreML::Specification::BayesianProbitRegressor_Gaussian* BayesianProbitRegressor_FeatureValueWeight::release_featureweight() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureWeight)
::CoreML::Specification::BayesianProbitRegressor_Gaussian* temp = featureweight_;
featureweight_ = NULL;
return temp;
}
inline void BayesianProbitRegressor_FeatureValueWeight::set_allocated_featureweight(::CoreML::Specification::BayesianProbitRegressor_Gaussian* featureweight) {
delete featureweight_;
featureweight_ = featureweight;
if (featureweight) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight.featureWeight)
}
// -------------------------------------------------------------------
// BayesianProbitRegressor_FeatureWeight
// uint32 featureId = 1;
inline void BayesianProbitRegressor_FeatureWeight::clear_featureid() {
featureid_ = 0u;
}
inline ::google::protobuf::uint32 BayesianProbitRegressor_FeatureWeight::featureid() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.featureId)
return featureid_;
}
inline void BayesianProbitRegressor_FeatureWeight::set_featureid(::google::protobuf::uint32 value) {
featureid_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.featureId)
}
// repeated .CoreML.Specification.BayesianProbitRegressor.FeatureValueWeight weights = 2;
inline int BayesianProbitRegressor_FeatureWeight::weights_size() const {
return weights_.size();
}
inline void BayesianProbitRegressor_FeatureWeight::clear_weights() {
weights_.Clear();
}
inline const ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight& BayesianProbitRegressor_FeatureWeight::weights(int index) const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.weights)
return weights_.Get(index);
}
inline ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight* BayesianProbitRegressor_FeatureWeight::mutable_weights(int index) {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.weights)
return weights_.Mutable(index);
}
inline ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight* BayesianProbitRegressor_FeatureWeight::add_weights() {
// @@protoc_insertion_point(field_add:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.weights)
return weights_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight >*
BayesianProbitRegressor_FeatureWeight::mutable_weights() {
// @@protoc_insertion_point(field_mutable_list:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.weights)
return &weights_;
}
inline const ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureValueWeight >&
BayesianProbitRegressor_FeatureWeight::weights() const {
// @@protoc_insertion_point(field_list:CoreML.Specification.BayesianProbitRegressor.FeatureWeight.weights)
return weights_;
}
// -------------------------------------------------------------------
// BayesianProbitRegressor
// uint32 numberOfFeatures = 1;
inline void BayesianProbitRegressor::clear_numberoffeatures() {
numberoffeatures_ = 0u;
}
inline ::google::protobuf::uint32 BayesianProbitRegressor::numberoffeatures() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.numberOfFeatures)
return numberoffeatures_;
}
inline void BayesianProbitRegressor::set_numberoffeatures(::google::protobuf::uint32 value) {
numberoffeatures_ = value;
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.numberOfFeatures)
}
// .CoreML.Specification.BayesianProbitRegressor.Gaussian bias = 2;
inline bool BayesianProbitRegressor::has_bias() const {
return this != internal_default_instance() && bias_ != NULL;
}
inline void BayesianProbitRegressor::clear_bias() {
if (GetArenaNoVirtual() == NULL && bias_ != NULL) delete bias_;
bias_ = NULL;
}
inline const ::CoreML::Specification::BayesianProbitRegressor_Gaussian& BayesianProbitRegressor::bias() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.bias)
return bias_ != NULL ? *bias_
: *::CoreML::Specification::BayesianProbitRegressor_Gaussian::internal_default_instance();
}
inline ::CoreML::Specification::BayesianProbitRegressor_Gaussian* BayesianProbitRegressor::mutable_bias() {
if (bias_ == NULL) {
bias_ = new ::CoreML::Specification::BayesianProbitRegressor_Gaussian;
}
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.bias)
return bias_;
}
inline ::CoreML::Specification::BayesianProbitRegressor_Gaussian* BayesianProbitRegressor::release_bias() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.bias)
::CoreML::Specification::BayesianProbitRegressor_Gaussian* temp = bias_;
bias_ = NULL;
return temp;
}
inline void BayesianProbitRegressor::set_allocated_bias(::CoreML::Specification::BayesianProbitRegressor_Gaussian* bias) {
delete bias_;
bias_ = bias;
if (bias) {
} else {
}
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.bias)
}
// repeated .CoreML.Specification.BayesianProbitRegressor.FeatureWeight features = 3;
inline int BayesianProbitRegressor::features_size() const {
return features_.size();
}
inline void BayesianProbitRegressor::clear_features() {
features_.Clear();
}
inline const ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight& BayesianProbitRegressor::features(int index) const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.features)
return features_.Get(index);
}
inline ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight* BayesianProbitRegressor::mutable_features(int index) {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.features)
return features_.Mutable(index);
}
inline ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight* BayesianProbitRegressor::add_features() {
// @@protoc_insertion_point(field_add:CoreML.Specification.BayesianProbitRegressor.features)
return features_.Add();
}
inline ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight >*
BayesianProbitRegressor::mutable_features() {
// @@protoc_insertion_point(field_mutable_list:CoreML.Specification.BayesianProbitRegressor.features)
return &features_;
}
inline const ::google::protobuf::RepeatedPtrField< ::CoreML::Specification::BayesianProbitRegressor_FeatureWeight >&
BayesianProbitRegressor::features() const {
// @@protoc_insertion_point(field_list:CoreML.Specification.BayesianProbitRegressor.features)
return features_;
}
// string regressionInputFeatureName = 10;
inline void BayesianProbitRegressor::clear_regressioninputfeaturename() {
regressioninputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::regressioninputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
return regressioninputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_regressioninputfeaturename(const ::std::string& value) {
regressioninputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_regressioninputfeaturename(::std::string&& value) {
regressioninputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_regressioninputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
regressioninputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
}
inline void BayesianProbitRegressor::set_regressioninputfeaturename(const char* value, size_t size) {
regressioninputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_regressioninputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
return regressioninputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_regressioninputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
return regressioninputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_regressioninputfeaturename(::std::string* regressioninputfeaturename) {
if (regressioninputfeaturename != NULL) {
} else {
}
regressioninputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), regressioninputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.regressionInputFeatureName)
}
// string optimismInputFeatureName = 11;
inline void BayesianProbitRegressor::clear_optimisminputfeaturename() {
optimisminputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::optimisminputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
return optimisminputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_optimisminputfeaturename(const ::std::string& value) {
optimisminputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_optimisminputfeaturename(::std::string&& value) {
optimisminputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_optimisminputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
optimisminputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
}
inline void BayesianProbitRegressor::set_optimisminputfeaturename(const char* value, size_t size) {
optimisminputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_optimisminputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
return optimisminputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_optimisminputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
return optimisminputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_optimisminputfeaturename(::std::string* optimisminputfeaturename) {
if (optimisminputfeaturename != NULL) {
} else {
}
optimisminputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), optimisminputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.optimismInputFeatureName)
}
// string samplingScaleInputFeatureName = 12;
inline void BayesianProbitRegressor::clear_samplingscaleinputfeaturename() {
samplingscaleinputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::samplingscaleinputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
return samplingscaleinputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_samplingscaleinputfeaturename(const ::std::string& value) {
samplingscaleinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_samplingscaleinputfeaturename(::std::string&& value) {
samplingscaleinputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_samplingscaleinputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
samplingscaleinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
}
inline void BayesianProbitRegressor::set_samplingscaleinputfeaturename(const char* value, size_t size) {
samplingscaleinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_samplingscaleinputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
return samplingscaleinputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_samplingscaleinputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
return samplingscaleinputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_samplingscaleinputfeaturename(::std::string* samplingscaleinputfeaturename) {
if (samplingscaleinputfeaturename != NULL) {
} else {
}
samplingscaleinputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), samplingscaleinputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.samplingScaleInputFeatureName)
}
// string samplingTruncationInputFeatureName = 13;
inline void BayesianProbitRegressor::clear_samplingtruncationinputfeaturename() {
samplingtruncationinputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::samplingtruncationinputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
return samplingtruncationinputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_samplingtruncationinputfeaturename(const ::std::string& value) {
samplingtruncationinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_samplingtruncationinputfeaturename(::std::string&& value) {
samplingtruncationinputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_samplingtruncationinputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
samplingtruncationinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
}
inline void BayesianProbitRegressor::set_samplingtruncationinputfeaturename(const char* value, size_t size) {
samplingtruncationinputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_samplingtruncationinputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
return samplingtruncationinputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_samplingtruncationinputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
return samplingtruncationinputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_samplingtruncationinputfeaturename(::std::string* samplingtruncationinputfeaturename) {
if (samplingtruncationinputfeaturename != NULL) {
} else {
}
samplingtruncationinputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), samplingtruncationinputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.samplingTruncationInputFeatureName)
}
// string meanOutputFeatureName = 20;
inline void BayesianProbitRegressor::clear_meanoutputfeaturename() {
meanoutputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::meanoutputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
return meanoutputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_meanoutputfeaturename(const ::std::string& value) {
meanoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_meanoutputfeaturename(::std::string&& value) {
meanoutputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_meanoutputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
meanoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
}
inline void BayesianProbitRegressor::set_meanoutputfeaturename(const char* value, size_t size) {
meanoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_meanoutputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
return meanoutputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_meanoutputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
return meanoutputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_meanoutputfeaturename(::std::string* meanoutputfeaturename) {
if (meanoutputfeaturename != NULL) {
} else {
}
meanoutputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), meanoutputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.meanOutputFeatureName)
}
// string varianceOutputFeatureName = 21;
inline void BayesianProbitRegressor::clear_varianceoutputfeaturename() {
varianceoutputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::varianceoutputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
return varianceoutputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_varianceoutputfeaturename(const ::std::string& value) {
varianceoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_varianceoutputfeaturename(::std::string&& value) {
varianceoutputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_varianceoutputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
varianceoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
}
inline void BayesianProbitRegressor::set_varianceoutputfeaturename(const char* value, size_t size) {
varianceoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_varianceoutputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
return varianceoutputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_varianceoutputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
return varianceoutputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_varianceoutputfeaturename(::std::string* varianceoutputfeaturename) {
if (varianceoutputfeaturename != NULL) {
} else {
}
varianceoutputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), varianceoutputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.varianceOutputFeatureName)
}
// string pessimisticProbabilityOutputFeatureName = 22;
inline void BayesianProbitRegressor::clear_pessimisticprobabilityoutputfeaturename() {
pessimisticprobabilityoutputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::pessimisticprobabilityoutputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
return pessimisticprobabilityoutputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_pessimisticprobabilityoutputfeaturename(const ::std::string& value) {
pessimisticprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_pessimisticprobabilityoutputfeaturename(::std::string&& value) {
pessimisticprobabilityoutputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_pessimisticprobabilityoutputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
pessimisticprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
}
inline void BayesianProbitRegressor::set_pessimisticprobabilityoutputfeaturename(const char* value, size_t size) {
pessimisticprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_pessimisticprobabilityoutputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
return pessimisticprobabilityoutputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_pessimisticprobabilityoutputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
return pessimisticprobabilityoutputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_pessimisticprobabilityoutputfeaturename(::std::string* pessimisticprobabilityoutputfeaturename) {
if (pessimisticprobabilityoutputfeaturename != NULL) {
} else {
}
pessimisticprobabilityoutputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), pessimisticprobabilityoutputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.pessimisticProbabilityOutputFeatureName)
}
// string sampledProbabilityOutputFeatureName = 23;
inline void BayesianProbitRegressor::clear_sampledprobabilityoutputfeaturename() {
sampledprobabilityoutputfeaturename_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline const ::std::string& BayesianProbitRegressor::sampledprobabilityoutputfeaturename() const {
// @@protoc_insertion_point(field_get:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
return sampledprobabilityoutputfeaturename_.GetNoArena();
}
inline void BayesianProbitRegressor::set_sampledprobabilityoutputfeaturename(const ::std::string& value) {
sampledprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value);
// @@protoc_insertion_point(field_set:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
}
#if LANG_CXX11
inline void BayesianProbitRegressor::set_sampledprobabilityoutputfeaturename(::std::string&& value) {
sampledprobabilityoutputfeaturename_.SetNoArena(
&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::move(value));
// @@protoc_insertion_point(field_set_rvalue:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
}
#endif
inline void BayesianProbitRegressor::set_sampledprobabilityoutputfeaturename(const char* value) {
GOOGLE_DCHECK(value != NULL);
sampledprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value));
// @@protoc_insertion_point(field_set_char:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
}
inline void BayesianProbitRegressor::set_sampledprobabilityoutputfeaturename(const char* value, size_t size) {
sampledprobabilityoutputfeaturename_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(),
::std::string(reinterpret_cast<const char*>(value), size));
// @@protoc_insertion_point(field_set_pointer:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
}
inline ::std::string* BayesianProbitRegressor::mutable_sampledprobabilityoutputfeaturename() {
// @@protoc_insertion_point(field_mutable:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
return sampledprobabilityoutputfeaturename_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline ::std::string* BayesianProbitRegressor::release_sampledprobabilityoutputfeaturename() {
// @@protoc_insertion_point(field_release:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
return sampledprobabilityoutputfeaturename_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
}
inline void BayesianProbitRegressor::set_allocated_sampledprobabilityoutputfeaturename(::std::string* sampledprobabilityoutputfeaturename) {
if (sampledprobabilityoutputfeaturename != NULL) {
} else {
}
sampledprobabilityoutputfeaturename_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), sampledprobabilityoutputfeaturename);
// @@protoc_insertion_point(field_set_allocated:CoreML.Specification.BayesianProbitRegressor.sampledProbabilityOutputFeatureName)
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// -------------------------------------------------------------------
// @@protoc_insertion_point(namespace_scope)
} // namespace Specification
} // namespace CoreML
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_BayesianProbitRegressor_2eproto__INCLUDED
| {'content_hash': 'fcca003d0e3553ad18274e7c6639e802', 'timestamp': '', 'source': 'github', 'line_count': 1223, 'max_line_length': 204, 'avg_line_length': 49.561733442354864, 'alnum_prop': 0.7785990035305375, 'repo_name': 'apple/coremltools', 'id': 'b63b83ed1126314c565b7049595ea7dd114bc5cb', 'size': '60614', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'mlmodel/build/format/BayesianProbitRegressor.pb.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '79917'}, {'name': 'C++', 'bytes': '1420033'}, {'name': 'CMake', 'bytes': '20418'}, {'name': 'Makefile', 'bytes': '4258'}, {'name': 'Mustache', 'bytes': '2676'}, {'name': 'Objective-C', 'bytes': '4061'}, {'name': 'Objective-C++', 'bytes': '28933'}, {'name': 'Python', 'bytes': '5004520'}, {'name': 'Shell', 'bytes': '19662'}]} |
A voice and tone style guide boilerplate.
| {'content_hash': 'd1853777043cf8000a7e4b8444442818', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 41, 'avg_line_length': 42.0, 'alnum_prop': 0.8095238095238095, 'repo_name': 'kevinglover/voice-and-tone-guide', 'id': 'd78bf941e1e220698009c9f3401003618580cfa7', 'size': '65', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': []} |
<?php
/**
* WordPress Coding Standard.
*
* @package WPCS\WordPressCodingStandards
* @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards
* @license https://opensource.org/licenses/MIT MIT
*/
/**
* Enforces Yoda conditional statements.
*
* @link https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/#yoda-conditions
*
* @package WPCS\WordPressCodingStandards
*
* @since 0.3.0
* @since 0.12.0 This class now extends WordPress_Sniff.
*/
class WordPress_Sniffs_PHP_YodaConditionsSniff extends WordPress_Sniff {
/**
* The tokens that indicate the start of a condition.
*
* @since 0.12.0
*
* @var array
*/
protected $condition_start_tokens;
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register() {
$starters = PHP_CodeSniffer_Tokens::$booleanOperators;
$starters += PHP_CodeSniffer_Tokens::$assignmentTokens;
$starters[ T_CASE ] = T_CASE;
$starters[ T_RETURN ] = T_RETURN;
$starters[ T_SEMICOLON ] = T_SEMICOLON;
$starters[ T_OPEN_PARENTHESIS ] = T_OPEN_PARENTHESIS;
$this->condition_start_tokens = $starters;
return array(
T_IS_EQUAL,
T_IS_NOT_EQUAL,
T_IS_IDENTICAL,
T_IS_NOT_IDENTICAL,
);
}
/**
* Processes this test, when one of its tokens is encountered.
*
* @param int $stackPtr The position of the current token in the stack.
*
* @return void
*/
public function process_token( $stackPtr ) {
$start = $this->phpcsFile->findPrevious( $this->condition_start_tokens, $stackPtr, null, false, null, true );
$needs_yoda = false;
// Note: going backwards!
for ( $i = $stackPtr; $i > $start; $i-- ) {
// Ignore whitespace.
if ( isset( PHP_CodeSniffer_Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) {
continue;
}
// If this is a variable or array, we've seen all we need to see.
if ( T_VARIABLE === $this->tokens[ $i ]['code']
|| T_CLOSE_SQUARE_BRACKET === $this->tokens[ $i ]['code']
) {
$needs_yoda = true;
break;
}
// If this is a function call or something, we are OK.
if ( T_CLOSE_PARENTHESIS === $this->tokens[ $i ]['code'] ) {
return;
}
}
if ( ! $needs_yoda ) {
return;
}
// Check if this is a var to var comparison, e.g.: if ( $var1 == $var2 ).
$next_non_empty = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true );
if ( isset( PHP_CodeSniffer_Tokens::$castTokens[ $this->tokens[ $next_non_empty ]['code'] ] ) ) {
$next_non_empty = $this->phpcsFile->findNext( PHP_CodeSniffer_Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true );
}
if ( in_array( $this->tokens[ $next_non_empty ]['code'], array( T_SELF, T_PARENT, T_STATIC ), true ) ) {
$next_non_empty = $this->phpcsFile->findNext(
array_merge( PHP_CodeSniffer_Tokens::$emptyTokens, array( T_DOUBLE_COLON ) )
, ( $next_non_empty + 1 )
, null
, true
);
}
if ( T_VARIABLE === $this->tokens[ $next_non_empty ]['code'] ) {
return;
}
$this->phpcsFile->addError( 'Use Yoda Condition checks, you must.', $stackPtr, 'NotYoda' );
} // End process().
} // End class.
| {'content_hash': '04731ac5eb9e1b45e2c342740385b472', 'timestamp': '', 'source': 'github', 'line_count': 119, 'max_line_length': 125, 'avg_line_length': 27.537815126050422, 'alnum_prop': 0.6185535550808666, 'repo_name': 'mikaeljorhult/brackets-php-code-quality-tools', 'id': '8cf7e996326c59ee7355ecddb8fd2dfd6feb8e66', 'size': '3277', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/vendor/phpcs/rulesets/WordPress/Sniffs/PHP/YodaConditionsSniff.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '739'}, {'name': 'HTML', 'bytes': '4829'}, {'name': 'JavaScript', 'bytes': '34748'}]} |
import { Injectable, Injector } from '@angular/core';
import { Util } from '../util/util';
import { NumberService } from './number.service';
@Injectable({
providedIn: 'root'
})
export class CurrencyService {
public static DEFAULT_CURRENCY_SYMBOL = '$';
public static DEFAULT_CURRENCY_SYMBOL_POSITION = 'left';
protected _numberService: NumberService;
protected _symbol: string;
protected _symbolPosition: string;
constructor(protected injector: Injector) {
this._numberService = this.injector.get(NumberService);
// TODO: initialize from config
this._symbol = CurrencyService.DEFAULT_CURRENCY_SYMBOL;
this._symbolPosition = CurrencyService.DEFAULT_CURRENCY_SYMBOL_POSITION;
}
get symbol(): string {
return this._symbol;
}
set symbol(value: string) {
this._symbol = value;
}
get symbolPosition(): string {
return this._symbolPosition;
}
set symbolPosition(value: string) {
this._symbolPosition = value;
}
getCurrencyValue(value: any, args: any) {
let symbol = args ? args.currencySimbol : undefined;
let symbolPosition = args ? args.currencySymbolPosition : undefined;
if (!Util.isDefined(symbol)) {
symbol = this._symbol;
}
if (!Util.isDefined(symbolPosition)) {
symbolPosition = this._symbolPosition;
}
let currencyValue = this._numberService.getRealValue(value, args);
switch (symbolPosition) {
case 'left':
currencyValue = symbol + ' ' + currencyValue;
break;
case 'right':
currencyValue = currencyValue + ' ' + symbol;
break;
}
return currencyValue;
}
}
| {'content_hash': '99cc3f0fe7f948c8214fe87c9ef48d03', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 76, 'avg_line_length': 25.546875, 'alnum_prop': 0.6703363914373088, 'repo_name': 'OntimizeWeb/ontimize-web-ngx', 'id': '35b655023da92a195c8a6ed366233ea3e05598d7', 'size': '1635', 'binary': False, 'copies': '2', 'ref': 'refs/heads/8.x.x', 'path': 'projects/ontimize-web-ngx/src/lib/services/currency.service.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '190381'}, {'name': 'JavaScript', 'bytes': '7594'}, {'name': 'SCSS', 'bytes': '125972'}, {'name': 'TypeScript', 'bytes': '1533764'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sounds</title>
<script src="./lib/web-animations.min.js"></script>
<script src="./lib/shim.min.js"></script>
<script src="./lib/Reflect.js"></script>
<script src="./lib/zone.min.js"></script>
<script src="./lib/system.js"></script>
<script src="./system.config.js"></script>
<script src="./lib/Rx.js"></script>
<link rel="stylesheet" href="./index.css">
</head>
<body>
<sounds-app></sounds-app>
<script>
System.import('./main');
</script>
</body>
</html>
| {'content_hash': '403dd8d374d1adba72ab8d1fab4c33c4', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 55, 'avg_line_length': 24.82608695652174, 'alnum_prop': 0.5971978984238179, 'repo_name': 'pe8ter/sounds', 'id': '539aa1312ef6083ea013e96e45c5e16c632713d0', 'size': '572', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '945'}, {'name': 'JavaScript', 'bytes': '6795'}, {'name': 'TypeScript', 'bytes': '2928'}]} |
describe TwoWayMapper::Node::Base do
describe '#keys' do
subject { described_class.new('key1.key11.key111') }
its(:keys) { should eql %i[key1 key11 key111] }
end
describe 'writable?' do
it 'should be truthy if write_if options not set' do
node = described_class.new('key1.key11.key111')
expect(node).to be_writable 'current', 'new'
end
it 'should be truthy if write_if option set' do
node = described_class.new(
'key1.key11.key111',
write_if: ->(c, n) { c == 'current' || n == 'new' }
)
expect(node).to be_writable 'current', 'new1'
expect(node).to be_writable 'current1', 'new'
expect(node).not_to be_writable 'current1', 'new1'
end
end
end
| {'content_hash': 'bea6f1c8840eb5fa6c9619379ebbfe53', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 59, 'avg_line_length': 28.346153846153847, 'alnum_prop': 0.6132971506105834, 'repo_name': 'timsly/two-way-mapper', 'id': '949eb59bb6936d84d3669db212175911496f3f71', 'size': '768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/node/base_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '31853'}]} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_60-ea) on Mon Oct 03 10:36:48 EDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer (Public javadocs 2016.10.0 API)</title>
<meta name="date" content="2016-10-03">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer (Public javadocs 2016.10.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/class-use/InMemoryHandlerConsumer.html" target="_top">Frames</a></li>
<li><a href="InMemoryHandlerConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer" class="title">Uses of Interface<br>org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management">org.wildfly.swarm.config.management</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management.access">org.wildfly.swarm.config.management.access</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/package-summary.html">org.wildfly.swarm.config.management</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/AuditAccess.html" title="type parameter in AuditAccess">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">AuditAccess.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/AuditAccess.html#inMemoryHandler-java.lang.String-org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer-">inMemoryHandler</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> childKey,
<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a> consumer)</code>
<div class="block">Create and configure a InMemoryHandler object to the list of subresources</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.management.access">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="type parameter in InMemoryHandlerConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">InMemoryHandlerConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html#andThen-org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="type parameter in InMemoryHandlerConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/access/package-summary.html">org.wildfly.swarm.config.management.access</a> with parameters of type <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>default <a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="type parameter in InMemoryHandlerConsumer">T</a>></code></td>
<td class="colLast"><span class="typeNameLabel">InMemoryHandlerConsumer.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html#andThen-org.wildfly.swarm.config.management.access.InMemoryHandlerConsumer-">andThen</a></span>(<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">InMemoryHandlerConsumer</a><<a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="type parameter in InMemoryHandlerConsumer">T</a>> after)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/access/InMemoryHandlerConsumer.html" title="interface in org.wildfly.swarm.config.management.access">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2016.10.0</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/access/class-use/InMemoryHandlerConsumer.html" target="_top">Frames</a></li>
<li><a href="InMemoryHandlerConsumer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': '4b0527ab8da15dd094f5da9a8c3b40dc', 'timestamp': '', 'source': 'github', 'line_count': 206, 'max_line_length': 702, 'avg_line_length': 60.55339805825243, 'alnum_prop': 0.677970177970178, 'repo_name': 'wildfly-swarm/wildfly-swarm-javadocs', 'id': 'b00b2ab8144812d8cb159d612b54a3aa42966406', 'size': '12474', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2016.10.0/apidocs/org/wildfly/swarm/config/management/access/class-use/InMemoryHandlerConsumer.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package org.hibernate.validator.referenceguide.chapter05;
import jakarta.validation.GroupSequence;
import jakarta.validation.groups.Default;
@GroupSequence({ Default.class, CarChecks.class, DriverChecks.class })
public interface OrderedChecks {
}
| {'content_hash': '1f1c2b9f3c94569032c20dad1ee33c13', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 70, 'avg_line_length': 31.125, 'alnum_prop': 0.8313253012048193, 'repo_name': 'hibernate/hibernate-validator', 'id': '825dd5746bc9ff567b9de46c7cf227990fa80aee', 'size': '249', 'binary': False, 'copies': '3', 'ref': 'refs/heads/main', 'path': 'documentation/src/test/java/org/hibernate/validator/referenceguide/chapter05/OrderedChecks.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '7782'}, {'name': 'HTML', 'bytes': '1387'}, {'name': 'Java', 'bytes': '4884336'}, {'name': 'Shell', 'bytes': '476'}]} |
@implementation lwMall_AddressModel
@end
| {'content_hash': 'e79a882602663537f1929b582df6b038', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 35, 'avg_line_length': 14.0, 'alnum_prop': 0.8333333333333334, 'repo_name': 'liuxiaobaibaibai/LMall', 'id': '18be2b0f7af290e7b51f3b9f3cba191461a03619', 'size': '200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LMall/shopCart/Model/地址信息/lwMall_AddressModel.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '1301782'}, {'name': 'C++', 'bytes': '163270'}, {'name': 'CSS', 'bytes': '2972'}, {'name': 'HTML', 'bytes': '6079'}, {'name': 'JavaScript', 'bytes': '2498'}, {'name': 'Objective-C', 'bytes': '422833'}, {'name': 'Swift', 'bytes': '2274'}]} |
package com.github.jamesnetherton.lolcat4j.internal.console.utils;
import java.io.OutputStream;
import java.io.PrintStream;
public class LoggingPrintStream extends PrintStream {
private final StringBuilder loggedOutput = new StringBuilder();
public LoggingPrintStream(OutputStream out) {
super(out);
}
@Override
public void println() {
loggedOutput.append("\n");
}
@Override
public void print(String s) {
loggedOutput.append(s);
}
public String getLoggedOutput() {
return loggedOutput.toString();
}
}
| {'content_hash': 'ebaa140d17adf68bf54273e97fb915b6', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 67, 'avg_line_length': 21.62962962962963, 'alnum_prop': 0.6815068493150684, 'repo_name': 'jamesnetherton/lolcat4j', 'id': 'd4e18ba15df15babc77d40d2b319dae7fe6cd5c1', 'size': '1740', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/github/jamesnetherton/lolcat4j/internal/console/utils/LoggingPrintStream.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '70564'}]} |
package org.apache.rocketmq.client.producer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.rocketmq.client.ClientConfig;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.hook.SendMessageContext;
import org.apache.rocketmq.client.hook.SendMessageHook;
import org.apache.rocketmq.client.impl.CommunicationMode;
import org.apache.rocketmq.client.impl.MQClientAPIImpl;
import org.apache.rocketmq.client.impl.MQClientManager;
import org.apache.rocketmq.client.impl.factory.MQClientInstance;
import org.apache.rocketmq.client.impl.producer.DefaultMQProducerImpl;
import org.apache.rocketmq.client.impl.producer.TopicPublishInfo;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.protocol.header.SendMessageRequestHeader;
import org.apache.rocketmq.common.protocol.route.BrokerData;
import org.apache.rocketmq.common.protocol.route.QueueData;
import org.apache.rocketmq.common.protocol.route.TopicRouteData;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.remoting.netty.NettyRemotingClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.failBecauseExceptionWasNotThrown;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class DefaultMQProducerTest {
@Spy
private MQClientInstance mQClientFactory = MQClientManager.getInstance().getAndCreateMQClientInstance(new ClientConfig());
@Mock
private MQClientAPIImpl mQClientAPIImpl;
private DefaultMQProducer producer;
private Message message;
private Message zeroMsg;
private String topic = "FooBar";
private String producerGroupPrefix = "FooBar_PID";
@Before
public void init() throws Exception {
String producerGroupTemp = producerGroupPrefix + System.currentTimeMillis();
producer = new DefaultMQProducer(producerGroupTemp);
producer.setNamesrvAddr("127.0.0.1:9876");
message = new Message(topic, new byte[] {'a'});
zeroMsg = new Message(topic, new byte[] {});
producer.start();
Field field = DefaultMQProducerImpl.class.getDeclaredField("mQClientFactory");
field.setAccessible(true);
field.set(producer.getDefaultMQProducerImpl(), mQClientFactory);
field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
field.setAccessible(true);
field.set(mQClientFactory, mQClientAPIImpl);
producer.getDefaultMQProducerImpl().getmQClientFactory().registerProducer(producerGroupTemp, producer.getDefaultMQProducerImpl());
when(mQClientAPIImpl.sendMessage(anyString(), anyString(), any(Message.class), any(SendMessageRequestHeader.class), anyLong(), any(CommunicationMode.class),
nullable(SendMessageContext.class), any(DefaultMQProducerImpl.class))).thenCallRealMethod();
when(mQClientAPIImpl.sendMessage(anyString(), anyString(), any(Message.class), any(SendMessageRequestHeader.class), anyLong(), any(CommunicationMode.class),
nullable(SendCallback.class), nullable(TopicPublishInfo.class), nullable(MQClientInstance.class), anyInt(), nullable(SendMessageContext.class), any(DefaultMQProducerImpl.class)))
.thenReturn(createSendResult(SendStatus.SEND_OK));
}
@After
public void terminate() {
producer.shutdown();
}
@Test
public void testSendMessage_ZeroMessage() throws InterruptedException, RemotingException, MQBrokerException {
try {
producer.send(zeroMsg);
failBecauseExceptionWasNotThrown(MQClientException.class);
} catch (MQClientException e) {
assertThat(e).hasMessageContaining("message body length is zero");
}
}
@Test
public void testSendMessage_NoNameSrv() throws RemotingException, InterruptedException, MQBrokerException {
when(mQClientAPIImpl.getNameServerAddressList()).thenReturn(new ArrayList<String>());
try {
producer.send(message);
failBecauseExceptionWasNotThrown(MQClientException.class);
} catch (MQClientException e) {
assertThat(e).hasMessageContaining("No name server address");
}
}
@Test
public void testSendMessage_NoRoute() throws RemotingException, InterruptedException, MQBrokerException {
when(mQClientAPIImpl.getNameServerAddressList()).thenReturn(Collections.singletonList("127.0.0.1:9876"));
try {
producer.send(message);
failBecauseExceptionWasNotThrown(MQClientException.class);
} catch (MQClientException e) {
assertThat(e).hasMessageContaining("No route info of this topic");
}
}
@Test
public void testSendMessageSync_Success() throws RemotingException, InterruptedException, MQBrokerException, MQClientException {
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
SendResult sendResult = producer.send(message);
assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
assertThat(sendResult.getQueueOffset()).isEqualTo(456L);
}
@Test
public void testSendMessageSync_SuccessWithHook() throws Throwable {
when(mQClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
final Throwable[] assertionErrors = new Throwable[1];
final CountDownLatch countDownLatch = new CountDownLatch(2);
producer.getDefaultMQProducerImpl().registerSendMessageHook(new SendMessageHook() {
@Override
public String hookName() {
return "TestHook";
}
@Override
public void sendMessageBefore(final SendMessageContext context) {
assertionErrors[0] = assertInOtherThread(new Runnable() {
@Override
public void run() {
assertThat(context.getMessage()).isEqualTo(message);
assertThat(context.getProducer()).isEqualTo(producer);
assertThat(context.getCommunicationMode()).isEqualTo(CommunicationMode.SYNC);
assertThat(context.getSendResult()).isNull();
}
});
countDownLatch.countDown();
}
@Override
public void sendMessageAfter(final SendMessageContext context) {
assertionErrors[0] = assertInOtherThread(new Runnable() {
@Override
public void run() {
assertThat(context.getMessage()).isEqualTo(message);
assertThat(context.getProducer()).isEqualTo(producer.getDefaultMQProducerImpl());
assertThat(context.getCommunicationMode()).isEqualTo(CommunicationMode.SYNC);
assertThat(context.getSendResult()).isNotNull();
}
});
countDownLatch.countDown();
}
});
SendResult sendResult = producer.send(message);
assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
assertThat(sendResult.getQueueOffset()).isEqualTo(456L);
countDownLatch.await();
if (assertionErrors[0] != null) {
throw assertionErrors[0];
}
}
@Test
public void testSetCallbackExecutor() throws MQClientException {
String producerGroupTemp = producerGroupPrefix + System.currentTimeMillis();
producer = new DefaultMQProducer(producerGroupTemp);
producer.setNamesrvAddr("127.0.0.1:9876");
producer.start();
ExecutorService customized = Executors.newCachedThreadPool();
producer.setCallbackExecutor(customized);
NettyRemotingClient remotingClient = (NettyRemotingClient) producer.getDefaultMQProducerImpl()
.getmQClientFactory().getMQClientAPIImpl().getRemotingClient();
assertThat(remotingClient.getCallbackExecutor()).isEqualTo(customized);
}
public static TopicRouteData createTopicRoute() {
TopicRouteData topicRouteData = new TopicRouteData();
topicRouteData.setFilterServerTable(new HashMap<String, List<String>>());
List<BrokerData> brokerDataList = new ArrayList<BrokerData>();
BrokerData brokerData = new BrokerData();
brokerData.setBrokerName("BrokerA");
brokerData.setCluster("DefaultCluster");
HashMap<Long, String> brokerAddrs = new HashMap<Long, String>();
brokerAddrs.put(0L, "127.0.0.1:10911");
brokerData.setBrokerAddrs(brokerAddrs);
brokerDataList.add(brokerData);
topicRouteData.setBrokerDatas(brokerDataList);
List<QueueData> queueDataList = new ArrayList<QueueData>();
QueueData queueData = new QueueData();
queueData.setBrokerName("BrokerA");
queueData.setPerm(6);
queueData.setReadQueueNums(3);
queueData.setWriteQueueNums(4);
queueData.setTopicSynFlag(0);
queueDataList.add(queueData);
topicRouteData.setQueueDatas(queueDataList);
return topicRouteData;
}
private SendResult createSendResult(SendStatus sendStatus) {
SendResult sendResult = new SendResult();
sendResult.setMsgId("123");
sendResult.setOffsetMsgId("123");
sendResult.setQueueOffset(456);
sendResult.setSendStatus(sendStatus);
sendResult.setRegionId("HZ");
return sendResult;
}
private Throwable assertInOtherThread(final Runnable runnable) {
final Throwable[] assertionErrors = new Throwable[1];
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
runnable.run();
} catch (AssertionError e) {
assertionErrors[0] = e;
}
}
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
assertionErrors[0] = e;
}
return assertionErrors[0];
}
} | {'content_hash': 'a6a05ddcf49cbe23a50ed2424476b0be', 'timestamp': '', 'source': 'github', 'line_count': 258, 'max_line_length': 190, 'avg_line_length': 43.16279069767442, 'alnum_prop': 0.6923491379310345, 'repo_name': 'lindzh/incubator-rocketmq', 'id': 'ded22ada914b163589b909a24d0f1b3a6b02e46c', 'size': '11937', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'client/src/test/java/org/apache/rocketmq/client/producer/DefaultMQProducerTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '12464'}, {'name': 'Java', 'bytes': '4082946'}, {'name': 'Python', 'bytes': '17535'}, {'name': 'Shell', 'bytes': '33708'}]} |
/**
* @module zrender/graphic/Style
*/
var STYLE_COMMON_PROPS = [
['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
];
// var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
// var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
var Style = function (opts) {
this.extendFrom(opts);
};
function createLinearGradient(ctx, obj, rect) {
// var size =
var x = obj.x;
var x2 = obj.x2;
var y = obj.y;
var y2 = obj.y2;
if (!obj.global) {
x = x * rect.width + rect.x;
x2 = x2 * rect.width + rect.x;
y = y * rect.height + rect.y;
y2 = y2 * rect.height + rect.y;
}
var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
return canvasGradient;
}
function createRadialGradient(ctx, obj, rect) {
var width = rect.width;
var height = rect.height;
var min = Math.min(width, height);
var x = obj.x;
var y = obj.y;
var r = obj.r;
if (!obj.global) {
x = x * width + rect.x;
y = y * height + rect.y;
r = r * min;
}
var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
return canvasGradient;
}
Style.prototype = {
constructor: Style,
/**
* @type {string}
*/
fill: '#000000',
/**
* @type {string}
*/
stroke: null,
/**
* @type {number}
*/
opacity: 1,
/**
* @type {Array.<number>}
*/
lineDash: null,
/**
* @type {number}
*/
lineDashOffset: 0,
/**
* @type {number}
*/
shadowBlur: 0,
/**
* @type {number}
*/
shadowOffsetX: 0,
/**
* @type {number}
*/
shadowOffsetY: 0,
/**
* @type {number}
*/
lineWidth: 1,
/**
* If stroke ignore scale
* @type {Boolean}
*/
strokeNoScale: false,
// Bounding rect text configuration
// Not affected by element transform
/**
* @type {string}
*/
text: null,
/**
* @type {string}
*/
textFill: '#000',
/**
* @type {string}
*/
textStroke: null,
/**
* 'inside', 'left', 'right', 'top', 'bottom'
* [x, y]
* @type {string|Array.<number>}
* @default 'inside'
*/
textPosition: 'inside',
/**
* @type {string}
*/
textBaseline: null,
/**
* @type {string}
*/
textAlign: null,
/**
* @type {string}
*/
textVerticalAlign: null,
/**
* Only useful in Path and Image element
* @type {number}
*/
textDistance: 5,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowBlur: 0,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowOffsetX: 0,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowOffsetY: 0,
/**
* If transform text
* Only useful in Path and Image element
* @type {boolean}
*/
textTransform: false,
/**
* Text rotate around position of Path or Image
* Only useful in Path and Image element and textTransform is false.
*/
textRotation: 0,
/**
* @type {string}
* https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
*/
blend: null,
/**
* @param {CanvasRenderingContext2D} ctx
*/
bind: function (ctx, el, prevEl) {
var style = this;
var prevStyle = prevEl && prevEl.style;
var firstDraw = !prevStyle;
for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
var prop = STYLE_COMMON_PROPS[i];
var styleName = prop[0];
if (firstDraw || style[styleName] !== prevStyle[styleName]) {
// FIXME Invalid property value will cause style leak from previous element.
ctx[styleName] = style[styleName] || prop[1];
}
}
if ((firstDraw || style.fill !== prevStyle.fill)) {
ctx.fillStyle = style.fill;
}
if ((firstDraw || style.stroke !== prevStyle.stroke)) {
ctx.strokeStyle = style.stroke;
}
if ((firstDraw || style.opacity !== prevStyle.opacity)) {
ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
}
if ((firstDraw || style.blend !== prevStyle.blend)) {
ctx.globalCompositeOperation = style.blend || 'source-over';
}
if (this.hasStroke()) {
var lineWidth = style.lineWidth;
ctx.lineWidth = lineWidth / (
(this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
);
}
},
hasFill: function () {
var fill = this.fill;
return fill != null && fill !== 'none';
},
hasStroke: function () {
var stroke = this.stroke;
return stroke != null && stroke !== 'none' && this.lineWidth > 0;
},
/**
* Extend from other style
* @param {zrender/graphic/Style} otherStyle
* @param {boolean} overwrite
*/
extendFrom: function (otherStyle, overwrite) {
if (otherStyle) {
var target = this;
for (var name in otherStyle) {
if (otherStyle.hasOwnProperty(name)
&& (overwrite || ! target.hasOwnProperty(name))
) {
target[name] = otherStyle[name];
}
}
}
},
/**
* Batch setting style with a given object
* @param {Object|string} obj
* @param {*} [obj]
*/
set: function (obj, value) {
if (typeof obj === 'string') {
this[obj] = value;
}
else {
this.extendFrom(obj, true);
}
},
/**
* Clone
* @return {zrender/graphic/Style} [description]
*/
clone: function () {
var newStyle = new this.constructor();
newStyle.extendFrom(this, true);
return newStyle;
},
getGradient: function (ctx, obj, rect) {
var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
var canvasGradient = method(ctx, obj, rect);
var colorStops = obj.colorStops;
for (var i = 0; i < colorStops.length; i++) {
canvasGradient.addColorStop(
colorStops[i].offset, colorStops[i].color
);
}
return canvasGradient;
}
};
var styleProto = Style.prototype;
for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
var prop = STYLE_COMMON_PROPS[i];
if (!(prop[0] in styleProto)) {
styleProto[prop[0]] = prop[1];
}
}
// Provide for others
Style.getGradient = styleProto.getGradient;
module.exports = Style;
| {'content_hash': '8a65433f7a0898530c25d8da3cc6660b', 'timestamp': '', 'source': 'github', 'line_count': 310, 'max_line_length': 109, 'avg_line_length': 25.45806451612903, 'alnum_prop': 0.4513431322858591, 'repo_name': 'ytbryan/chart', 'id': '57a4f499a6b45211b7043182141384c1a1356df6', 'size': '7892', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'node_modules/zrender/lib/graphic/Style.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '48205'}, {'name': 'Shell', 'bytes': '115'}]} |
<?php
/*
Safe sample
input : use exec to execute the script /tmp/tainted.php and store the output in $tainted
SANITIZE : use of preg_replace
construction : concatenation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$script = "/tmp/tainted.php";
exec($script, $result, $return);
$tainted = $result[0];
$tainted = preg_replace('/\'/', '', $tainted);
$query = "SELECT lastname, firstname FROM drivers, vehicles WHERE drivers.id = vehicles.ownerid AND vehicles.tag='". $tainted . "'";
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | {'content_hash': '002bb33ed54c586ecaec79b4b578c20b', 'timestamp': '', 'source': 'github', 'line_count': 66, 'max_line_length': 132, 'avg_line_length': 25.863636363636363, 'alnum_prop': 0.7381370826010545, 'repo_name': 'stivalet/PHP-Vulnerability-test-suite', 'id': '9d8fe2171b04dab1c5716afca8630cecc5033394', 'size': '1707', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Injection/CWE_89/safe/CWE_89__exec__func_preg_replace__join-concatenation_simple_quote.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '64184004'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.