text
stringlengths 2
1.04M
| meta
dict |
---|---|
/**************************************************************************************/
/* */
/* Visualization Library */
/* http://www.visualizationlibrary.org */
/* */
/* Copyright (c) 2005-2010, Michele Bosi */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without modification, */
/* are permitted provided that the following conditions are met: */
/* */
/* - Redistributions of source code must retain the above copyright notice, this */
/* list of conditions and the following disclaimer. */
/* */
/* - Redistributions in binary form must reproduce the above copyright notice, this */
/* list of conditions and the following disclaimer in the documentation and/or */
/* other materials provided with the distribution. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND */
/* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED */
/* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */
/* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR */
/* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */
/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */
/* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON */
/* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS */
/* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* */
/**************************************************************************************/
#ifndef stdtypes_INCLUDE_ONCE
#define stdtypes_INCLUDE_ONCE
#include <vlCore/config.hpp>
#include <vlCore/checks.hpp>
namespace vl
{
/** 8 bits signed integer */
typedef char i8;
/** 8 bits unsigned integer */
typedef unsigned char u8;
/** 16 bits signed integer */
typedef short i16;
/** 16 bits unsigned integer */
typedef unsigned short u16;
/** 32 bits signed integer */
typedef int i32;
/** 32 bits unsigned integer */
typedef unsigned int u32;
/** 64 bits signed integer */
typedef long long i64;
/** 64 bits unsigned integer */
typedef unsigned long long u64;
/** 32 bits floating point value */
typedef float f32;
/** 64 bits floating point value */
typedef double f64;
// trigonometric constants
//! Greek Pi constant using \p double precision.
const double dPi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093845;
//! Constant to convert degree into radian using \p double precision.
const double dDEG_TO_RAD = dPi / 180.0;
//! Constant to convert radian into degree using \p double precision.
const double dRAD_TO_DEG = 180.0 / dPi;
//! Greek Pi constant using \p float precision.
const float fPi = (float)3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093845;
//! Constant to convert degree into radian using \p float precision.
const float fDEG_TO_RAD = float(dPi / 180.0);
//! Constant to convert radian into degree using \p float precision.
const float fRAD_TO_DEG = float(180.0 / dPi);
class degree;
/** Simple class representing quantities in radians, converts automatically to vl::degree and real. */
class radian
{
public:
radian(real val): mValue(val) {}
operator real() { return mValue; }
operator degree();
private:
real mValue;
};
/** Simple class representing quantities in degrees, converts automatically to vl::radian and real. */
class degree
{
public:
degree(real val): mValue(val) {}
operator real() { return mValue; }
operator radian();
private:
real mValue;
};
inline radian::operator degree() { return mValue*(real)dRAD_TO_DEG; }
inline degree::operator radian() { return mValue*(real)dDEG_TO_RAD; }
//! Swaps the byte order of the given object.
template<typename T>
void swapBytes(T& value)
{
union
{
T* value;
char* ptr;
} u;
u.value = &value;
char* a = u.ptr;
char* b = u.ptr + sizeof(T) - 1;
while(a<b)
{
char tmp = *a;
*a = *b;
*b = tmp;
++a;
--b;
}
}
VL_COMPILE_TIME_CHECK( sizeof(i8)*8 == 8 );
VL_COMPILE_TIME_CHECK( sizeof(u8)*8 == 8 );
VL_COMPILE_TIME_CHECK( sizeof(i16)*8 == 16 );
VL_COMPILE_TIME_CHECK( sizeof(u16)*8 == 16 );
VL_COMPILE_TIME_CHECK( sizeof(i32)*8 == 32 );
VL_COMPILE_TIME_CHECK( sizeof(u32)*8 == 32 );
VL_COMPILE_TIME_CHECK( sizeof(i64)*8 == 64 );
VL_COMPILE_TIME_CHECK( sizeof(u64)*8 == 64 );
VL_COMPILE_TIME_CHECK( sizeof(f32)*8 == 32 );
VL_COMPILE_TIME_CHECK( sizeof(f64)*8 == 64 );
}
#endif
| {
"content_hash": "e10acf528f4c9269f8016cb806b3788c",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 156,
"avg_line_length": 41.65714285714286,
"alnum_prop": 0.5516117969821673,
"repo_name": "VizLibrary/Visualization-Library",
"id": "b639ee9c016ee6fa5dc6997bfc244d7f181fe63a",
"size": "5832",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/vlCore/std_types.hpp",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "148297"
},
{
"name": "Awk",
"bytes": "3965"
},
{
"name": "C",
"bytes": "11037686"
},
{
"name": "C#",
"bytes": "54113"
},
{
"name": "C++",
"bytes": "5990445"
},
{
"name": "CLIPS",
"bytes": "6933"
},
{
"name": "CSS",
"bytes": "33956"
},
{
"name": "F#",
"bytes": "95185"
},
{
"name": "Gosu",
"bytes": "7302"
},
{
"name": "JavaScript",
"bytes": "299070"
},
{
"name": "Objective-C",
"bytes": "52379"
},
{
"name": "Pascal",
"bytes": "40318"
},
{
"name": "Python",
"bytes": "170452"
},
{
"name": "Shell",
"bytes": "553424"
},
{
"name": "Smalltalk",
"bytes": "10530"
}
],
"symlink_target": ""
} |
using System;
using System.Runtime.WootzJs;
using WootzJs.Testing;
namespace WootzJs.Compiler.Tests
{
public class EventTests : TestFixture
{
[Test]
public void BasicEvent()
{
var o = new EventClass();
var success = false;
o.Foo += () => success = true;
o.OnFoo();
AssertTrue(success);
}
[Test]
public void BasicEventExplicitThis()
{
var o = new EventClass();
var success = false;
o.FooThis += () => success = true;
o.OnFooThis();
AssertTrue(success);
}
[Test]
public void MulticastEvent()
{
var o = new EventClass();
var success1 = false;
var success2 = false;
o.Foo += () => success1 = true;
o.Foo += () => success2 = true;
o.OnFoo();
AssertTrue(success1);
AssertTrue(success2);
}
[Test]
public void MulticastEventRemove()
{
var o = new EventClass();
var success1 = false;
var success2 = false;
Action foo1 = () => success1 = true;
o.Foo += foo1;
o.Foo += () => success2 = true;
o.Foo -= foo1;
o.OnFoo();
AssertTrue((!success1));
AssertTrue(success2);
}
[Test]
public void EventAccessor()
{
var eventClass = new EventClass();
var ran = false;
Action evt = () => ran = true;
eventClass.Bar += evt;
eventClass.OnBar();
AssertTrue(ran);
ran = false;
eventClass.Bar -= evt;
eventClass.OnBar();
AssertTrue((!ran));
}
[Test]
public void MulticastEventKeepsDelegateType()
{
var i = 0;
var eventClass = new EventClass();
eventClass.Foo += () => i++;
eventClass.Foo += () => i++;
var action = eventClass.GetFoo();
AssertTrue((action is Action));
}
[Test]
public void RemoveMethodHandler()
{
var eventClass = new EventClass();
var eventHandlers = new EventHandlers();
eventClass.Foo += eventHandlers.M1;
eventClass.Foo += eventHandlers.M2;
eventClass.OnFoo();
AssertEquals(eventHandlers.m1, "M1");
AssertEquals(eventHandlers.m2, "M2");
eventHandlers.m1 = null;
eventHandlers.m2 = null;
eventClass.Foo -= eventHandlers.M1;
eventClass.OnFoo();
AssertEquals(eventHandlers.m2, "M2");
AssertTrue((eventHandlers.m1 == null));
}
public class EventClass
{
public event Action Foo;
private Action bar;
public void OnFoo()
{
if (Foo != null)
Foo();
}
public Action GetFoo()
{
return Foo;
}
public event Action FooThis;
public void OnFooThis()
{
if (this.FooThis != null)
this.FooThis();
}
public event Action Bar
{
add { bar = (Action)Delegate.Combine(bar, value); }
remove { bar = null; }
}
public void OnBar()
{
if (bar != null)
bar();
}
}
public class EventHandlers
{
public string m1;
public string m2;
public void M1()
{
m1 = "M1";
}
public void M2()
{
m2 = "M2";
}
}
[Test]
public void AutoEventFieldInvoke()
{
var o = new AutoEventFieldClass();
var flag = false;
o.MyEvent += () => flag = true;
var eventInfo = o.GetType().GetEvent("MyEvent");
var @delegate = (Action)eventInfo.DelegateField.GetValue(o);
@delegate();
AssertTrue(flag);
}
[Test]
public void AutoEventFieldDelegateInvoke()
{
var o = new AutoEventFieldClass();
var flag = false;
o.MyEvent += () => flag = true;
var eventInfo = o.GetType().GetEvent("MyEvent");
var @delegate = (Delegate)eventInfo.DelegateField.GetValue(o);
@delegate.DynamicInvoke();
AssertTrue(flag);
}
[Test]
public void AutoEventFieldDelegateInvokeWithStringArg()
{
var o = new AutoEventFieldClass();
var s = "";
o.MyStringEvent += x => s = x;
var eventInfo = o.GetType().GetEvent("MyStringEvent");
var @delegate = (Delegate)eventInfo.DelegateField.GetValue(o);
@delegate.DynamicInvoke("foo");
AssertEquals(s, "foo");
}
public class AutoEventFieldClass
{
public event Action MyEvent;
public event Action<string> MyStringEvent;
}
}
}
| {
"content_hash": "0bd8fceb5a8e119fceabb5bbfffb8fc9",
"timestamp": "",
"source": "github",
"line_count": 201,
"max_line_length": 74,
"avg_line_length": 26.945273631840795,
"alnum_prop": 0.4495937961595273,
"repo_name": "kswoll/WootzJs",
"id": "f676acde9e77f7f2216f8ed10e30f27ce52fb89e",
"size": "6761",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "WootzJs.Compiler.Tests/EventTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "217"
},
{
"name": "Batchfile",
"bytes": "1700"
},
{
"name": "C#",
"bytes": "3320561"
},
{
"name": "CSS",
"bytes": "35057"
},
{
"name": "HTML",
"bytes": "1678"
},
{
"name": "JavaScript",
"bytes": "53767"
},
{
"name": "Pascal",
"bytes": "79949"
},
{
"name": "PowerShell",
"bytes": "125251"
},
{
"name": "Puppet",
"bytes": "1879"
}
],
"symlink_target": ""
} |
package org.assertj.core.api.classes;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.ClassAssert;
import org.assertj.core.api.ClassAssertBaseTest;
/**
* Tests for <code>{@link org.assertj.core.api.ClassAssert#isAnnotation()}</code>.
*
* @author William Delanoue
*/
public class ClassAssert_isAnnotation_Test extends ClassAssertBaseTest {
@Override
protected ClassAssert invoke_api_method() {
return assertions.isAnnotation();
}
@Override
protected void verify_internal_effects() {
verify(classes).assertIsAnnotation(getInfo(assertions), getActual(assertions));
}
}
| {
"content_hash": "7ebf40ebb1bbd81626f4f43306b10c33",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 83,
"avg_line_length": 23.846153846153847,
"alnum_prop": 0.7532258064516129,
"repo_name": "xasx/assertj-core",
"id": "e60fc42106e3e3f7909e0eb857a08917805bf9a1",
"size": "1226",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/org/assertj/core/api/classes/ClassAssert_isAnnotation_Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "13307657"
},
{
"name": "Shell",
"bytes": "37294"
}
],
"symlink_target": ""
} |
// Copyright (C) 2008 The Android Open Source Project
//
// 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 com.google.gerrit.reviewdb.client;
import com.google.gwtorm.client.Column;
import com.google.gwtorm.client.IntKey;
import java.sql.Timestamp;
/**
* Information about a single user.
* <p>
* A user may have multiple identities they can use to login to Gerrit (see
* {@link AccountExternalId}), but in such cases they always map back to a
* single Account entity.
*<p>
* Entities "owned" by an Account (that is, their primary key contains the
* {@link Account.Id} key as part of their key structure):
* <ul>
* <li>{@link AccountAgreement}: any record of the user's acceptance of a
* predefined {@link ContributorAgreement}. Multiple records indicate
* potentially multiple agreements, especially if agreements must be retired and
* replaced with new agreements.</li>
*
* <li>{@link AccountExternalId}: OpenID identities and email addresses known to
* be registered to this user. Multiple records can exist when the user has more
* than one public identity, such as a work and a personal email address.</li>
*
* <li>{@link AccountGroupMember}: membership of the user in a specific human
* managed {@link AccountGroup}. Multiple records can exist when the user is a
* member of more than one group.</li>
*
* <li>{@link AccountProjectWatch}: user's email settings related to a specific
* {@link Project}. One record per project the user is interested in tracking.</li>
*
* <li>{@link AccountSshKey}: user's public SSH keys, for authentication through
* the internal SSH daemon. One record per SSH key uploaded by the user, keys
* are checked in random order until a match is found.</li>
*
* <li>{@link StarredChange}: user has starred the change, tracking
* notifications of updates on that change, or just book-marking it for faster
* future reference. One record per starred change.</li>
*
* <li>{@link AccountDiffPreference}: user's preferences for rendering side-to-side
* and unified diff</li>
*
* </ul>
*/
public final class Account {
public static enum FieldName {
FULL_NAME, USER_NAME, REGISTER_NEW_EMAIL;
}
public static final String USER_NAME_PATTERN_FIRST = "[a-zA-Z]";
public static final String USER_NAME_PATTERN_REST = "[a-zA-Z0-9._-]";
public static final String USER_NAME_PATTERN_LAST = "[a-zA-Z0-9]";
/** Regular expression that {@link #userName} must match. */
public static final String USER_NAME_PATTERN = "^" + //
"(" + //
USER_NAME_PATTERN_FIRST + //
USER_NAME_PATTERN_REST + "*" + //
USER_NAME_PATTERN_LAST + //
"|" + //
USER_NAME_PATTERN_FIRST + //
")" + //
"$";
/** Key local to Gerrit to identify a user. */
public static class Id extends IntKey<com.google.gwtorm.client.Key<?>> {
private static final long serialVersionUID = 1L;
@Column(id = 1)
protected int id;
protected Id() {
}
public Id(final int id) {
this.id = id;
}
@Override
public int get() {
return id;
}
@Override
protected void set(int newValue) {
id = newValue;
}
/** Parse an Account.Id out of a string representation. */
public static Id parse(final String str) {
final Id r = new Id();
r.fromString(str);
return r;
}
}
@Column(id = 1)
protected Id accountId;
/** Date and time the user registered with the review server. */
@Column(id = 2)
protected Timestamp registeredOn;
/** Full name of the user ("Given-name Surname" style). */
@Column(id = 3, notNull = false)
protected String fullName;
/** Email address the user prefers to be contacted through. */
@Column(id = 4, notNull = false)
protected String preferredEmail;
/** When did the user last give us contact information? Null if never. */
@Column(id = 5, notNull = false)
protected Timestamp contactFiledOn;
/** This user's preferences */
@Column(id = 6, name = Column.NONE)
protected AccountGeneralPreferences generalPreferences;
/** Is this user active */
@Column(id = 7)
protected boolean inactive;
/** <i>computed</i> the username selected from the identities. */
protected String userName;
protected Account() {
}
/**
* Create a new account.
*
* @param newId unique id, see
* {@link com.google.gerrit.reviewdb.server.ReviewDb#nextAccountId()}.
*/
public Account(final Account.Id newId) {
accountId = newId;
registeredOn = new Timestamp(System.currentTimeMillis());
generalPreferences = new AccountGeneralPreferences();
generalPreferences.resetToDefaults();
}
/** Get local id of this account, to link with in other entities */
public Account.Id getId() {
return accountId;
}
/** Get the full name of the user ("Given-name Surname" style). */
public String getFullName() {
return fullName;
}
/** Set the full name of the user ("Given-name Surname" style). */
public void setFullName(final String name) {
if (name != null && !name.trim().isEmpty()) {
fullName = name.trim();
} else {
fullName = null;
}
}
/** Email address the user prefers to be contacted through. */
public String getPreferredEmail() {
return preferredEmail;
}
/** Set the email address the user prefers to be contacted through. */
public void setPreferredEmail(final String addr) {
preferredEmail = addr;
}
/** Get the date and time the user first registered. */
public Timestamp getRegisteredOn() {
return registeredOn;
}
public AccountGeneralPreferences getGeneralPreferences() {
return generalPreferences;
}
public void setGeneralPreferences(final AccountGeneralPreferences p) {
generalPreferences = p;
}
public boolean isContactFiled() {
return contactFiledOn != null;
}
public Timestamp getContactFiledOn() {
return contactFiledOn;
}
public void setContactFiled() {
contactFiledOn = new Timestamp(System.currentTimeMillis());
}
public boolean isActive() {
return ! inactive;
}
public void setActive(boolean active) {
inactive = ! active;
}
/** @return the computed user name for this account */
public String getUserName() {
return userName;
}
/** Update the computed user name property. */
public void setUserName(final String userName) {
this.userName = userName;
}
}
| {
"content_hash": "6d1e19151539fc0b82c01472abfb06d3",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 83,
"avg_line_length": 29.89177489177489,
"alnum_prop": 0.6832729905865315,
"repo_name": "zommarin/gerrit",
"id": "94b37e144c46148c19e35d4f9c45aa1f72681cda",
"size": "6905",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gerrit-reviewdb/src/main/java/com/google/gerrit/reviewdb/client/Account.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5925270"
},
{
"name": "JavaScript",
"bytes": "1590"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "17421"
},
{
"name": "Python",
"bytes": "19659"
},
{
"name": "Shell",
"bytes": "36343"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('icekit_events', '0014_eventbase_human_times'),
('fluent_contents', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='TodaysOccurrences',
fields=[
('contentitem_ptr', models.OneToOneField(to='fluent_contents.ContentItem', primary_key=True, auto_created=True, parent_link=True, serialize=False)),
('include_finished', models.BooleanField(default=False, help_text=b'include occurrences that have already finished today')),
('types_to_show', models.ManyToManyField(blank=True, db_table=b'ik_todays_occurrences_types', to='icekit_events.EventType', help_text=b'Leave empty to show all events.')),
],
options={
'verbose_name': "Today's events",
'db_table': 'contentitem_ik_events_todays_occurrences_todaysoccurrences',
},
bases=('fluent_contents.contentitem',),
),
]
| {
"content_hash": "9ed36898bea24f64859576926bf30938",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 187,
"avg_line_length": 41.44444444444444,
"alnum_prop": 0.6210902591599643,
"repo_name": "ic-labs/icekit-events",
"id": "602ba23ffc8436dfacfb10381710beaa0ddc6ea3",
"size": "1143",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "icekit_events/plugins/todays_occurrences/migrations/0001_initial.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1334"
},
{
"name": "HTML",
"bytes": "19090"
},
{
"name": "JavaScript",
"bytes": "1759"
},
{
"name": "Python",
"bytes": "208757"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>24-timers værvarsel for Rudolstadt</title>
<link rel="stylesheet" type="text/css" href="main.css" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta charset="UTF-8" />
<meta http-equiv="refresh" content="1800" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<img id="de_ru" src="/weather_info/de_ru.png" />
</body>
</html>
| {
"content_hash": "ebf9dc179605c841f2b7a140a7149ff6",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 121,
"avg_line_length": 37.13333333333333,
"alnum_prop": 0.6391382405745063,
"repo_name": "thingol/simple_cnc",
"id": "80b93110e6e2973e7c20a93f185f2211de640048",
"size": "558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "static/de_ru_png.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "1954"
},
{
"name": "HTML",
"bytes": "3510"
},
{
"name": "JavaScript",
"bytes": "3719"
},
{
"name": "Python",
"bytes": "1414"
}
],
"symlink_target": ""
} |
"""Implementation of an S3-like storage server based on local files.
Useful to test features that will eventually run on S3, or if you want to
run something locally that was once running on S3.
We don't support all the features of S3, but it does work with the
standard S3 client for the most basic semantics. To use the standard
S3 client with this module:
c = S3.AWSAuthConnection("", "", server="localhost", port=8888,
is_secure=False)
c.create_bucket("mybucket")
c.put("mybucket", "mykey", "a value")
print c.get("mybucket", "mykey").body
"""
import bisect
import datetime
import hashlib
import os
import os.path
import urllib
from tornado import escape
from tornado import httpserver
from tornado import ioloop
from tornado import web
from tornado.util import unicode_type
from tornado.options import options, define
try:
long
except NameError:
long = int
define("port", default=9888, help="TCP port to listen on")
define("root_directory", default="/tmp/s3", help="Root storage directory")
define("bucket_depth", default=0, help="Bucket file system depth limit")
def start(port, root_directory, bucket_depth):
"""Starts the mock S3 server on the given port at the given path."""
application = S3Application(root_directory, bucket_depth)
http_server = httpserver.HTTPServer(application)
http_server.listen(port)
ioloop.IOLoop.current().start()
class S3Application(web.Application):
"""Implementation of an S3-like storage server based on local files.
If bucket depth is given, we break files up into multiple directories
to prevent hitting file system limits for number of files in each
directories. 1 means one level of directories, 2 means 2, etc.
"""
def __init__(self, root_directory, bucket_depth=0):
web.Application.__init__(self, [
(r"/", RootHandler),
(r"/([^/]+)/(.+)", ObjectHandler),
(r"/([^/]+)/", BucketHandler),
])
self.directory = os.path.abspath(root_directory)
if not os.path.exists(self.directory):
os.makedirs(self.directory)
self.bucket_depth = bucket_depth
class BaseRequestHandler(web.RequestHandler):
SUPPORTED_METHODS = ("PUT", "GET", "DELETE")
def render_xml(self, value):
assert isinstance(value, dict) and len(value) == 1
self.set_header("Content-Type", "application/xml; charset=UTF-8")
name = list(value.keys())[0]
parts = []
parts.append('<' + name +
' xmlns="http://doc.s3.amazonaws.com/2006-03-01">')
self._render_parts(value[name], parts)
parts.append('</' + name + '>')
self.finish('<?xml version="1.0" encoding="UTF-8"?>\n' +
''.join(parts))
def _render_parts(self, value, parts=[]):
if isinstance(value, (unicode_type, bytes)):
parts.append(escape.xhtml_escape(value))
elif isinstance(value, (int, long)):
parts.append(str(value))
elif isinstance(value, datetime.datetime):
parts.append(value.strftime("%Y-%m-%dT%H:%M:%S.000Z"))
elif isinstance(value, dict):
for name, subvalue in value.items():
if not isinstance(subvalue, list):
subvalue = [subvalue]
for subsubvalue in subvalue:
parts.append('<' + name + '>')
self._render_parts(subsubvalue, parts)
parts.append('</' + name + '>')
else:
raise Exception("Unknown S3 value type %r", value)
def _object_path(self, bucket, object_name):
if self.application.bucket_depth < 1:
return os.path.abspath(os.path.join(
self.application.directory, bucket, object_name))
hash = hashlib.md5(object_name).hexdigest()
path = os.path.abspath(os.path.join(
self.application.directory, bucket))
for i in range(self.application.bucket_depth):
path = os.path.join(path, hash[:2 * (i + 1)])
return os.path.join(path, object_name)
class RootHandler(BaseRequestHandler):
def get(self):
names = os.listdir(self.application.directory)
buckets = []
for name in names:
path = os.path.join(self.application.directory, name)
info = os.stat(path)
buckets.append({
"Name": name,
"CreationDate": datetime.datetime.utcfromtimestamp(
info.st_ctime),
})
self.render_xml({"ListAllMyBucketsResult": {
"Buckets": {"Bucket": buckets},
}})
class BucketHandler(BaseRequestHandler):
def get(self, bucket_name):
prefix = self.get_argument("prefix", u"")
marker = self.get_argument("marker", u"")
max_keys = int(self.get_argument("max-keys", 50000))
path = os.path.abspath(os.path.join(self.application.directory,
bucket_name))
terse = int(self.get_argument("terse", 0))
if not path.startswith(self.application.directory) or \
not os.path.isdir(path):
raise web.HTTPError(404)
object_names = []
for root, dirs, files in os.walk(path):
for file_name in files:
object_names.append(os.path.join(root, file_name))
skip = len(path) + 1
for i in range(self.application.bucket_depth):
skip += 2 * (i + 1) + 1
object_names = [n[skip:] for n in object_names]
object_names.sort()
contents = []
start_pos = 0
if marker:
start_pos = bisect.bisect_right(object_names, marker, start_pos)
if prefix:
start_pos = bisect.bisect_left(object_names, prefix, start_pos)
truncated = False
for object_name in object_names[start_pos:]:
if not object_name.startswith(prefix):
break
if len(contents) >= max_keys:
truncated = True
break
object_path = self._object_path(bucket_name, object_name)
c = {"Key": object_name}
if not terse:
info = os.stat(object_path)
c.update({
"LastModified": datetime.datetime.utcfromtimestamp(
info.st_mtime),
"Size": info.st_size,
})
contents.append(c)
marker = object_name
self.render_xml({"ListBucketResult": {
"Name": bucket_name,
"Prefix": prefix,
"Marker": marker,
"MaxKeys": max_keys,
"IsTruncated": truncated,
"Contents": contents,
}})
def put(self, bucket_name):
path = os.path.abspath(os.path.join(
self.application.directory, bucket_name))
if not path.startswith(self.application.directory) or \
os.path.exists(path):
raise web.HTTPError(403)
os.makedirs(path)
self.finish()
def delete(self, bucket_name):
path = os.path.abspath(os.path.join(
self.application.directory, bucket_name))
if not path.startswith(self.application.directory) or \
not os.path.isdir(path):
raise web.HTTPError(404)
if len(os.listdir(path)) > 0:
raise web.HTTPError(403)
os.rmdir(path)
self.set_status(204)
self.finish()
class ObjectHandler(BaseRequestHandler):
def get(self, bucket, object_name):
object_name = urllib.unquote(object_name)
path = self._object_path(bucket, object_name)
if not path.startswith(self.application.directory) or \
not os.path.isfile(path):
raise web.HTTPError(404)
info = os.stat(path)
self.set_header("Content-Type", "application/unknown")
self.set_header("Last-Modified", datetime.datetime.utcfromtimestamp(
info.st_mtime))
object_file = open(path, "rb")
try:
self.finish(object_file.read())
finally:
object_file.close()
def put(self, bucket, object_name):
object_name = urllib.unquote(object_name)
bucket_dir = os.path.abspath(os.path.join(
self.application.directory, bucket))
if not bucket_dir.startswith(self.application.directory) or \
not os.path.isdir(bucket_dir):
raise web.HTTPError(404)
path = self._object_path(bucket, object_name)
if not path.startswith(bucket_dir) or os.path.isdir(path):
raise web.HTTPError(403)
directory = os.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
object_file = open(path, "w")
object_file.write(self.request.body)
object_file.close()
self.finish()
def delete(self, bucket, object_name):
object_name = urllib.unquote(object_name)
path = self._object_path(bucket, object_name)
if not path.startswith(self.application.directory) or \
not os.path.isfile(path):
raise web.HTTPError(404)
os.unlink(path)
self.set_status(204)
self.finish()
if __name__ == "__main__":
options.parse_command_line()
start(options.port, options.root_directory, options.bucket_depth)
| {
"content_hash": "160afc723cf5dfb27f26c84676213371",
"timestamp": "",
"source": "github",
"line_count": 256,
"max_line_length": 76,
"avg_line_length": 36.8828125,
"alnum_prop": 0.5883287439101885,
"repo_name": "hhru/tornado",
"id": "4e85794461ecf209d99eaa792ebb46414683bba3",
"size": "10017",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demos/s3server/s3server.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1664"
},
{
"name": "HTML",
"bytes": "25"
},
{
"name": "Python",
"bytes": "1625160"
},
{
"name": "Ruby",
"bytes": "1428"
},
{
"name": "Shell",
"bytes": "4070"
}
],
"symlink_target": ""
} |
require "find"
beginTime = Time::now
p "begin time: #{beginTime}"
packBySubDir =
[
# 'ArtSource/Enemy',
# 'ArtSource/Character',
]
targetFileInfos =
[
# {
# 'folder' => 'ArtSource/GameObject',
# 'plist' => 'ArtProduction/GameObject/GameObject.plist',
# 'ccz' => 'ArtProduction/GameObject/GameObject.pvr.ccz'
# },
{
'folder' => 'ArtSource/UI',
'plist' => 'ArtProduction/UI/UI.plist',
'ccz' => 'ArtProduction/UI/UI.pvr.ccz'
},
]
def haveSubDir(dir)
Find.find(dir)
.select { |path| File.directory?(path) and !path.include?('.svn') }
.length > 0
end
def getTargetFileInfos(dir)
paths =
Find.find(dir)
.select { |path| !path.include?('.svn') and
File.directory?(path) and
Find.find(path)
.select { |path2| path2 != path and
File.directory?(path2) and
!path2.include?('.svn') }
.length == 0 }
.collect { |path| path.slice(path.index(dir) + dir.size + 1, path.size) }
.uniq()
sourceFolders = paths
# p 'sourceFolders', sourceFolders
targetDir = dir.sub('ArtSource', 'ArtProduction')
targetFileInfo =
sourceFolders.collect { |folder| fileName = folder.gsub(/\//, '_'); { 'folder'=> "#{dir}/#{folder}", 'plist'=> "#{targetDir}/#{fileName}.plist", 'ccz'=> "#{targetDir}/#{fileName}.pvr.ccz" } }
end
def isNeedToPack( info )
if !File.exist?(info['plist'])
return true
end
artProductionLastModifedTime = File.mtime(info['plist'])
artSourceLastModifedTimes =
Find.find(info['folder'])
.select { |path| !File.directory?(path) and !path.include?('.svn') }
.collect { |path| File.mtime path }.sort
artSourceLastModifedTime = artSourceLastModifedTimes[artSourceLastModifedTimes.length-1]
# p artSourceLastModifedTime
# p artProductionLastModifedTime
if artSourceLastModifedTime == nil
p "#{info['folder']} is empty"
end
return artSourceLastModifedTime > artProductionLastModifedTime
end
packBySubDir.each { |dir| targetFileInfos.push getTargetFileInfos(dir) }
targetFileInfos = targetFileInfos.flatten()
.select { |info| isNeedToPack info }
# targetFileInfos.each { |info| p info, '' }
targetFileInfos.each { |info| system "
folder='#{info['folder']}'
plist='#{info['plist']}'
ccz='#{info['ccz']}'
echo $folder, $plist, $ccz
/usr/local/bin/TexturePacker --smart-update \
--format cocos2d \
--data $plist \
--sheet $ccz \
--algorithm MaxRects \
--dither-fs-alpha \
--premultiply-alpha \
--opt RGBA8888 \
$folder
" }
endTime = Time::now
p "end time: #{endTime}"
p "total cost time: #{endTime - beginTime} seconds" | {
"content_hash": "e26bd7b0f0ff5b23e5c3fc984f612244",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 194,
"avg_line_length": 23.669642857142858,
"alnum_prop": 0.6352319879290834,
"repo_name": "pipi32167/DoubleScreenMatchIt",
"id": "7fe2b45230d133b0afab75e8962bd73cf4cab428",
"size": "2651",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DoubleScreenMatchIt/Tools/PackTextures.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "270670"
},
{
"name": "C++",
"bytes": "16728"
},
{
"name": "Matlab",
"bytes": "1875"
},
{
"name": "Objective-C",
"bytes": "1438398"
},
{
"name": "Ruby",
"bytes": "3710"
},
{
"name": "Shell",
"bytes": "119"
}
],
"symlink_target": ""
} |
package main
import (
zmq "github.com/pebbe/zmq3"
"github.com/pebbe/zmq3/examples/kvsimple"
"fmt"
)
func main() {
// Prepare our context and updates socket
updates, _ := zmq.NewSocket(zmq.SUB)
updates.SetSubscribe("")
updates.Connect("tcp://localhost:5556")
kvmap := make(map[string]*kvsimple.Kvmsg)
sequence := int64(0)
for ; true; sequence++ {
kvmsg, err := kvsimple.RecvKvmsg(updates)
if err != nil {
break // Interrupted
}
kvmsg.Store(kvmap)
}
fmt.Printf("Interrupted\n%d messages in\n", sequence)
}
| {
"content_hash": "e78701ecc17fac36056d8797871572a7",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 54,
"avg_line_length": 19.77777777777778,
"alnum_prop": 0.6779026217228464,
"repo_name": "cider-plugins/cider-github-trigger",
"id": "6300f38977656f8f55e3d45b7a99b768781429f2",
"size": "568",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "Godeps/_workspace/src/github.com/pebbe/zmq3/examples/clonecli1.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "1777311"
},
{
"name": "Python",
"bytes": "3478"
},
{
"name": "Shell",
"bytes": "1568"
}
],
"symlink_target": ""
} |
require_relative 'field'
module Rubytypeformio
class RatingField < Field
def initialize (question, description, required)
return super(question, description, required, 'rating')
end
def self.from_json(string)
data = JSON.load(string)
obj = self.new( data["question"],
data["description"],
data["required"])
obj.id = data["id"]
return obj
end
end
end
| {
"content_hash": "968e18b6f3bf69e1e678f510eaa9f947",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 61,
"avg_line_length": 21.38095238095238,
"alnum_prop": 0.5902004454342984,
"repo_name": "zachgoldstein/rubytypeformio",
"id": "4cbd9e5e5e4e8eba6f962d4470aedbfaab6930c0",
"size": "449",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/rubytypeformio/rating_field.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "19620"
}
],
"symlink_target": ""
} |
- Added support for the *externalAskSubmit* message type in the ***send-notification*** command.
| {
"content_hash": "317e91ba098b579d0940a5ff71a76c4d",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 96,
"avg_line_length": 97,
"alnum_prop": 0.7628865979381443,
"repo_name": "demisto/content",
"id": "74c0870a0cd9fdab5ba8d28b702e89a7f88a50e3",
"size": "131",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Packs/Slack/ReleaseNotes/2_5_2.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "2146"
},
{
"name": "HTML",
"bytes": "205901"
},
{
"name": "JavaScript",
"bytes": "1584075"
},
{
"name": "PowerShell",
"bytes": "442288"
},
{
"name": "Python",
"bytes": "47881712"
},
{
"name": "Rich Text Format",
"bytes": "480911"
},
{
"name": "Shell",
"bytes": "108066"
},
{
"name": "YARA",
"bytes": "1185"
}
],
"symlink_target": ""
} |
This folder will host unit tests that test individual HoloToolkit-Unity components.
#### Creating a unit test:
1. Unit tests can be located anywhere under an Editor folder but consider placing it under the HoloToolkit-UnitTests\Editor folder so that HoloToolkit-Unity can be easily deployed without the tests if required.
2. Use the **NUnit 2.6.4** features to create the tests.
3. Cover us much as possible the new code so that other people can test your code even without knowing its internals.
4. Execute all the tests before submitting a pull request.
#### Running the unit tests:
1. Unit tests execution is integrated into the Unity editor (since 5.3).
2. Open the **Editor Tests** window by clicking on the menu item **Window** | **Editor Tests Runner**.
3. Click on the buttons **Run All**, **Run Selected** or **Run Failed** to run the tests.
| {
"content_hash": "cb23aeecc35995ed4d868e67b8873dd3",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 210,
"avg_line_length": 57.2,
"alnum_prop": 0.7552447552447552,
"repo_name": "reislerjul/HoloIoT",
"id": "c69fdc5bff89bdfde4533277639cee00d15d9d05",
"size": "882",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "UnityProject/HoloIoT/Assets/HoloToolkit-UnitTests/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1930"
},
{
"name": "C#",
"bytes": "2368755"
},
{
"name": "GLSL",
"bytes": "8141"
},
{
"name": "HLSL",
"bytes": "31087"
},
{
"name": "PowerShell",
"bytes": "8923"
},
{
"name": "ShaderLab",
"bytes": "108087"
}
],
"symlink_target": ""
} |
namespace Autofac.Test.Scenarios.ScannedAssembly
{
public interface ICloseCommand : ICommand<object>
{
}
} | {
"content_hash": "aec4a929770247022f47eddd16f66140",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 53,
"avg_line_length": 19.666666666666668,
"alnum_prop": 0.7288135593220338,
"repo_name": "jruckert/Autofac",
"id": "bc07e943b124a399eb0d7a5dcd14e172a6cee65f",
"size": "118",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "test/Autofac.Test.Scenarios.ScannedAssembly/ICloseCommand.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1687"
},
{
"name": "C#",
"bytes": "1096604"
},
{
"name": "HTML",
"bytes": "8093"
}
],
"symlink_target": ""
} |
.class public Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.super Lorg/jets3t/service/multi/event/ServiceEvent;
.source "DownloadObjectsEvent.java"
# instance fields
.field private objects:[Lorg/jets3t/service/model/StorageObject;
# direct methods
.method private constructor <init>(ILjava/lang/Object;)V
.locals 1
.param p1, "eventCode" # I
.param p2, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 43
invoke-direct {p0, p1, p2}, Lorg/jets3t/service/multi/event/ServiceEvent;-><init>(ILjava/lang/Object;)V
.line 40
const/4 v0, 0x0
iput-object v0, p0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->objects:[Lorg/jets3t/service/model/StorageObject;
.line 44
return-void
.end method
.method public static newCancelledEvent([Lorg/jets3t/service/model/StorageObject;Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "incompletedObjects" # [Lorg/jets3t/service/model/StorageObject;
.param p1, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 74
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x4
invoke-direct {v0, v1, p1}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 75
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
invoke-direct {v0, p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setObjects([Lorg/jets3t/service/model/StorageObject;)V
.line 76
return-object v0
.end method
.method public static newCompletedEvent(Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 69
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x2
invoke-direct {v0, v1, p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 70
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
return-object v0
.end method
.method public static newErrorEvent(Ljava/lang/Throwable;Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "t" # Ljava/lang/Throwable;
.param p1, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 48
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x0
invoke-direct {v0, v1, p1}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 49
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
invoke-virtual {v0, p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setErrorCause(Ljava/lang/Throwable;)V
.line 50
return-object v0
.end method
.method public static newIgnoredErrorsEvent(Lorg/jets3t/service/multi/ThreadWatcher;[Ljava/lang/Throwable;Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "threadWatcher" # Lorg/jets3t/service/multi/ThreadWatcher;
.param p1, "ignoredErrors" # [Ljava/lang/Throwable;
.param p2, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 82
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x5
invoke-direct {v0, v1, p2}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 83
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
invoke-virtual {v0, p1}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setIgnoredErrors([Ljava/lang/Throwable;)V
.line 84
return-object v0
.end method
.method public static newInProgressEvent(Lorg/jets3t/service/multi/ThreadWatcher;[Lorg/jets3t/service/model/StorageObject;Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "threadWatcher" # Lorg/jets3t/service/multi/ThreadWatcher;
.param p1, "completedObjects" # [Lorg/jets3t/service/model/StorageObject;
.param p2, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 62
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x3
invoke-direct {v0, v1, p2}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 63
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
invoke-virtual {v0, p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setThreadWatcher(Lorg/jets3t/service/multi/ThreadWatcher;)V
.line 64
invoke-direct {v0, p1}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setObjects([Lorg/jets3t/service/model/StorageObject;)V
.line 65
return-object v0
.end method
.method public static newStartedEvent(Lorg/jets3t/service/multi/ThreadWatcher;Ljava/lang/Object;)Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
.locals 2
.param p0, "threadWatcher" # Lorg/jets3t/service/multi/ThreadWatcher;
.param p1, "uniqueOperationId" # Ljava/lang/Object;
.prologue
.line 54
new-instance v0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
const/4 v1, 0x1
invoke-direct {v0, v1, p1}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;-><init>(ILjava/lang/Object;)V
.line 55
.local v0, "event":Lorg/jets3t/service/multi/event/DownloadObjectsEvent;
invoke-virtual {v0, p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->setThreadWatcher(Lorg/jets3t/service/multi/ThreadWatcher;)V
.line 56
return-object v0
.end method
.method private setObjects([Lorg/jets3t/service/model/StorageObject;)V
.locals 0
.param p1, "objects" # [Lorg/jets3t/service/model/StorageObject;
.prologue
.line 89
iput-object p1, p0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->objects:[Lorg/jets3t/service/model/StorageObject;
.line 90
return-void
.end method
# virtual methods
.method public getCancelledObjects()[Lorg/jets3t/service/model/StorageObject;
.locals 2
.annotation system Ldalvik/annotation/Throws;
value = {
Ljava/lang/IllegalStateException;
}
.end annotation
.prologue
.line 112
invoke-virtual {p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->getEventCode()I
move-result v0
const/4 v1, 0x4
if-eq v0, v1, :cond_0
.line 113
new-instance v0, Ljava/lang/IllegalStateException;
const-string v1, "Cancelled Objects are only available from EVENT_CANCELLED events"
invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V
throw v0
.line 115
:cond_0
iget-object v0, p0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->objects:[Lorg/jets3t/service/model/StorageObject;
return-object v0
.end method
.method public getDownloadedObjects()[Lorg/jets3t/service/model/StorageObject;
.locals 2
.annotation system Ldalvik/annotation/Throws;
value = {
Ljava/lang/IllegalStateException;
}
.end annotation
.prologue
.line 99
invoke-virtual {p0}, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->getEventCode()I
move-result v0
const/4 v1, 0x3
if-eq v0, v1, :cond_0
.line 100
new-instance v0, Ljava/lang/IllegalStateException;
const-string v1, "Downloaded Objects are only available from EVENT_IN_PROGRESS events"
invoke-direct {v0, v1}, Ljava/lang/IllegalStateException;-><init>(Ljava/lang/String;)V
throw v0
.line 102
:cond_0
iget-object v0, p0, Lorg/jets3t/service/multi/event/DownloadObjectsEvent;->objects:[Lorg/jets3t/service/model/StorageObject;
return-object v0
.end method
| {
"content_hash": "c97c65cbcc26f0d94c2e385f5c07329a",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 194,
"avg_line_length": 33.34322033898305,
"alnum_prop": 0.7260134705807599,
"repo_name": "GaHoKwan/tos_device_meizu_mx4",
"id": "4b760efeec3b14c7be8f9a3564a4116630b01942",
"size": "7869",
"binary": false,
"copies": "2",
"ref": "refs/heads/TPS-YUNOS",
"path": "patch/smali/pack/services.jar/smali/org/jets3t/service/multi/event/DownloadObjectsEvent.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2407"
},
{
"name": "Groff",
"bytes": "8687"
},
{
"name": "Makefile",
"bytes": "31774"
},
{
"name": "Shell",
"bytes": "6226"
},
{
"name": "Smali",
"bytes": "350951922"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace JMS\Serializer\Construction;
use Doctrine\Persistence\ManagerRegistry;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\Exception\InvalidArgumentException;
use JMS\Serializer\Exception\ObjectConstructionException;
use JMS\Serializer\Exclusion\ExpressionLanguageExclusionStrategy;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Visitor\DeserializationVisitorInterface;
use function is_array;
/**
* Doctrine object constructor for new (or existing) objects during deserialization.
*/
final class DoctrineObjectConstructor implements ObjectConstructorInterface
{
public const ON_MISSING_NULL = 'null';
public const ON_MISSING_EXCEPTION = 'exception';
public const ON_MISSING_FALLBACK = 'fallback';
/**
* @var string
*/
private $fallbackStrategy;
/**
* @var ManagerRegistry
*/
private $managerRegistry;
/**
* @var ObjectConstructorInterface
*/
private $fallbackConstructor;
/**
* @var ExpressionLanguageExclusionStrategy|null
*/
private $expressionLanguageExclusionStrategy;
/**
* @param ManagerRegistry $managerRegistry Manager registry
* @param ObjectConstructorInterface $fallbackConstructor Fallback object constructor
*/
public function __construct(
ManagerRegistry $managerRegistry,
ObjectConstructorInterface $fallbackConstructor,
string $fallbackStrategy = self::ON_MISSING_NULL,
?ExpressionLanguageExclusionStrategy $expressionLanguageExclusionStrategy = null
) {
$this->managerRegistry = $managerRegistry;
$this->fallbackConstructor = $fallbackConstructor;
$this->fallbackStrategy = $fallbackStrategy;
$this->expressionLanguageExclusionStrategy = $expressionLanguageExclusionStrategy;
}
/**
* {@inheritdoc}
*/
public function construct(DeserializationVisitorInterface $visitor, ClassMetadata $metadata, $data, array $type, DeserializationContext $context): ?object
{
// Locate possible ObjectManager
$objectManager = $this->managerRegistry->getManagerForClass($metadata->name);
if (!$objectManager) {
// No ObjectManager found, proceed with normal deserialization
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
// Locate possible ClassMetadata
$classMetadataFactory = $objectManager->getMetadataFactory();
if ($classMetadataFactory->isTransient($metadata->name)) {
// No ClassMetadata found, proceed with normal deserialization
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
// Managed entity, check for proxy load
if (!is_array($data) && !(is_object($data) && 'SimpleXMLElement' === get_class($data))) {
// Single identifier, load proxy
return $objectManager->getReference($metadata->name, $data);
}
// Fallback to default constructor if missing identifier(s)
$classMetadata = $objectManager->getClassMetadata($metadata->name);
$identifierList = [];
foreach ($classMetadata->getIdentifierFieldNames() as $name) {
// Avoid calling objectManager->find if some identification properties are excluded
if (!isset($metadata->propertyMetadata[$name])) {
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
$propertyMetadata = $metadata->propertyMetadata[$name];
// Avoid calling objectManager->find if some identification properties are excluded by some exclusion strategy
if ($this->isIdentifierFieldExcluded($propertyMetadata, $context)) {
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
if (is_array($data) && !array_key_exists($propertyMetadata->serializedName, $data)) {
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
} elseif (is_object($data) && !property_exists($data, $propertyMetadata->serializedName)) {
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
if (is_object($data) && 'SimpleXMLElement' === get_class($data)) {
$identifierList[$name] = (string) $data->{$propertyMetadata->serializedName};
} else {
$identifierList[$name] = $data[$propertyMetadata->serializedName];
}
}
if (empty($identifierList)) {
// $classMetadataFactory->isTransient() fails on embeddable class with file metadata driver
// https://github.com/doctrine/persistence/issues/37
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
}
// Entity update, load it from database
$object = $objectManager->find($metadata->name, $identifierList);
if (null === $object) {
switch ($this->fallbackStrategy) {
case self::ON_MISSING_NULL:
return null;
case self::ON_MISSING_EXCEPTION:
throw new ObjectConstructionException(sprintf('Entity %s can not be found', $metadata->name));
case self::ON_MISSING_FALLBACK:
return $this->fallbackConstructor->construct($visitor, $metadata, $data, $type, $context);
default:
throw new InvalidArgumentException('The provided fallback strategy for the object constructor is not valid');
}
}
$objectManager->initializeObject($object);
return $object;
}
private function isIdentifierFieldExcluded(PropertyMetadata $propertyMetadata, DeserializationContext $context): bool
{
$exclusionStrategy = $context->getExclusionStrategy();
if (null !== $exclusionStrategy && $exclusionStrategy->shouldSkipProperty($propertyMetadata, $context)) {
return true;
}
return null !== $this->expressionLanguageExclusionStrategy && $this->expressionLanguageExclusionStrategy->shouldSkipProperty($propertyMetadata, $context);
}
}
| {
"content_hash": "b77990162e5ac81e3c9d4248d663a4c2",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 162,
"avg_line_length": 40.82911392405063,
"alnum_prop": 0.6595876608277786,
"repo_name": "mpoiriert/serializer",
"id": "7fc4cd51cbb8c38b20be465bc42bee1d77876d4d",
"size": "6451",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Construction/DoctrineObjectConstructor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "858142"
}
],
"symlink_target": ""
} |
package com.wso2telco.dep.mediator.executor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.mozilla.javascript.*;
import org.wso2.carbon.apimgt.api.APIManagementException;
import java.util.*;
public class ExecutorInfoHostObject extends ScriptableObject {
//TODO:write method to get fullqulified name
private static final Log log = LogFactory.getLog(ExecutorInfoHostObject.class);
private final String hostObjectName = "Executor";
//private ExecutorDAO executorDAO;
private HashMap<String,ExecutorObj> executors = new HashMap <String,ExecutorObj>();
private HashMap<String, HandlerObj> handlers = new HashMap<String, HandlerObj>();
@Override
public String getClassName() {
return hostObjectName;
}
public ExecutorInfoHostObject () {
log.info("initializing Executor host object");
bindExecutors();
bindHandlers();
//executorDAO = new ExecutorDAO();
}
public static NativeArray jsFunction_getAllExecutors (Context cx, Scriptable thisObj, Object[] args,
Function funObj) {
//TODO:load operators from search dto class as in store host object
return getExecutorsList(thisObj);
}
public static NativeObject jsFunction_getExecutorwithDesc (Context cx, Scriptable thisObj, Object[] args,
Function funObj) {
return getExecutorwithDesc(thisObj);
}
/**
* Js function_get each executor's description from osgi.
*
* @param cx the cx
* @param thisObj the this obj
* @param args the args
* @param funObj the fun obj
* @return executor description
* @throws Exception
*/
public static String jsFunction_getExecutorDescription (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException{
String description = null;
if (args.length == 0) {
description = "No description";
} else {
String executorName = (String) args[0];
description = getExecutorDescription(thisObj,executorName);
}
return description;
}
public static String jsFunction_getExecutorFQN (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
String executorFQN = null;
if (args.length == 0) {
executorFQN = "Executor Name Not Received";
} else {
String executorName = (String)args[0];
executorFQN = getExecutorFQN(thisObj, executorFQN);
}
return executorFQN;
}
public static NativeArray jsFunction_getHandlers (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
return getHandlerList(thisObj);
}
public static String jsFunction_getHandlerDescription (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
String handlerDescription = null;
if (args.length == 0) {
handlerDescription = "Handler Name Not Received";
} else {
String handlerName = (String)args[0];
handlerDescription = getHandlerDescription(thisObj, handlerName);
}
return handlerDescription;
}
public static String jsFunction_getHandlerFQN (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
String handlerFQN = null;
if (args.length == 0) {
handlerFQN = "Handler Name Not Received";
} else {
String handlerName = (String)args[0];
handlerFQN = getHandlerFQN(thisObj, handlerName);
}
return handlerFQN;
}
public static NativeArray jsFunction_getHandlerObjects (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
return getHandlerObjects(thisObj);
}
public static NativeArray jsFunction_getExecutorObjects (Context cx, Scriptable thisObj, Object[] args,
Function funObj) throws APIManagementException {
return getExecutorObjects(thisObj);
}
//TODO:use osgi service to bind data.
private void bindExecutors () {
executors.put("Default_Executor", new ExecutorObj("Default_executor","com.wso2telco.dep.mediator.impl.DefaultExecutor", "Default Executor Description"));
executors.put("Credit_Executor", new ExecutorObj("Credit_executor","com.wso2telco.dep.mediator.impl.credit.CreditExecutor", "Credit Executor Description"));
executors.put("Location_Executor", new ExecutorObj("Location_executor","com.wso2telco.dep.mediator.impl.LocationExecutor", "Location Executor Description"));
executors.put("Payment_Executor", new ExecutorObj("Payment_executor","com.wso2telco.dep.mediator.impl.payment.PaymentExecutor", "Payment Executor Description"));
executors.put("Provision_Executor", new ExecutorObj("Provision_executor","com.wso2telco.dep.mediator.impl.provision.ProvisionExecutor", "Provision Executor Description"));
executors.put("SMS_Executor", new ExecutorObj("SMS_executor","com.wso2telco.dep.mediator.impl.smsmessaging.SMSExecutor", "SMS Executor Description"));
executors.put("USSD_Executor", new ExecutorObj("USSD_executor","com.wso2telco.dep.mediator.impl.ussd.USSDExecutor", "USSD Executor Description"));
executors.put("Wallet_Executor", new ExecutorObj("Wallet_executor","com.wso2telco.dep.mediator.impl.wallet.WalletExecutor", "Wallet Executor Description"));
}
//TODO: bind these handlers in correct sequence. Sequence here is the same sequence that will be added to the synapse configuration file.
private void bindHandlers () {
handlers.put("APIRequestHandler", new HandlerObj("APIRequestHandler", "com.wso2telco.dep.verificationhandler.verifier.APIRequestHandler"));
handlers.put("BlacklistHandler", new HandlerObj("BlacklistHandler", "com.wso2telco.dep.verificationhandler.verifier.BlacklistHandler"));
handlers.put("DialogSubscriptionHandler", new HandlerObj("DialogSubscriptionHandler", "com.wso2telco.dep.verificationhandler.verifier.SubscriptionHandler"));
handlers.put("DialogPaymentHandler", new HandlerObj("DialogPaymentHandler", "com.wso2telco.dep.verificationhandler.verifier.PaymentHandler"));
handlers.put("DialogWhitelistHandler", new HandlerObj("DialogWhitelistHandler", "com.wso2telco.dep.verificationhandler.verifier.WhitelistHandler"));
}
public static NativeArray getHandlerObjects (Scriptable thisObj) {
return ((ExecutorInfoHostObject)thisObj).getHandlerObjects();
}
public static NativeArray getExecutorObjects (Scriptable thisObj) {
return ((ExecutorInfoHostObject)thisObj).getExecutorObjects();
}
public static NativeArray getHandlerList (Scriptable thisObj) {
return ((ExecutorInfoHostObject)thisObj).getHandlerList();
}
public static String getHandlerFQN (Scriptable thisObj, String handlerName) {
return ((ExecutorInfoHostObject)thisObj).getHandlerFQN(handlerName);
}
public static NativeArray getExecutorsList (Scriptable thisObj) {
return ((ExecutorInfoHostObject)thisObj).getExecutorsList();
}
public static NativeObject getExecutorwithDesc (Scriptable thisObj) {
return ((ExecutorInfoHostObject)thisObj).getExecutorwithDesc();
}
public static String getExecutorDescription (Scriptable thisObj, String executor) {
return ((ExecutorInfoHostObject)thisObj).getExecutorDescription(executor);
}
public static String getHandlerDescription (Scriptable thisObj, String handler) {
return ((ExecutorInfoHostObject)thisObj).getHandlerDescription(handler);
}
public static String getExecutorFQN (Scriptable thisObj, String executor) {
return ((ExecutorInfoHostObject)thisObj).getExecutorFQN(executor);
}
private NativeArray getHandlerList () {
Object[] keys = handlers.keySet().toArray();
NativeArray array = new NativeArray(keys);
return array;
}
private NativeArray getExecutorsList () {
Object[] keys = executors.keySet().toArray();
NativeArray array = new NativeArray(keys);
//Object[] keys = executors.keySet().toArray();
//String [] executorsList = Arrays.copyOf(keys, keys.length,String[].class);
return array;
}
private NativeArray getHandlerObjects () {
Object[] values = handlers.values().toArray();
NativeArray nativeArray = new NativeArray(1);
JSONArray jsonArray = new JSONArray();
for (Object obj : values) {
HandlerObj object = (HandlerObj) obj;
JSONObject jsonObject = new JSONObject();
jsonObject.put("handlerName", object.getHandlerName());
jsonObject.put("handlerFQN", object.getHandlerFullQulifiedName());
jsonArray.add(jsonObject);
//NativeObject nativeObject = new NativeObject();
//nativeObject.put(object.getHandlerName(), nativeObject, object.getHandlerFullQulifiedName());
}
nativeArray.put(0, nativeArray, jsonArray.toJSONString());
return nativeArray;
}
private NativeArray getExecutorObjects () {
Object[] values = executors.values().toArray();
NativeArray nativeArray = new NativeArray(1);
JSONArray jsonArray = new JSONArray();
for (Object obj :values) {
ExecutorObj executorObj = (ExecutorObj) obj;
JSONObject jsonObject = new JSONObject();
jsonObject.put("executorName", executorObj.getExecutorName());
jsonObject.put("executorFQN", executorObj.getFullQulifiedName());
jsonArray.add(jsonObject);
}
nativeArray.put(0, nativeArray, jsonArray.toJSONString());
return nativeArray;
}
private NativeObject getExecutorwithDesc () {
NativeObject executor = new NativeObject();
for (ExecutorObj excObj : executors.values()) {
executor.put(excObj.getExecutorName(), executor, excObj.getExecutorDescription());
}
return executor ;
}
private String getExecutorDescription (String executor) {
String executorDes = null;
if (executors.containsKey(executor)) {
executorDes = executors.get(executor).getExecutorDescription();
}
return executorDes;
}
private String getHandlerDescription (String handler) {
String handlerDescription = null;
if (handlers.containsKey(handler)) {
handlerDescription = handlers.get(handler).getHandlerDescription();
}
return handlerDescription;
}
private String getExecutorFQN (String executor) {
String executorFQN = null;
if (executors.containsKey(executor)) {
executorFQN = executors.get(executor).getFullQulifiedName();
} else {
}
return executorFQN;
}
private String getHandlerFQN (String handler) {
String handlerFQN = null;
if (handlers.containsKey(handler)) {
handlerFQN = handlers.get(handler).getHandlerFullQulifiedName();
} else {
}
return handlerFQN;
}
//exception handling
/**
* Handle exception.
*
* @param msg
* the msg
* @throws APIManagementException
* the API management exception
*/
private static void handleException(String msg) throws APIManagementException {
log.error(msg);
throw new APIManagementException(msg);
}
/**
* Handle exception.
*
* @param msg
* the msg
* @param t
* the t
* @throws APIManagementException
* the API management exception
*/
private static void handleException(String msg, Throwable t) throws APIManagementException {
log.error(msg, t);
throw new APIManagementException(msg, t);
}
}
| {
"content_hash": "20f5c69d449d162239d856b460f1c9a4",
"timestamp": "",
"source": "github",
"line_count": 413,
"max_line_length": 179,
"avg_line_length": 30.774818401937047,
"alnum_prop": 0.6519276160503541,
"repo_name": "buddhimihara/component-dep",
"id": "c4268d240bd0fff2e8790a75029ff6930e7d08b9",
"size": "13391",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "components/mediator/src/main/java/com/wso2telco/dep/mediator/executor/ExecutorInfoHostObject.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2638497"
},
{
"name": "HTML",
"bytes": "231299"
},
{
"name": "Java",
"bytes": "2576465"
},
{
"name": "JavaScript",
"bytes": "11668673"
},
{
"name": "Shell",
"bytes": "5681"
},
{
"name": "XSLT",
"bytes": "47380"
}
],
"symlink_target": ""
} |
package org.zaproxy.clientapi.gen.deprecated;
import java.util.HashMap;
import java.util.Map;
import org.zaproxy.clientapi.core.ClientApi;
import org.zaproxy.clientapi.core.ClientApiException;
/** API implementation with deprecated methods, (re)moved from generated class. */
@SuppressWarnings("javadoc")
public class SearchDeprecated {
private final ClientApi api;
public SearchDeprecated(ClientApi api) {
this.api = api;
}
/**
* @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
* constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
* String)}).
*/
@Deprecated
public byte[] harByUrlRegex(
String apikey, String regex, String baseurl, String start, String count)
throws ClientApiException {
Map<String, String> map = new HashMap<>();
if (apikey != null) {
map.put("apikey", apikey);
}
map.put("regex", regex);
if (baseurl != null) {
map.put("baseurl", baseurl);
}
if (start != null) {
map.put("start", start);
}
if (count != null) {
map.put("count", count);
}
return api.callApiOther("search", "other", "harByUrlRegex", map);
}
/**
* @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
* constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
* String)}).
*/
@Deprecated
public byte[] harByRequestRegex(
String apikey, String regex, String baseurl, String start, String count)
throws ClientApiException {
Map<String, String> map = new HashMap<>();
if (apikey != null) {
map.put("apikey", apikey);
}
map.put("regex", regex);
if (baseurl != null) {
map.put("baseurl", baseurl);
}
if (start != null) {
map.put("start", start);
}
if (count != null) {
map.put("count", count);
}
return api.callApiOther("search", "other", "harByRequestRegex", map);
}
/**
* @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
* constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
* String)}).
*/
@Deprecated
public byte[] harByResponseRegex(
String apikey, String regex, String baseurl, String start, String count)
throws ClientApiException {
Map<String, String> map = new HashMap<>();
if (apikey != null) {
map.put("apikey", apikey);
}
map.put("regex", regex);
if (baseurl != null) {
map.put("baseurl", baseurl);
}
if (start != null) {
map.put("start", start);
}
if (count != null) {
map.put("count", count);
}
return api.callApiOther("search", "other", "harByResponseRegex", map);
}
/**
* @deprecated (1.1.0) Use the method without the API key and use one of the {@code ClientApi}
* constructors that allow to set the API key (e.g. {@link ClientApi#ClientApi(String, int,
* String)}).
*/
@Deprecated
public byte[] harByHeaderRegex(
String apikey, String regex, String baseurl, String start, String count)
throws ClientApiException {
Map<String, String> map = new HashMap<>();
if (apikey != null) {
map.put("apikey", apikey);
}
map.put("regex", regex);
if (baseurl != null) {
map.put("baseurl", baseurl);
}
if (start != null) {
map.put("start", start);
}
if (count != null) {
map.put("count", count);
}
return api.callApiOther("search", "other", "harByHeaderRegex", map);
}
}
| {
"content_hash": "de751a6e0224daa94fe205794517c4f9",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 99,
"avg_line_length": 33.049180327868854,
"alnum_prop": 0.5533234126984127,
"repo_name": "zaproxy/zap-api-java",
"id": "d9a397e3d9d74c05002819879149b478c0b16282",
"size": "4770",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "subprojects/zap-clientapi/src/main/java/org/zaproxy/clientapi/gen/deprecated/SearchDeprecated.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "613681"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32.c
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-32.tmpl.c
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: listen_socket Read data using a listen socket (server side)
* GoodSource: Fixed string
* Sink: w32_execv
* BadSink : execute command with execv
* Flow Variant: 32 Data flow using two pointers to the same value within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#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>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif
#define TCP_PORT 27015
#define LISTEN_BACKLOG 5
#include <process.h>
#define EXECV _execv
#ifndef OMITBAD
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32_bad()
{
char * data;
char * *dataPtr1 = &data;
char * *dataPtr2 = &data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
char * data = *dataPtr1;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
char *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = strlen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(char)] = '\0';
/* Eliminate CRLF */
replace = strchr(data, '\r');
if (replace)
{
*replace = '\0';
}
replace = strchr(data, '\n');
if (replace)
{
*replace = '\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
*dataPtr1 = data;
}
{
char * data = *dataPtr2;
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECV(COMMAND_INT_PATH, args);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
char * *dataPtr1 = &data;
char * *dataPtr2 = &data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
{
char * data = *dataPtr1;
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
*dataPtr1 = data;
}
{
char * data = *dataPtr2;
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
/* execv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECV(COMMAND_INT_PATH, args);
}
}
}
void CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "5b97e9faff820a2d52d4c5924884b551",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 113,
"avg_line_length": 30.09009009009009,
"alnum_prop": 0.5354790419161677,
"repo_name": "JianpingZeng/xcc",
"id": "dee2253540365c08a5940ffefb038486134bcd1c",
"size": "6680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_listen_socket_w32_execv_32.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Joey Wong • About</title>
<link href="img/jkangaroo.png" rel="SHORTCUT ICON" type="image/x-icon">
<link href="img/jkangaroo.png" rel="ICON" type="image/ico">
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- Custom styles for this template -->
<link href="css/clean-blog.min.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<i class="fa fa-bars"></i>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="index.html">Work</a>
</li>
<li class="nav-item">
<a class="nav-link" href="about.html">About</a>
</li>
</ul>
</div>
</nav>
<!-- Page Header -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<div class="site-heading" style="padding: 35px">
</div>
</div>
</div>
<!-- Main Content -->
<div class="container">
<div class="row">
<img src="img/JoeyZ.jpg" style="float:left; margin-top: 30px; margin: 30px; width: auto;
height: auto;">
<div class="col-sm-9 col-lg-6">
<!-- <div class="col-sm-9 col-md-6"> -->
<p><h5>Hi, I am Joey.</h5>
I currently design in the auto consumer space by creating solutions to improve the car buying experience. Previously, I designed at <a href="https://healthy.kaiserpermanente.org/">Kaiser Permanente</a>, where I delivered designs for patients and healthcare professionals.
<p><h6>Some things I love</h6> kickboxing, muay thai, kayaking, and ice cream!</p>
<p><h6><strike>2020 Bucket List</strike> Things I've done during quarantine</h6>
<strike>Travel to Europe</strike> Only thing I accomplished off my bucket list
<br>
Learn how to cut men's hair
<br>
Run 100 miles in a month
<br>
Embroidery
<br>
Cook and bake more
<br>
Support local businesses
</ul>
</p>
</div>
</div>
</div>
<br>
<br>
<br>
<br>
<br>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
<ul class="list-inline text-center">
<li class="list-inline-item">
<a class="" href="https://www.linkedin.com/in/joeywwong">
<i class="fa fa-linkedin"></i>
</a>
</li>
<li class="list-inline-item">
<a href="https://www.instagram.com/joeyw.jpeg/">
<i class="fa fa-instagram"></i>
</a>
</li>
</ul>
<p class="copyright text-muted">© Joey Wong 2017</p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/jquery/jquery.min copy.js"></script>
<!-- Plugin JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/popper/popper.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Custom scripts for this template -->
<script src="js/clean-blog.min.js"></script>
<script src="js/agency.min.js"></script>
</body>
</html>
| {
"content_hash": "d43d0ea72c7585b1a77b4c489ed65f5a",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 285,
"avg_line_length": 34.666666666666664,
"alnum_prop": 0.5747863247863247,
"repo_name": "joeyca/joeyca.github.io",
"id": "f8a1830906ff468f50f41c175e0fb9d01792aacb",
"size": "4680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "about.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23857"
},
{
"name": "HTML",
"bytes": "104076"
},
{
"name": "JavaScript",
"bytes": "44261"
},
{
"name": "PHP",
"bytes": "1242"
}
],
"symlink_target": ""
} |
* * *
title: Graph Paper Programming view: page_curriculum theme: none
* * *
<%= partial('curriculum_header', :title=> 'Graph Paper Programming', :unplugged=>true,:disclaimer=>'Basic lesson time includes activity only. Introductory and Wrap-Up suggestions can be used to delve deeper when time allows.', :time=>20) %>
[content]
## Lesson Overview
By "programming" one another to draw pictures, students will begin to understand what programming is really about. The class will begin by having students instruct each other to color squares in on graph paper in an effort to reproduce an existing picture. If there’s time, the lesson can conclude with images that the students create themselves.
[summary]
## Teaching Summary
### **Getting Started** - 15 minutes
1) [Vocabulary](#Vocab)
2) [Introduce Graph Paper Programming](#GetStarted)
3) [Practice Together](#Practice)
### **Activity: Graph Paper Programming** - 20 minutes
4) [Four-by-Fours](#Activity1)
### **Wrap-up** - 5 minutes
5) [Flash Chat: What did we learn?](#FlashChat)
6) [Vocab Shmocab](#Shmocab)
### **Assessment** - 10 minutes
7) [Graph Paper Programming Assessment](#Assessment)
[/summary]
## Lesson Objectives
Students will:
* Understand the difficulty of translating real problems into programs
* Learn that ideas may feel clear and yet still be misinterpreted by a computer
* Practice communicating ideas through codes and symbols
# Teaching Guide
## Materials, Resources and Prep
### For the Student
* [Four-by-Fours Activity Worksheet](Activity1-GraphPaperProgramming.pdf)
* [Graph Paper Programming Assessment](Assessment1-GraphPaperProgramming.pdf)
* Sheets of 4x4 paper grids for the students to use as practice (These are provided as part of the [Four-by-Fours Activity Worksheet](Activity1-GraphPaperProgramming.pdf), but if you have the students create their own, you can include Common Core Math standard 2.G.2.)
* Blank paper or index cards for programs
* Markers, pens, or pencils
### For the Teacher
* [Lesson Video](http://youtu.be/Yy1zbkfRtIg?list=PL2DhNKNdmOtobJjiTYvpBDZ0xzhXRj11N)
* Print out one [Four-by-Fours Activity Worksheet](Activity1-GraphPaperProgramming.pdf) for each group
* Print one [Graph Paper Programming Assessment](Assessment1-GraphPaperProgramming.pdf) for each student
* Supply each group with several drawing grids, paper, and pens/pencils
## Getting Started (15 min)
### <a name="Vocab"></a>1) Vocabulary
This lesson has two new and important words:
[centerIt]

[/centerIt]
**Algorithm** - Say it with me: Al-go-ri-thm
A list of steps that you can follow to finish a task
**Program** - Say it with me: Pro-gram
An algorithm that has been coded into something that can be run by a machine
### <a name="GetStarted"></a>2) Introduce Graph Paper Programming
In this activity, we are going to guide each other toward making drawings, without letting the other people in our group see the original image.
For this exercise, we will use sheets of 4x4 graph paper. Starting at the upper left-hand corner, we’ll guide our teammates’ Automatic Realization Machine (ARM) with simple instructions. Those instructions include:
* Move One Square Right
* Move One Square Left
* Move One Square Up
* Move One Square Down
* Fill-In Square with color
For example, here’s how we would write an algorithm to instruct a friend (who is pretending to be a drawing machine) to color their blank grid so that it looks like the image below:
[centerIt]

[/centerIt]
That’s simple enough, but it would take a lot of writing to provide instructions for a square like this:
[centerIt]

[/centerIt]
With one little substitution, we can do this much more easily! Instead of having to write out an entire phrase for each instruction, we can use arrows.
[centerIt]

[/centerIt]
In this instance, the arrow symbols are the “program” code and the words are the “algorithm” piece. This means that we could write the algorithm:
> “Move one square right, Move one square right, Fill-in square with color”
and that would correspond to the program:
> 
Using arrows, we can redo the code from the previous image much more easily!
[centerIt]

[/centerIt]
### <a name="Practice"></a>3) Practice Together
Start your class off in the world of programming by drawing or projecting the provided key onto the board.
[centerIt]

[/centerIt]
Select a simple drawing, such as this one to use as an example.
[centerIt]

[/centerIt]
This is a good way to introduce all of the symbols in the key. To begin, fill in the graph for the class -- square by square -- then ask them to help describe what you’ve just done. First, you can speak the algorithm out loud, then you can turn your verbal instructions into a program.
A sample algorithm:
> “Move Right, Fill-In Square, Move Right, Move Down
> Fill-In Square, Move Left, Move Left, Fill-In Square
> Move Down, Move Right, Fill-In Square, Move Right”
Some of your class may notice that there is an unnecessary step, but hold them off until after the programming stage.
Walk the class through translating the algorithm into the program:
> 
The classroom may be buzzing with suggestions by this point. If the class gets the gist of the exercise, this is a good place to discuss alternate ways of filling out the same grid. If there is still confusion, save that piece for another day and work with another example.
> 
If the class can shout out the algorithm and define the correct symbols to use for each step, they’re ready to move on. Depending on your class and their age, you can either try doing a more complicated grid together or skip straight to having them work in groups on their [Four-by-Fours Activity Worksheet](/curriculum/course2/1/Activity1-GraphPaperProgramming.pdf).
[tip]
# Lesson Tip
Have the class imagine that your arm is an Automatic Realization Machine (ARM). The idea of "algorithms" and "programs" will be brought to life even further if students feel like they're actually in control of your movements.
[/tip]
## Activity: Graph Paper Programming (20 min)
### <a name="Activity1"></a>4) [Four-by-Fours Activity Worksheet](/curriculum/course2/1/Activity1-GraphPaperProgramming.pdf)
1. Divide students into pairs.
2. Have each pair choose an image from the worksheet.
3. Discuss the algorithm to draw that image with partner.
4. Convert algorithm into a program using symbols.
5. Trade programs with another pair and draw one another's image.
6. Choose another image and go again!
[centerIt]

[/centerIt]
## Wrap-up (5 min)
### <a name="FlashChat"></a>5) Flash Chat: What did we learn?
* What did we learn today?
* What if we used the same arrows, but replaced "Fill-In Square" with "Lay Brick"? What might we be able to do?
* What else could we program if we just changed what the arrows meant?
### <a name="Shmocab"></a>6) Vocab Shmocab
* Which one of these definitions did we learn a word for today?
> "A large tropical parrot with a very long tail and beautiful feathers"
> "A list of steps that you can follow to finish a task"
> "An incredibly stinky flower that blooms only once a year"
>
>
> > ...and what is the word that we learned?
* Which one of these is the *most* like a "program"?
> *A shoebox full of pretty rocks
> *Twelve pink flowers in a vase
> *Sheet music for your favorite song
>
>
> > Explain why you chose your answer.
## <a name="Assessment"></a> Assessment (10 min)
### 7) [Graph Paper Programming Assessment](Assessment1-GraphPaperProgramming.pdf)
## Extended Learning
Use these activities to enhance student learning. They can be used as outside of class activities or other enrichment.
### Better and Better
* Have your class try making up their own images.
* Can they figure out how to program the images that they create?
### Class Challenge
* As the teacher, draw an image on a 5x5 grid.
* Can the class code that up along with you?
[standards]
## Connections and Background Information
### ISTE Standards (formerly NETS)
* 1.b - Create original works as a means of personal or group expression.
* 1.c - Use models and simulation to explore complex systems and issues.
* 2.d - Contribute to project teams to solve problems.
* 4.b - Plan and manage activities to develop a solution or complete a project.
* 4.d - Use multiple processes and diverse perspectives to explore alternative solutions.
### CSTA K-12 Computer Science Standards
* CPP.L1:3-04 - Construct a set of statements to be acted out to accomplish a simple task.
* CPP.L1:6-05. Construct a program as a set of step-by-step instructions to be acted out.
* CT.L1:3-03 - Understand how to arrange information into useful order without using a computer.
* CT.L1:6-01 - Understand and use the basic steps in algorithmic problem-solving.
* CT.L1:6-02 - Develop a simple understanding of an algorithm using computer-free exercises.
* CT.L2-07 - Represent data in a variety of ways: text, sounds, pictures, numbers.
### NGSS Science and Engineering Practices
* K-2-ETS1-2 - Develop a simple sketch, drawing, or physical model to illustrate how the shape of an object helps it function as needed to solve a given problem.
* 3-5-ETS1-2 - Generate and compare multiple possible solutions to a problem based on how well each is likely to meet the criteria and constraints of the problem.
### Common Core Mathematical Practices
* 1. Make sense of problems and persevere in solving them.
* 1. Reason abstractly and quantitatively.
* 1. Construct viable arguments and critique the reasoning of others.
* 1. Attend to precision.
* 1. Look for and make use of structure.
* 1. Look for and express regularity in repeated reasoning.
### Common Core Math Standards
* 2.G.2 - Partition a rectangle into rows and columns of same-size squares and count to find the total number of them.
### Common Core Language Arts Standards
* SL.1.1 - Participate in collaborative conversations with diverse partners about grade 1 topics and texts with peers and adults in small and larger groups.
* SL.1.2 - Ask and answer questions about key details in a text read aloud or information presented orally or through other media.
* L.1.6 - Use words and phrases acquired through conversations, reading and being read to, and responding to texts, including using frequently occurring conjunctions to signal simple relationships.
* SL.2.1 - Participate in collaborative conversations with diverse partners about grade 2 topics and texts with peers and adults in small and larger groups.
* SL.2.2 - Recount or describe key ideas or details from a text read aloud or information presented orally or through other media.
* L.2.6 - Use words and phrases acquired through conversations, reading and being read to, and responding to texts, including using adjectives and adverbs to describe.
* SL.3.1 - Engage effectively in a range of collaborative discussions (one-on-one, in groups, and teacher-led) with diverse partners on grade 3 topics and texts, building on others' ideas and expressing their own clearly.
* SL.3.3 - Ask and answer questions about information from a speaker, offering appropriate elaboration and detail.
* L.3.6 - Acquire and use accurately grade-appropriate conversational, general academic, and domain-specific words and phrases, including those that signal spatial and temporal relationships.
[/standards]
[<img src="http://www.thinkersmith.org/images/creativeCommons.png" border="0" />](http://creativecommons.org/)
[<img src="http://www.thinkersmith.org/images/thinker.png" border="0" />](http://thinkersmith.org/)
[/content]
<link rel="stylesheet" type="text/css" href="../docs/morestyle.css" /> | {
"content_hash": "891f1f923c43188a5079d4c92d7a078e",
"timestamp": "",
"source": "github",
"line_count": 319,
"max_line_length": 367,
"avg_line_length": 37.96865203761755,
"alnum_prop": 0.740505284015852,
"repo_name": "dillia23/code-dot-org",
"id": "3d0a6808051505384b6fd41b3b826205b95e2b7e",
"size": "12142",
"binary": false,
"copies": "5",
"ref": "refs/heads/staging",
"path": "i18n/locales/nl-NL/curriculum/course2/1/Teacher.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "93"
},
{
"name": "C++",
"bytes": "4844"
},
{
"name": "CSS",
"bytes": "2398346"
},
{
"name": "Cucumber",
"bytes": "130717"
},
{
"name": "Emacs Lisp",
"bytes": "2410"
},
{
"name": "HTML",
"bytes": "9371177"
},
{
"name": "JavaScript",
"bytes": "83773111"
},
{
"name": "PHP",
"bytes": "2303483"
},
{
"name": "Perl",
"bytes": "14821"
},
{
"name": "Processing",
"bytes": "11068"
},
{
"name": "Prolog",
"bytes": "679"
},
{
"name": "Python",
"bytes": "124866"
},
{
"name": "Racket",
"bytes": "131852"
},
{
"name": "Ruby",
"bytes": "2070008"
},
{
"name": "Shell",
"bytes": "37544"
},
{
"name": "SourcePawn",
"bytes": "74109"
}
],
"symlink_target": ""
} |
package za.org.grassroot.webapp.controller.android1;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import za.org.grassroot.core.GrassrootApplicationProfiles;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.VerificationTokenCode;
import za.org.grassroot.core.dto.UserDTO;
import za.org.grassroot.core.enums.AlertPreference;
import za.org.grassroot.core.enums.DeliveryRoute;
import za.org.grassroot.core.enums.UserInterfaceType;
import za.org.grassroot.core.enums.VerificationCodeType;
import za.org.grassroot.core.util.InvalidPhoneNumberException;
import za.org.grassroot.core.util.PhoneNumberUtil;
import za.org.grassroot.integration.NotificationService;
import za.org.grassroot.integration.messaging.MessagingServiceBroker;
import za.org.grassroot.services.PermissionBroker;
import za.org.grassroot.services.geo.GeoLocationBroker;
import za.org.grassroot.services.user.PasswordTokenService;
import za.org.grassroot.services.user.UserManagementService;
import za.org.grassroot.webapp.enums.RestMessage;
import za.org.grassroot.webapp.model.rest.wrappers.AuthWrapper;
import za.org.grassroot.webapp.model.rest.wrappers.ProfileSettingsDTO;
import za.org.grassroot.webapp.model.rest.wrappers.ResponseWrapper;
import za.org.grassroot.webapp.util.RestUtil;
import java.time.Instant;
import java.util.Locale;
/**
* Created by paballo.
*/
@RestController
@Api("/api/user") @Slf4j
@RequestMapping(value = "/api/user")
public class UserRestController {
private final UserManagementService userManagementService;
private final PasswordTokenService passwordTokenService;
private final GeoLocationBroker geoLocationBroker;
private final MessagingServiceBroker messagingServiceBroker;
private final NotificationService notificationService;
private final PermissionBroker permissionBroker;
private final Environment environment;
@Autowired
public UserRestController(UserManagementService userManagementService, PasswordTokenService passwordTokenService,
GeoLocationBroker geoLocationBroker, MessagingServiceBroker messagingServiceBroker,
NotificationService notificationService, PermissionBroker permissionBroker, Environment environment) {
this.userManagementService = userManagementService;
this.passwordTokenService = passwordTokenService;
this.geoLocationBroker = geoLocationBroker;
this.messagingServiceBroker = messagingServiceBroker;
this.notificationService = notificationService;
this.permissionBroker = permissionBroker;
this.environment = environment;
}
@RequestMapping(value = "/add/{phoneNumber}/{displayName}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> add(@PathVariable("phoneNumber") String phoneNumber, @PathVariable("displayName") String displayName) {
try {
final String msisdn = PhoneNumberUtil.convertPhoneNumber(phoneNumber);
if (!ifExists(msisdn)) {
log.info("Creating a verifier for a new user with phoneNumber ={}", phoneNumber);
String tokenCode = temporaryTokenSend(userManagementService.generateAndroidUserVerifier(phoneNumber, displayName, null), msisdn, false);
return RestUtil.okayResponseWithData(RestMessage.VERIFICATION_TOKEN_SENT, tokenCode);
} else {
log.info("Creating a verifier for user with phoneNumber ={}, user already exists.", phoneNumber);
return RestUtil.errorResponse(HttpStatus.CONFLICT, RestMessage.USER_ALREADY_EXISTS);
}
} catch (InvalidPhoneNumberException e) {
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.INVALID_MSISDN);
}
}
@RequestMapping(value = "/verify/resend/{phoneNumber}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> resendOtp(@PathVariable("phoneNumber") String phoneNumber) {
final String msisdn = PhoneNumberUtil.convertPhoneNumber(phoneNumber);
try {
final String tokenCode = temporaryTokenSend(userManagementService.regenerateUserVerifier(msisdn, true), msisdn, true); // will be empty in production
return RestUtil.okayResponseWithData(RestMessage.VERIFICATION_TOKEN_SENT, tokenCode);
} catch (Exception e) {
log.info("here is the error : " + e.toString());
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.OTP_REQ_BEFORE_ADD);
}
}
@RequestMapping(value = "/verify/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> verify(@PathVariable("phoneNumber") String phoneNumber, @PathVariable("code") String otpEntered) {
final String msisdn = PhoneNumberUtil.convertPhoneNumber(phoneNumber);
if (passwordTokenService.isShortLivedOtpValid(msisdn, otpEntered)) {
log.info("user dto and code verified, now creating user with phoneNumber={}", phoneNumber);
UserDTO userDTO = userManagementService.loadUserCreateRequest(msisdn);
User user = userManagementService.createAndroidUserProfile(userDTO);
VerificationTokenCode token = passwordTokenService.generateLongLivedAuthCode(user.getUid());
passwordTokenService.expireVerificationCode(user.getUid(), VerificationCodeType.SHORT_OTP);
AuthWrapper authWrapper = AuthWrapper.create(true, token, user, false, 0); // by definition, no groups or notiifcations
return new ResponseEntity<>(authWrapper, HttpStatus.OK);
} else {
log.info("Token verification for new user failed");
return RestUtil.errorResponse(HttpStatus.UNAUTHORIZED, RestMessage.INVALID_OTP);
}
}
@RequestMapping(value = "/login/{phoneNumber}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> logon(@PathVariable("phoneNumber") String phoneNumber) {
try {
final String msisdn = PhoneNumberUtil.convertPhoneNumber(phoneNumber);
if (ifExists(msisdn)) {
// this will send the token by SMS and return an empty string if in production, or return the token if on staging
String token = temporaryTokenSend(userManagementService.generateAndroidUserVerifier(msisdn, null, null), msisdn, false);
return RestUtil.okayResponseWithData(RestMessage.VERIFICATION_TOKEN_SENT, token);
} else {
return RestUtil.errorResponse(HttpStatus.NOT_FOUND, RestMessage.USER_DOES_NOT_EXIST);
}
} catch (InvalidPhoneNumberException e) {
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.INVALID_MSISDN);
}
}
@RequestMapping(value = "/login/authenticate/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> authenticate(@PathVariable("phoneNumber") String phoneNumber,
@PathVariable("code") String token) {
if (passwordTokenService.isShortLivedOtpValid(phoneNumber, token)) {
log.info("User authentication successful for user with phoneNumber={}", phoneNumber);
User user = userManagementService.findByInputNumber(phoneNumber);
if (!user.isHasAndroidProfile()) {
userManagementService.createAndroidUserProfile(new UserDTO(user));
}
userManagementService.setMessagingPreference(user.getUid(), DeliveryRoute.ANDROID_APP); // todo : maybe move to gcm registration
passwordTokenService.expireVerificationCode(user.getUid(), VerificationCodeType.SHORT_OTP);
VerificationTokenCode longLivedToken = passwordTokenService.generateLongLivedAuthCode(user.getUid());
boolean hasGroups = permissionBroker.countActiveGroupsWithPermission(user, null) != 0;
int notificationCount = notificationService.countUnviewedAndroidNotifications(user.getUid());
AuthWrapper authWrapper = AuthWrapper.create(false, longLivedToken, user, hasGroups, notificationCount);
return new ResponseEntity<>(authWrapper, HttpStatus.OK);
} else {
log.info("Android: Okay invalid code supplied by user={}");
return RestUtil.errorResponse(HttpStatus.UNAUTHORIZED, RestMessage.INVALID_OTP);
}
}
@RequestMapping(value = "/connect/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> checkConnection(@PathVariable String phoneNumber,
@PathVariable String code) {
// just load the user, to make sure exists (or it will return server error), and send back
User user = userManagementService.findByInputNumber(phoneNumber);
log.info("reconnected user : " + user.getPhoneNumber());
return RestUtil.messageOkayResponse(RestMessage.USER_OKAY);
}
@RequestMapping(value = "/auth/extend/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> extendToken(@PathVariable String phoneNumber, @PathVariable String code) {
try {
boolean tokenRefreshed = passwordTokenService.extendAuthCodeIfExpiring(phoneNumber, code);
return RestUtil.messageOkayResponse(tokenRefreshed ? RestMessage.TOKEN_EXTENDED : RestMessage.TOKEN_STILL_VALID);
} catch (NullPointerException e) {
log.error("Error extending token: {}", e.getMessage());
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.BAD_TOKEN_UPDATE);
} catch (AccessDeniedException e) {
return RestUtil.accessDeniedResponse();
}
}
@RequestMapping(value = "/auth/refresh/initiate/{phoneNumber}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> initiateTokenRefresh(@PathVariable String phoneNumber) {
try {
final String msisdn = PhoneNumberUtil.convertPhoneNumber(phoneNumber);
// this will send the token by SMS and return an empty string if in production, or return the token if on staging
String token = temporaryTokenSend(
userManagementService.regenerateUserVerifier(msisdn, false), msisdn, false);
return RestUtil.okayResponseWithData(RestMessage.VERIFICATION_TOKEN_SENT, token);
} catch (InvalidPhoneNumberException|AccessDeniedException e) {
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.BAD_TOKEN_UPDATE);
}
}
@RequestMapping(value = "/auth/refresh/verify/{phoneNumber}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> verifyTokenRefresh(@PathVariable String phoneNumber,
@RequestParam String otp) {
if (passwordTokenService.isShortLivedOtpValid(phoneNumber, otp)) {
User user = userManagementService.findByInputNumber(phoneNumber);
passwordTokenService.expireVerificationCode(user.getUid(), VerificationCodeType.SHORT_OTP);
VerificationTokenCode longLivedToken = passwordTokenService.generateLongLivedAuthCode(user.getUid());
return RestUtil.okayResponseWithData(RestMessage.LOGIN_SUCCESS, longLivedToken.getCode());
} else {
return RestUtil.errorResponse(HttpStatus.UNAUTHORIZED, RestMessage.INVALID_OTP);
}
}
@RequestMapping(value = "/logout/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> logoutUser(@PathVariable String phoneNumber, @PathVariable String code) {
User user = userManagementService.findByInputNumber(phoneNumber);
userManagementService.setMessagingPreference(user.getUid(), DeliveryRoute.SMS);
passwordTokenService.expireVerificationCode(user.getUid(), VerificationCodeType.LONG_AUTH);
return RestUtil.messageOkayResponse(RestMessage.USER_LOGGED_OUT);
}
@RequestMapping(value="/profile/settings/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> getProfileSettings(@PathVariable("phoneNumber") String phoneNumber, @PathVariable("code") String code){
User user = userManagementService.findByInputNumber(phoneNumber);
ProfileSettingsDTO profileSettingsDTO = new ProfileSettingsDTO(user.getDisplayName(),
user.getLocale().getLanguage(), user.getAlertPreference().toString());
return RestUtil.okayResponseWithData(RestMessage.PROFILE_SETTINGS, profileSettingsDTO);
}
@RequestMapping(value = "/profile/settings/rename/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> renameUser(@PathVariable String phoneNumber, @PathVariable String code,
@RequestParam String displayName) {
User user = userManagementService.findByInputNumber(phoneNumber);
userManagementService.updateDisplayName(user.getUid(), user.getUid(), displayName);
return RestUtil.messageOkayResponse(RestMessage.PROFILE_SETTINGS_UPDATED);
}
/*
note : it might be slightly more efficient to just have the integer (for notification priority) directly from the client, _but_ there is some
uncertainty about how notification priorities will evolve, and integer meanings within core/services may shift, hence
the use of strings for flexibility etc
*/
@RequestMapping(value = "/profile/settings/notify/priority/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> changeNotificationPriority(@PathVariable String phoneNumber, @PathVariable String code,
@RequestParam AlertPreference alertPreference) {
User user = userManagementService.findByInputNumber(phoneNumber);
userManagementService.updateAlertPreferences(user.getUid(), alertPreference);
return RestUtil.messageOkayResponse(RestMessage.PROFILE_SETTINGS_UPDATED);
}
@RequestMapping(value = "/profile/settings/language/{phoneNumber}/{code}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> changeUserLanguage(@PathVariable String phoneNumber, @PathVariable String code,
@RequestParam String language) {
User user = userManagementService.findByInputNumber(phoneNumber);
try {
Locale passedLocale = new Locale(language);
log.info("received a passed locale ... here it is :" + passedLocale.toString());
userManagementService.updateUserLanguage(user.getUid(), passedLocale, UserInterfaceType.ANDROID);
return RestUtil.messageOkayResponse(RestMessage.PROFILE_SETTINGS_UPDATED);
} catch (IllegalArgumentException e) {
return RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.INVALID_LANG_CODE);
}
}
@RequestMapping(value= "/location/{phoneNumber}/{code}/{latitude}/{longitude:.+}", method = RequestMethod.GET)
public ResponseEntity<ResponseWrapper> logUserLocation(@PathVariable String phoneNumber, @PathVariable String code,
@PathVariable double latitude, @PathVariable double longitude) {
User user = userManagementService.findByInputNumber(phoneNumber);
log.info("Recording a location! With longitude = {} and lattitude = {}, from path string", longitude, latitude);
geoLocationBroker.logUserLocation(user.getUid(), latitude, longitude, Instant.now(), UserInterfaceType.ANDROID);
return RestUtil.messageOkayResponse(RestMessage.LOCATION_RECORDED);
}
private boolean ifExists(String phoneNumber) {
return userManagementService.userExist(PhoneNumberUtil.convertPhoneNumber(phoneNumber));
}
private String temporaryTokenSend(String token, String destinationNumber, boolean resending) {
if (environment.acceptsProfiles(Profiles.of(GrassrootApplicationProfiles.PRODUCTION))) {
if (token != null) {
// todo : wire up a message source for this
final String prefix = resending ? "Grassroot code (resent): " : "Grassroot code: ";
messagingServiceBroker.sendPrioritySMS(prefix + token, destinationNumber);
} else {
log.warn("Did not send verification message. No system messaging configuration found.");
}
return "";
} else {
return token;
}
}
} | {
"content_hash": "c0637ad503282d4c5aab4bab45144f5f",
"timestamp": "",
"source": "github",
"line_count": 290,
"max_line_length": 161,
"avg_line_length": 59.83448275862069,
"alnum_prop": 0.7169778699861687,
"repo_name": "grassrootza/grassroot-platform",
"id": "e3a91e4d580715944045927d7b0d3b2c39ef2838",
"size": "17352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grassroot-webapp/src/main/java/za/org/grassroot/webapp/controller/android1/UserRestController.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "15432"
},
{
"name": "CSS",
"bytes": "876"
},
{
"name": "Dockerfile",
"bytes": "827"
},
{
"name": "HTML",
"bytes": "29802"
},
{
"name": "Java",
"bytes": "3488612"
},
{
"name": "PLSQL",
"bytes": "3059"
},
{
"name": "PLpgSQL",
"bytes": "5246"
},
{
"name": "SQLPL",
"bytes": "2733"
},
{
"name": "Shell",
"bytes": "6615"
},
{
"name": "TSQL",
"bytes": "45559"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "5e17d3e8c15b8b49fe8204b23e608a4e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "ff70a1a77ad3a98052e9da934c42a3940e6dba73",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Tricalysia/Tricalysia idiura/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef __PolyVox_ArraySizes_H__
#define __PolyVox_ArraySizes_H__
#include "Impl/ArraySizesImpl.h"
#include "Impl/TypeDef.h"
namespace PolyVox
{
///The ArraySizes class provide a convienient way to specify the dimensions of an Array.
////////////////////////////////////////////////////////////////////////////////
/// The Array class requires an array of integers to be passed to the constructor
/// to specify the dimensions of the Array to be built. C++ does not allow this to
/// be done in place, and so it typically requires an extra line of code - something
/// like this:
///
/// \code
/// uint32_t dimensions[3] = {10, 20, 30}; // Array dimensions
/// Array<3,float> array(dimensions);
/// \endcode
///
/// The ArraySizes class can be constructed in place, and also provides implicit
/// conversion to an array of integers. Hence it is now possible to declare the
/// above Array as follows:
///
/// \code
/// Array<3,float> array(ArraySizes(10)(20)(30));
/// \endcode
///
/// Usage of this class is therefore very simple, although the template code
/// behind it may appear complex. For reference, it is based upon the article here:
/// http://www.drdobbs.com/cpp/184401319/
////////////////////////////////////////////////////////////////////////////////
class POLYVOX_API ArraySizes
{
typedef const uint32_t (&UIntArray1)[1];
public:
/// Constructor
explicit ArraySizes(uint32_t uSize);
/// Duplicates this object but with an extra dimension
ArraySizesImpl<2> operator () (uint32_t uSize);
/// Converts this object to an array of integers
operator UIntArray1 () const;
private:
// This class is only one dimensional. Higher dimensions
// are implemented via the ArraySizesImpl class.
uint32_t m_pSizes[1];
};
}//namespace PolyVox
#endif //__PolyVox_ArraySizes_H__
| {
"content_hash": "fb5e1c3bd5b243f97408246da64aeddf",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 89,
"avg_line_length": 33.839285714285715,
"alnum_prop": 0.6200527704485488,
"repo_name": "celeron55/buildat",
"id": "93bd6d0c57a64309c8964ced4af017241c2a6876",
"size": "2927",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "3rdparty/polyvox/library/PolyVoxCore/include/PolyVoxCore/ArraySizes.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "41918"
},
{
"name": "C++",
"bytes": "570762"
},
{
"name": "Lua",
"bytes": "176171"
},
{
"name": "Python",
"bytes": "18642"
},
{
"name": "Shell",
"bytes": "3552"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace ParusnikServiceDesk.WebStatus
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| {
"content_hash": "008b1e661900df4584ce52e72650256b",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 64,
"avg_line_length": 24.32,
"alnum_prop": 0.5805921052631579,
"repo_name": "Parusnik/Parusnik.OnlineAssistant",
"id": "9f1868c22e9e9712d0aa92c05c3e6d0b0b1bf8f1",
"size": "610",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "src/Web/ParusnikServiceDesk.WebStatus/Program.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "156190"
},
{
"name": "CSS",
"bytes": "2361"
},
{
"name": "JavaScript",
"bytes": "67275"
}
],
"symlink_target": ""
} |
$(function () {
"use strict";
var $container = $('#masonry');
$container.imagesLoaded(function () {
$container.masonry({
columnWidth: '.item',
itemSelector: '.item',
gutter: 0,
transitionDuration: '1s'
});
}).done(function () {
$(window).trigger('resize');
});
});
| {
"content_hash": "cd3475416147d3490b1f8ccb383db40b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 41,
"avg_line_length": 17.333333333333332,
"alnum_prop": 0.46703296703296704,
"repo_name": "mul14/porto-two",
"id": "8e7a757d612eb2761269f5094cad13e212c53e8d",
"size": "364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/scripts/app.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "20554"
},
{
"name": "CoffeeScript",
"bytes": "1674"
},
{
"name": "JavaScript",
"bytes": "364"
},
{
"name": "PHP",
"bytes": "7078"
}
],
"symlink_target": ""
} |
package io.apiman.manager.api.jpa;
import io.apiman.common.util.crypt.DataEncryptionContext;
import io.apiman.common.util.crypt.IDataEncrypter;
import io.apiman.manager.api.beans.apis.ApiBean;
import io.apiman.manager.api.beans.apis.ApiDefinitionBean;
import io.apiman.manager.api.beans.apis.ApiGatewayBean;
import io.apiman.manager.api.beans.apis.ApiPlanBean;
import io.apiman.manager.api.beans.apis.ApiStatus;
import io.apiman.manager.api.beans.apis.ApiVersionBean;
import io.apiman.manager.api.beans.audit.AuditEntityType;
import io.apiman.manager.api.beans.audit.AuditEntryBean;
import io.apiman.manager.api.beans.clients.ClientBean;
import io.apiman.manager.api.beans.clients.ClientStatus;
import io.apiman.manager.api.beans.clients.ClientVersionBean;
import io.apiman.manager.api.beans.contracts.ContractBean;
import io.apiman.manager.api.beans.download.DownloadBean;
import io.apiman.manager.api.beans.gateways.GatewayBean;
import io.apiman.manager.api.beans.gateways.GatewayType;
import io.apiman.manager.api.beans.idm.PermissionBean;
import io.apiman.manager.api.beans.idm.PermissionType;
import io.apiman.manager.api.beans.idm.RoleBean;
import io.apiman.manager.api.beans.idm.RoleMembershipBean;
import io.apiman.manager.api.beans.idm.UserBean;
import io.apiman.manager.api.beans.orgs.OrganizationBean;
import io.apiman.manager.api.beans.plans.PlanBean;
import io.apiman.manager.api.beans.plans.PlanStatus;
import io.apiman.manager.api.beans.plans.PlanVersionBean;
import io.apiman.manager.api.beans.plugins.PluginBean;
import io.apiman.manager.api.beans.policies.PolicyBean;
import io.apiman.manager.api.beans.policies.PolicyDefinitionBean;
import io.apiman.manager.api.beans.policies.PolicyType;
import io.apiman.manager.api.beans.search.PagingBean;
import io.apiman.manager.api.beans.search.SearchCriteriaBean;
import io.apiman.manager.api.beans.search.SearchCriteriaFilterOperator;
import io.apiman.manager.api.beans.search.SearchResultsBean;
import io.apiman.manager.api.beans.summary.ApiEntryBean;
import io.apiman.manager.api.beans.summary.ApiPlanSummaryBean;
import io.apiman.manager.api.beans.summary.ApiRegistryBean;
import io.apiman.manager.api.beans.summary.ApiSummaryBean;
import io.apiman.manager.api.beans.summary.ApiVersionSummaryBean;
import io.apiman.manager.api.beans.summary.ClientSummaryBean;
import io.apiman.manager.api.beans.summary.ClientVersionSummaryBean;
import io.apiman.manager.api.beans.summary.ContractSummaryBean;
import io.apiman.manager.api.beans.summary.GatewaySummaryBean;
import io.apiman.manager.api.beans.summary.OrganizationSummaryBean;
import io.apiman.manager.api.beans.summary.PlanSummaryBean;
import io.apiman.manager.api.beans.summary.PlanVersionSummaryBean;
import io.apiman.manager.api.beans.summary.PluginSummaryBean;
import io.apiman.manager.api.beans.summary.PolicyDefinitionSummaryBean;
import io.apiman.manager.api.beans.summary.PolicyFormType;
import io.apiman.manager.api.beans.summary.PolicySummaryBean;
import io.apiman.manager.api.core.IStorage;
import io.apiman.manager.api.core.IStorageQuery;
import io.apiman.manager.api.core.exceptions.StorageException;
import io.apiman.manager.api.core.util.PolicyTemplateUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Alternative;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A JPA implementation of the storage interface.
*
* @author [email protected]
*/
@SuppressWarnings("nls")
@ApplicationScoped @Alternative
public class JpaStorage extends AbstractJpaStorage implements IStorage, IStorageQuery {
private static Logger logger = LoggerFactory.getLogger(JpaStorage.class);
@Inject IDataEncrypter encrypter;
@PostConstruct
public void postConstruct() {
// Kick the encrypter, causing it to be loaded/resolved in CDI
encrypter.encrypt("", new DataEncryptionContext());
}
/**
* Constructor.
*/
public JpaStorage() {
}
/**
* @see io.apiman.manager.api.core.IStorage#beginTx()
*/
@Override
public void beginTx() throws StorageException {
super.beginTx();
}
/**
* @see io.apiman.manager.api.core.IStorage#commitTx()
*/
@Override
public void commitTx() throws StorageException {
super.commitTx();
}
/**
* @see io.apiman.manager.api.core.IStorage#rollbackTx()
*/
@Override
public void rollbackTx() {
super.rollbackTx();
}
@Override
public void initialize() {
// No-Op for JPA
}
/**
* @see io.apiman.manager.api.core.IStorage#createClient(io.apiman.manager.api.beans.clients.ClientBean)
*/
@Override
public void createClient(ClientBean client) throws StorageException {
super.create(client);
}
/**
* @see io.apiman.manager.api.core.IStorage#createClientVersion(io.apiman.manager.api.beans.clients.ClientVersionBean)
*/
@Override
public void createClientVersion(ClientVersionBean version) throws StorageException {
super.create(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#createContract(io.apiman.manager.api.beans.contracts.ContractBean)
*/
@Override
public void createContract(ContractBean contract) throws StorageException {
List<ContractSummaryBean> contracts = getClientContractsInternal(contract.getClient().getClient().getOrganization().getId(),
contract.getClient().getClient().getId(), contract.getClient().getVersion());
for (ContractSummaryBean csb : contracts) {
if (csb.getApiOrganizationId().equals(contract.getApi().getApi().getOrganization().getId()) &&
csb.getApiId().equals(contract.getApi().getApi().getId()) &&
csb.getApiVersion().equals(contract.getApi().getVersion()))
{
throw new StorageException("Error creating contract: duplicate contract detected."); //$NON-NLS-1$
}
}
super.create(contract);
}
/**
* @see io.apiman.manager.api.core.IStorage#createGateway(io.apiman.manager.api.beans.gateways.GatewayBean)
*/
@Override
public void createGateway(GatewayBean gateway) throws StorageException {
super.create(gateway);
}
/**
* @see io.apiman.manager.api.core.IStorage#createDownload(io.apiman.manager.api.beans.download.DownloadBean)
*/
@Override
public void createDownload(DownloadBean download) throws StorageException {
super.create(download);
}
/**
* @see io.apiman.manager.api.core.IStorage#createPlugin(io.apiman.manager.api.beans.plugins.PluginBean)
*/
@Override
public void createPlugin(PluginBean plugin) throws StorageException {
super.create(plugin);
}
/**
* @see io.apiman.manager.api.core.IStorage#createOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean)
*/
@Override
public void createOrganization(OrganizationBean organization) throws StorageException {
super.create(organization);
}
/**
* @see io.apiman.manager.api.core.IStorage#createPlan(io.apiman.manager.api.beans.plans.PlanBean)
*/
@Override
public void createPlan(PlanBean plan) throws StorageException {
super.create(plan);
}
/**
* @see io.apiman.manager.api.core.IStorage#createPlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean)
*/
@Override
public void createPlanVersion(PlanVersionBean version) throws StorageException {
super.create(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#createPolicy(io.apiman.manager.api.beans.policies.PolicyBean)
*/
@Override
public void createPolicy(PolicyBean policy) throws StorageException {
super.create(policy);
}
/**
* @see io.apiman.manager.api.core.IStorage#createPolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean)
*/
@Override
public void createPolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException {
super.create(policyDef);
}
/**
* @see io.apiman.manager.api.core.IStorage#createApi(io.apiman.manager.api.beans.apis.ApiBean)
*/
@Override
public void createApi(ApiBean api) throws StorageException {
super.create(api);
}
/**
* @see io.apiman.manager.api.core.IStorage#createApiVersion(io.apiman.manager.api.beans.apis.ApiVersionBean)
*/
@Override
public void createApiVersion(ApiVersionBean version) throws StorageException {
super.create(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateClient(io.apiman.manager.api.beans.clients.ClientBean)
*/
@Override
public void updateClient(ClientBean client) throws StorageException {
super.update(client);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateClientVersion(io.apiman.manager.api.beans.clients.ClientVersionBean)
*/
@Override
public void updateClientVersion(ClientVersionBean version) throws StorageException {
super.update(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateGateway(io.apiman.manager.api.beans.gateways.GatewayBean)
*/
@Override
public void updateGateway(GatewayBean gateway) throws StorageException {
super.update(gateway);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean)
*/
@Override
public void updateOrganization(OrganizationBean organization) throws StorageException {
super.update(organization);
}
/**
* @see io.apiman.manager.api.core.IStorage#updatePlan(io.apiman.manager.api.beans.plans.PlanBean)
*/
@Override
public void updatePlan(PlanBean plan) throws StorageException {
super.update(plan);
}
/**
* @see io.apiman.manager.api.core.IStorage#updatePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean)
*/
@Override
public void updatePlanVersion(PlanVersionBean version) throws StorageException {
super.update(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#updatePolicy(io.apiman.manager.api.beans.policies.PolicyBean)
*/
@Override
public void updatePolicy(PolicyBean policy) throws StorageException {
super.update(policy);
}
/**
* @see io.apiman.manager.api.core.IStorage#updatePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean)
*/
@Override
public void updatePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException {
super.update(policyDef);
}
/**
* @see io.apiman.manager.api.core.IStorage#updatePlugin(io.apiman.manager.api.beans.plugins.PluginBean)
*/
@Override
public void updatePlugin(PluginBean pluginBean) throws StorageException {
super.update(pluginBean);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateApi(io.apiman.manager.api.beans.apis.ApiBean)
*/
@Override
public void updateApi(ApiBean api) throws StorageException {
super.update(api);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateApiVersion(io.apiman.manager.api.beans.apis.ApiVersionBean)
*/
@Override
public void updateApiVersion(ApiVersionBean version) throws StorageException {
super.update(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateApiDefinition(io.apiman.manager.api.beans.apis.ApiVersionBean, java.io.InputStream)
*/
@Override
public void updateApiDefinition(ApiVersionBean version, InputStream definitionStream)
throws StorageException {
try {
ApiDefinitionBean bean = super.get(version.getId(), ApiDefinitionBean.class);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
IOUtils.copy(definitionStream, baos);
byte [] data = baos.toByteArray();
if (bean != null) {
bean.setData(data);
super.update(bean);
} else {
bean = new ApiDefinitionBean();
bean.setId(version.getId());
bean.setData(data);
bean.setApiVersion(version);
super.create(bean);
}
} catch (IOException e) {
throw new StorageException(e);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteOrganization(io.apiman.manager.api.beans.orgs.OrganizationBean)
*/
@Override
public void deleteOrganization(OrganizationBean organization) throws StorageException {
// Remove memberships
deleteAllMemberships(organization);
// Remove audit entries (as now orphaned)
deleteAllAuditEntries(organization);
// Remove contracts
deleteAllContracts(organization);
// Remove Policies
deleteAllPolicies(organization);
remove(organization);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteClient(io.apiman.manager.api.beans.clients.ClientBean)
*/
@Override
public void deleteClient(ClientBean client) throws StorageException {
// Remove audit
deleteAllAuditEntries(client);
// Remove contracts
deleteAllContracts(client);
// Remove policies
deleteAllPolicies(client);
remove(client);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteClientVersion(io.apiman.manager.api.beans.clients.ClientVersionBean)
*/
@Override
public void deleteClientVersion(ClientVersionBean version) throws StorageException {
remove(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteContract(io.apiman.manager.api.beans.contracts.ContractBean)
*/
@Override
public void deleteContract(ContractBean contract) throws StorageException {
remove(contract);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteApi(io.apiman.manager.api.beans.apis.ApiBean)
*/
@Override
public void deleteApi(ApiBean api) throws StorageException {
// Remove audit entries (as now orphaned)
deleteAllAuditEntries(api);
// Remove contracts
deleteAllContracts(api);
// Remove policies
deleteAllPolicies(api);
remove(api);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteApiVersion(io.apiman.manager.api.beans.apis.ApiVersionBean)
*/
@Override
public void deleteApiVersion(ApiVersionBean version) throws StorageException {
remove(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteApiDefinition(io.apiman.manager.api.beans.apis.ApiVersionBean)
*/
@Override
public void deleteApiDefinition(ApiVersionBean version) throws StorageException {
ApiDefinitionBean bean = super.get(version.getId(), ApiDefinitionBean.class);
if (bean != null) {
super.delete(bean);
} else {
throw new StorageException("No definition found.");
}
}
/**
* @see io.apiman.manager.api.core.IStorage#deletePlan(io.apiman.manager.api.beans.plans.PlanBean)
*/
@Override
public void deletePlan(PlanBean plan) throws StorageException {
// Delete audit entries
deleteAllAuditEntries(plan);
// Delete entity
super.delete(plan);
}
/**
* @see io.apiman.manager.api.core.IStorage#deletePlanVersion(io.apiman.manager.api.beans.plans.PlanVersionBean)
*/
@Override
public void deletePlanVersion(PlanVersionBean version) throws StorageException {
super.delete(version);
}
/**
* @see io.apiman.manager.api.core.IStorage#deletePolicy(io.apiman.manager.api.beans.policies.PolicyBean)
*/
@Override
public void deletePolicy(PolicyBean policy) throws StorageException {
super.delete(policy);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteGateway(io.apiman.manager.api.beans.gateways.GatewayBean)
*/
@Override
public void deleteGateway(GatewayBean gateway) throws StorageException {
super.delete(gateway);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteDownload(io.apiman.manager.api.beans.download.DownloadBean)
*/
@Override
public void deleteDownload(DownloadBean download) throws StorageException {
super.delete(download);
}
/**
* @see io.apiman.manager.api.core.IStorage#deletePlugin(io.apiman.manager.api.beans.plugins.PluginBean)
*/
@Override
public void deletePlugin(PluginBean plugin) throws StorageException {
super.delete(plugin);
}
/**
* @see io.apiman.manager.api.core.IStorage#deletePolicyDefinition(io.apiman.manager.api.beans.policies.PolicyDefinitionBean)
*/
@Override
public void deletePolicyDefinition(PolicyDefinitionBean policyDef) throws StorageException {
super.delete(policyDef);
}
/**
* @see io.apiman.manager.api.core.IStorage#getOrganization(java.lang.String)
*/
@Override
public OrganizationBean getOrganization(String id) throws StorageException {
return super.get(id, OrganizationBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getClient(java.lang.String, java.lang.String)
*/
@Override
public ClientBean getClient(String organizationId, String id) throws StorageException {
return super.get(organizationId, id, ClientBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getContract(java.lang.Long)
*/
@Override
public ContractBean getContract(Long id) throws StorageException {
return super.get(id, ContractBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getApi(java.lang.String, java.lang.String)
*/
@Override
public ApiBean getApi(String organizationId, String id) throws StorageException {
return super.get(organizationId, id, ApiBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getPlan(java.lang.String, java.lang.String)
*/
@Override
public PlanBean getPlan(String organizationId, String id) throws StorageException {
return super.get(organizationId, id, PlanBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getPolicy(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.lang.Long)
*/
@Override
public PolicyBean getPolicy(PolicyType type, String organizationId, String entityId, String version,
Long id) throws StorageException {
PolicyBean policyBean = super.get(id, PolicyBean.class);
if (policyBean == null || policyBean.getType() != type) {
return null;
}
if (!policyBean.getOrganizationId().equals(organizationId)) {
return null;
}
if (!policyBean.getEntityId().equals(entityId)) {
return null;
}
if (!policyBean.getEntityVersion().equals(version)) {
return null;
}
return policyBean;
}
/**
* @see io.apiman.manager.api.core.IStorage#getGateway(java.lang.String)
*/
@Override
public GatewayBean getGateway(String id) throws StorageException {
return super.get(id, GatewayBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getDownload(java.lang.String)
*/
@Override
public DownloadBean getDownload(String id) throws StorageException {
return super.get(id, DownloadBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getPlugin(long)
*/
@Override
public PluginBean getPlugin(long id) throws StorageException {
return super.get(id, PluginBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#getPlugin(java.lang.String, java.lang.String)
*/
@Override
public PluginBean getPlugin(String groupId, String artifactId) throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
String sql =
"SELECT p.id, p.artifact_id, p.group_id, p.version, p.classifier, p.type, p.name, p.description, p.created_by, p.created_on, p.deleted" +
" FROM plugins p" +
" WHERE p.group_id = ? AND p.artifact_id = ?";
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, groupId);
query.setParameter(2, artifactId);
List<Object[]> rows = query.getResultList();
if (!rows.isEmpty()) {
Object[] row = rows.get(0);
PluginBean plugin = new PluginBean();
plugin.setId(((Number) row[0]).longValue());
plugin.setArtifactId(String.valueOf(row[1]));
plugin.setGroupId(String.valueOf(row[2]));
plugin.setVersion(String.valueOf(row[3]));
plugin.setClassifier((String) row[4]);
plugin.setType((String) row[5]);
plugin.setName(String.valueOf(row[6]));
plugin.setDescription(String.valueOf(row[7]));
plugin.setCreatedBy(String.valueOf(row[8]));
plugin.setCreatedOn((Date) row[9]);
plugin.setDeleted((Boolean) row[10]);
return plugin;
} else {
return null;
}
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getPolicyDefinition(java.lang.String)
*/
@Override
public PolicyDefinitionBean getPolicyDefinition(String id) throws StorageException {
return super.get(id, PolicyDefinitionBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#reorderPolicies(io.apiman.manager.api.beans.policies.PolicyType, java.lang.String, java.lang.String, java.lang.String, java.util.List)
*/
@Override
public void reorderPolicies(PolicyType type, String organizationId, String entityId,
String entityVersion, List<Long> newOrder) throws StorageException {
int orderIndex = 0;
for (Long policyId : newOrder) {
PolicyBean storedPolicy = getPolicy(type, organizationId, entityId, entityVersion, policyId);
if (storedPolicy == null) {
throw new StorageException("Invalid policy id: " + policyId);
}
storedPolicy.setOrderIndex(orderIndex++);
updatePolicy(storedPolicy);
}
}
/**
* @see io.apiman.manager.api.jpa.AbstractJpaStorage#find(io.apiman.manager.api.beans.search.SearchCriteriaBean, java.lang.Class)
*/
@Override
protected <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, Class<T> type) throws StorageException {
beginTx();
try {
SearchResultsBean<T> rval = super.find(criteria, type);
return rval;
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findOrganizations(io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<OrganizationSummaryBean> findOrganizations(SearchCriteriaBean criteria)
throws StorageException {
SearchResultsBean<OrganizationBean> orgs = find(criteria, OrganizationBean.class);
SearchResultsBean<OrganizationSummaryBean> rval = new SearchResultsBean<>();
rval.setTotalSize(orgs.getTotalSize());
List<OrganizationBean> beans = orgs.getBeans();
for (OrganizationBean bean : beans) {
OrganizationSummaryBean osb = new OrganizationSummaryBean();
osb.setId(bean.getId());
osb.setName(bean.getName());
osb.setDescription(bean.getDescription());
rval.getBeans().add(osb);
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findClients(io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<ClientSummaryBean> findClients(SearchCriteriaBean criteria)
throws StorageException {
SearchResultsBean<ClientBean> result = find(criteria, ClientBean.class);
SearchResultsBean<ClientSummaryBean> rval = new SearchResultsBean<>();
rval.setTotalSize(result.getTotalSize());
List<ClientBean> beans = result.getBeans();
rval.setBeans(new ArrayList<>(beans.size()));
for (ClientBean client : beans) {
ClientSummaryBean summary = new ClientSummaryBean();
OrganizationBean organization = client.getOrganization();
summary.setId(client.getId());
summary.setName(client.getName());
summary.setDescription(client.getDescription());
// TODO find the number of contracts - probably need native SQL for that
summary.setNumContracts(0);
summary.setOrganizationId(client.getOrganization().getId());
summary.setOrganizationName(organization.getName());
rval.getBeans().add(summary);
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findApis(io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<ApiSummaryBean> findApis(SearchCriteriaBean criteria)
throws StorageException {
SearchResultsBean<ApiBean> result = find(criteria, ApiBean.class);
SearchResultsBean<ApiSummaryBean> rval = new SearchResultsBean<>();
rval.setTotalSize(result.getTotalSize());
List<ApiBean> beans = result.getBeans();
rval.setBeans(new ArrayList<>(beans.size()));
for (ApiBean api : beans) {
ApiSummaryBean summary = new ApiSummaryBean();
OrganizationBean organization = api.getOrganization();
summary.setId(api.getId());
summary.setName(api.getName());
summary.setDescription(api.getDescription());
summary.setCreatedOn(api.getCreatedOn());
summary.setOrganizationId(api.getOrganization().getId());
summary.setOrganizationName(organization.getName());
rval.getBeans().add(summary);
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findPlans(java.lang.String, io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<PlanSummaryBean> findPlans(String organizationId, SearchCriteriaBean criteria)
throws StorageException {
criteria.addFilter("organization.id", organizationId, SearchCriteriaFilterOperator.eq);
SearchResultsBean<PlanBean> result = find(criteria, PlanBean.class);
SearchResultsBean<PlanSummaryBean> rval = new SearchResultsBean<>();
rval.setTotalSize(result.getTotalSize());
List<PlanBean> plans = result.getBeans();
rval.setBeans(new ArrayList<>(plans.size()));
for (PlanBean plan : plans) {
PlanSummaryBean summary = new PlanSummaryBean();
OrganizationBean organization = plan.getOrganization();
summary.setId(plan.getId());
summary.setName(plan.getName());
summary.setDescription(plan.getDescription());
summary.setOrganizationId(plan.getOrganization().getId());
summary.setOrganizationName(organization.getName());
rval.getBeans().add(summary);
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorage#createAuditEntry(io.apiman.manager.api.beans.audit.AuditEntryBean)
*/
@Override
public void createAuditEntry(AuditEntryBean entry) throws StorageException {
super.create(entry);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#auditEntity(java.lang.String, java.lang.String, java.lang.String, java.lang.Class, io.apiman.manager.api.beans.search.PagingBean)
*/
@Override
public <T> SearchResultsBean<AuditEntryBean> auditEntity(String organizationId, String entityId, String entityVersion,
Class<T> type, PagingBean paging) throws StorageException {
SearchCriteriaBean criteria = new SearchCriteriaBean();
if (paging != null) {
criteria.setPaging(paging);
} else {
criteria.setPage(1);
criteria.setPageSize(20);
}
criteria.setOrder("id", false);
if (organizationId != null) {
criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq);
}
if (entityId != null) {
criteria.addFilter("entityId", entityId, SearchCriteriaFilterOperator.eq);
}
if (entityVersion != null) {
criteria.addFilter("entityVersion", entityVersion, SearchCriteriaFilterOperator.eq);
}
if (type != null) {
AuditEntityType entityType = null;
if (type == OrganizationBean.class) {
entityType = AuditEntityType.Organization;
} else if (type == ClientBean.class) {
entityType = AuditEntityType.Client;
} else if (type == ApiBean.class) {
entityType = AuditEntityType.Api;
} else if (type == PlanBean.class) {
entityType = AuditEntityType.Plan;
}
if (entityType != null) {
criteria.addFilter("entityType", entityType.name(), SearchCriteriaFilterOperator.eq);
}
}
return find(criteria, AuditEntryBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#auditUser(java.lang.String, io.apiman.manager.api.beans.search.PagingBean)
*/
@Override
public <T> SearchResultsBean<AuditEntryBean> auditUser(String userId, PagingBean paging)
throws StorageException {
SearchCriteriaBean criteria = new SearchCriteriaBean();
if (paging != null) {
criteria.setPaging(paging);
} else {
criteria.setPage(1);
criteria.setPageSize(20);
}
criteria.setOrder("createdOn", false);
if (userId != null) {
criteria.addFilter("who", userId, SearchCriteriaFilterOperator.eq);
}
return find(criteria, AuditEntryBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#listGateways()
*/
@Override
public List<GatewaySummaryBean> listGateways() throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String sql =
"SELECT g.id, g.name, g.description, g.type" +
" FROM gateways g" +
" ORDER BY g.name ASC";
Query query = entityManager.createNativeQuery(sql);
List<Object[]> rows = query.getResultList();
List<GatewaySummaryBean> gateways = new ArrayList<>(rows.size());
for (Object [] row : rows) {
GatewaySummaryBean gateway = new GatewaySummaryBean();
gateway.setId(String.valueOf(row[0]));
gateway.setName(String.valueOf(row[1]));
gateway.setDescription(String.valueOf(row[2]));
gateway.setType(GatewayType.valueOf(String.valueOf(row[3])));
gateways.add(gateway);
}
return gateways;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#listPlugins()
*/
@Override
public List<PluginSummaryBean> listPlugins() throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String sql =
"SELECT p.id, p.artifact_id, p.group_id, p.version, p.classifier, p.type, p.name, p.description, p.created_by, p.created_on" +
" FROM plugins p" +
" WHERE p.deleted IS NULL OR p.deleted = 0" +
" ORDER BY p.name ASC";
Query query = entityManager.createNativeQuery(sql);
List<Object[]> rows = query.getResultList();
List<PluginSummaryBean> plugins = new ArrayList<>(rows.size());
for (Object [] row : rows) {
PluginSummaryBean plugin = new PluginSummaryBean();
plugin.setId(((Number) row[0]).longValue());
plugin.setArtifactId(String.valueOf(row[1]));
plugin.setGroupId(String.valueOf(row[2]));
plugin.setVersion(String.valueOf(row[3]));
plugin.setClassifier((String) row[4]);
plugin.setType((String) row[5]);
plugin.setName(String.valueOf(row[6]));
plugin.setDescription(String.valueOf(row[7]));
plugin.setCreatedBy(String.valueOf(row[8]));
plugin.setCreatedOn((Date) row[9]);
plugins.add(plugin);
}
return plugins;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#listPolicyDefinitions()
*/
@Override
public List<PolicyDefinitionSummaryBean> listPolicyDefinitions() throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String sql =
"SELECT pd.id, pd.policy_impl, pd.name, pd.description, pd.icon, pd.plugin_id, pd.form_type" +
" FROM policydefs pd" +
" WHERE pd.deleted IS NULL OR pd.deleted = 0" +
" ORDER BY pd.name ASC";
Query query = entityManager.createNativeQuery(sql);
List<Object[]> rows = query.getResultList();
List<PolicyDefinitionSummaryBean> rval = new ArrayList<>(rows.size());
for (Object [] row : rows) {
PolicyDefinitionSummaryBean bean = new PolicyDefinitionSummaryBean();
bean.setId(String.valueOf(row[0]));
bean.setPolicyImpl(String.valueOf(row[1]));
bean.setName(String.valueOf(row[2]));
bean.setDescription(String.valueOf(row[3]));
bean.setIcon(String.valueOf(row[4]));
if (row[5] != null) {
bean.setPluginId(((Number) row[5]).longValue());
}
if (row[6] != null) {
bean.setFormType(PolicyFormType.valueOf(String.valueOf(row[6])));
}
rval.add(bean);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getOrgs(java.util.Set)
*/
@Override
public List<OrganizationSummaryBean> getOrgs(Set<String> orgIds) throws StorageException {
List<OrganizationSummaryBean> orgs = new ArrayList<>();
if (orgIds == null || orgIds.isEmpty()) {
return orgs;
}
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT o from OrganizationBean o WHERE o.id IN :orgs ORDER BY o.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgs", orgIds);
List<OrganizationBean> qr = query.getResultList();
for (OrganizationBean bean : qr) {
OrganizationSummaryBean summary = new OrganizationSummaryBean();
summary.setId(bean.getId());
summary.setName(bean.getName());
summary.setDescription(bean.getDescription());
orgs.add(summary);
}
return orgs;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getClientsInOrg(java.lang.String)
*/
@Override
public List<ClientSummaryBean> getClientsInOrg(String orgId) throws StorageException {
Set<String> orgIds = new HashSet<>();
orgIds.add(orgId);
return getClientsInOrgs(orgIds);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getClientsInOrgs(java.util.Set)
*/
@Override
public List<ClientSummaryBean> getClientsInOrgs(Set<String> orgIds) throws StorageException {
List<ClientSummaryBean> rval = new ArrayList<>();
if (orgIds == null || orgIds.isEmpty()) {
return rval;
}
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT a FROM ClientBean a JOIN a.organization o WHERE o.id IN :orgs ORDER BY a.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgs", orgIds);
List<ClientBean> qr = query.getResultList();
for (ClientBean bean : qr) {
ClientSummaryBean summary = new ClientSummaryBean();
summary.setId(bean.getId());
summary.setName(bean.getName());
summary.setDescription(bean.getDescription());
// TODO find the number of contracts - probably need a native SQL query to pull that together
summary.setNumContracts(0);
OrganizationBean org = bean.getOrganization();
summary.setOrganizationId(org.getId());
summary.setOrganizationName(org.getName());
rval.add(summary);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getApisInOrg(java.lang.String)
*/
@Override
public List<ApiSummaryBean> getApisInOrg(String orgId) throws StorageException {
Set<String> orgIds = new HashSet<>();
orgIds.add(orgId);
return getApisInOrgs(orgIds);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getApisInOrgs(java.util.Set)
*/
@Override
public List<ApiSummaryBean> getApisInOrgs(Set<String> orgIds) throws StorageException {
List<ApiSummaryBean> rval = new ArrayList<>();
if (orgIds == null || orgIds.isEmpty()) {
return rval;
}
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT a FROM ApiBean a JOIN a.organization o WHERE o.id IN :orgs ORDER BY a.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgs", orgIds);
List<ApiBean> qr = query.getResultList();
for (ApiBean bean : qr) {
ApiSummaryBean summary = new ApiSummaryBean();
summary.setId(bean.getId());
summary.setName(bean.getName());
summary.setDescription(bean.getDescription());
summary.setCreatedOn(bean.getCreatedOn());
OrganizationBean org = bean.getOrganization();
summary.setOrganizationId(org.getId());
summary.setOrganizationName(org.getName());
rval.add(summary);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getApiVersion(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public ApiVersionBean getApiVersion(String orgId, String apiId, String version)
throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v from ApiVersionBean v JOIN v.api s JOIN s.organization o WHERE o.id = :orgId AND s.id = :apiId AND v.version = :version";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", orgId);
query.setParameter("apiId", apiId);
query.setParameter("version", version);
return (ApiVersionBean) query.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getApiDefinition(io.apiman.manager.api.beans.apis.ApiVersionBean)
*/
@Override
public InputStream getApiDefinition(ApiVersionBean apiVersion) throws StorageException {
ApiDefinitionBean bean = super.get(apiVersion.getId(), ApiDefinitionBean.class);
if (bean == null) {
return null;
} else {
return new ByteArrayInputStream(bean.getData());
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getApiVersions(java.lang.String, java.lang.String)
*/
@Override
public List<ApiVersionSummaryBean> getApiVersions(String orgId, String apiId)
throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT v "
+ " FROM ApiVersionBean v"
+ " JOIN v.api s"
+ " JOIN s.organization o"
+ " WHERE o.id = :orgId"
+ " AND s.id = :apiId"
+ " ORDER BY v.createdOn DESC";
Query query = entityManager.createQuery(jpql);
query.setMaxResults(500);
query.setParameter("orgId", orgId);
query.setParameter("apiId", apiId);
List<ApiVersionBean> apiVersions = query.getResultList();
List<ApiVersionSummaryBean> rval = new ArrayList<>(apiVersions.size());
for (ApiVersionBean apiVersion : apiVersions) {
ApiVersionSummaryBean svsb = new ApiVersionSummaryBean();
svsb.setOrganizationId(apiVersion.getApi().getOrganization().getId());
svsb.setOrganizationName(apiVersion.getApi().getOrganization().getName());
svsb.setId(apiVersion.getApi().getId());
svsb.setName(apiVersion.getApi().getName());
svsb.setDescription(apiVersion.getApi().getDescription());
svsb.setVersion(apiVersion.getVersion());
svsb.setStatus(apiVersion.getStatus());
svsb.setPublicAPI(apiVersion.isPublicAPI());
rval.add(svsb);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getApiVersionPlans(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public List<ApiPlanSummaryBean> getApiVersionPlans(String organizationId, String apiId,
String version) throws StorageException {
List<ApiPlanSummaryBean> plans = new ArrayList<>();
beginTx();
try {
ApiVersionBean versionBean = getApiVersion(organizationId, apiId, version);
Set<ApiPlanBean> apiPlans = versionBean.getPlans();
if (apiPlans != null) {
for (ApiPlanBean spb : apiPlans) {
PlanVersionBean planVersion = getPlanVersion(organizationId, spb.getPlanId(), spb.getVersion());
ApiPlanSummaryBean summary = new ApiPlanSummaryBean();
summary.setPlanId(planVersion.getPlan().getId());
summary.setPlanName(planVersion.getPlan().getName());
summary.setPlanDescription(planVersion.getPlan().getDescription());
summary.setVersion(spb.getVersion());
plans.add(summary);
}
}
return plans;
} catch (StorageException e) {
throw e;
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getContracts(java.lang.String, java.lang.String, java.lang.String, int, int)
*/
@Override
public List<ContractSummaryBean> getContracts(String organizationId, String apiId,
String version, int page, int pageSize) throws StorageException {
int start = (page - 1) * pageSize;
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.api apiv " +
" JOIN apiv.api api " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN api.organization sorg" +
" JOIN client.organization aorg" +
" WHERE api.id = :apiId " +
" AND sorg.id = :orgId " +
" AND apiv.version = :version " +
" ORDER BY sorg.id, api.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("apiId", apiId);
query.setParameter("version", version);
query.setFirstResult(start);
query.setMaxResults(pageSize);
List<ContractBean> contracts = query.getResultList();
List<ContractSummaryBean> rval = new ArrayList<>(contracts.size());
for (ContractBean contractBean : contracts) {
ClientBean client = contractBean.getClient().getClient();
ApiBean api = contractBean.getApi().getApi();
PlanBean plan = contractBean.getPlan().getPlan();
OrganizationBean clientOrg = entityManager.find(OrganizationBean.class, client.getOrganization().getId());
OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());
ContractSummaryBean csb = new ContractSummaryBean();
csb.setClientId(client.getId());
csb.setClientOrganizationId(client.getOrganization().getId());
csb.setClientOrganizationName(clientOrg.getName());
csb.setClientName(client.getName());
csb.setClientVersion(contractBean.getClient().getVersion());
csb.setContractId(contractBean.getId());
csb.setCreatedOn(contractBean.getCreatedOn());
csb.setPlanId(plan.getId());
csb.setPlanName(plan.getName());
csb.setPlanVersion(contractBean.getPlan().getVersion());
csb.setApiDescription(api.getDescription());
csb.setApiId(api.getId());
csb.setApiName(api.getName());
csb.setApiOrganizationId(apiOrg.getId());
csb.setApiOrganizationName(apiOrg.getName());
csb.setApiVersion(contractBean.getApi().getVersion());
rval.add(csb);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getClientVersion(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public ClientVersionBean getClientVersion(String orgId, String clientId, String version)
throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v from ClientVersionBean v JOIN v.client a JOIN a.organization o WHERE o.id = :orgId AND a.id = :clientId AND v.version = :version";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", orgId);
query.setParameter("clientId", clientId);
query.setParameter("version", version);
return (ClientVersionBean) query.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getClientVersions(java.lang.String, java.lang.String)
*/
@Override
public List<ClientVersionSummaryBean> getClientVersions(String orgId, String clientId)
throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT v"
+ " FROM ClientVersionBean v"
+ " JOIN v.client a"
+ " JOIN a.organization o"
+ " WHERE o.id = :orgId"
+ " AND a.id = :clientId"
+ " ORDER BY v.createdOn DESC";
Query query = entityManager.createQuery(jpql);
query.setMaxResults(500);
query.setParameter("orgId", orgId);
query.setParameter("clientId", clientId);
List<ClientVersionBean> clientVersions = query.getResultList();
List<ClientVersionSummaryBean> rval = new ArrayList<>();
for (ClientVersionBean clientVersion : clientVersions) {
ClientVersionSummaryBean avsb = new ClientVersionSummaryBean();
avsb.setOrganizationId(clientVersion.getClient().getOrganization().getId());
avsb.setOrganizationName(clientVersion.getClient().getOrganization().getName());
avsb.setId(clientVersion.getClient().getId());
avsb.setName(clientVersion.getClient().getName());
avsb.setDescription(clientVersion.getClient().getDescription());
avsb.setVersion(clientVersion.getVersion());
avsb.setApiKey(clientVersion.getApikey());
avsb.setStatus(clientVersion.getStatus());
rval.add(avsb);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getClientContracts(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public List<ContractSummaryBean> getClientContracts(String organizationId, String clientId,
String version) throws StorageException {
beginTx();
try {
return getClientContractsInternal(organizationId, clientId, version);
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* Returns a list of all contracts for the given client.
* @param organizationId
* @param clientId
* @param version
* @throws StorageException
*/
protected List<ContractSummaryBean> getClientContractsInternal(String organizationId, String clientId,
String version) throws StorageException {
List<ContractSummaryBean> rval = new ArrayList<>();
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN client.organization aorg" +
" WHERE client.id = :clientId " +
" AND aorg.id = :orgId " +
" AND clientv.version = :version " +
" ORDER BY aorg.id, client.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId); //$NON-NLS-1$
query.setParameter("clientId", clientId); //$NON-NLS-1$
query.setParameter("version", version); //$NON-NLS-1$
List<ContractBean> contracts = query.getResultList();
for (ContractBean contractBean : contracts) {
ClientBean client = contractBean.getClient().getClient();
ApiBean api = contractBean.getApi().getApi();
PlanBean plan = contractBean.getPlan().getPlan();
OrganizationBean clientOrg = entityManager.find(OrganizationBean.class, client.getOrganization().getId());
OrganizationBean apiOrg = entityManager.find(OrganizationBean.class, api.getOrganization().getId());
ContractSummaryBean csb = new ContractSummaryBean();
csb.setClientId(client.getId());
csb.setClientOrganizationId(client.getOrganization().getId());
csb.setClientOrganizationName(clientOrg.getName());
csb.setClientName(client.getName());
csb.setClientVersion(contractBean.getClient().getVersion());
csb.setContractId(contractBean.getId());
csb.setCreatedOn(contractBean.getCreatedOn());
csb.setPlanId(plan.getId());
csb.setPlanName(plan.getName());
csb.setPlanVersion(contractBean.getPlan().getVersion());
csb.setApiDescription(api.getDescription());
csb.setApiId(api.getId());
csb.setApiName(api.getName());
csb.setApiOrganizationId(apiOrg.getId());
csb.setApiOrganizationName(apiOrg.getName());
csb.setApiVersion(contractBean.getApi().getVersion());
rval.add(csb);
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getApiRegistry(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public ApiRegistryBean getApiRegistry(String organizationId, String clientId, String version)
throws StorageException {
ApiRegistryBean rval = new ApiRegistryBean();
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN client.organization aorg" +
" WHERE client.id = :clientId " +
" AND aorg.id = :orgId " +
" AND clientv.version = :version " +
" ORDER BY c.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("clientId", clientId);
query.setParameter("version", version);
List<ContractBean> contracts = query.getResultList();
for (ContractBean contractBean : contracts) {
ApiVersionBean svb = contractBean.getApi();
ApiBean api = svb.getApi();
PlanBean plan = contractBean.getPlan().getPlan();
OrganizationBean apiOrg = api.getOrganization();
ApiEntryBean entry = new ApiEntryBean();
entry.setApiId(api.getId());
entry.setApiName(api.getName());
entry.setApiOrgId(apiOrg.getId());
entry.setApiOrgName(apiOrg.getName());
entry.setApiVersion(svb.getVersion());
entry.setPlanId(plan.getId());
entry.setPlanName(plan.getName());
entry.setPlanVersion(contractBean.getPlan().getVersion());
Set<ApiGatewayBean> gateways = svb.getGateways();
if (gateways != null && !gateways.isEmpty()) {
ApiGatewayBean sgb = gateways.iterator().next();
entry.setGatewayId(sgb.getGatewayId());
}
rval.getApis().add(entry);
}
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
return rval;
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrg(java.lang.String)
*/
@Override
public List<PlanSummaryBean> getPlansInOrg(String orgId) throws StorageException {
Set<String> orgIds = new HashSet<>();
orgIds.add(orgId);
return getPlansInOrgs(orgIds);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getPlansInOrgs(java.util.Set)
*/
@Override
public List<PlanSummaryBean> getPlansInOrgs(Set<String> orgIds) throws StorageException {
List<PlanSummaryBean> rval = new ArrayList<>();
if (orgIds == null || orgIds.isEmpty()) {
return rval;
}
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT p FROM PlanBean p JOIN p.organization o WHERE o.id IN :orgs ORDER BY p.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgs", orgIds);
query.setMaxResults(500);
List<PlanBean> qr = query.getResultList();
for (PlanBean bean : qr) {
PlanSummaryBean summary = new PlanSummaryBean();
summary.setId(bean.getId());
summary.setName(bean.getName());
summary.setDescription(bean.getDescription());
OrganizationBean org = bean.getOrganization();
summary.setOrganizationId(org.getId());
summary.setOrganizationName(org.getName());
rval.add(summary);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getPlanVersion(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public PlanVersionBean getPlanVersion(String orgId, String planId, String version)
throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v from PlanVersionBean v JOIN v.plan p JOIN p.organization o WHERE o.id = :orgId AND p.id = :planId AND v.version = :version";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", orgId);
query.setParameter("planId", planId);
query.setParameter("version", version);
return (PlanVersionBean) query.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getPlanVersions(java.lang.String, java.lang.String)
*/
@Override
public List<PlanVersionSummaryBean> getPlanVersions(String orgId, String planId) throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v from PlanVersionBean v" +
" JOIN v.plan p" +
" JOIN p.organization o" +
" WHERE o.id = :orgId" +
" AND p.id = :planId" +
" ORDER BY v.createdOn DESC";
Query query = entityManager.createQuery(jpql);
query.setMaxResults(500);
query.setParameter("orgId", orgId);
query.setParameter("planId", planId);
List<PlanVersionBean> planVersions = query.getResultList();
List<PlanVersionSummaryBean> rval = new ArrayList<>(planVersions.size());
for (PlanVersionBean planVersion : planVersions) {
PlanVersionSummaryBean pvsb = new PlanVersionSummaryBean();
pvsb.setOrganizationId(planVersion.getPlan().getOrganization().getId());
pvsb.setOrganizationName(planVersion.getPlan().getOrganization().getName());
pvsb.setId(planVersion.getPlan().getId());
pvsb.setName(planVersion.getPlan().getName());
pvsb.setDescription(planVersion.getPlan().getDescription());
pvsb.setVersion(planVersion.getVersion());
pvsb.setStatus(planVersion.getStatus());
rval.add(pvsb);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getPolicies(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType)
*/
@Override
public List<PolicySummaryBean> getPolicies(String organizationId, String entityId, String version,
PolicyType type) throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT p from PolicyBean p "
+ " WHERE p.organizationId = :orgId "
+ " AND p.entityId = :entityId "
+ " AND p.entityVersion = :entityVersion "
+ " AND p.type = :type"
+ " ORDER BY p.orderIndex ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("entityId", entityId);
query.setParameter("entityVersion", version);
query.setParameter("type", type);
List<PolicyBean> policyBeans = query.getResultList();
List<PolicySummaryBean> rval = new ArrayList<>(policyBeans.size());
for (PolicyBean policyBean : policyBeans) {
PolicyTemplateUtil.generatePolicyDescription(policyBean);
PolicySummaryBean psb = new PolicySummaryBean();
psb.setId(policyBean.getId());
psb.setName(policyBean.getName());
psb.setDescription(policyBean.getDescription());
psb.setPolicyDefinitionId(policyBean.getDefinition().getId());
psb.setIcon(policyBean.getDefinition().getIcon());
psb.setCreatedBy(policyBean.getCreatedBy());
psb.setCreatedOn(policyBean.getCreatedOn());
rval.add(psb);
}
return rval;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getMaxPolicyOrderIndex(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType)
*/
@Override
public int getMaxPolicyOrderIndex(String organizationId, String entityId, String entityVersion,
PolicyType type) throws StorageException {
SearchCriteriaBean criteria = new SearchCriteriaBean();
criteria.addFilter("organizationId", organizationId, SearchCriteriaFilterOperator.eq);
criteria.addFilter("entityId", entityId, SearchCriteriaFilterOperator.eq);
criteria.addFilter("entityVersion", entityVersion, SearchCriteriaFilterOperator.eq);
criteria.addFilter("type", type.name(), SearchCriteriaFilterOperator.eq);
criteria.setOrder("orderIndex", false);
criteria.setPage(1);
criteria.setPageSize(1);
SearchResultsBean<PolicyBean> resultsBean = find(criteria, PolicyBean.class);
if (resultsBean.getBeans() == null || resultsBean.getBeans().isEmpty()) {
return 0;
} else {
return resultsBean.getBeans().get(0).getOrderIndex();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#listPluginPolicyDefs(java.lang.Long)
*/
@Override
public List<PolicyDefinitionSummaryBean> listPluginPolicyDefs(Long pluginId) throws StorageException {
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
String sql =
"SELECT pd.id, pd.policy_impl, pd.name, pd.description, pd.icon, pd.plugin_id, pd.form_type" +
" FROM policydefs pd" +
" WHERE pd.plugin_id = ?" +
" ORDER BY pd.name ASC";
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, pluginId);
List<Object[]> rows = query.getResultList();
List<PolicyDefinitionSummaryBean> beans = new ArrayList<>(rows.size());
for (Object [] row : rows) {
PolicyDefinitionSummaryBean bean = new PolicyDefinitionSummaryBean();
bean.setId(String.valueOf(row[0]));
bean.setPolicyImpl(String.valueOf(row[1]));
bean.setName(String.valueOf(row[2]));
bean.setDescription(String.valueOf(row[3]));
bean.setIcon(String.valueOf(row[4]));
if (row[5] != null) {
bean.setPluginId(((Number) row[5]).longValue());
}
if (row[6] != null) {
bean.setFormType(PolicyFormType.valueOf(String.valueOf(row[6])));
}
beans.add(bean);
}
return beans;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#createUser(io.apiman.manager.api.beans.idm.UserBean)
*/
@Override
public void createUser(UserBean user) throws StorageException {
super.create(user);
}
/**
* @see io.apiman.manager.api.core.IStorage#getUser(java.lang.String)
*/
@Override
public UserBean getUser(String userId) throws StorageException {
return super.get(userId, UserBean.class);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateUser(io.apiman.manager.api.beans.idm.UserBean)
*/
@Override
public void updateUser(UserBean user) throws StorageException {
super.update(user);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findUsers(io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<UserBean> findUsers(SearchCriteriaBean criteria) throws StorageException {
beginTx();
try {
return super.find(criteria, UserBean.class);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#createRole(io.apiman.manager.api.beans.idm.RoleBean)
*/
@Override
public void createRole(RoleBean role) throws StorageException {
super.create(role);
}
/**
* @see io.apiman.manager.api.core.IStorage#updateRole(io.apiman.manager.api.beans.idm.RoleBean)
*/
@Override
public void updateRole(RoleBean role) throws StorageException {
super.update(role);
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteRole(io.apiman.manager.api.beans.idm.RoleBean)
*/
@Override
public void deleteRole(RoleBean role) throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
RoleBean prole = get(role.getId(), RoleBean.class);
// First delete all memberships in this role
Query query = entityManager.createQuery("DELETE from RoleMembershipBean m WHERE m.roleId = :roleId" );
query.setParameter("roleId", role.getId());
query.executeUpdate();
// Then delete the role itself.
super.delete(prole);
} catch (Throwable t) {
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#getRole(java.lang.String)
*/
@Override
public RoleBean getRole(String roleId) throws StorageException {
return getRoleInternal(roleId);
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#findRoles(io.apiman.manager.api.beans.search.SearchCriteriaBean)
*/
@Override
public SearchResultsBean<RoleBean> findRoles(SearchCriteriaBean criteria) throws StorageException {
beginTx();
try {
return super.find(criteria, RoleBean.class);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorage#createMembership(io.apiman.manager.api.beans.idm.RoleMembershipBean)
*/
@Override
public void createMembership(RoleMembershipBean membership) throws StorageException {
super.create(membership);
}
/**
* @see io.apiman.manager.api.core.IStorage#getMembership(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public RoleMembershipBean getMembership(String userId, String roleId, String organizationId) throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
Query query = entityManager.createQuery("SELECT m FROM RoleMembershipBean m WHERE m.roleId = :roleId AND m.userId = :userId AND m.organizationId = :orgId" );
query.setParameter("roleId", roleId);
query.setParameter("userId", userId);
query.setParameter("orgId", organizationId);
RoleMembershipBean bean = null;
List<?> resultList = query.getResultList();
if (!resultList.isEmpty()) {
bean = (RoleMembershipBean) resultList.iterator().next();
}
return bean;
} catch (Throwable t) {
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteMembership(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void deleteMembership(String userId, String roleId, String organizationId) throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
Query query = entityManager.createQuery("DELETE FROM RoleMembershipBean m WHERE m.roleId = :roleId AND m.userId = :userId AND m.organizationId = :orgId" );
query.setParameter("roleId", roleId);
query.setParameter("userId", userId);
query.setParameter("orgId", organizationId);
query.executeUpdate();
} catch (Throwable t) {
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorage#deleteMemberships(java.lang.String, java.lang.String)
*/
@Override
public void deleteMemberships(String userId, String organizationId) throws StorageException {
try {
EntityManager entityManager = getActiveEntityManager();
Query query = entityManager.createQuery("DELETE FROM RoleMembershipBean m WHERE m.userId = :userId AND m.organizationId = :orgId" );
query.setParameter("userId", userId);
query.setParameter("orgId", organizationId);
query.executeUpdate();
} catch (Throwable t) {
throw new StorageException(t);
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String)
*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId) throws StorageException {
Set<RoleMembershipBean> memberships = new HashSet<>();
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
criteriaQuery.where(builder.equal(from.get("userId"), userId));
TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
List<RoleMembershipBean> resultList = typedQuery.getResultList();
memberships.addAll(resultList);
return memberships;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getUserMemberships(java.lang.String, java.lang.String)
*/
@Override
public Set<RoleMembershipBean> getUserMemberships(String userId, String organizationId) throws StorageException {
Set<RoleMembershipBean> memberships = new HashSet<>();
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
criteriaQuery.where(
builder.equal(from.get("userId"), userId),
builder.equal(from.get("organizationId"), organizationId) );
TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
List<RoleMembershipBean> resultList = typedQuery.getResultList();
memberships.addAll(resultList);
return memberships;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getOrgMemberships(java.lang.String)
*/
@Override
public Set<RoleMembershipBean> getOrgMemberships(String organizationId) throws StorageException {
Set<RoleMembershipBean> memberships = new HashSet<>();
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
criteriaQuery.where(builder.equal(from.get("organizationId"), organizationId));
TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
List<RoleMembershipBean> resultList = typedQuery.getResultList();
memberships.addAll(resultList);
return memberships;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @see io.apiman.manager.api.core.IStorageQuery#getPermissions(java.lang.String)
*/
@Override
public Set<PermissionBean> getPermissions(String userId) throws StorageException {
Set<PermissionBean> permissions = new HashSet<>();
beginTx();
try {
EntityManager entityManager = getActiveEntityManager();
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<RoleMembershipBean> criteriaQuery = builder.createQuery(RoleMembershipBean.class);
Root<RoleMembershipBean> from = criteriaQuery.from(RoleMembershipBean.class);
criteriaQuery.where(builder.equal(from.get("userId"), userId));
TypedQuery<RoleMembershipBean> typedQuery = entityManager.createQuery(criteriaQuery);
typedQuery.setMaxResults(500);
List<RoleMembershipBean> resultList = typedQuery.getResultList();
for (RoleMembershipBean membership : resultList) {
RoleBean role = getRoleInternal(membership.getRoleId());
String qualifier = membership.getOrganizationId();
for (PermissionType permission : role.getPermissions()) {
PermissionBean p = new PermissionBean();
p.setName(permission);
p.setOrganizationId(qualifier);
permissions.add(p);
}
}
return permissions;
} catch (Throwable t) {
logger.error(t.getMessage(), t);
throw new StorageException(t);
} finally {
rollbackTx();
}
}
/**
* @param roleId the role id
* @return a role by id
* @throws StorageException
*/
protected RoleBean getRoleInternal(String roleId) throws StorageException {
return super.get(roleId, RoleBean.class);
}
@Override
public Iterator<OrganizationBean> getAllOrganizations() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jqpl = "SELECT b FROM OrganizationBean b ORDER BY b.id ASC";
Query query = entityManager.createQuery(jqpl);
return super.getAll(OrganizationBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllPlans(java.lang.String)
*/
@Override
public Iterator<PlanBean> getAllPlans(String organizationId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM PlanBean b "
+ "WHERE b.organization.id = :orgId "
+ "ORDER BY b.id ASC"; //$NON-NLS-1$
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
return super.getAll(PlanBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllApis(java.lang.String)
*/
@Override
public Iterator<ApiBean> getAllApis(String organizationId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM ApiBean b "
+ "WHERE b.organization.id = :orgId "
+ "ORDER BY b.id ASC"; //$NON-NLS-1$
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
return super.getAll(ApiBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllClients(java.lang.String)
*/
@Override
public Iterator<ClientBean> getAllClients(String organizationId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM ClientBean b "
+ "WHERE b.organization.id = :orgId "
+ "ORDER BY b.id ASC"; //$NON-NLS-1$
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
return super.getAll(ClientBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllClientVersions(java.lang.String, java.lang.String)
*/
@Override
public Iterator<ClientVersionBean> getAllClientVersions(String organizationId,
String clientId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v "
+ " FROM ClientVersionBean v "
+ " JOIN v.client a "
+ " JOIN a.organization o "
+ " WHERE o.id = :orgId "
+ " AND a.id = :clientId"
+ " ORDER BY v.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("clientId", clientId);
return super.getAll(ClientVersionBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllContracts(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public Iterator<ContractBean> getAllContracts(String organizationId, String clientId, String version)
throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT c from ContractBean c " +
" JOIN c.client clientv " +
" JOIN clientv.client client " +
" JOIN client.organization aorg" +
" WHERE client.id = :clientId " +
" AND aorg.id = :orgId " +
" AND clientv.version = :version " +
" ORDER BY c.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("clientId", clientId);
query.setParameter("version", version);
return getAll(ContractBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllPolicies(java.lang.String, java.lang.String, java.lang.String, io.apiman.manager.api.beans.policies.PolicyType)
*/
@Override
public Iterator<PolicyBean> getAllPolicies(String organizationId, String entityId, String version,
PolicyType type) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT p from PolicyBean p "
+ " WHERE p.organizationId = :orgId "
+ " AND p.entityId = :entityId "
+ " AND p.entityVersion = :entityVersion "
+ " AND p.type = :type"
+ " ORDER BY p.orderIndex ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("entityId", entityId);
query.setParameter("entityVersion", version);
query.setParameter("type", type);
return getAll(PolicyBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllPlanVersions(java.lang.String, java.lang.String)
*/
@Override
public Iterator<PlanVersionBean> getAllPlanVersions(String organizationId, String planId)
throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v "
+ " FROM PlanVersionBean v "
+ " JOIN v.plan p "
+ " JOIN p.organization o "
+ " WHERE o.id = :orgId "
+ " AND p.id = :planId"
+ " ORDER BY v.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("planId", planId);
return super.getAll(PlanVersionBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllApiVersions(java.lang.String, java.lang.String)
*/
@Override
public Iterator<ApiVersionBean> getAllApiVersions(String organizationId, String apiId)
throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql = "SELECT v "
+ " FROM ApiVersionBean v "
+ " JOIN v.api s "
+ " JOIN s.organization o "
+ " WHERE o.id = :orgId "
+ " AND s.id = :apiId"
+ " ORDER BY v.id ASC";
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", organizationId);
query.setParameter("apiId", apiId);
return super.getAll(ApiVersionBean.class, query);
}
@Override
public Iterator<GatewayBean> getAllGateways() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b FROM GatewayBean b ORDER BY b.id ASC";
Query query = entityManager.createQuery(jpql);
return super.getAll(GatewayBean.class, query);
}
@Override
public Iterator<AuditEntryBean> getAllAuditEntries(String orgId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM AuditEntryBean b "
+ "WHERE organization_id = :orgId "
+ "ORDER BY b.id ASC"; //$NON-NLS-1$
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", orgId);
return super.getAll(AuditEntryBean.class, query);
}
@Override
public Iterator<PluginBean> getAllPlugins() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM PluginBean b "
+ "ORDER BY b.id ASC";
Query query = entityManager.createQuery(jpql);
return super.getAll(PluginBean.class, query);
}
/**
* @see io.apiman.manager.api.core.IStorage#getAllPolicyDefinitions()
*/
@Override
public Iterator<PolicyDefinitionBean> getAllPolicyDefinitions() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM PolicyDefinitionBean b "
+ "ORDER BY b.id ASC";
Query query = entityManager.createQuery(jpql);
return super.getAll(PolicyDefinitionBean.class, query);
}
@Override
public Iterator<RoleMembershipBean> getAllMemberships(String orgId) throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM RoleMembershipBean b "
+ "WHERE organizationId = :orgId "
+ "ORDER BY b.id ASC"; //$NON-NLS-1$
Query query = entityManager.createQuery(jpql);
query.setParameter("orgId", orgId);
return super.getAll(RoleMembershipBean.class, query);
}
@Override
public Iterator<UserBean> getAllUsers() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM UserBean b "
+ "ORDER BY b.username ASC";
Query query = entityManager.createQuery(jpql);
return super.getAll(UserBean.class, query);
}
@Override
public Iterator<RoleBean> getAllRoles() throws StorageException {
EntityManager entityManager = getActiveEntityManager();
String jpql =
"SELECT b "
+ "FROM RoleBean b "
+ "ORDER BY b.id ASC";
Query query = entityManager.createQuery(jpql);
return super.getAll(RoleBean.class, query);
}
@Override
public Iterator<ContractBean> getAllContracts(OrganizationBean organizationBean, int lim) throws StorageException {
String jpql =
" SELECT contractBean "
+ " FROM ContractBean contractBean "
// Api
+ " JOIN contractBean.api apiVersion "
+ " JOIN apiVersion.api api "
+ " JOIN api.organization apiOrg "
// Client
+ " JOIN contractBean.client clientVersion "
+ " JOIN clientVersion.client client "
+ " JOIN api.organization clientOrg "
// Check API status
+ " WHERE (apiOrg.id = :orgId AND apiVersion.status = :apiStatus)"
// Check In-Org ClientApp status
+ " OR (clientOrg.id = :orgId AND clientVersion.status = :clientStatus)";
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
query.setParameter("clientStatus", ClientStatus.Registered);
query.setParameter("apiStatus", ApiStatus.Published);
if (lim > 0) {
query.setMaxResults(lim);
}
return super.getAll(ContractBean.class, query);
}
@Override
public Iterator<ClientVersionBean> getAllClientVersions(OrganizationBean organizationBean, int lim) throws StorageException {
return getAllClientVersions(organizationBean, null, lim);
}
@Override
public Iterator<ClientVersionBean> getAllClientVersions(OrganizationBean organizationBean, ClientStatus status, int lim) throws StorageException {
String jpql = "SELECT v "
+ " FROM ClientVersionBean v "
+ " JOIN v.client c "
+ " JOIN c.organization o "
+ "WHERE o.id = :orgId ";
if (status != null) {
jpql += String.format(" AND v.status = '%s' ", status.name());
}
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
if (lim > 0) {
query.setMaxResults(lim);
}
return super.getAll(ClientVersionBean.class, query);
}
@Override
public Iterator<ApiVersionBean> getAllApiVersions(OrganizationBean organizationBean, int lim) throws StorageException {
return getAllApiVersions(organizationBean, null, lim);
}
@Override
public Iterator<ApiVersionBean> getAllApiVersions(OrganizationBean organizationBean, ApiStatus status, int lim) throws StorageException {
String jpql = "SELECT v "
+ " FROM ApiVersionBean v "
+ " JOIN v.api a"
+ " JOIN a.organization o "
+ " WHERE o.id = :orgId ";
if (status != null) {
jpql += String.format(" AND v.status = '%s' ", status.name());
}
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
if (lim > 0) {
query.setMaxResults(lim);
}
return super.getAll(ApiVersionBean.class, query);
}
@Override
public Iterator<PlanVersionBean> getAllPlanVersions(OrganizationBean organizationBean, int lim) throws StorageException {
return getAllPlanVersions(organizationBean, null, lim);
}
@Override
public Iterator<PlanVersionBean> getAllPlanVersions(OrganizationBean organizationBean, PlanStatus status, int lim) throws StorageException {
String jpql = "SELECT v "
+ " FROM PlanVersionBean v "
+ " JOIN v.plan p "
+ " JOIN p.organization o "
+ " WHERE o.id = :orgId ";
if (status != null) {
jpql += String.format(" AND v.status = '%s' ", status.name());
}
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
if (lim > 0) {
query.setMaxResults(lim);
}
return super.getAll(PlanVersionBean.class, query);
}
private void deleteAllPolicies(OrganizationBean organizationBean) throws StorageException {
deleteAllPolicies(organizationBean, null);
}
private void deleteAllPolicies(ApiBean apiBean) throws StorageException {
deleteAllPolicies(apiBean.getOrganization(), apiBean.getId());
}
private void deleteAllPolicies(ClientBean clientBean) throws StorageException {
deleteAllPolicies(clientBean.getOrganization(), clientBean.getId());
}
private void deleteAllPolicies(OrganizationBean organizationBean, String entityId) throws StorageException {
String jpql = "DELETE PolicyBean b "
+ " WHERE b.organizationId = :orgId ";
if (entityId != null) {
jpql += String.format("AND b.entityId = '%s'", entityId);
}
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
}
private void deleteAllMemberships(OrganizationBean organizationBean) throws StorageException {
String jpql = "DELETE RoleMembershipBean b "
+ " WHERE b.organizationId = :orgId ";
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
query.executeUpdate();
}
private void deleteAllAuditEntries(PlanBean plan) throws StorageException {
deleteAllAuditEntries(plan.getOrganization(), AuditEntityType.Plan, plan.getId());
}
private void deleteAllAuditEntries(ApiBean apiBean) throws StorageException {
deleteAllAuditEntries(apiBean.getOrganization(), AuditEntityType.Api, apiBean.getId());
}
private void deleteAllAuditEntries(ClientBean clientBean) throws StorageException {
deleteAllAuditEntries(clientBean.getOrganization(), AuditEntityType.Client, clientBean.getId());
}
private void deleteAllAuditEntries(OrganizationBean organizationBean) throws StorageException {
deleteAllAuditEntries(organizationBean, null, null);
}
private void deleteAllAuditEntries(OrganizationBean organizationBean, AuditEntityType entityType, String entityId) throws StorageException {
String jpql = "DELETE AuditEntryBean b "
+ " WHERE b.organizationId = :orgId ";
if (entityId != null && entityType != null) {
jpql += String.format("AND b.entityId = '%s' AND b.entityType = '%s' ", entityId, entityType.name());
}
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
query.executeUpdate();
}
private void deleteAllContracts(ApiBean apiBean) throws StorageException {
Query query;
if (isMySql()) {
String sql =
"DELETE c " +
" FROM contracts c " +
" JOIN api_versions " +
" ON c.apiv_id = api_versions.id " +
" JOIN apis " +
" ON api_versions.api_id = apis.id " +
" AND api_versions.api_org_id = apis.organization_id " +
" JOIN organizations " +
" ON apis.organization_id = organizations.id " +
"WHERE organizations.id = :orgId " +
"AND apis.id = :apiId ;";
query = getActiveEntityManager().createNativeQuery(sql);
} else {
String jpql =
"DELETE ContractBean deleteBean " +
" WHERE deleteBean IN ( " +
" SELECT b " +
" FROM ContractBean b " +
" JOIN b.api apiVersion " +
" JOIN apiVersion.api api " +
" JOIN api.organization o " +
" WHERE o.id = :orgId " +
" AND api.id = :apiId " +
" )";
query = getActiveEntityManager().createQuery(jpql);
}
query.setParameter("orgId", apiBean.getOrganization().getId());
query.setParameter("apiId", apiBean.getId());
query.executeUpdate();
}
private void deleteAllContracts(ClientBean clientBean) throws StorageException {
Query query;
if (isMySql()) {
String sql =
"DELETE c " +
" FROM contracts c " +
" JOIN client_versions " +
" ON c.clientv_id = client_versions.id " +
" JOIN clients " +
" ON client_versions.client_id = clients.id " +
" AND client_versions.client_org_id = clients.organization_id " +
" JOIN organizations " +
" ON clients.organization_id = organizations.id " +
"WHERE organizations.id = :orgId " +
"AND clients.id = :clientId ;";
query = getActiveEntityManager().createNativeQuery(sql);
} else {
String jpql =
"DELETE ContractBean deleteBean " +
" WHERE deleteBean IN ( " +
" SELECT b " +
" FROM ContractBean b " +
" JOIN b.client clientVersion " +
" JOIN clientVersion.client client " +
" JOIN client.organization o " +
" WHERE o.id = :orgId " +
" AND client.id = :clientId " +
" )";
query = getActiveEntityManager().createQuery(jpql);
}
query.setParameter("orgId", clientBean.getOrganization().getId());
query.setParameter("clientId", clientBean.getId());
query.executeUpdate();
}
private void deleteAllContracts(OrganizationBean organizationBean) throws StorageException {
Query query;
if (isMySql()) {
String sql =
"DELETE c " +
" FROM contracts c " +
" JOIN api_versions " +
" ON c.apiv_id = api_versions.id " +
" JOIN apis " +
" ON api_versions.api_id = apis.id " +
" AND api_versions.api_org_id = apis.organization_id " +
" JOIN organizations " +
" ON apis.organization_id = organizations.id " +
"WHERE organizations.id = :orgId ;";
query = getActiveEntityManager().createNativeQuery(sql);
} else {
String jpql =
"DELETE ContractBean deleteBean " +
" WHERE deleteBean IN ( " +
" SELECT b " +
" FROM ContractBean b " +
" JOIN b.api apiVersion " +
" JOIN apiVersion.api api " +
" JOIN api.organization o " +
" WHERE o.id = :orgId " +
" )";
query = getActiveEntityManager().createQuery(jpql);
}
query.setParameter("orgId", organizationBean.getId());
query.executeUpdate();
}
private boolean isMySql() throws StorageException {
return StringUtils.containsIgnoreCase(getDialect(), "mysql");
}
private <T> void remove(T entity) throws StorageException {
EntityManager em = getActiveEntityManager();
em.remove(em.contains(entity) ? entity : em.merge(entity));
}
public void deleteAllPlans(OrganizationBean organizationBean) throws StorageException {
deleteAllPlanVersions(organizationBean);
String jpql = "DELETE PlanBean p "
+ " WHERE p.organization.id = :orgId ";
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
query.executeUpdate();
}
private void deleteAllPlanVersions(OrganizationBean organizationBean) throws StorageException {
String jpql = "DELETE PlanVersionBean deleteBean "
+ " WHERE deleteBean IN ("
+ "SELECT v"
+ " FROM PlanVersionBean v "
+ " JOIN v.plan p "
+ " JOIN p.organization o "
+ " WHERE o.id = :orgId "
+ ")";
Query query = getActiveEntityManager().createQuery(jpql);
query.setParameter("orgId", organizationBean.getId());
query.executeUpdate();
}
}
| {
"content_hash": "585a4b75bfcef9f151065a3b7a1c425c",
"timestamp": "",
"source": "github",
"line_count": 2548,
"max_line_length": 182,
"avg_line_length": 40.035321821036106,
"alnum_prop": 0.6131751789040291,
"repo_name": "jcechace/apiman",
"id": "9f06f2a5434ee828f6b0abf2366d29811379ec88",
"size": "102603",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/JpaStorage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "58563"
},
{
"name": "HTML",
"bytes": "358504"
},
{
"name": "Java",
"bytes": "3731061"
},
{
"name": "JavaScript",
"bytes": "20095"
},
{
"name": "Shell",
"bytes": "1900"
},
{
"name": "TypeScript",
"bytes": "362947"
}
],
"symlink_target": ""
} |
#ifndef GGADGET_JS_JSCRIPT_MASSAGER_H_
#define GGADGET_JS_JSCRIPT_MASSAGER_H_
#include <string>
namespace ggadget {
namespace js {
/**
* @ingroup JSLibrary
* @{
*/
std::string MassageJScript(const char *input, bool debug,
const char *filename, int lineno);
/** @} */
} // namespace js
} // namespace ggadget
#endif // GGADGET_JS_JSCRIPT_MASSAGER_H_
| {
"content_hash": "8e32be7d66f471374b78d23ea9dcd55f",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 61,
"avg_line_length": 16.82608695652174,
"alnum_prop": 0.6382428940568475,
"repo_name": "tectronics/google-gadgets-for-linux",
"id": "7e2ab0eed9c1b279e5de07e57498a5c149479a06",
"size": "965",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "ggadget/js/jscript_massager.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "9124"
},
{
"name": "C++",
"bytes": "6216017"
},
{
"name": "CMake",
"bytes": "124918"
},
{
"name": "Groff",
"bytes": "2143"
},
{
"name": "JavaScript",
"bytes": "861502"
},
{
"name": "Lex",
"bytes": "11048"
},
{
"name": "Makefile",
"bytes": "3183"
},
{
"name": "Objective-C++",
"bytes": "57589"
},
{
"name": "Shell",
"bytes": "63602"
}
],
"symlink_target": ""
} |
/*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.slides.v1.model;
/**
* Deletes a column from a table.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Google Slides API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class DeleteTableColumnRequest extends com.google.api.client.json.GenericJson {
/**
* The reference table cell location from which a column will be deleted.
*
* The column this cell spans will be deleted. If this is a merged cell, multiple columns will be
* deleted. If no columns remain in the table after this deletion, the whole table is deleted.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private TableCellLocation cellLocation;
/**
* The table to delete columns from.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String tableObjectId;
/**
* The reference table cell location from which a column will be deleted.
*
* The column this cell spans will be deleted. If this is a merged cell, multiple columns will be
* deleted. If no columns remain in the table after this deletion, the whole table is deleted.
* @return value or {@code null} for none
*/
public TableCellLocation getCellLocation() {
return cellLocation;
}
/**
* The reference table cell location from which a column will be deleted.
*
* The column this cell spans will be deleted. If this is a merged cell, multiple columns will be
* deleted. If no columns remain in the table after this deletion, the whole table is deleted.
* @param cellLocation cellLocation or {@code null} for none
*/
public DeleteTableColumnRequest setCellLocation(TableCellLocation cellLocation) {
this.cellLocation = cellLocation;
return this;
}
/**
* The table to delete columns from.
* @return value or {@code null} for none
*/
public java.lang.String getTableObjectId() {
return tableObjectId;
}
/**
* The table to delete columns from.
* @param tableObjectId tableObjectId or {@code null} for none
*/
public DeleteTableColumnRequest setTableObjectId(java.lang.String tableObjectId) {
this.tableObjectId = tableObjectId;
return this;
}
@Override
public DeleteTableColumnRequest set(String fieldName, Object value) {
return (DeleteTableColumnRequest) super.set(fieldName, value);
}
@Override
public DeleteTableColumnRequest clone() {
return (DeleteTableColumnRequest) super.clone();
}
}
| {
"content_hash": "be48fff235322a166dcfb67f703af750",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 182,
"avg_line_length": 35.343434343434346,
"alnum_prop": 0.7250643040868819,
"repo_name": "googleapis/google-api-java-client-services",
"id": "1e3d046c3b8e19c3658fa66f7ee6447968513e9f",
"size": "3499",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "clients/google-api-services-slides/v1/1.29.2/com/google/api/services/slides/v1/model/DeleteTableColumnRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
class CreateActiveRecordOrmPrimals < ActiveRecord::Migration
def change
create_table :active_record_orm_primals do |t|
t.string :string_field
t.text :text_field
t.string :select_field
t.integer :integer_field
t.float :float_field
t.decimal :decimal_field
t.datetime :datetime_field
t.timestamp :timestamp_field
t.time :time_field
t.date :date_field
t.boolean :boolean_field
end
end
end
| {
"content_hash": "5bf623fd88e8577950f4d0b3da6b68bd",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 60,
"avg_line_length": 27.294117647058822,
"alnum_prop": 0.6637931034482759,
"repo_name": "puffer/puffer",
"id": "f6200ca1fe3910698e1e3f5b4263252412bbc525",
"size": "464",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/dummy/db/migrate/20110930183902_create_active_record_orm_primals.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "13257"
},
{
"name": "JavaScript",
"bytes": "296740"
},
{
"name": "Ruby",
"bytes": "173571"
}
],
"symlink_target": ""
} |
import os
import StringIO
import cProfile
from datetime import datetime
import pytz
from django.shortcuts import *
from django.utils import timezone
class TimezoneMiddleware(object):
def process_request(self, request):
if request.user.is_authenticated():
tzname = request.user.profile.timezone
if tzname:
timezone.activate(pytz.timezone(tzname))
else:
if "/settings" not in request.path and "/admin" not in request.path and "/static" not in request.path:
return redirect('/settings')
from django.conf import settings
from django.http import HttpResponseRedirect
class SSLMiddleware(object):
def process_request(self, request):
if not any([settings.DEBUG, request.is_secure(), request.META.get("HTTP_X_FORWARDED_PROTO", "") == 'https']):
url = request.build_absolute_uri(request.get_full_path())
secure_url = url.replace("http://", "https://")
return HttpResponseRedirect(secure_url) | {
"content_hash": "3ae6b329f2a5c79a160d20ada51dd378",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 118,
"avg_line_length": 31.647058823529413,
"alnum_prop": 0.6384758364312267,
"repo_name": "twitterdev/twitter-leaderboard",
"id": "c8d7ffd8efec4874e9c975f35de6a34f83b1a4d9",
"size": "1076",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "services/middleware.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "86313"
},
{
"name": "HTML",
"bytes": "15519"
},
{
"name": "JavaScript",
"bytes": "316932"
},
{
"name": "Python",
"bytes": "22390"
}
],
"symlink_target": ""
} |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :set_locale
before_action :set_languages
before_action :configure_permitted_parameters, if: :devise_controller?
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, :notice => exception.message
end
protected
def configure_permitted_parameters
keys = [:first_name, :last_name, :avatar, :avatar_cache, :remove_avatar, :wallet]
devise_parameter_sanitizer.permit(:sign_up, keys: keys)
devise_parameter_sanitizer.permit(:account_update, keys: keys)
end
private
def set_languages
case cookies[:language]
when 'en'
@current_language = I18n.t('language.english')
@languages = [I18n.t('language.russian'), I18n.t('language.english')]
when 'ru'
@current_language = I18n.t('language.russian')
@languages = [I18n.t('language.english'), I18n.t('language.russian')]
end
end
def set_locale
cookies[:language] ||= 'en'
I18n.locale = cookies[:language]
end
end
| {
"content_hash": "4bc5192cd2d5845d4a4a30541492cd5b",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 87,
"avg_line_length": 31.514285714285716,
"alnum_prop": 0.6727107887579329,
"repo_name": "lisovskey/crowdfach",
"id": "4e98765ef2fe645559f3f401518ddb3298cb06c7",
"size": "1103",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/application_controller.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18042"
},
{
"name": "CoffeeScript",
"bytes": "1692"
},
{
"name": "HTML",
"bytes": "52120"
},
{
"name": "JavaScript",
"bytes": "101"
},
{
"name": "Ruby",
"bytes": "102399"
}
],
"symlink_target": ""
} |
hello
=====
hello world test
download (clone)
=====
git clone https://github.com/Combe-Martin/hello.git
building
=====
* default
```Bash
mkdir build
cd build
cmake ../
make
```
* debug version:
```Bash
mkdir debug
cd debug
cmake -DCMAKE_BUILD_TYPE=Debug ../
make
```
* release version:
```Bash
mkdir release
cd release
cmake -DCMAKE_BUILD_TYPE=Release ../
make
```
| {
"content_hash": "00fa47801d20a14ad5bd82180b4d04a7",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 51,
"avg_line_length": 9.45,
"alnum_prop": 0.6613756613756614,
"repo_name": "Combe-Martin/hello",
"id": "1b0f1f19b15270ea0525f16ad8ae7824caf3ce8d",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "218"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>chapar: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.1 / chapar - 8.14.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
chapar
<small>
8.14.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-03-25 11:16:21 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-03-25 11:16:21 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.08.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.08.1 Official release 4.08.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-community/chapar"
dev-repo: "git+https://github.com/coq-community/chapar.git"
bug-reports: "https://github.com/coq-community/chapar/issues"
license: "MIT"
synopsis: "A framework for verification of causal consistency for distributed key-value stores and their clients in Coq"
description: """
A framework for modular verification of causal consistency for replicated key-value
store implementations and their client programs in Coq. Includes proofs of the causal consistency
of two key-value store implementations and a simple automatic model checker for the correctness
of client programs."""
build: [make "-j%{jobs}%"]
install: [make "install"]
depends: [
"coq" {>= "8.14" & < "8.16~"}
]
tags: [
"category:Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems"
"keyword:causal consistency"
"keyword:key-value stores"
"keyword:distributed algorithms"
"keyword:program verification"
"logpath:Chapar"
"date:2021-01-12"
]
authors: [
"Mohsen Lesani"
"Christian J. Bell"
"Adam Chlipala"
]
url {
src: "https://github.com/coq-community/chapar/archive/v8.14.0.tar.gz"
checksum: "sha512=cd4ead48ba9cd877b980fc67e05d9413f1a779ab9b7cb9076c5bd12a10437413238692f9dbb384fb3fdf45f7fb8e5763c634132b0947791b08c4f88b29d40337"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-chapar.8.14.0 coq.8.11.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.1).
The following dependencies couldn't be met:
- coq-chapar -> coq >= 8.14
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-chapar.8.14.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "13003f5c17007a1a42337d800ffe9c73",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 159,
"avg_line_length": 41.160919540229884,
"alnum_prop": 0.5618542306618263,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ea447e35c0d57e824d94e8d35676c5fb972e48f8",
"size": "7187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.11.1/chapar/8.14.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
LineItem.class_eval do
delegate :basket, :to => :purchasable_item
end
| {
"content_hash": "48784155d9bd4cfc753b93e1eb54b8df",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 44,
"avg_line_length": 24,
"alnum_prop": 0.7361111111111112,
"repo_name": "kete/kete_gets_trollied",
"id": "961f9d4d5d9003c92285ad340c697636c630078b",
"size": "123",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/kete_gets_trollied/extensions/models/line_item.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "21474"
}
],
"symlink_target": ""
} |
package service
import (
"net"
"reflect"
"time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
"github.com/GoogleCloudPlatform/kubernetes/pkg/master/ports"
"github.com/golang/glog"
)
const (
SCHEDULER_SERVICE_NAME = "k8sm-scheduler"
)
func (m *SchedulerServer) newServiceWriter(stop <-chan struct{}) func() {
return func() {
for {
// Update service & endpoint records.
// TODO(k8s): when it becomes possible to change this stuff,
// stop polling and start watching.
if err := m.createSchedulerServiceIfNeeded(SCHEDULER_SERVICE_NAME, ports.SchedulerPort); err != nil {
glog.Errorf("Can't create scheduler service: %v", err)
}
if err := m.setEndpoints(SCHEDULER_SERVICE_NAME, net.IP(m.Address), m.Port); err != nil {
glog.Errorf("Can't create scheduler endpoints: %v", err)
}
select {
case <-stop:
return
case <-time.After(10 * time.Second):
}
}
}
}
// createSchedulerServiceIfNeeded will create the specified service if it
// doesn't already exist.
func (m *SchedulerServer) createSchedulerServiceIfNeeded(serviceName string, servicePort int) error {
ctx := api.NewDefaultContext()
if _, err := m.client.Services(api.NamespaceValue(ctx)).Get(serviceName); err == nil {
// The service already exists.
return nil
}
svc := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: serviceName,
Namespace: api.NamespaceDefault,
Labels: map[string]string{"provider": "k8sm", "component": "scheduler"},
},
Spec: api.ServiceSpec{
Port: servicePort,
// maintained by this code, not by the pod selector
Selector: nil,
Protocol: api.ProtocolTCP,
SessionAffinity: api.AffinityTypeNone,
},
}
if m.ServiceAddress != nil {
svc.Spec.PortalIP = m.ServiceAddress.String()
}
_, err := m.client.Services(api.NamespaceValue(ctx)).Create(svc)
if err != nil && errors.IsAlreadyExists(err) {
err = nil
}
return err
}
// setEndpoints sets the endpoints for the given service.
// in a multi-master scenario only the master will be publishing an endpoint.
// see SchedulerServer.bootstrap.
func (m *SchedulerServer) setEndpoints(serviceName string, ip net.IP, port int) error {
// The setting we want to find.
want := []api.EndpointSubset{{
Addresses: []api.EndpointAddress{{IP: ip.String()}},
Ports: []api.EndpointPort{{Port: port, Protocol: api.ProtocolTCP}},
}}
ctx := api.NewDefaultContext()
e, err := m.client.Endpoints(api.NamespaceValue(ctx)).Get(serviceName)
createOrUpdate := m.client.Endpoints(api.NamespaceValue(ctx)).Update
if err != nil {
if errors.IsNotFound(err) {
createOrUpdate = m.client.Endpoints(api.NamespaceValue(ctx)).Create
}
e = &api.Endpoints{
ObjectMeta: api.ObjectMeta{
Name: serviceName,
Namespace: api.NamespaceDefault,
},
}
}
if !reflect.DeepEqual(e.Subsets, want) {
e.Subsets = want
glog.Infof("setting endpoints for master service %q to %+v", serviceName, e)
_, err = createOrUpdate(e)
return err
}
// We didn't make any changes, no need to actually call update.
return nil
}
| {
"content_hash": "ae7a1b0a26fe70dab4235d7bcc2a58ef",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 104,
"avg_line_length": 29.055555555555557,
"alnum_prop": 0.6963033779477374,
"repo_name": "ruo91/kubernetes-mesos",
"id": "99722ac4b84446c59bf93db553d841cdba6536d2",
"size": "3716",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/scheduler/service/publish.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "437171"
},
{
"name": "HTML",
"bytes": "850"
},
{
"name": "JavaScript",
"bytes": "961"
},
{
"name": "Makefile",
"bytes": "9231"
},
{
"name": "PHP",
"bytes": "1974"
},
{
"name": "Shell",
"bytes": "38344"
}
],
"symlink_target": ""
} |
require 'equalizer'
require 'abstract_type'
require 'knight/version'
require 'knight/rule'
require 'knight/rule/presence'
require 'knight/rule/exact_length'
require 'knight/rule/maximum_length'
require 'knight/rule/minimum_length'
require 'knight/rule/range_length'
require 'knight/rule/format'
require 'knight/rule/inclusion'
require 'knight/error'
require 'knight/result'
require 'knight/validator'
require 'knight/instance_methods'
module Knight
end
| {
"content_hash": "abab74d0604e9fb158ef4c6e78b60b1e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 36,
"avg_line_length": 23.94736842105263,
"alnum_prop": 0.8,
"repo_name": "handiwiguna/knight",
"id": "141d85f2b974132bea25a4e729564d7d5c7132ed",
"size": "474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/knight.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "39443"
}
],
"symlink_target": ""
} |
<?php
/**
* This is the tinyMCE (rich text editor) configuration file. Please visit
* http://tinymce.moxiecode.com for more information.
*/
if ($GLOBALS['TL_CONFIG']['useRTE']): ?>
<script src="<?php echo $this->base; ?>assets/tinymce/tiny_mce_gzip.js"></script>
<script>
tinyMCE_GZ.init({
plugins : "advimage,autosave,directionality,emotions,inlinepopups,paste,save,searchreplace,style,tabfocus,table,template,typolinks,xhtmlxtras",
themes : "advanced",
languages : "<?php echo $this->language; ?>",
disk_cache : false,
debug : false
});
</script>
<script>
tinyMCE.init({
mode : "none",
height : "300",
language : "<?php echo $this->language; ?>",
elements : "<?php echo $this->rteFields; ?>",
remove_linebreaks : false,
force_hex_style_colors : true,
fix_list_elements : true,
fix_table_elements : true,
doctype : '<!DOCTYPE html>',
element_format : 'html',
document_base_url : "<?php echo $this->base; ?>",
entities : "160,nbsp,60,lt,62,gt,173,shy",
cleanup_on_startup : true,
save_enablewhendirty : true,
save_on_tinymce_forms : true,
file_browser_callback : "TinyCallback.fileBrowser",
init_instance_callback : "TinyCallback.getScrollOffset",
advimage_update_dimensions_onchange : false,
template_external_list_url : "<?php echo TL_PATH; ?>/assets/tinymce/plugins/typolinks/typotemplates.php",
plugins : "advimage,autosave,directionality,emotions,inlinepopups,paste,save,searchreplace,style,tabfocus,table,template,typolinks,xhtmlxtras",
content_css : "<?php echo TL_PATH; ?>/system/themes/tinymce.css,<?php echo TL_PATH .'/'. $this->uploadPath; ?>/tinymce.css",
event_elements : "a,div,h1,h2,h3,h4,h5,h6,img,p,span",
extended_valid_elements : "q[cite|class|title],article,section,hgroup,figure,figcaption",
tabfocus_elements : ":prev,:next",
theme : "advanced",
theme_advanced_resizing : true,
theme_advanced_resize_horizontal : false,
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
theme_advanced_source_editor_width : "700",
theme_advanced_blockformats : "div,p,address,pre,h1,h2,h3,h4,h5,h6",
theme_advanced_buttons1 : "newdocument,save,separator,anchor,separator,typolinks,unlink,separator,image,typobox,separator,sub,sup,separator,abbr,separator,styleprops,attribs,separator,search,replace,separator,undo,redo,separator,removeformat,cleanup,separator,code",
theme_advanced_buttons2 : "formatselect,fontsizeselect,styleselect,separator,bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,indent,outdent,separator,blockquote,separator,forecolor,backcolor",
theme_advanced_buttons3 : "tablecontrols,separator,template,separator,charmap,emotions,separator,help",
theme_advanced_font_sizes : "9px,10px,11px,12px,13px,14px,15px,16px,17px,18px,19px,20px,21px,22px,23px,24px"
});
</script>
<?php endif; ?>
| {
"content_hash": "1c5d5cc15fe7410843cde50d579f5582",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 268,
"avg_line_length": 48.09836065573771,
"alnum_prop": 0.7382413087934561,
"repo_name": "westwerk-ac/metamodels-cc15-demo",
"id": "5aaa5de4a95b6cb424767f20fe754b105125f391",
"size": "3032",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "system/config/tinyMCE.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1009"
},
{
"name": "CSS",
"bytes": "231273"
},
{
"name": "HTML",
"bytes": "160855"
},
{
"name": "JavaScript",
"bytes": "1118633"
},
{
"name": "PHP",
"bytes": "255812"
},
{
"name": "Shell",
"bytes": "15719"
}
],
"symlink_target": ""
} |
<?php
/*
* This file is part of Mongator.
*
* (c) Pablo Díez <[email protected]>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Mongator;
use Mongator\Cache\AbstractCache;
use Mongator\Document\Event;
use SRG\Odm\MongatorRepository;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Laminas\EventManager\SharedEventManager;
use Laminas\ServiceManager\AbstractFactory\ReflectionBasedAbstractFactory;
use Laminas\ServiceManager\ServiceManager;
/**
* Mongator.
*
* @author Pablo Díez <[email protected]>
*
* @api
*/
class Mongator
{
const VERSION = '1.0.0-DEV';
private $metadataFactory;
private $fieldsCache;
private $dataCache;
private $unitOfWork;
private $connections;
private $defaultConnectionName;
private $repositories;
private $dispatcher;
/**
* @var ServiceManager
*/
private $serviceManager;
/**
* @var SharedEventManager
*/
private $sharedEventManager;
static $doTranslate=false;
/**
* Constructor.
*
* @param ServiceManager $serviceManager
* @internal param MetadataFactory $metadataFactory The metadata factory.
*
* @api
*/
public function __construct(ServiceManager $serviceManager, SharedEventManager $sharedEventManager)
{
$this->serviceManager = $serviceManager;
$this->sharedEventManager = $sharedEventManager;
$this->unitOfWork = new UnitOfWork($this);
$this->connections = array();
$this->repositories = array();
}
/**
* Set Metadata factory
* @param MetadataFactory $metadataFactory
*/
public function setMetadataFactory(MetadataFactory $metadataFactory){
$this->metadataFactory = $metadataFactory;
}
/**
* Returns the metadata factory.
*
* @return MetadataFactory The metadata factory.
*
* @api
*/
public function getMetadataFactory()
{
return $this->metadataFactory;
}
/**
* Get shared event manager
* @return SharedEventManager
*/
public function getSharedEventManager(){
return $this->sharedEventManager;
}
/**
* Returns the fields cache.
*
* @return CacheInterface The cache.
*
* @api
*/
public function getFieldsCache()
{
return $this->fieldsCache;
}
/**
* Returns the fields cache.
*
* @return CacheInterface The cache.
*
* @api
*/
public function getDataCache()
{
return $this->dataCache;
}
/**
* Sets the fields cache.
*
* @return CacheInterface The cache.
*
* @api
*/
public function setFieldsCache(AbstractCache $cache)
{
$this->fieldsCache = $cache;
}
/**
* Sets the data cache.
*
* @return CacheInterface The cache.
*
* @api
*/
public function setDataCache(AbstractCache $cache)
{
$this->dataCache = $cache;
}
/**
* Returns the UnitOfWork.
*
* @return UnitOfWork The UnitOfWork.
*
* @api
*/
public function getUnitOfWork()
{
return $this->unitOfWork;
}
/**
* Set a connection.
*
* @param string $name The connection name.
* @param ConnectionInterface $connection The connection.
*
* @api
*/
public function setConnection($name, ConnectionInterface $connection)
{
$this->connections[$name] = $connection;
}
/**
* Set the connections.
*
* @param array $connections An array of connections.
*
* @api
*/
public function setConnections(array $connections)
{
$this->connections = array();
foreach ($connections as $name => $connection) {
$this->setConnection($name, $connection);
}
}
/**
* Remove a connection.
*
* @param string $name The connection name.
*
* @throws \InvalidArgumentException If the connection does not exists.
*
* @api
*/
public function removeConnection($name)
{
if (!$this->hasConnection($name)) {
throw new \InvalidArgumentException(sprintf('The connection "%s" does not exists.', $name));
}
unset($this->connections[$name]);
}
/**
* Clear the connections.
*
* @api
*/
public function clearConnections()
{
$this->connections = array();
}
/**
* Returns if a connection exists.
*
* @param string $name The connection name.
*
* @return boolean Returns if a connection exists.
*
* @api
*/
public function hasConnection($name)
{
return isset($this->connections[$name]);
}
/**
* Return a connection.
*
* @param string $name The connection name.
*
* @return ConnectionInterface The connection.
*
* @throws \InvalidArgumentException If the connection does not exists.
*
* @api
*/
public function getConnection($name)
{
if (!$this->hasConnection($name)) {
throw new \InvalidArgumentException(sprintf('The connection "%s" does not exist.', $name));
}
return $this->connections[$name];
}
/**
* Returns the connections.
*
* @return array The array of connections.
*
* @api
*/
public function getConnections()
{
return $this->connections;
}
/**
* Set the default connection name.
*
* @param string $name The connection name.
*
* @api
*/
public function setDefaultConnectionName($name)
{
$this->defaultConnectionName = $name;
}
/**
* Returns the default connection name.
*
* @return string The default connection name.
*
* @api
*/
public function getDefaultConnectionName()
{
return $this->defaultConnectionName;
}
/**
* Returns the default connection.
*
* @return \Mongator\ConnectionInterface The default connection.
*
* @throws \RuntimeException If there is not default connection name.
* @throws \RuntimeException If the default connection does not exists.
*
* @api
*/
public function getDefaultConnection()
{
if (null === $this->defaultConnectionName) {
throw new \RuntimeException('There is not default connection name.');
}
if (!isset($this->connections[$this->defaultConnectionName])) {
throw new \RuntimeException(sprintf('The default connection "%s" does not exists.', $this->defaultConnectionName));
}
return $this->connections[$this->defaultConnectionName];
}
/**
* Returns the metadata of a document class.
*
* @param string $documentClass The document class.
*
* @return array The metadata.
*
* @api
*/
public function getMetadata($documentClass)
{
return $this->metadataFactory->getClass($documentClass);
}
/**
* Creates a new document.
*
* @param string $documentClass The document class.
* @param array $initializeArgs The args to initialize method of the document (optional).
*
* @return \Mongator\Document\Document The document.
*
* @api
*/
public function create($documentClass, array $initializeArgs = array())
{
$document = new $documentClass($this);
if (method_exists($document, 'initialize')) {
call_user_func_array(array($document, 'initialize'), $initializeArgs);
}
return $document;
}
/**
* Returns repositories by document class.
*
* @param string $documentClass The document class.
*
* @return MongatorRepository The repository.
*
* @throws \InvalidArgumentException If the document class is not a valid document class.
* @throws \RuntimeException If the repository class build does not exist.
*
* @api
*/
public function getRepository($documentClass)
{
if (!isset($this->repositories[$documentClass])) {
if (!$this->metadataFactory->hasClass($documentClass) || !$this->metadataFactory->isDocumentClass($documentClass)) {
throw new \InvalidArgumentException(sprintf('The class "%s" is not a valid document class.', $documentClass));
}
$repositoryClass = $documentClass.'Repository';
if (!class_exists($repositoryClass)) {
throw new \RuntimeException(sprintf('The class "%s" does not exists.', $repositoryClass));
}
$factory = new ReflectionBasedAbstractFactory();
$this->repositories[$documentClass] = $factory($this->serviceManager, $repositoryClass);
}
return $this->repositories[$documentClass];
}
/**
* Returns all repositories.
*
* @return array All repositories.
*
* @api
*/
public function getAllRepositories()
{
foreach ($this->metadataFactory->getDocumentClasses() as $class) {
$this->getRepository($class);
}
return $this->repositories;
}
/**
* Ensure the indexes of all repositories.
*
* @api
*/
public function ensureAllIndexes()
{
foreach ($this->getAllRepositories() as $repository) {
$repository->createIndexes();
}
}
/**
* Fixes all the missing references.
*/
public function fixAllMissingReferences($documentsPerBatch = 1000)
{
foreach ($this->getAllRepositories() as $repository) {
$repository->fixMissingReferences($documentsPerBatch);
}
}
/**
* Access to UnitOfWork ->persist() method.
*
* @see UnitOfWork::persist()
*
* @api
*/
public function persist($documents)
{
$this->unitOfWork->persist($documents);
}
/**
* Access to UnitOfWork ->remove() method.
*
* @see Mongator\UnitOfWork::remove()
*
* @api
*/
public function remove($document)
{
$this->unitOfWork->remove($document);
}
/**
* Access to UnitOfWork ->commit() method.
*
* @see Mongator\UnitOfWork::commit()
*
* @api
*/
public function flush()
{
$this->unitOfWork->commit();
}
/**
* Set the EventDispatcher
*
* @api
*/
public function setEventDispatcher(EventDispatcher $dispatcher)
{
$this->dispatcher = $dispatcher;
}
/**
* Dispatch a DocumentEvent to the dispatcher
*
* @param string $name
* @param Event $event
*
* @api
*/
public function dispatchEvent($name, Event $event)
{
if (!$this->dispatcher) {
return;
}
$this->dispatcher->dispatch($name, $event);
}
}
| {
"content_hash": "f47e36d7616619ac61ce0c57e8ae439a",
"timestamp": "",
"source": "github",
"line_count": 475,
"max_line_length": 128,
"avg_line_length": 23.04,
"alnum_prop": 0.5884502923976608,
"repo_name": "srggroup/mongator",
"id": "f5bdf05f6962b0645395481a6be3d4f12f18527d",
"size": "10946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Mongator/Mongator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "594157"
},
{
"name": "Shell",
"bytes": "163"
},
{
"name": "Twig",
"bytes": "72542"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "5c8dcd762dd54ff125600324f87b0c09",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "0367aa719b8459164df942ab42a24e94f0208e1b",
"size": "178",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/Rhadinothamnus/Rhadinothamnus rudis/Rhadinothamnus rudis rudis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
FROM balenalib/imx7-var-som-alpine:3.12-build
# remove several traces of python
RUN apk del python*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# key 63C7CC90: public key "Simon McVittie <[email protected]>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <[email protected]>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
# point Python at a system-provided certificate database. Otherwise, we might hit CERTIFICATE_VERIFY_FAILED.
# https://www.python.org/dev/peps/pep-0476/#trust-database
ENV SSL_CERT_FILE /etc/ssl/certs/ca-certificates.crt
ENV PYTHON_VERSION 3.5.10
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.0.1
ENV SETUPTOOLS_VERSION 56.0.0
RUN set -x \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \
&& echo "85b19d06c1c69acbc9e01d19a13dc157b7c16c1bba5a600d2728456a8741d29e Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-alpine-armv7hf-openssl1.1.tar.gz" \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# install "virtualenv", since the vast majority of users of this image will want it
RUN pip3 install --no-cache-dir virtualenv
ENV PYTHON_DBUS_VERSION 1.2.8
# install dbus-python dependencies
RUN apk add --no-cache \
dbus-dev \
dbus-glib-dev
# install dbus-python
RUN set -x \
&& mkdir -p /usr/src/dbus-python \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz" -o dbus-python.tar.gz \
&& curl -SL "http://dbus.freedesktop.org/releases/dbus-python/dbus-python-$PYTHON_DBUS_VERSION.tar.gz.asc" -o dbus-python.tar.gz.asc \
&& gpg --verify dbus-python.tar.gz.asc \
&& tar -xzC /usr/src/dbus-python --strip-components=1 -f dbus-python.tar.gz \
&& rm dbus-python.tar.gz* \
&& cd /usr/src/dbus-python \
&& PYTHON_VERSION=$(expr match "$PYTHON_VERSION" '\([0-9]*\.[0-9]*\)') ./configure \
&& make -j$(nproc) \
&& make install -j$(nproc) \
&& cd / \
&& rm -rf /usr/src/dbus-python
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/[email protected]" \
&& echo "Running test-stack@python" \
&& chmod +x [email protected] \
&& bash [email protected] \
&& rm -rf [email protected]
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo $'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Alpine Linux 3.12 \nVariant: build variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.5.10, Pip v21.0.1, Setuptools v56.0.0 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo $'#!/bin/bash\nbalena-info\nbusybox ln -sf /bin/busybox /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& ln -f /bin/sh /bin/sh.real \
&& ln -f /bin/sh-shim /bin/sh | {
"content_hash": "98154ea44a98aab89dfc3f7a2e78ad36",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 716,
"avg_line_length": 51.82795698924731,
"alnum_prop": 0.7076763485477179,
"repo_name": "nghiant2710/base-images",
"id": "fe3e1ff72c23773e213e05be76669eeb5a2a0cc1",
"size": "4841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/python/imx7-var-som/alpine/3.12/3.5.10/build/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
<?php
class ConfigurationsController extends AppController {
var $name = 'Configurations';
var $uses = array();
function beforeFilter(){
parent::beforeFilter();
//debug($this->Session->read('Auth.User.group_id')); die;
if ($this->Session->read('Auth.User.group_id') == '3'){
$this->Session->setFlash(__('Acceso Restringido.', true));
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
}
}
function index() {
}
function help(){
}
function sitebackup () {
$this->autoRender = false;
if ((!$this->Session->check('Auth.User')) || ($this->Session->read('Auth.User.group_id') != 1)) {
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
}
//$dir = '/home/guzman6001/Dropbox/atesis/app/backups';
$dir = $_SERVER['HTTP_HOST'] . $this->base . "/app/";
//$dir = "C:".DS."Program Files (x86)".DS."Apache Software Foundation".DS."Apache2.2".DS."htdocs".DS."tesis".DS."webroot".DS."backups".DS;
$respaldar = $_SERVER['HTTP_HOST']. $this->base . "/app/webroot/backups/";
//$respaldar = $_SERVER['HTTP_HOST'] . $this->base.DS.'app'.DS.'webroot'.DS.'backups'.DS;
//$respaldar = "C:".DS."Program Files (x86)".DS."Apache Software Foundation".DS."Apache2.2".DS."htdocs".DS."tesis".DS."webroot".DS."backups".DS;
// Directory to backup.
$filename = 'bvmjm' . date("_Y_m_d_H_i_s") . '.tar'; //path to where the file will be saved.
$C_RUTA_ARCHIVO = $dir . $filename;
//ejecutamos
//if (!function_exists('shell_exec')) {
// $this->Session->setFlash(__('No está habilitada la función PHP shell_exec en el servidor.', true));
//} else {
if(!shell_exec("tar cvf $C_RUTA_ARCHIVO $respaldar")) {
//$this->Session->setFlash(__('No se pudo comprimir el respaldo, por favor verifique que está instalado TAR.', true));
echo "<div style='border: solid #803C00; border-style: !important;'>No se pudo comprimir el respaldo, por favor verifique que está instalado .tar.</div>";
} else {
//$this->Session->setFlash(__('Respaldo creado con éxito.', true));
echo "<div style='border: solid #803C00; border-style: !important;'>Respaldo creado con éxito. <br /><a href='".$C_RUTA_ARCHIVO."' target='_new'>Abrir</a></div>";
}
//}
//$this->set('path', $C_RUTA_ARCHIVO);
//$this->redirect(array('action' => 'index'));
}
function dbbackup() {
$this->autoRender = false;
if ((!$this->Session->check('Auth.User')) || ($this->Session->read('Auth.User.group_id') != 1)) {
$this->redirect(array('controller' => 'pages', 'action' => 'home'));
}
//Directorio
//$dir = $_SERVER['HTTP_HOST'] . $this->base.DS.'webroot'.DS.'backups'.DS;
$dir = $this->base . "/html/app/webroot/backups";
//Servidor MySql
$C_SERVER = 'localhost';
//Base de datos
$C_BASE_DATOS = 'bvmjm';
//$C_BASE_DATOS = 'ofeliast_tesis';
//Usuario y contraseña de la base de datos mysql
$C_USUARIO = 'bvmjm';
//$C_USUARIO = 'ofeliast_tesis';
$C_CONTRASENA = 't2kf3w7d3i';
//$C_CONTRASENA = '7z4gyhf18)Dc';
//Ruta archivo de salida
//(el nombre lo componemos con Y_m_d_H_i_s para que sea diferente en cada backup)
$C_RUTA_NAME = 'backup_' . date("Y_m_d_H_i_s") . '.sql';
$C_RUTA_URL = $this->base . "/webroot/backups/" . $C_RUTA_NAME;
$C_RUTA_ARCHIVO = $dir . $C_RUTA_NAME;
//Si vamos a comprimirlo ...
//$C_COMPRIMIR_MYSQL = 'true';
$command = "mysqldump --opt --host=$C_SERVER --user=$C_USUARIO --password=$C_CONTRASENA $C_BASE_DATOS > \"$C_RUTA_ARCHIVO\"";
//Ejecutamos
if (!function_exists('shell_exec')) {
//$this->Session->setFlash(__('No está habilitada la función PHP shell_exec en el servidor.', true));
echo "<div style='border: solid #803C00; border-style: !important;'>No está habilitada la función PHP shell_exec en el servidor.</div>";
} else {
//if(!system($command)){
//$this->Session->setFlash(__('No se pudo ejecutar mysqldump, por favor verifique que está instalado en el servidor.', true));
//echo 'No se pudo ejecutar mysqldump, por favor verifique que está instalado en el servidor.<br>';
//echo system($command);
//} else {
//$this->Session->setFlash(__("Respaldo creado con éxito. <a href='".$C_RUTA_ARCHIVO."'></a>", true));
echo "<div style='border: solid #803C00; border-style: !important;'>Respaldo creado con éxito. <br /><a href='".$C_RUTA_URL."' target='_new'>Abrir</a></div>";
//}
$output = shell_exec($command);
// Write to the log file
/*
if (preg_match('/Got error/', $output)) {
$this->Session->setFlash(__('No se pudo ejecutar mysqldump, por favor verifique que está instalado en el servidor.', true));
} else {
$this->Session->setFlash(__("Respaldo creado con éxito. <a href='".$C_RUTA_ARCHIVO."'></a>", true));
}*/
}
//$this->render('index');
//$this->set('ruta', $C_RUTA_ARCHIVO);
//$this->redirect(array('action' => 'index'));
}
}
?> | {
"content_hash": "27aaae671346c93feed485925555f482",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 166,
"avg_line_length": 40.524193548387096,
"alnum_prop": 0.60318407960199,
"repo_name": "ragmar/bvmjm",
"id": "ebf3d28336497cfa429541673b517450400fac0a",
"size": "5042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controllers/configurations_controller.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "335"
},
{
"name": "CSS",
"bytes": "832003"
},
{
"name": "JavaScript",
"bytes": "3251935"
},
{
"name": "PHP",
"bytes": "6344017"
},
{
"name": "Perl",
"bytes": "12036"
}
],
"symlink_target": ""
} |
package lectures;
import static org.assertj.core.api.Assertions.assertThat;
import com.google.common.collect.ImmutableList;
import java.awt.*;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
public class Lecture4 {
@Test
public void distinct() throws Exception {
final List<Integer> numbers = ImmutableList.of(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9);
List<Integer> distinct = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinct);
}
@Test
public void distinctWithSet() throws Exception {
final List<Integer> numbers = ImmutableList.of(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9);
numbers.stream()
.collect(Collectors.toSet())
.forEach(System.out::println);
}
}
| {
"content_hash": "84fe3f383e0b5b654ce61871821d387b",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 114,
"avg_line_length": 26.727272727272727,
"alnum_prop": 0.6394557823129252,
"repo_name": "europa1613/java",
"id": "b787bc6d1c3b23dcce3d618a10e4826f5b716190",
"size": "882",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "streams-base/src/test/java/lectures/Lecture4.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "750"
},
{
"name": "Java",
"bytes": "147589"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.codecommit.model;
import javax.annotation.Generated;
/**
* <p>
* An approval rule name is required, but was not specified.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ApprovalRuleNameRequiredException extends com.amazonaws.services.codecommit.model.AWSCodeCommitException {
private static final long serialVersionUID = 1L;
/**
* Constructs a new ApprovalRuleNameRequiredException with the specified error message.
*
* @param message
* Describes the error encountered.
*/
public ApprovalRuleNameRequiredException(String message) {
super(message);
}
}
| {
"content_hash": "5d825a6e01aae11b3a203314c5be15fe",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 119,
"avg_line_length": 27.24,
"alnum_prop": 0.7209985315712188,
"repo_name": "aws/aws-sdk-java",
"id": "fdc72332f73f421e2741a583324fcd05d9697a23",
"size": "1261",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-codecommit/src/main/java/com/amazonaws/services/codecommit/model/ApprovalRuleNameRequiredException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package account
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// UserAgent returns the UserAgent string to use when sending http.Requests.
func UserAgent() string {
return "Azure-SDK-For-Go/v12.4.0-beta services"
}
// Version returns the semantic version (see http://semver.org) of the client.
func Version() string {
return "v12.4.0-beta"
}
| {
"content_hash": "23b4f396e1aa40c0a63c69f193cf62dd",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 84,
"avg_line_length": 38.214285714285715,
"alnum_prop": 0.7495327102803738,
"repo_name": "mrogers950/origin",
"id": "f215bf10ffe4c6322d2235017ab5cd16e6bf31a9",
"size": "1070",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "vendor/github.com/Azure/azure-sdk-for-go/services/datalake/analytics/mgmt/2016-11-01/account/version.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "921"
},
{
"name": "DIGITAL Command Language",
"bytes": "117"
},
{
"name": "Go",
"bytes": "14899633"
},
{
"name": "HTML",
"bytes": "3131"
},
{
"name": "Makefile",
"bytes": "8599"
},
{
"name": "Perl",
"bytes": "365"
},
{
"name": "Python",
"bytes": "16070"
},
{
"name": "Ruby",
"bytes": "484"
},
{
"name": "Shell",
"bytes": "989155"
}
],
"symlink_target": ""
} |
<?php
namespace InfluxDB;
use Prophecy\Argument;
class ManagerTest extends \PHPUnit_Framework_TestCase
{
public function testQueryCommandWithCallables()
{
$client = $this->prophesize("InfluxDB\Client");
$client->query("CREATE DATABASE mydb")->shouldBeCalledTimes(1);
$manager = new Manager($client->reveal());
$manager->addQuery("createDatabase", function($name) {
return "CREATE DATABASE {$name}";
});
$manager->createDatabase("mydb");
}
public function testQueryCommandReturnsTheCommandData()
{
$client = $this->prophesize("InfluxDB\Client");
$client->query(Argument::Any())->willReturn("OK");
$manager = new Manager($client->reveal());
$manager->addQuery("anything", function() {});
$data = $manager->anything();
$this->assertEquals("OK", $data);
}
public function testInvokableCommands()
{
$client = $this->prophesize("InfluxDB\Client");
$client->query("CREATE DATABASE mydb")->shouldBeCalledTimes(1);
$manager = new Manager($client->reveal());
$manager->addQuery(new CreateDatabaseMock());
$manager->createDatabase("mydb");
}
/**
* @expectedException InvalidArgumentException
*/
public function testNotCallableMethods()
{
$client = $this->prophesize("InfluxDB\Client");
$manager = new Manager($client->reveal());
$manager->addQuery(new NotCallable());
}
/**
* @expectedException InvalidArgumentException
*/
public function testClassWithoutNameException()
{
$client = $this->prophesize("InfluxDB\Client");
$manager = new Manager($client->reveal());
$manager->addQuery(new NoName());
}
public function testFallbackToClientMethods()
{
$client = $this->prophesize("InfluxDB\Client");
$client->mark("hello", ["data" => true])->shouldBeCalledTimes(1);
$manager = new Manager($client->reveal());
$manager->mark("hello", ["data" => true]);
}
/**
* @expectedException RuntimeException
* @expectedExceptionMessage The method you are using is not allowed: 'missingMethod', do you have to add it with 'addQuery'
*/
public function testCallMissingMethod()
{
$client = $this->prophesize("InfluxDB\Client");
$manager = new Manager($client->reveal());
$manager->missingMethod();
}
}
class NoName
{
public function __invoke($args)
{
return "TEST";
}
}
class NotCallable
{
public function __toString()
{
return "hello";
}
}
class CreateDatabaseMock
{
public function __invoke($name)
{
return "CREATE DATABASE {$name}";
}
public function __toString()
{
return "createDatabase";
}
}
| {
"content_hash": "db7eb915c09a2009e2834f92f08c8683",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 128,
"avg_line_length": 25.017543859649123,
"alnum_prop": 0.6048387096774194,
"repo_name": "corley/influxdb-php-sdk",
"id": "ae0d6d628618bf0077a088aa41d48accbff30c3e",
"size": "2852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/ManagerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "62301"
}
],
"symlink_target": ""
} |
The `ide-haskell-cabal` package provides a build backend for `ide-haskell`
package based on `cabal` or `stack`.
It supports easy switching between multiple versions of GHC by having a set of configuration settings for each version of GHC, plus a drop-down box to pick a GHC version. For each GHC version you can specify:
* The path (either adding to your system path or replacing it completely)
* The sandbox file (cabal `CABAL_SANDBOX_CONFIG` environment variable)
* The build directory (cabal `--builddir` parameter). This defaults to `dist/`.
It also provides support for `ide-haskell`'s build target selection by reading and parsing the `.cabal` file and extracting the available targets (it uses a thin `ghcjs`-compiled wrapper around the `Cabal` library to read the `.cabal` file).
## Installation and configuration
Please refer to documentation site https://atom-haskell.github.io
# License
Copyright © 2015 Atom-Haskell
Contributors (by number of commits):
<!-- BEGIN CONTRIBUTORS LIST -->
* Nikolay Yakimov
* Edsko de Vries
<!-- END CONTRIBUTORS LIST -->
See the [LICENSE.md][LICENSE] for details.
[LICENSE]: https://github.com/atom-haskell/ide-haskell-cabal/blob/master/LICENSE.md
| {
"content_hash": "77e84b9b4ce1eb0e691161de2cab0d99",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 241,
"avg_line_length": 40.1,
"alnum_prop": 0.7630922693266833,
"repo_name": "atom-haskell/ide-haskell-cabal",
"id": "250773bea53ff4caa113baf867b971f71b8ff907",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "494"
},
{
"name": "TypeScript",
"bytes": "56497"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_07) on Tue May 27 14:37:22 EEST 2014 -->
<title>net.sf.jasperreports.components.map.fill Class Hierarchy (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="net.sf.jasperreports.components.map.fill Class Hierarchy (JasperReports 5.6.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../net/sf/jasperreports/components/map/package-tree.html">Prev</a></li>
<li><a href="../../../../../../net/sf/jasperreports/components/map/type/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?net/sf/jasperreports/components/map/fill/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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 class="title">Hierarchy For Package net.sf.jasperreports.components.map.fill</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../../../../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">net.sf.jasperreports.engine.component.<a href="../../../../../../net/sf/jasperreports/engine/component/BaseFillComponent.html" title="class in net.sf.jasperreports.engine.component"><span class="strong">BaseFillComponent</span></a> (implements net.sf.jasperreports.engine.component.<a href="../../../../../../net/sf/jasperreports/engine/component/FillComponent.html" title="interface in net.sf.jasperreports.engine.component">FillComponent</a>)
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/MapFillComponent.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">MapFillComponent</span></a> (implements net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillContextProvider.html" title="interface in net.sf.jasperreports.components.map.fill">FillContextProvider</a>)</li>
</ul>
</li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillItem.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillItem</span></a> (implements net.sf.jasperreports.components.map.<a href="../../../../../../net/sf/jasperreports/components/map/Item.html" title="interface in net.sf.jasperreports.components.map">Item</a>)
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillPlaceItem.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillPlaceItem</span></a></li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillStyleItem.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillStyleItem</span></a></li>
</ul>
</li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillItemData.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillItemData</span></a>
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillPlaceItemData.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillPlaceItemData</span></a></li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillStyleItemData.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillStyleItemData</span></a></li>
</ul>
</li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillMarker.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillMarker</span></a> (implements net.sf.jasperreports.components.map.<a href="../../../../../../net/sf/jasperreports/components/map/Marker.html" title="interface in net.sf.jasperreports.components.map">Marker</a>)</li>
<li type="circle">net.sf.jasperreports.engine.fill.<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillDatasetRun.html" title="class in net.sf.jasperreports.engine.fill"><span class="strong">JRFillDatasetRun</span></a> (implements net.sf.jasperreports.engine.<a href="../../../../../../net/sf/jasperreports/engine/JRDatasetRun.html" title="interface in net.sf.jasperreports.engine">JRDatasetRun</a>)
<ul>
<li type="circle">net.sf.jasperreports.components.list.<a href="../../../../../../net/sf/jasperreports/components/list/FillDatasetRun.html" title="class in net.sf.jasperreports.components.list"><span class="strong">FillDatasetRun</span></a>
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/MarkerFillDatasetRun.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">MarkerFillDatasetRun</span></a></li>
</ul>
</li>
</ul>
</li>
<li type="circle">net.sf.jasperreports.engine.fill.<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillElementDataset.html" title="class in net.sf.jasperreports.engine.fill"><span class="strong">JRFillElementDataset</span></a> (implements net.sf.jasperreports.engine.<a href="../../../../../../net/sf/jasperreports/engine/JRElementDataset.html" title="interface in net.sf.jasperreports.engine">JRElementDataset</a>)
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillItemDataset.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">FillItemDataset</span></a></li>
</ul>
</li>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/MapFillFactory.html" title="class in net.sf.jasperreports.components.map.fill"><span class="strong">MapFillFactory</span></a> (implements net.sf.jasperreports.engine.component.<a href="../../../../../../net/sf/jasperreports/engine/component/ComponentFillFactory.html" title="interface in net.sf.jasperreports.engine.component">ComponentFillFactory</a>)</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">net.sf.jasperreports.components.map.fill.<a href="../../../../../../net/sf/jasperreports/components/map/fill/FillContextProvider.html" title="interface in net.sf.jasperreports.components.map.fill"><span class="strong">FillContextProvider</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../net/sf/jasperreports/components/map/package-tree.html">Prev</a></li>
<li><a href="../../../../../../net/sf/jasperreports/components/map/type/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?net/sf/jasperreports/components/map/fill/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.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>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001-2010 Jaspersoft Corporation <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
| {
"content_hash": "b0f0f6ef6e8f5721bb7c85f4417dc27a",
"timestamp": "",
"source": "github",
"line_count": 169,
"max_line_length": 495,
"avg_line_length": 61.74556213017752,
"alnum_prop": 0.6751317680881649,
"repo_name": "phurtado1112/cnaemvc",
"id": "2804aa5de6eda9d15e2a2044bc0745811a1477e9",
"size": "10435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/JasperReport__5.6/docs/api/net/sf/jasperreports/components/map/fill/package-tree.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "HTML",
"bytes": "112926414"
},
{
"name": "Java",
"bytes": "532942"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace Doctrine\Tests\ORM\Mapping;
use Doctrine\Common\Annotations\AnnotationException;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\ORM\Cache\Exception\CacheException;
use Doctrine\ORM\Mapping;
use Doctrine\ORM\Mapping\Cache;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\DiscriminatorMap;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\InheritanceType;
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\MappedSuperclass;
use Doctrine\ORM\Mapping\MappingException;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\PostLoad;
use Doctrine\ORM\Mapping\PreUpdate;
use Doctrine\Persistence\Mapping\Driver\MappingDriver;
use Doctrine\Persistence\Mapping\RuntimeReflectionService;
use Doctrine\Tests\Models\CMS\CmsUser;
use Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithoutOverride;
use Doctrine\Tests\Models\DDC1872\DDC1872ExampleEntityWithOverride;
use Doctrine\Tests\Models\DirectoryTree\Directory;
use Doctrine\Tests\Models\DirectoryTree\File;
use Doctrine\Tests\Models\ECommerce\ECommerceCart;
class AnnotationDriverTest extends AbstractMappingDriverTest
{
/**
* @group DDC-268
*/
public function testLoadMetadataForNonEntityThrowsException(): void
{
$cm = new ClassMetadata('stdClass');
$cm->initializeReflection(new RuntimeReflectionService());
$reader = new AnnotationReader();
$annotationDriver = new AnnotationDriver($reader);
$this->expectException(MappingException::class);
$annotationDriver->loadMetadataForClass('stdClass', $cm);
}
public function testFailingSecondLevelCacheAssociation(): void
{
$this->expectException(CacheException::class);
$this->expectExceptionMessage('Entity association field "Doctrine\Tests\ORM\Mapping\AnnotationSLC#foo" not configured as part of the second-level cache.');
$mappingDriver = $this->loadDriver();
$class = new ClassMetadata(AnnotationSLC::class);
$mappingDriver->loadMetadataForClass(AnnotationSLC::class, $class);
}
/**
* @group DDC-268
*/
public function testColumnWithMissingTypeDefaultsToString(): void
{
$cm = new ClassMetadata(ColumnWithoutType::class);
$cm->initializeReflection(new RuntimeReflectionService());
$annotationDriver = $this->loadDriver();
$annotationDriver->loadMetadataForClass(Mapping\InvalidColumn::class, $cm);
self::assertEquals('string', $cm->fieldMappings['id']['type']);
}
/**
* @group DDC-318
*/
public function testGetAllClassNamesIsIdempotent(): void
{
$annotationDriver = $this->loadDriverForCMSModels();
$original = $annotationDriver->getAllClassNames();
$annotationDriver = $this->loadDriverForCMSModels();
$afterTestReset = $annotationDriver->getAllClassNames();
self::assertEquals($original, $afterTestReset);
}
/**
* @group DDC-318
*/
public function testGetAllClassNamesIsIdempotentEvenWithDifferentDriverInstances(): void
{
$annotationDriver = $this->loadDriverForCMSModels();
$original = $annotationDriver->getAllClassNames();
$annotationDriver = $this->loadDriverForCMSModels();
$afterTestReset = $annotationDriver->getAllClassNames();
self::assertEquals($original, $afterTestReset);
}
/**
* @group DDC-318
*/
public function testGetAllClassNamesReturnsAlreadyLoadedClassesIfAppropriate(): void
{
$this->ensureIsLoaded(CmsUser::class);
$annotationDriver = $this->loadDriverForCMSModels();
$classes = $annotationDriver->getAllClassNames();
self::assertContains(CmsUser::class, $classes);
}
/**
* @group DDC-318
*/
public function testGetClassNamesReturnsOnlyTheAppropriateClasses(): void
{
$this->ensureIsLoaded(ECommerceCart::class);
$annotationDriver = $this->loadDriverForCMSModels();
$classes = $annotationDriver->getAllClassNames();
self::assertNotContains(ECommerceCart::class, $classes);
}
protected function loadDriverForCMSModels(): AnnotationDriver
{
$annotationDriver = $this->loadDriver();
$annotationDriver->addPaths([__DIR__ . '/../../Models/CMS/']);
return $annotationDriver;
}
protected function loadDriver(): MappingDriver
{
return $this->createAnnotationDriver();
}
/**
* @psalm-var class-string<object> $entityClassName
*/
protected function ensureIsLoaded(string $entityClassName): void
{
new $entityClassName();
}
/**
* @group DDC-671
*
* Entities for this test are in AbstractMappingDriverTest
*/
public function testJoinTablesWithMappedSuperclassForAnnotationDriver(): void
{
$annotationDriver = $this->loadDriver();
$annotationDriver->addPaths([__DIR__ . '/../../Models/DirectoryTree/']);
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
$classPage = $factory->getMetadataFor(File::class);
self::assertEquals(File::class, $classPage->associationMappings['parentDirectory']['sourceEntity']);
$classDirectory = $factory->getMetadataFor(Directory::class);
self::assertEquals(Directory::class, $classDirectory->associationMappings['parentDirectory']['sourceEntity']);
}
/**
* @group DDC-945
*/
public function testInvalidMappedSuperClassWithManyToManyAssociation(): void
{
$annotationDriver = $this->loadDriver();
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
$this->expectException(MappingException::class);
$this->expectExceptionMessage(
'It is illegal to put an inverse side one-to-many or many-to-many association on ' .
"mapped superclass 'Doctrine\Tests\ORM\Mapping\InvalidMappedSuperClass#users'"
);
$factory->getMetadataFor(UsingInvalidMappedSuperClass::class);
}
/**
* @group DDC-1050
*/
public function testInvalidMappedSuperClassWithInheritanceInformation(): void
{
$annotationDriver = $this->loadDriver();
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
$this->expectException(MappingException::class);
$this->expectExceptionMessage(
'It is not supported to define inheritance information on a mapped ' .
"superclass '" . MappedSuperClassInheritence::class . "'."
);
$usingInvalidMsc = $factory->getMetadataFor(MappedSuperClassInheritence::class);
}
/**
* @group DDC-1034
*/
public function testInheritanceSkipsParentLifecycleCallbacks(): void
{
$annotationDriver = $this->loadDriver();
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
$cm = $factory->getMetadataFor(AnnotationChild::class);
self::assertEquals(['postLoad' => ['postLoad'], 'preUpdate' => ['preUpdate']], $cm->lifecycleCallbacks);
$cm = $factory->getMetadataFor(AnnotationParent::class);
self::assertEquals(['postLoad' => ['postLoad'], 'preUpdate' => ['preUpdate']], $cm->lifecycleCallbacks);
}
/**
* @group DDC-1156
*/
public function testMappedSuperclassInMiddleOfInheritanceHierarchy(): void
{
$annotationDriver = $this->loadDriver();
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
self::assertInstanceOf(ClassMetadata::class, $factory->getMetadataFor(ChildEntity::class));
}
public function testInvalidFetchOptionThrowsException(): void
{
$annotationDriver = $this->loadDriver();
$em = $this->getTestEntityManager();
$em->getConfiguration()->setMetadataDriverImpl($annotationDriver);
$factory = new ClassMetadataFactory();
$factory->setEntityManager($em);
$this->expectException(MappingException::class);
$this->expectExceptionMessage("Entity 'Doctrine\Tests\ORM\Mapping\InvalidFetchOption' has a mapping with invalid fetch mode 'eager'");
$factory->getMetadataFor(InvalidFetchOption::class);
}
public function testAttributeOverridesMappingWithTrait(): void
{
$factory = $this->createClassMetadataFactory();
$metadataWithoutOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithoutOverride::class);
$metadataWithOverride = $factory->getMetadataFor(DDC1872ExampleEntityWithOverride::class);
self::assertEquals('trait_foo', $metadataWithoutOverride->fieldMappings['foo']['columnName']);
self::assertEquals('foo_overridden', $metadataWithOverride->fieldMappings['foo']['columnName']);
self::assertArrayHasKey('example_trait_bar_id', $metadataWithoutOverride->associationMappings['bar']['joinColumnFieldNames']);
self::assertArrayHasKey('example_entity_overridden_bar_id', $metadataWithOverride->associationMappings['bar']['joinColumnFieldNames']);
}
}
/**
* @Entity
*/
class ColumnWithoutType
{
/**
* @var int
* @Id
* @Column
*/
public $id;
}
/**
* @MappedSuperclass
*/
class InvalidMappedSuperClass
{
/**
* @psalm-var Collection<int, CmsUser>
* @ManyToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", mappedBy="invalid")
*/
private $users;
}
/**
* @Entity
*/
class UsingInvalidMappedSuperClass extends InvalidMappedSuperClass
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
}
/**
* @MappedSuperclass
* @InheritanceType("JOINED")
* @DiscriminatorMap({"test" = "ColumnWithoutType"})
*/
class MappedSuperClassInheritence
{
}
/**
* @Entity
* @InheritanceType("JOINED")
* @DiscriminatorMap({"parent" = "AnnotationParent", "child" = "AnnotationChild"})
* @HasLifecycleCallbacks
*/
class AnnotationParent
{
/**
* @var int
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @PostLoad
*/
public function postLoad(): void
{
}
/**
* @PreUpdate
*/
public function preUpdate(): void
{
}
}
/**
* @Entity
* @HasLifecycleCallbacks
*/
class AnnotationChild extends AnnotationParent
{
}
/**
* @Entity
* @InheritanceType("SINGLE_TABLE")
* @DiscriminatorMap({"s"="SuperEntity", "c"="ChildEntity"})
*/
class SuperEntity
{
/**
* @var string
* @Id
* @Column(type="string")
*/
private $id;
}
/**
* @MappedSuperclass
*/
class MiddleMappedSuperclass extends SuperEntity
{
/**
* @var string
* @Column(type="string")
*/
private $name;
}
/**
* @Entity
*/
class ChildEntity extends MiddleMappedSuperclass
{
/**
* @var string
* @Column(type="string")
*/
private $text;
}
/**
* @Entity
*/
class InvalidFetchOption
{
/**
* @var CmsUser
* @OneToMany(targetEntity="Doctrine\Tests\Models\CMS\CmsUser", fetch="eager")
*/
private $collection;
}
/**
* @Entity
* @Cache
*/
class AnnotationSLC
{
/**
* @var AnnotationSLCFoo
* @Id
* @ManyToOne(targetEntity="AnnotationSLCFoo")
*/
public $foo;
}
/**
* @Entity
*/
class AnnotationSLCFoo
{
/**
* @var string
* @Column(type="string")
*/
public $id;
}
| {
"content_hash": "0c093ad8764f207cd9bd6586befc4f19",
"timestamp": "",
"source": "github",
"line_count": 441,
"max_line_length": 163,
"avg_line_length": 28.17233560090703,
"alnum_prop": 0.6659690920798454,
"repo_name": "doctrine/doctrine2",
"id": "00a9c6b127ea8e4896395d72eb7fdb9a6542f7f8",
"size": "12424",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.11.x",
"path": "tests/Doctrine/Tests/ORM/Mapping/AnnotationDriverTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "220"
},
{
"name": "PHP",
"bytes": "4601048"
},
{
"name": "Shell",
"bytes": "1544"
}
],
"symlink_target": ""
} |
package com.google.ads.googleads.v11.services;
public final class KeywordPlanAdGroupServiceProto {
private KeywordPlanAdGroupServiceProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsRequest_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v11_services_KeywordPlanAdGroupOperation_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v11_services_KeywordPlanAdGroupOperation_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsResponse_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupResult_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupResult_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\nEgoogle/ads/googleads/v11/services/keyw" +
"ord_plan_ad_group_service.proto\022!google." +
"ads.googleads.v11.services\032>google/ads/g" +
"oogleads/v11/resources/keyword_plan_ad_g" +
"roup.proto\032\034google/api/annotations.proto" +
"\032\027google/api/client.proto\032\037google/api/fi" +
"eld_behavior.proto\032\031google/api/resource." +
"proto\032 google/protobuf/field_mask.proto\032" +
"\027google/rpc/status.proto\"\305\001\n MutateKeywo" +
"rdPlanAdGroupsRequest\022\030\n\013customer_id\030\001 \001" +
"(\tB\003\340A\002\022W\n\noperations\030\002 \003(\0132>.google.ads" +
".googleads.v11.services.KeywordPlanAdGro" +
"upOperationB\003\340A\002\022\027\n\017partial_failure\030\003 \001(" +
"\010\022\025\n\rvalidate_only\030\004 \001(\010\"\263\002\n\033KeywordPlan" +
"AdGroupOperation\022/\n\013update_mask\030\004 \001(\0132\032." +
"google.protobuf.FieldMask\022H\n\006create\030\001 \001(" +
"\01326.google.ads.googleads.v11.resources.K" +
"eywordPlanAdGroupH\000\022H\n\006update\030\002 \001(\01326.go" +
"ogle.ads.googleads.v11.resources.Keyword" +
"PlanAdGroupH\000\022B\n\006remove\030\003 \001(\tB0\372A-\n+goog" +
"leads.googleapis.com/KeywordPlanAdGroupH" +
"\000B\013\n\toperation\"\252\001\n!MutateKeywordPlanAdGr" +
"oupsResponse\0221\n\025partial_failure_error\030\003 " +
"\001(\0132\022.google.rpc.Status\022R\n\007results\030\002 \003(\013" +
"2A.google.ads.googleads.v11.services.Mut" +
"ateKeywordPlanAdGroupResult\"i\n\036MutateKey" +
"wordPlanAdGroupResult\022G\n\rresource_name\030\001" +
" \001(\tB0\372A-\n+googleads.googleapis.com/Keyw" +
"ordPlanAdGroup2\352\002\n\031KeywordPlanAdGroupSer" +
"vice\022\205\002\n\031MutateKeywordPlanAdGroups\022C.goo" +
"gle.ads.googleads.v11.services.MutateKey" +
"wordPlanAdGroupsRequest\032D.google.ads.goo" +
"gleads.v11.services.MutateKeywordPlanAdG" +
"roupsResponse\"]\202\323\344\223\002>\"9/v11/customers/{c" +
"ustomer_id=*}/keywordPlanAdGroups:mutate" +
":\001*\332A\026customer_id,operations\032E\312A\030googlea" +
"ds.googleapis.com\322A\'https://www.googleap" +
"is.com/auth/adwordsB\212\002\n%com.google.ads.g" +
"oogleads.v11.servicesB\036KeywordPlanAdGrou" +
"pServiceProtoP\001ZIgoogle.golang.org/genpr" +
"oto/googleapis/ads/googleads/v11/service" +
"s;services\242\002\003GAA\252\002!Google.Ads.GoogleAds." +
"V11.Services\312\002!Google\\Ads\\GoogleAds\\V11\\" +
"Services\352\002%Google::Ads::GoogleAds::V11::" +
"Servicesb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.ads.googleads.v11.resources.KeywordPlanAdGroupProto.getDescriptor(),
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
com.google.rpc.StatusProto.getDescriptor(),
});
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsRequest_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsRequest_descriptor,
new java.lang.String[] { "CustomerId", "Operations", "PartialFailure", "ValidateOnly", });
internal_static_google_ads_googleads_v11_services_KeywordPlanAdGroupOperation_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_ads_googleads_v11_services_KeywordPlanAdGroupOperation_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v11_services_KeywordPlanAdGroupOperation_descriptor,
new java.lang.String[] { "UpdateMask", "Create", "Update", "Remove", "Operation", });
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsResponse_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsResponse_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupsResponse_descriptor,
new java.lang.String[] { "PartialFailureError", "Results", });
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupResult_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupResult_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v11_services_MutateKeywordPlanAdGroupResult_descriptor,
new java.lang.String[] { "ResourceName", });
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor
.internalUpdateFileDescriptor(descriptor, registry);
com.google.ads.googleads.v11.resources.KeywordPlanAdGroupProto.getDescriptor();
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
com.google.rpc.StatusProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| {
"content_hash": "a0511d492c0b863f016da31d9f38d952",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 112,
"avg_line_length": 58.763888888888886,
"alnum_prop": 0.7514771921531553,
"repo_name": "googleads/google-ads-java",
"id": "fc0c447c4787ac05922414913e85e9b071a815ec",
"size": "8604",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "google-ads-stubs-v11/src/main/java/com/google/ads/googleads/v11/services/KeywordPlanAdGroupServiceProto.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28701198"
}
],
"symlink_target": ""
} |
package com.netflix.discovery.shared.resolver;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Tomasz Bak
*/
public class DefaultEndpoint implements EurekaEndpoint {
protected final String networkAddress;
protected final int port;
protected final boolean isSecure;
protected final String relativeUri;
protected final String serviceUrl;
public DefaultEndpoint(String serviceUrl) {
this.serviceUrl = serviceUrl;
try {
URL url = new URL(serviceUrl);
this.networkAddress = url.getHost();
this.port = url.getPort();
this.isSecure = "https".equals(url.getProtocol());
this.relativeUri = url.getPath();
} catch (Exception e) {
throw new IllegalArgumentException("Malformed serviceUrl: " + serviceUrl);
}
}
public DefaultEndpoint(String networkAddress, int port, boolean isSecure, String relativeUri) {
this.networkAddress = networkAddress;
this.port = port;
this.isSecure = isSecure;
this.relativeUri = relativeUri;
StringBuilder sb = new StringBuilder()
.append(isSecure ? "https" : "http")
.append("://")
.append(networkAddress);
if (port >= 0) {
sb.append(':')
.append(port);
}
if (relativeUri != null) {
if (!relativeUri.startsWith("/")) {
sb.append('/');
}
sb.append(relativeUri);
}
this.serviceUrl = sb.toString();
}
@Override
public String getServiceUrl() {
return serviceUrl;
}
@Deprecated
@Override
public String getHostName() {
return networkAddress;
}
@Override
public String getNetworkAddress() {
return networkAddress;
}
@Override
public int getPort() {
return port;
}
@Override
public boolean isSecure() {
return isSecure;
}
@Override
public String getRelativeUri() {
return relativeUri;
}
public static List<EurekaEndpoint> createForServerList(
List<String> hostNames, int port, boolean isSecure, String relativeUri) {
if (hostNames.isEmpty()) {
return Collections.emptyList();
}
List<EurekaEndpoint> eurekaEndpoints = new ArrayList<>(hostNames.size());
for (String hostName : hostNames) {
eurekaEndpoints.add(new DefaultEndpoint(hostName, port, isSecure, relativeUri));
}
return eurekaEndpoints;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof DefaultEndpoint)) return false;
DefaultEndpoint that = (DefaultEndpoint) o;
if (isSecure != that.isSecure) return false;
if (port != that.port) return false;
if (networkAddress != null ? !networkAddress.equals(that.networkAddress) : that.networkAddress != null) return false;
if (relativeUri != null ? !relativeUri.equals(that.relativeUri) : that.relativeUri != null) return false;
if (serviceUrl != null ? !serviceUrl.equals(that.serviceUrl) : that.serviceUrl != null) return false;
return true;
}
@Override
public int hashCode() {
int result = networkAddress != null ? networkAddress.hashCode() : 0;
result = 31 * result + port;
result = 31 * result + (isSecure ? 1 : 0);
result = 31 * result + (relativeUri != null ? relativeUri.hashCode() : 0);
result = 31 * result + (serviceUrl != null ? serviceUrl.hashCode() : 0);
return result;
}
@Override
public int compareTo(Object that) {
return serviceUrl.compareTo(((DefaultEndpoint) that).getServiceUrl());
}
@Override
public String toString() {
return "DefaultEndpoint{ serviceUrl='" + serviceUrl + '}';
}
}
| {
"content_hash": "1c39f5f1e39f86193b03d2f4ce339eaf",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 125,
"avg_line_length": 29.147058823529413,
"alnum_prop": 0.6082240161453077,
"repo_name": "qiangdavidliu/eureka",
"id": "2a4d1ffd81eb080d699d477255b3f95549b912d5",
"size": "4560",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "eureka-client/src/main/java/com/netflix/discovery/shared/resolver/DefaultEndpoint.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2048"
},
{
"name": "Java",
"bytes": "2034896"
},
{
"name": "Shell",
"bytes": "3048"
}
],
"symlink_target": ""
} |
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2016-02-14 using
// generator-karma 1.0.1
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
// as well as any additional frameworks (requirejs/chai/sinon/...)
frameworks: [
"jasmine"
],
// list of files / patterns to load in the browser
files: [
// bower:js
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/bootstrap/dist/js/bootstrap.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-xeditable/dist/js/xeditable.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/scripts/**/*.js",
"test/mock/**/*.js",
"test/spec/**/*.js"
],
// list of files / patterns to exclude
exclude: [
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
"PhantomJS"
],
// Which plugins to enable
plugins: [
"karma-phantomjs-launcher",
"karma-jasmine"
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
| {
"content_hash": "3d9bf32d66965c27bb7e47ec5e17b668",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 85,
"avg_line_length": 28.5,
"alnum_prop": 0.6278195488721805,
"repo_name": "marcsauter/igcstat",
"id": "696d539439bbf2b95eb72389e219d1d43cbb3786",
"size": "2394",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config-ui/test/karma.conf.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "110"
},
{
"name": "CSS",
"bytes": "1416"
},
{
"name": "Go",
"bytes": "9598"
},
{
"name": "HTML",
"bytes": "13172"
},
{
"name": "JavaScript",
"bytes": "16732"
},
{
"name": "Makefile",
"bytes": "1103"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication2.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | {
"content_hash": "c3a12ff7d67bc84ee5af5f546c8274b9",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 67,
"avg_line_length": 19.4,
"alnum_prop": 0.5670103092783505,
"repo_name": "jdg12/BootstrapMVA",
"id": "29fb65482c39648d7f47d9090d3793981dfc6616",
"size": "584",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "Module 2 - Components/Live Demo Version That Kind Of Works/WebApplication2/Controllers/HomeController.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "52042"
},
{
"name": "C#",
"bytes": "753260"
},
{
"name": "CSS",
"bytes": "120110"
},
{
"name": "HTML",
"bytes": "67838"
},
{
"name": "JavaScript",
"bytes": "256977"
}
],
"symlink_target": ""
} |
import { Component } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import '../../../scripts/jest/toHaveCssClass';
import { CarouselModule } from '../index';
import { getBsVer, IBsVersion } from 'ngx-bootstrap/utils';
@Component({ selector: 'carousel-test', template: '' })
class TestCarouselComponent {
myInterval = 5000;
noWrapSlides = false;
showIndicators = true;
itemsPerSlide = 1;
singleSlideOffset = false;
startFromIndex = 0;
get _bsVer(): IBsVersion {
return getBsVer();
}
slides: { image: string, text: string, active?: boolean }[] = [
{ image: '//placekitten.com/600/300', text: 'slide0' },
{ image: '//placekitten.com/600/300', text: 'slide1' },
{ image: '//placekitten.com/600/300', text: 'slide2' },
{ image: '//placekitten.com/600/300', text: 'slide3' },
{ image: '//placekitten.com/600/300', text: 'slide4' },
{ image: '//placekitten.com/600/300', text: 'slide5' }
];
}
const html = `
<div id='c1'>
<carousel [interval]='myInterval'
[noWrap]='noWrapSlides'
[showIndicators]='showIndicators'
[itemsPerSlide]='itemsPerSlide'>
<slide *ngFor='let slide of slides; let index=index'
[active]='slide.active'>
<img [src]='slide.image' style='margin:auto;' alt='slide image'>
<div class='carousel-caption'>
<h4>Slide {{index}}</h4>
<p>{{slide.text}}</p>
</div>
</slide>
</carousel>
</div>
<div id='c2'>
<carousel>
<slide>slide1</slide>
<slide>slide2</slide>
</carousel>
</div>
`;
function expectActiveSlides(nativeEl: HTMLDivElement, active: boolean[], bsVersion: IBsVersion): void {
const slideElms = nativeEl.querySelectorAll('.carousel-item');
const indicatorElms = bsVersion.isBs5 ? nativeEl.querySelectorAll('div.carousel-indicators > button') : nativeEl.querySelectorAll('ol.carousel-indicators > li');
expect(slideElms.length).toBe(active.length);
expect(indicatorElms.length).toBe(active.length);
for (let i = 0; i < active.length; i++) {
if (active[i]) {
expect(slideElms[i].classList).toContain('active');
expect(indicatorElms[i].classList).toContain('active');
} else {
expect(slideElms[i].classList).not.toContain('active');
expect(indicatorElms[i].classList).not.toContain('active');
}
}
}
describe('Component: Carousel', () => {
let fixture: ComponentFixture<TestCarouselComponent>;
let context: TestCarouselComponent;
let element;
const stableAct = (action) => {
action();
fixture.detectChanges();
return fixture.whenStable();
};
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestCarouselComponent],
imports: [CarouselModule]
});
TestBed.overrideComponent(TestCarouselComponent, {
set: { template: html }
});
fixture = TestBed.createComponent(TestCarouselComponent);
context = fixture.componentInstance;
element = fixture.nativeElement.querySelector('#c1');
fixture.detectChanges();
});
afterAll(async () => {
await new Promise<void>(resolve => setTimeout(() => resolve(), 500)); // avoid jest open handle error
});
it('should set first slide as active by default', () => {
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
});
// TODO:
xit('should be able to select a slide via model changes', () => {
context.slides[2].active = true;
fixture.detectChanges();
expectActiveSlides(element, [false, false, true, false, false, false],fixture.componentInstance._bsVer);
});
it('should create next/prev nav button', () => {
const prev = element.querySelectorAll('a.left');
const next = element.querySelectorAll('a.right');
expect(prev.length).toBe(1);
expect(next.length).toBe(1);
});
it('should display slide indicators', () => {
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
expect(indicators.length).toBe(6);
});
it('should hide navigation when only one slide', () => {
context.slides.splice(0, 5);
fixture.detectChanges();
expect(context.slides.length).toBe(1);
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
expect(indicators.length).toBe(0);
const prev = element.querySelectorAll('a.left');
expect(prev.length).toBe(0);
const next = element.querySelectorAll('a.right');
expect(next.length).toBe(0);
});
it('should disable prev button when slide index is 0, noWrap is truthy', () => {
context.noWrapSlides = true;
fixture.detectChanges();
const prev = element.querySelector('a.left');
expect(prev.classList).toContain('disabled');
});
it('should disable next button when last slide is active, noWrap is truthy', () => {
context.noWrapSlides = true;
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
indicators[5].click();
fixture.detectChanges();
const next = element.querySelector('a.right');
expect(next.classList).toContain('disabled');
});
it('should enable next button when last slide is active, noWrap is truthy', () => {
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
indicators[5].click();
fixture.detectChanges();
const next = element.querySelector('a.right');
expect(next.classList).not.toContain('disabled');
});
it('should change slide on indicator click', () => {
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
indicators[2].click();
fixture.detectChanges();
expectActiveSlides(element, [false, false, true, false, false, false],fixture.componentInstance._bsVer);
indicators[1].click();
fixture.detectChanges();
expectActiveSlides(element, [false, true, false, false, false, false],fixture.componentInstance._bsVer);
});
it('should hide carousel-indicators if property showIndicators is == false', () => {
context.showIndicators = false;
fixture.detectChanges();
expect(element.querySelector('ol')).toBeNull();
});
it('should change slide on carousel control click', () => {
const prev = element.querySelector('a.left');
const next = element.querySelector('a.right');
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, true, false, false, false, false],fixture.componentInstance._bsVer);
prev.click();
fixture.detectChanges();
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
});
it('should wrap slide changes by default', () => {
const prev = element.querySelector('a.left');
const next = element.querySelector('a.right');
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, true, false, false, false, false],fixture.componentInstance._bsVer);
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, false, true, false, false, false],fixture.componentInstance._bsVer);
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, false, false, true, false, false],fixture.componentInstance._bsVer);
prev.click();
fixture.detectChanges();
expectActiveSlides(element, [false, false, true, false, false, false],fixture.componentInstance._bsVer);
prev.click();
fixture.detectChanges();
expectActiveSlides(element, [false, true, false, false, false, false],fixture.componentInstance._bsVer);
prev.click();
fixture.detectChanges();
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
});
it('should not wrap slide changes if noWrap == true', () => {
context.noWrapSlides = true;
fixture.detectChanges();
const prev = element.querySelector('a.left');
const next = element.querySelector('a.right');
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
prev.click();
fixture.detectChanges();
expectActiveSlides(element, [true, false, false, false, false, false],fixture.componentInstance._bsVer);
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, true, false, false, false, false],fixture.componentInstance._bsVer);
next.click();
fixture.detectChanges();
expectActiveSlides(element, [false, false, true, false, false, false],fixture.componentInstance._bsVer);
});
it('Multilist: should select slides on carousel via indicator', fakeAsync(() => {
const indicators = fixture.componentInstance._bsVer.isBs5 ? element.querySelectorAll('div.carousel-indicators > button') : element.querySelectorAll('ol.carousel-indicators > li');
context.itemsPerSlide = 3;
fixture.detectChanges();
fixture.whenStable()
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => indicators[2].click()))
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => indicators[3].click()))
.then(() => expectActiveSlides(element, [false, false, false, true, true, true],fixture.componentInstance._bsVer));
}));
it('Multilist: should shift visible slides on carousel control click' +
'by number equal to itemsPerSlide value', fakeAsync(() => {
context.itemsPerSlide = 3;
fixture.detectChanges();
const prev = element.querySelector('a.left');
const next = element.querySelector('a.right');
fixture.whenStable()
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [false, false, false, true, true, true],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => prev.click()))
.then(() => expectActiveSlides(element, [false, false, false, true, true, true],fixture.componentInstance._bsVer));
}));
it('Multilist: carousel should not shifts if noWrap is false' +
'last or first items are visible', fakeAsync(() => {
context.itemsPerSlide = 3;
fixture.detectChanges();
context.noWrapSlides = false;
fixture.detectChanges();
tick();
const prev = element.querySelector('a.left');
const next = element.querySelector('a.right');
fixture.whenStable()
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [false, false, false, true, true, true],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [false, false, false, true, true, true],fixture.componentInstance._bsVer))
.then(() => prev.click())
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => prev.click())
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer));
}));
it('Multilist: carousel should shifts by 1 one item if singleSlideOffset is true', fakeAsync(() => {
context.itemsPerSlide = 3;
context.singleSlideOffset = true;
fixture.detectChanges();
const next = element.querySelector('a.right');
fixture.whenStable()
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [false, true, true, true, false, false],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [false, false, true, true, true, false],fixture.componentInstance._bsVer));
}));
it('Multilist: carousel should starts from specific index if fromStartIndex is defined', fakeAsync(() => {
context.itemsPerSlide = 3;
context.startFromIndex = 5;
fixture.detectChanges();
const next = element.querySelector('a.right');
fixture.whenStable()
.then(() => expectActiveSlides(element, [true, true, false, false, false, true],fixture.componentInstance._bsVer))
.then(() => stableAct(() => next.click()))
.then(() => expectActiveSlides(element, [true, true, true, false, false, false],fixture.componentInstance._bsVer));
}));
});
| {
"content_hash": "0ddb76eb1f0e5119e9f03115695daed1",
"timestamp": "",
"source": "github",
"line_count": 333,
"max_line_length": 184,
"avg_line_length": 40.98498498498498,
"alnum_prop": 0.674164712778429,
"repo_name": "valor-software/ngx-bootstrap",
"id": "f910e073106664aa715de85316d5ea8231e83f59",
"size": "13648",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "src/carousel/testing/carousel.component.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19320"
},
{
"name": "Dockerfile",
"bytes": "229"
},
{
"name": "HTML",
"bytes": "210213"
},
{
"name": "JavaScript",
"bytes": "40313"
},
{
"name": "SCSS",
"bytes": "59145"
},
{
"name": "Shell",
"bytes": "6129"
},
{
"name": "TypeScript",
"bytes": "3366817"
}
],
"symlink_target": ""
} |
package Paws::CognitoIdp::EmailConfigurationType;
use Moose;
has ReplyToEmailAddress => (is => 'ro', isa => 'Str');
has SourceArn => (is => 'ro', isa => 'Str');
1;
### main pod documentation begin ###
=head1 NAME
Paws::CognitoIdp::EmailConfigurationType
=head1 USAGE
This class represents one of two things:
=head3 Arguments in a call to a service
Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.
As an example, if Att1 is expected to be a Paws::CognitoIdp::EmailConfigurationType object:
$service_obj->Method(Att1 => { ReplyToEmailAddress => $value, ..., SourceArn => $value });
=head3 Results returned from an API call
Use accessors for each attribute. If Att1 is expected to be an Paws::CognitoIdp::EmailConfigurationType object:
$result = $service_obj->Method(...);
$result->Att1->ReplyToEmailAddress
=head1 DESCRIPTION
The email configuration type.
=head1 ATTRIBUTES
=head2 ReplyToEmailAddress => Str
The REPLY-TO email address.
=head2 SourceArn => Str
The Amazon Resource Name (ARN) of the email source.
=head1 SEE ALSO
This class forms part of L<Paws>, describing an object used in L<Paws::CognitoIdp>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: https://github.com/pplu/aws-sdk-perl
Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues
=cut
| {
"content_hash": "1c5df234dd2bb55a89cc514407ff91d3",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 111,
"avg_line_length": 23.838709677419356,
"alnum_prop": 0.7368064952638701,
"repo_name": "ioanrogers/aws-sdk-perl",
"id": "ce866d1f418f9f7cb82b08c379484dfdd4b1e8d7",
"size": "1478",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "auto-lib/Paws/CognitoIdp/EmailConfigurationType.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "1292"
},
{
"name": "Perl",
"bytes": "20360380"
},
{
"name": "Perl 6",
"bytes": "99393"
},
{
"name": "Shell",
"bytes": "445"
}
],
"symlink_target": ""
} |
<div class="doxter-video">
{%- if name == 'youtube' -%}
<iframe
width="560"
height="315"
src="https://youtube.com/embed/{{ src }}"
frameborder="0"
webkitallowfullscreen
mozallowfullscreen
allowfullscreen>
</iframe>
{%- endif -%}
{% if name == 'vimeo' %}
<iframe
width="560"
height="315"
src="https://player.vimeo.com/video/{{ src }}?color={{ color }}&title={{ title }}&byline={{ byline }}&portrait=0"
frameborder="0"
webkitallowfullscreen
mozallowfullscreen
allowfullscreen>
</iframe>
{%- endif -%}
</div>
| {
"content_hash": "93d534082ffb0d1a9338c1204f788190",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 121,
"avg_line_length": 27.083333333333332,
"alnum_prop": 0.5276923076923077,
"repo_name": "selvinortiz/doxter",
"id": "c4c14e2a146023ca80e0877ed273c143ac1079a1",
"size": "650",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/templates/shortcodes/_video.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2292"
},
{
"name": "PHP",
"bytes": "43668"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<assembly>
<id>bin</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>true</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>src/main</directory>
<outputDirectory>${file.separator}bin</outputDirectory>
<fileMode>0755</fileMode>
<includes>
<include>*.sh</include>
<include>*.bat</include>
<include>*.exe</include>
<include>*.dll</include>
</includes>
</fileSet>
<fileSet>
<directory>src/conf</directory>
<outputDirectory>${file.separator}conf</outputDirectory>
<fileMode>0755</fileMode>
<includes>
<include>log4j2.xml</include>
<include>xcc.logging.properties</include>
</includes>
</fileSet>
<fileSet>
<directory>src/lib</directory>
<outputDirectory>${file.separator}lib</outputDirectory>
<fileMode>0664</fileMode>
<includes>
<include>*.jar</include>
<include>*/*</include>
</includes>
</fileSet>
<fileSet>
<directory>src</directory>
<outputDirectory>${file.separator}src</outputDirectory>
<includes>
<include>main/java/com/marklogic/mapreduce/examples/**</include>
<include>main/resources/sample-data</include>
</includes>
</fileSet>
<fileSet>
<directory>target/site/javadoc</directory>
<outputDirectory>${file.separator}docs</outputDirectory>
<excludes>
<exclude>**/class-use/**</exclude>
</excludes>
</fileSet>
</fileSets>
<files>
<file>
<source>NOTICE.txt</source>
<outputDirectory>${file.separator}</outputDirectory>
</file>
<file>
<source>LICENSE.txt</source>
<outputDirectory>${file.separator}</outputDirectory>
</file>
<file>
<source>${project.build.directory}/BUNDLE_ARTIFACT</source>
<outputDirectory>${file.separator}</outputDirectory>
</file>
<file>
<source>src/lib/commons-license.txt</source>
<outputDirectory>${file.separator}lib</outputDirectory>
</file>
</files>
<dependencySets>
<dependencySet>
<scope>runtime</scope>
<outputDirectory>${file.separator}lib</outputDirectory>
<includes>
<include>org.apache.httpcomponents:httpclient:jar:*</include>
<include>commons-io:commons-io:jar:*</include>
<include>commons-modeler:commons-modeler:jar:*</include>
<include>org.apache.htrace:htrace-core:jar:*</include>
<include>com.sun.jersey:jersey-core:jar:*</include>
<include>com.sun.jersey:jersey-client:jar:*</include>
<include>commons-collections:commons-collections:jar:*</include>
<include>com.marklogic:*:*:*</include>
<include>org.apache.avro:avro:jar:*</include>
<include>commons-cli:commons-cli:jar:*</include>
<include>commons-codec:commons-codec:jar:*</include>
<include>org.apache.commons:commons-configuration2:jar:*</include>
<include>org.apache.commons:commons-lang3:jar:*</include>
<include>commons-lang:commons-lang:jar:*</include>
<include>commons-logging:commons-logging:jar:*</include>
<include>com.google.guava:guava:jar:*</include>
<include>com.google.guava:failureaccess:jar:*</include>
<include>org.apache.hadoop:hadoop-annotations:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-auth:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-common:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-hdfs:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-mapreduce-client-common:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-mapreduce-client-core:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-mapreduce-client-jobclient:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-yarn-api:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-yarn-common:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-yarn-client:jar:*mapr*</include>
<include>org.apache.hadoop:hadoop-mapreduce-client-contrib:jar:*mapr*</include>
<include>com.fasterxml.jackson.core:jackson-annotations:jar:*</include>
<include>com.fasterxml.jackson.core:jackson-core:jar:*</include>
<include>com.fasterxml.jackson.core:jackson-databind:jar:*</include>
<include>org.apache.logging.log4j:log4j-1.2-api:jar:*</include>
<include>org.apache.logging.log4j:log4j-api:jar:*</include>
<include>org.apache.logging.log4j:log4j-core:jar:*</include>
<include>org.apache.logging.log4j:log4j-jcl:jar:*</include>
<include>org.apache.logging.log4j:log4j-slf4j-impl:jar:*</include>
<include>org.slf4j:slf4j-api:jar:*</include>
<include>xerces:xercesImpl:jar:*</include>
<include>xpp3:xpp3:jar:*</include>
<include>com.github.jsonld-java:jsonld-java:jar:*</include>
<include>org.apache.jena:jena-arq:jar:*</include>
<include>org.apache.jena:jena-core:jar:*</include>
<include>org.apache.jena:jena-iri:jar:*</include>
<include>xml-apis:xml-apis:jar:*</include>
<include>com.thoughtworks.xstream:xstream:jar:*</include>
<include>junit:junit:jar:*</include>
<include>org.apache.hadoop:hadoop-client:jar:*</include>
<include>org.apache.hadoop.thirdparty:hadoop-shaded-guava:jar:*</include>
<include>org.apache.hadoop.thirdparty:hadoop-shaded-protobuf_3_7:jar:*</include>
</includes>
</dependencySet>
</dependencySets>
</assembly>
| {
"content_hash": "2525f368aa2fb9f145a12bdc93223a5c",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 89,
"avg_line_length": 43.55813953488372,
"alnum_prop": 0.6543869015839118,
"repo_name": "marklogic/marklogic-contentpump",
"id": "c25bb31f111ca92771924c626801a5435a8bb117",
"size": "5619",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/assemble/bindist-mapr.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "958"
},
{
"name": "CSS",
"bytes": "2618"
},
{
"name": "HTML",
"bytes": "7066"
},
{
"name": "Java",
"bytes": "1833596"
},
{
"name": "JavaScript",
"bytes": "4939"
},
{
"name": "Shell",
"bytes": "611"
},
{
"name": "XQuery",
"bytes": "4825"
}
],
"symlink_target": ""
} |
//-----------------------------------------------------------------------
// <copyright file="ActorMaterializerSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
using Akka.Actor;
using Akka.Pattern;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.TestKit;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
namespace Akka.Streams.Tests
{
public class ActorMaterializerSpec : AkkaSpec
{
public ActorMaterializerSpec(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void ActorMaterializer_should_report_shutdown_status_properly()
{
var m = Sys.Materializer();
m.IsShutdown.Should().BeFalse();
m.Shutdown();
m.IsShutdown.Should().BeTrue();
}
[Fact]
public void ActorMaterializer_should_properly_shut_down_actors_associated_with_it()
{
var m = Sys.Materializer();
var f = Source.Maybe<int>().RunAggregate(0, (x, y) => x + y, m);
m.Shutdown();
Action action = () => f.Wait(TimeSpan.FromSeconds(3));
action.ShouldThrow<AbruptTerminationException>();
}
[Fact]
public void ActorMaterializer_should_refuse_materialization_after_shutdown()
{
var m = Sys.Materializer();
m.Shutdown();
Action action = () => Source.From(Enumerable.Range(1, 5)).RunForeach(Console.Write, m);
action.ShouldThrow<IllegalStateException>();
}
[Fact]
public void ActorMaterializer_should_shut_down_supervisor_actor_it_encapsulates()
{
var m = Sys.Materializer() as ActorMaterializerImpl;
Source.From(Enumerable.Empty<object>()).To(Sink.Ignore<object>()).Run(m);
m.Supervisor.Tell(StreamSupervisor.GetChildren.Instance);
ExpectMsg<StreamSupervisor.Children>();
m.Shutdown();
m.Supervisor.Tell(StreamSupervisor.GetChildren.Instance);
ExpectNoMsg(TimeSpan.FromSeconds(1));
}
[Fact]
public void ActorMaterializer_should_handle_properly_broken_Props()
{
var m = Sys.Materializer();
Action action = () => Source.ActorPublisher<object>(Props.Create(typeof(TestActor), "wrong", "args")).RunWith(Sink.First<object>(), m);
action.ShouldThrow<ArgumentException>();
}
[Fact]
public void ActorMaterializer_should_report_correctly_if_it_has_been_shut_down_from_the_side()
{
var sys = ActorSystem.Create("test-system");
var m = sys.Materializer();
sys.Terminate().Wait();
m.IsShutdown.Should().BeTrue();
}
}
}
| {
"content_hash": "576bdbcaeb15213b686eaf5ab254bb1f",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 147,
"avg_line_length": 33.8,
"alnum_prop": 0.5785667324128863,
"repo_name": "simonlaroche/akka.net",
"id": "f38f8b3c2f4eff5dd739eb787d2a67b45746b403",
"size": "3044",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "src/core/Akka.Streams.Tests/ActorMaterializerSpec.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "765"
},
{
"name": "C#",
"bytes": "5594615"
},
{
"name": "F#",
"bytes": "107133"
},
{
"name": "Protocol Buffer",
"bytes": "62996"
},
{
"name": "Shell",
"bytes": "1024"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace spec\Sylius\Bundle\CoreBundle\Validator\Constraints;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\AttributeBundle\Validator\Constraints\ValidAttributeValue;
use Sylius\Component\Attribute\AttributeType\AttributeTypeInterface;
use Sylius\Component\Attribute\AttributeType\TextAttributeType;
use Sylius\Component\Attribute\Model\AttributeInterface;
use Sylius\Component\Attribute\Model\AttributeValueInterface;
use Sylius\Component\Registry\ServiceRegistryInterface;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
class LocalesAwareValidAttributeValueValidatorSpec extends ObjectBehavior
{
function let(ServiceRegistryInterface $attributeTypesRegistry, ExecutionContextInterface $context, TranslationLocaleProviderInterface $localeProvider): void
{
$this->beConstructedWith($attributeTypesRegistry, $localeProvider);
$this->initialize($context);
}
function it_is_constraint_validator(): void
{
$this->shouldHaveType(ConstraintValidator::class);
}
function it_validates_attribute_based_on_its_type_and_set_it_as_required_if_its_locale_is_same_as_default_locale(
AttributeInterface $attribute,
AttributeTypeInterface $attributeType,
AttributeValueInterface $attributeValue,
ServiceRegistryInterface $attributeTypesRegistry,
ValidAttributeValue $attributeValueConstraint,
TranslationLocaleProviderInterface $localeProvider
): void {
$attributeValue->getType()->willReturn(TextAttributeType::TYPE);
$attributeTypesRegistry->get('text')->willReturn($attributeType);
$attributeValue->getAttribute()->willReturn($attribute);
$attribute->getConfiguration()->willReturn(['min' => 2, 'max' => 255]);
$localeProvider->getDefaultLocaleCode()->willReturn('en_US');
$attributeValue->getLocaleCode()->willReturn('pl');
$attributeType->validate($attributeValue, Argument::any(ExecutionContextInterface::class), ['min' => 2, 'max' => 255])->shouldBeCalled();
$this->validate($attributeValue, $attributeValueConstraint);
}
function it_validates_attribute_value_based_on_its_type_and_do_not_set_it_as_required_if_its_locale_is_not_same_as_default_locale(
AttributeInterface $attribute,
AttributeTypeInterface $attributeType,
AttributeValueInterface $attributeValue,
ServiceRegistryInterface $attributeTypesRegistry,
ValidAttributeValue $attributeValueConstraint,
TranslationLocaleProviderInterface $localeProvider
): void {
$attributeValue->getType()->willReturn(TextAttributeType::TYPE);
$attributeTypesRegistry->get('text')->willReturn($attributeType);
$attributeValue->getAttribute()->willReturn($attribute);
$attribute->getConfiguration()->willReturn(['min' => 2, 'max' => 255]);
$localeProvider->getDefaultLocaleCode()->willReturn('en_US');
$attributeValue->getLocaleCode()->willReturn('en_US');
$attributeType->validate($attributeValue, Argument::any(ExecutionContextInterface::class), ['min' => 2, 'max' => 255, 'required' => true])->shouldBeCalled();
$this->validate($attributeValue, $attributeValueConstraint);
}
function it_throws_exception_if_validated_value_is_not_attribute_value(
\DateTime $badObject,
ValidAttributeValue $attributeValueConstraint
): void {
$this
->shouldThrow(\InvalidArgumentException::class)
->during('validate', [$badObject, $attributeValueConstraint])
;
}
}
| {
"content_hash": "844499ef1d42a6f27f262cefc24d71b0",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 165,
"avg_line_length": 44.44705882352941,
"alnum_prop": 0.7366331392271043,
"repo_name": "gorkalaucirica/Sylius",
"id": "ec1f79b6173315040ecbcf95f3b79edff304f913",
"size": "3989",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "src/Sylius/Bundle/CoreBundle/spec/Validator/Constraints/LocalesAwareValidAttributeValueValidatorSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2192"
},
{
"name": "Gherkin",
"bytes": "852085"
},
{
"name": "HTML",
"bytes": "310286"
},
{
"name": "JavaScript",
"bytes": "77867"
},
{
"name": "PHP",
"bytes": "6856666"
},
{
"name": "Shell",
"bytes": "28776"
}
],
"symlink_target": ""
} |
#ifndef __simple_scheduler_hpp__
#define __simple_scheduler_hpp__
#include <ioa/scheduler_interface.hpp>
namespace ioa {
class simple_scheduler_impl;
class simple_scheduler :
public scheduler_interface
{
private:
simple_scheduler_impl* m_impl;
simple_scheduler (const simple_scheduler&) { }
void operator= (const simple_scheduler&) { }
public:
simple_scheduler (int const threads = 1);
~simple_scheduler ();
aid_t get_current_aid ();
size_t binding_count (const action_executor_interface&);
void schedule (automaton::sys_create_type automaton::*ptr);
void schedule (automaton::sys_bind_type automaton::*ptr);
void schedule (automaton::sys_unbind_type automaton::*ptr);
void schedule (automaton::sys_destroy_type automaton::*ptr);
void schedule (action_runnable_interface*);
void schedule_after (action_runnable_interface*,
const time&);
void schedule_read_ready (action_runnable_interface*,
int fd);
void schedule_write_ready (action_runnable_interface*,
int fd);
void close (int fd);
void run (std::auto_ptr<allocator_interface> allocator);
void begin_sys_call ();
void end_sys_call ();
};
}
#endif
| {
"content_hash": "e1d63973cb1654207d2700047d76cbc5",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 64,
"avg_line_length": 21.677966101694917,
"alnum_prop": 0.6489444878811571,
"repo_name": "jrwilson/ioa",
"id": "c31380b9585bde670a473cd2e82c18260ac5a7da",
"size": "1871",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/ioa/simple_scheduler.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "516"
},
{
"name": "C++",
"bytes": "599644"
},
{
"name": "Shell",
"bytes": "332051"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "65de63bd5e828ee5e9ec8187a2a4e03f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "9b255f7c8c42030c67ae150480c31930de719fd8",
"size": "180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Mesosphaerum/Mesosphaerum rubicundum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.uberfire.ext.security.management.client.widgets.management;
import java.util.List;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.editor.client.EditorError;
import com.google.gwtmockito.GwtMockitoTestRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.uberfire.ext.security.management.client.widgets.management.events.ChangePasswordEvent;
import org.uberfire.ext.security.management.client.widgets.management.events.OnErrorEvent;
import org.uberfire.mocks.EventSourceMock;
import org.uberfire.mvp.Command;
import org.uberfire.workbench.events.NotificationEvent;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@RunWith(GwtMockitoTestRunner.class)
public class ChangePasswordTest extends AbstractSecurityManagementTest {
@Mock
EventSourceMock<ChangePasswordEvent> changePasswordEvent;
@Mock
EventSourceMock<OnErrorEvent> onErrorEvent;
@Mock
ChangePassword.View view;
private ChangePassword presenter;
@Before
public void setup() {
super.setup();
presenter = new ChangePassword(userSystemManager,
workbenchNotification,
onErrorEvent,
changePasswordEvent,
view);
assertEquals(view.asWidget(),
presenter.asWidget());
}
@Test
public void testClear() throws Exception {
presenter.clear();
verify(view,
times(1)).clear();
verify(view,
times(0)).show(anyString());
verify(view,
times(0)).hide();
assertNull(presenter.username);
assertNull(presenter.callback);
}
@Test
public void testShowError() throws Exception {
String error = "error1";
presenter.showErrorMessage(error);
verify(view,
times(0)).clear();
verify(view,
times(0)).show(anyString());
verify(view,
times(0)).hide();
verify(onErrorEvent,
times(1)).fire(any(OnErrorEvent.class));
}
@Test
public void testShow() throws Exception {
presenter.show("user1");
assertEquals(presenter.username,
"user1");
verify(view,
times(1)).clear();
verify(view,
times(1)).show(anyString());
}
@Test
public void testPasswordValidator() throws Exception {
List<EditorError> errors = presenter.passwordValidator.validate(mock(Editor.class),
"password1");
assertTrue(errors.isEmpty());
errors = presenter.passwordValidator.validate(mock(Editor.class),
"");
assertFalse(errors.isEmpty());
}
@Test
public void testValidatePasswordMatch() throws Exception {
assertTrue(presenter.validatePasswordsMatch("password1",
"password1"));
assertFalse(presenter.validatePasswordsMatch("password1",
"password2"));
}
@Test
public void testUpdatePassword() throws Exception {
final String newPassw = "new-password";
Command callback = mock(Command.class);
ChangePassword.ChangePasswordCallback changePasswordCallback = mock(ChangePassword.ChangePasswordCallback.class);
presenter.username = "user";
presenter.callback = changePasswordCallback;
presenter.onUpdatePassword(newPassw,
callback);
verify(userManagerService,
times(1)).changePassword(presenter.username,
newPassw);
verify(changePasswordEvent,
times(1)).fire(any(ChangePasswordEvent.class));
verify(workbenchNotification,
times(1)).fire(any(NotificationEvent.class));
verify(callback,
times(1)).execute();
verify(changePasswordCallback,
times(1)).onPasswordUpdated();
verify(view,
times(1)).hide();
}
}
| {
"content_hash": "08013019fdaa0f91a11e52ab0a4779e2",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 121,
"avg_line_length": 34.96825396825397,
"alnum_prop": 0.5941897412619156,
"repo_name": "porcelli-forks/uberfire",
"id": "4241ee1fef00cf304f1741a329bdfd422a42e0cd",
"size": "5030",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "uberfire-extensions/uberfire-security/uberfire-security-management/uberfire-widgets-security-management/src/test/java/org/uberfire/ext/security/management/client/widgets/management/ChangePasswordTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "74063"
},
{
"name": "FreeMarker",
"bytes": "46611"
},
{
"name": "HTML",
"bytes": "91780"
},
{
"name": "Java",
"bytes": "13164946"
},
{
"name": "JavaScript",
"bytes": "85658"
},
{
"name": "Shell",
"bytes": "5830"
}
],
"symlink_target": ""
} |
package io.qameta.allure.executor;
import io.qameta.allure.CommonJsonAggregator;
import io.qameta.allure.Constants;
import io.qameta.allure.Reader;
import io.qameta.allure.context.JacksonContext;
import io.qameta.allure.core.Configuration;
import io.qameta.allure.core.LaunchResults;
import io.qameta.allure.core.ResultsVisitor;
import io.qameta.allure.entity.ExecutorInfo;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author charlie (Dmitry Baev).
*/
public class ExecutorPlugin extends CommonJsonAggregator implements Reader {
public static final String EXECUTORS_BLOCK_NAME = "executor";
protected static final String JSON_FILE_NAME = "executor.json";
public ExecutorPlugin() {
super(Constants.WIDGETS_DIR, "executors.json");
}
@Override
public void readResults(final Configuration configuration,
final ResultsVisitor visitor,
final Path directory) {
final JacksonContext context = configuration.requireContext(JacksonContext.class);
final Path executorFile = directory.resolve(JSON_FILE_NAME);
if (Files.exists(executorFile)) {
try (InputStream is = Files.newInputStream(executorFile)) {
final ExecutorInfo info = context.getValue().readValue(is, ExecutorInfo.class);
visitor.visitExtra(EXECUTORS_BLOCK_NAME, info);
} catch (IOException e) {
visitor.error("Could not read executor file " + executorFile, e);
}
}
}
@Override
protected List<ExecutorInfo> getData(final List<LaunchResults> launches) {
return launches.stream()
.map(launchResults -> launchResults.getExtra(EXECUTORS_BLOCK_NAME))
.filter(Optional::isPresent)
.map(Optional::get)
.filter(ExecutorInfo.class::isInstance)
.map(ExecutorInfo.class::cast)
.collect(Collectors.toList());
}
}
| {
"content_hash": "314f9a7e2993e5a2db1bf89a52aa4d16",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 95,
"avg_line_length": 36.33898305084746,
"alnum_prop": 0.675839552238806,
"repo_name": "allure-framework/allure2",
"id": "16e667ea438476cef9d4ea153847cf2063065588",
"size": "2756",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "allure-generator/src/main/java/io/qameta/allure/executor/ExecutorPlugin.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "27"
},
{
"name": "FreeMarker",
"bytes": "891"
},
{
"name": "HTML",
"bytes": "10269"
},
{
"name": "Handlebars",
"bytes": "29579"
},
{
"name": "Java",
"bytes": "704947"
},
{
"name": "JavaScript",
"bytes": "130673"
},
{
"name": "Kotlin",
"bytes": "26519"
},
{
"name": "SCSS",
"bytes": "33652"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>ssl::context::use_certificate (2 of 2 overloads)</title>
<link rel="stylesheet" href="../../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../../index.html" title="Asio">
<link rel="up" href="../use_certificate.html" title="ssl::context::use_certificate">
<link rel="prev" href="overload1.html" title="ssl::context::use_certificate (1 of 2 overloads)">
<link rel="next" href="../use_certificate_chain.html" title="ssl::context::use_certificate_chain">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../use_certificate.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../use_certificate_chain.html"><img src="../../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="asio.reference.ssl__context.use_certificate.overload2"></a><a class="link" href="overload2.html" title="ssl::context::use_certificate (2 of 2 overloads)">ssl::context::use_certificate
(2 of 2 overloads)</a>
</h5></div></div></div>
<p>
Use a certificate from a memory buffer.
</p>
<pre class="programlisting"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">use_certificate</span><span class="special">(</span>
<span class="keyword">const</span> <span class="identifier">const_buffer</span> <span class="special">&</span> <span class="identifier">certificate</span><span class="special">,</span>
<span class="identifier">file_format</span> <span class="identifier">format</span><span class="special">,</span>
<span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<p>
This function is used to load a certificate into the context from a buffer.
</p>
<h6>
<a name="asio.reference.ssl__context.use_certificate.overload2.h0"></a>
<span><a name="asio.reference.ssl__context.use_certificate.overload2.parameters"></a></span><a class="link" href="overload2.html#asio.reference.ssl__context.use_certificate.overload2.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">certificate</span></dt>
<dd><p>
The buffer containing the certificate.
</p></dd>
<dt><span class="term">format</span></dt>
<dd><p>
The certificate format (ASN.1 or PEM).
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="asio.reference.ssl__context.use_certificate.overload2.h1"></a>
<span><a name="asio.reference.ssl__context.use_certificate.overload2.remarks"></a></span><a class="link" href="overload2.html#asio.reference.ssl__context.use_certificate.overload2.remarks">Remarks</a>
</h6>
<p>
Calls <code class="computeroutput"><span class="identifier">SSL_CTX_use_certificate</span></code>
or SSL_CTX_use_certificate_ASN1.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload1.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../use_certificate.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="../use_certificate_chain.html"><img src="../../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "782625821d7b83640a50c95b47ad77a2",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 372,
"avg_line_length": 60.666666666666664,
"alnum_prop": 0.63229078613694,
"repo_name": "sxlin/dist_ninja",
"id": "046e99bca6c4d834eaa185a867dbd63834df82ad",
"size": "4732",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "asio-1.10.6/doc/asio/reference/ssl__context/use_certificate/overload2.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "20021"
},
{
"name": "C++",
"bytes": "4694297"
},
{
"name": "CSS",
"bytes": "16051"
},
{
"name": "Emacs Lisp",
"bytes": "3333"
},
{
"name": "HTML",
"bytes": "18242842"
},
{
"name": "Java",
"bytes": "13629"
},
{
"name": "M4",
"bytes": "9302"
},
{
"name": "Makefile",
"bytes": "767796"
},
{
"name": "Perl",
"bytes": "6547"
},
{
"name": "Protocol Buffer",
"bytes": "491"
},
{
"name": "Python",
"bytes": "54986"
},
{
"name": "Shell",
"bytes": "87511"
},
{
"name": "Vim script",
"bytes": "2623"
}
],
"symlink_target": ""
} |
/* global describe, it, jsPDF, comparePdf */
/**
* Standard spec tests
*/
describe("Module: SetLanguage", () => {
it("set english (US)", () => {
const doc = new jsPDF({ floatPrecision: 2 });
doc.setLanguage("en-US");
comparePdf(doc.output(), "enUS.pdf", "setlanguage");
});
it("refuse non-existing-language", () => {
const doc = new jsPDF({ floatPrecision: 2 });
doc.setLanguage("zz");
comparePdf(doc.output(), "blank.pdf", "text");
});
});
| {
"content_hash": "140a16fcc4807a712f60b859ecb9b5f5",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 56,
"avg_line_length": 23.95,
"alnum_prop": 0.5803757828810021,
"repo_name": "yWorks/jsPDF",
"id": "f2e4144d21c7ddcbab54858cab657e4813a08741",
"size": "479",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/language.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "15835"
},
{
"name": "JavaScript",
"bytes": "1415453"
},
{
"name": "TypeScript",
"bytes": "16438"
}
],
"symlink_target": ""
} |
> Print descriptive statistics for all columns in a CSV file.
> Included in csvkit.
- Show all stats for all columns:
`csvstat {{data.csv}}`
- Show all stats for columns 2 and 4:
`csvstat -c {{2,4}} {{data.csv}}`
- Show sums for all columns:
`csvstat --sum {{data.csv}}`
- Show the max value length for column 3:
`csvstat -c {{3}} --len {{data.csv}}`
- Show the number of unique values in the "name" column:
`csvstat -c {{name}} --unique {{data.csv}}`
| {
"content_hash": "e5b99707cfc998e53618ce28a75a11d0",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 61,
"avg_line_length": 21,
"alnum_prop": 0.6558441558441559,
"repo_name": "cptdeka10/tldr",
"id": "36fcbb62cc03209be624dff7450f98b1f08337be",
"size": "473",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "pages/common/csvstat.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "997"
},
{
"name": "Python",
"bytes": "1035"
},
{
"name": "Shell",
"bytes": "2100"
},
{
"name": "TeX",
"bytes": "2723"
}
],
"symlink_target": ""
} |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>Sock Js Demo</title>
<script src="../../webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="../sock-js.html">
</head>
<body>
<dom-module id="sockjs-demo">
<link rel="import" href="/bower_components/paper-toast/paper-toast.html">
<template>
<paper-toast id="status" duration="0" opened></paper-toast>
</template>
<script>
UpdateInfoBehavior = {
onmessage: function(data) {
// Add you data treatment.
console.dir(data)
},
onstatuschange: function(status) {
console.debug('Status changed to:' + status);
if (status == 'connecting' || status == 'reconnecting') {
this.$.status.textContent = 'Establishing connection to server...';
this.$.status.show();
} else if (status != 'connected') {
this.$.status.textContent = 'Disconnected from server, data is not up-to-date';
this.$.status.show();
} else {
this.$.status.textContent = '';
this.$.status.hide();
}
},
onopen: function(status) {
console.debug('Authenticating.')
// Here you can change/remove sock authentification.
this.send('auth,' + this.authtoken)
},
};
Polymer({
is: 'sockjs-demo',
properties: {
/**
* SockJS Authentication token.
*/
authtoken: String
},
behaviors: [SockJsSimpleBehavior, UpdateInfoBehavior]
});
</script>
</dom-module>
<p>Example of <code><sock-js></code>.</p>
<sockjs-demo
url="https://localhost:8080/socket"
authtoken="${some_random_session_token}">
</sockjs-demo>
</body>
</html>
| {
"content_hash": "7fe979a46c6fdddd2b68a11f4154faba",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 112,
"avg_line_length": 31.8,
"alnum_prop": 0.5268505079825835,
"repo_name": "ymahnovskyy/polymer-sock-js",
"id": "f0292e178b0e35523fe4e5c9268a53185fd18f68",
"size": "2067",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/index.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "HTML",
"bytes": "5944"
}
],
"symlink_target": ""
} |
name 'deploy-play'
maintainer 'Sameer Arora'
maintainer_email '[email protected]'
license 'Apache 2.0'
description 'Deploys Play Application'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.0.0'
supports 'ubuntu'
recipe 'deploy-play::default', 'Deploys Play Application on your Node'
| {
"content_hash": "61e3cb6860ed652fa02b8b0f5376c62a",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 72,
"avg_line_length": 33,
"alnum_prop": 0.6721763085399449,
"repo_name": "sean-avalon/ChefPlay",
"id": "143039448f87af9bdaa3b0f2ddad9f60093365ef",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1335"
},
{
"name": "Ruby",
"bytes": "1996"
},
{
"name": "Shell",
"bytes": "1267"
}
],
"symlink_target": ""
} |
namespace Potassium.Providers
{
using System;
using System.Threading;
using Potassium.Internal;
/// <summary>
/// Toggle is an IProvider of type bool that starts with an initial value,
/// and flips it's value after each request to the Value property.
/// </summary>
public class Toggle : Provider<bool>
{
private bool value;
/// <summary>
/// Constructs a new Toggle, initialized to false.
/// </summary>
public Toggle()
: this(false)
{
}
/// <summary>
/// Constructs a new Toggle having the specified initial value
/// </summary>
/// <param name="initValue">The initial value for the Toggle</param>
public Toggle(bool initValue)
{
value = initValue;
}
/// <summary>
/// Get and toggle the current (bool) value.
/// </summary>
public override bool Value
{
get
{
if (Monitor.TryEnter(Constants.ProviderValueLock, Constants.LockTimeout))
{
try
{
var result = value;
value = !value;
return result;
}
finally
{
Monitor.Exit(Constants.ProviderValueLock);
}
}
throw new InvalidOperationException("Could not obtain the provider value lock");
}
}
}
}
| {
"content_hash": "284076ed192362f8ca21f36fc91dcb75",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 96,
"avg_line_length": 27.912280701754387,
"alnum_prop": 0.4751728472658705,
"repo_name": "jerometerry/potassium",
"id": "f9607a31d6a04c60c0d76420fa8a7c0a648bd496",
"size": "1593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Providers/Toggle.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "196590"
}
],
"symlink_target": ""
} |
<div>
When you are using Hudson for various automations, it's sometimes convenient
to be able to "parameterize" a build, by requiring a set of user inputs to
be made available to the build process. For example, you might be setting up
an on-demand test job, where the user can submit a zip file of the binaries to be tested.
<p>
This section configures what parameters your build takes. Parameters are distinguished
by their names, and so you can have multiple parameters provided that they have different names.
<p>
See <a href="http://wiki.hudson-ci.org/display/HUDSON/Parameterized+Build">the Wiki topic</a>
for more discussions about this feature.
<p>
It's possible to use Project cascading feature for this property. Please review <a href="http://wiki.hudson-ci.org/display/HUDSON/Project+cascading">
this document</a>.
</div> | {
"content_hash": "0367fe864955cca81e8fcc4d9fbf819d",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 153,
"avg_line_length": 52.11764705882353,
"alnum_prop": 0.7347629796839729,
"repo_name": "cnopens/hudson",
"id": "342b5de0fb843fca684c554ccf1989c02c841e73",
"size": "886",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "hudson-war/src/main/webapp/help/project-config/parameterized-build.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
from qingcloud.cli.misc.utils import explode_array
from qingcloud.cli.iaas_client.actions.base import BaseAction
class LeaveVxnetAction(BaseAction):
action = 'LeaveVxnet'
command = 'leave-vxnet'
usage = '%(prog)s --instances "instance_id, ..." --vxnet <vxnet_id> [-f <conf_file>]'
@classmethod
def add_ext_arguments(cls, parser):
parser.add_argument('-i', '--instances', dest='instances',
action='store', type=str, default='',
help='the IDs of instances that will leave a vxnet.')
parser.add_argument('-v', '--vxnet', dest='vxnet',
action='store', type=str, default='',
help='the ID of the vxnet the instances will leave. ')
@classmethod
def build_directive(cls, options):
instances = explode_array(options.instances)
if not options.vxnet or not instances:
print('error: [instances] and [vxnet] should be specified')
return None
return {
'vxnet': options.vxnet,
'instances': instances,
}
| {
"content_hash": "55d2ef470826a451ea4c537fc162d247",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 89,
"avg_line_length": 36.6,
"alnum_prop": 0.592896174863388,
"repo_name": "yunify/qingcloud-cli",
"id": "ff4311bf77c4e791a704db3d03ca81ae3e0e6548",
"size": "1931",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "qingcloud/cli/iaas_client/actions/vxnet/leave_vxnet.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "852"
},
{
"name": "Python",
"bytes": "607642"
}
],
"symlink_target": ""
} |
function detectTouchEvent(element, onTap, onLongTap) {
var start;
var coordX;
var coordY;
var namespace = onTap ? '.onTap' : '.onLongTap';
d3.select(element)
.on('touchstart' + namespace, function(d, i) {
start = d3.event.timeStamp;
coordX = d3.event.changedTouches[0].screenX;
coordY = d3.event.changedTouches[0].screenY;
})
.on('touchend' + namespace, function(d, i) {
coordX = Math.abs(coordX - d3.event.changedTouches[0].screenX);
coordY = Math.abs(coordY - d3.event.changedTouches[0].screenY);
if (coordX < 5 && coordY < 5) {
if (d3.event.timeStamp - start < 500)
return onTap ? onTap(d, i) : undefined;
return onLongTap ? onLongTap(d, i) : undefined;
} else return undefined;
});
}
//d3.selection.prototype.onTap
var onTap = function(callback) {
return this.each(function() {
detectTouchEvent(this, callback);
});
};
//d3.selection.prototype.onLongTap
var onLongTap = function(callback) {
return this.each(function() {
detectTouchEvent(this, null, callback);
});
};
export default {
onTap: onTap,
onLongTap: onLongTap
};
export {
onTap,
onLongTap
};
| {
"content_hash": "4c25f025c94f9db8791735aa961e0ec0",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 69,
"avg_line_length": 26.177777777777777,
"alnum_prop": 0.6434634974533107,
"repo_name": "Gapminder/vizabi",
"id": "0f6624d649e2f411ceb4bc135fc252b13e874a0a",
"size": "1178",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/helpers/d3.touchEvents.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "122533"
},
{
"name": "HTML",
"bytes": "40118"
},
{
"name": "JavaScript",
"bytes": "1266165"
},
{
"name": "Shell",
"bytes": "1503"
}
],
"symlink_target": ""
} |
//
// animation3.m
// MadMax+
//
// Created by ruany on 2016/12/26.
// Copyright © 2016年 ruany. All rights reserved.
//
#import "animation3.h"
#import <GPUImage/GPUImage.h>
#import <Masonry/Masonry.h>
#import <QuartzCore/QuartzCore.h>
#import "KYCuteView.h"
extern const NSString *str=@"全局变量";
static const NSString *str1=@"静态变量";
@interface animation3 ()
@property(nonatomic,strong)CADisplayLink * displayLink;
//需要隐藏气泡时候可以使用这个属性:self.frontView.hidden = YES;
@property(nonatomic, strong) UIView *frontView;
//父视图
@property(nonatomic, strong) UIView *containerView;
//气泡粘性系数,越大可以拉得越长
@property(nonatomic, assign) CGFloat viscosity;
//气泡上显示数字的label
// the label on the bubble
@property(nonatomic, strong) UILabel *bubbleLabel;
//气泡颜色
// bubble's color
@property(nonatomic, strong) UIColor *bubbleColor;
//气泡的直径
// bubble's diameter
@property(nonatomic, assign) CGFloat bubbleWidth;
@property(nonatomic,strong)UIDynamicAnimator *animator;
@property(nonatomic,strong)UIView * orangeBall;
@end
@implementation animation3
{
UIBezierPath *cutePath;
UIColor *fillColorForCute;
UIDynamicAnimator *animator;
UISnapBehavior *snap;
UIView *backView;
CGFloat r1; // backView
CGFloat r2; // frontView
CGFloat x1;
CGFloat y1;
CGFloat x2;
CGFloat y2;
CGFloat centerDistance;
CGFloat cosDigree;
CGFloat sinDigree;
CGPoint pointA; //A
CGPoint pointB; //B
CGPoint pointD; //D
CGPoint pointC; //C
CGPoint pointO; //O
CGPoint pointP; //P
CGRect oldBackViewFrame;
CGPoint initialPoint;
CGPoint oldBackViewCenter;
CAShapeLayer *shapeLayer;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self xiaodian];
[self initoOrangeBall];
}
-(void)xiaodian{
KYCuteView *cuteView = [[KYCuteView alloc]initWithPoint:CGPointMake(self.tabBarController.tabBar.subviews[5].frame.size.height*5/6,self.tabBarController.tabBar.subviews[5].frame.size.width/100) superView: self.tabBarController.tabBar.subviews[5]];
cuteView.viscosity = 20;
cuteView.bubbleWidth = 30;
cuteView.bubbleColor = [UIColor colorWithRed:0 green:0.722 blue:1 alpha:1];
[cuteView setUp];
[cuteView addGesture];
//注意:设置 'bubbleLabel.text' 一定要放在 '-setUp' 方法之后
//Tips:When you set the 'bubbleLabel.text',you must set it after '-setUp'
cuteView.bubbleLabel.text = @"13";
NSLog(@"%@,%@",self.tabBarController.tabBar.items[0],self.tabBarController.tabBar.subviews[0]) ;
}
-(void)initoOrangeBall{
self.orangeBall=[[UIView alloc]initWithFrame:CGRectMake(100, 100, 50, 50)];
self.orangeBall.backgroundColor=[UIColor orangeColor];
self.orangeBall.layer.cornerRadius=25;
self.orangeBall.layer.borderColor=[UIColor blackColor].CGColor;
self.orangeBall.layer.borderWidth=0;
[self.view addSubview:self.orangeBall];
self.animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.orangeBall];
}
-(void)gravity{
UIGravityBehavior * gb=[[UIGravityBehavior alloc]initWithItems:@[self.orangeBall]];
[self.animator addBehavior:gb];
}
-(void)gravity1{
UICollisionBehavior * cb=[[UICollisionBehavior alloc]initWithItems:@[self.orangeBall]];
cb.translatesReferenceBoundsIntoBoundary=YES;
[self.animator addBehavior:cb];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self gravity];
// [self gravity1];
}
+(void)animationWithView:(UIView *)view duration:(CFTimeInterval)duration{
CAKeyframeAnimation * animation;
animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.duration = duration;
animation.removedOnCompletion = NO;
animation.fillMode = kCAFillModeForwards;
NSMutableArray *values = [NSMutableArray array];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
animation.values = values;
animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
[view.layer addAnimation:animation forKey:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
| {
"content_hash": "f04f7effab90b32656b25be216284c8e",
"timestamp": "",
"source": "github",
"line_count": 161,
"max_line_length": 251,
"avg_line_length": 30.36024844720497,
"alnum_prop": 0.7236088379705401,
"repo_name": "paradisery/MadMax",
"id": "aecf9ebcb7a571d83f423ce338ace89fda90cf4a",
"size": "5039",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MadMax+/CSGOclass/animation3.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17279"
},
{
"name": "HTML",
"bytes": "387202"
},
{
"name": "JavaScript",
"bytes": "1516"
},
{
"name": "Objective-C",
"bytes": "273998"
},
{
"name": "Shell",
"bytes": "102"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace DeadManSwitch.Service.Wcf
{
[Serializable]
[DataContract]
public class LoginResponse
{
[DataMember]
public bool IsSuccessful
{
get { return (User != null); }
set { /* dummy set accessor for WCF */ }
}
[DataMember]
public User User { get; set; }
[DataMember]
public List<string> LoginFailedUserMessageList { get; set; } = new List<string>();
}
}
| {
"content_hash": "b7a25666e11599349fc75c64a20688a9",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 90,
"avg_line_length": 22.925925925925927,
"alnum_prop": 0.6155088852988692,
"repo_name": "tategriffin/DeadManSwitch",
"id": "2ebc5e7125c3ee2a2d314a235d2301ad99bf1fe0",
"size": "621",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Source/DeadManSwitch.Service.Wcf/LoginResponse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "36351"
},
{
"name": "C#",
"bytes": "881456"
},
{
"name": "CSS",
"bytes": "230018"
},
{
"name": "HTML",
"bytes": "37536"
},
{
"name": "JavaScript",
"bytes": "201963"
}
],
"symlink_target": ""
} |
package org.tendiwa.inflectible.antlr.parsed;
import java.util.Locale;
import org.tendiwa.inflectible.ArgumentName;
import org.tendiwa.inflectible.antlr.TemplateParser;
/**
* Argument name from ANTLR parse tree about which it is not known until
* runtime if its content is capitalized or not.
* @author Georgy Vlasov ([email protected])
* @version $Id$
* @since 0.2.0
*/
public final class AnParsedCapitalizable implements ArgumentName {
/**
* ANTLR parse tree with a probably capitalized argument name.
*/
private final transient
TemplateParser.CapitalizableArgumentNameContext ctx;
/**
* Ctor.
* @param context ANLTR parse tree with a probably capitalized argument name
*/
AnParsedCapitalizable(
final TemplateParser.CapitalizableArgumentNameContext context
) {
this.ctx = context;
}
@Override
public String string() throws Exception {
final String answer;
if (this.ctx.argumentName() == null) {
answer = this.ctx
.capitalizedArgumentName()
.CAPITALIZED_ARGUMENT_NAME()
.getText()
.toLowerCase(Locale.getDefault());
} else {
answer = this.ctx.argumentName().ARGUMENT_NAME().getText();
}
return answer;
}
}
| {
"content_hash": "8b5980af83ee74c65324df4843cafb5e",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 80,
"avg_line_length": 29.622222222222224,
"alnum_prop": 0.6481620405101275,
"repo_name": "Suseika/liblexeme",
"id": "a70ab801c32abac6d2eb4ccc84ee42af662d96e2",
"size": "2479",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/tendiwa/inflectible/antlr/parsed/AnParsedCapitalizable.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "5284"
},
{
"name": "Java",
"bytes": "472657"
}
],
"symlink_target": ""
} |
package com.metrix.ble;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.UUID;
import com.metrix.ble.R;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends ListActivity {
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
@Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivity(intent);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
@Override
public int getCount() {
return mLeDevices.size();
}
@Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
} | {
"content_hash": "b098794e9940f11b9ca5f70803081695",
"timestamp": "",
"source": "github",
"line_count": 257,
"max_line_length": 100,
"avg_line_length": 33.7431906614786,
"alnum_prop": 0.6193496309963099,
"repo_name": "metrix/MetrixBLEUtility",
"id": "177502cc7f7cdad59e3eb9ea810798f9e3d49aae",
"size": "9291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/metrix/ble/DeviceScanActivity.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "58779"
}
],
"symlink_target": ""
} |
class CscEventsScraperNew < Tess::Scrapers::Scraper
def self.config
{
name: 'CSC Events Scraper (New)',
root_url: 'https://www.csc.fi/en/training/',
json_api_url: 'https://www.csc.fi/o/events'
}
end
def scrape
cp = add_content_provider(Tess::API::ContentProvider.new(
{ title: "CSC - IT Center for Science",
url: "https://www.csc.fi",
image_url: "https://www.csc.fi/documents/10180/161914/CSC_2012_LOGO_RGB_72dpi.jpg/c65ddc42-63fc-44da-8d0f-9f88c54779d7?t=1411391121769",
description: "CSC - IT Center for Science Ltd. is a non-profit, state-owned company administered by the Finnish Ministry of Education and Culture. CSC maintains and develops the state-owned centralised IT infrastructure and uses it to provide nationwide IT services for research, libraries, archives, museums and culture as well as information, education and research management.
CSC has the task of promoting the operational framework of Finnish research, education, culture and administration. As a non-profit, government organisation, it is our duty to foster exemplary transparency, honesty and responsibility. Trust is the foundation of CSC's success. Customers, suppliers, owners and personnel alike must feel certain that we will fulfil our commitments and promises in an ethically sustainable manner.
CSC has offices in Espoo's Keilaniemi and in the Renforsin Ranta business park in Kajaani.",
content_provider_type: :organisation,
node_name: :FI
}))
events = parse_data(config[:json_api_url])
events.each do |event|
if for_tess?(event['keywords'])
add_event(Tess::API::Event.new(
content_provider: cp,
title: event['title'],
url: event['url'],
start: event['start'],
end: event['end'],
organizer: event['organizer'],
description: event['organization'],
event_types: [:workshops_and_courses],
# latitude: event['latitude'],
# longitude: event['longitude'],
venue: event['venue'],
postcode: event['postcode'],
city: event['city'],
country: event['country'],
keywords: event['keywords']
))
end
end
end
private
def parse_data(url)
JSON.parse(open_url(url).read)
end
def for_tess? keywords
return keywords.select{|x| x.upcase.include? "TESS"}.any?
end
end
| {
"content_hash": "34feeaf09d8f63138b3fab6fdb9b79a7",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 432,
"avg_line_length": 41.1,
"alnum_prop": 0.6597729115977291,
"repo_name": "ElixirUK/newtessscraper",
"id": "930c8315abc701acffec0f96620e6e5c6aa1848a",
"size": "2466",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/scrapers/csc_events_scraper_new.rb",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "HTML",
"bytes": "661163"
},
{
"name": "Ruby",
"bytes": "80967"
},
{
"name": "Shell",
"bytes": "453"
}
],
"symlink_target": ""
} |
#include <features.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/gmon.h>
#include <sys/gmon_out.h>
#include <sys/uio.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#ifdef __UCLIBC_PROFILING__
/* Head of basic-block list or NULL. */
struct __bb *__bb_head;
struct gmonparam _gmonparam = { state: GMON_PROF_OFF };
/*
* See profil(2) where this is described:
*/
static int s_scale;
#define SCALE_1_TO_1 0x10000L
#define ERR(s) write (STDERR_FILENO, s, sizeof (s) - 1)
void moncontrol __P ((int mode));
static void write_hist __P ((int fd));
static void write_call_graph __P ((int fd));
static void write_bb_counts __P ((int fd));
/*
* Control profiling
* profiling is what mcount checks to see if
* all the data structures are ready.
*/
void moncontrol (int mode)
{
struct gmonparam *p = &_gmonparam;
/* Don't change the state if we ran into an error. */
if (p->state == GMON_PROF_ERROR)
return;
if (mode)
{
/* start */
profil((void *) p->kcount, p->kcountsize, p->lowpc, s_scale);
p->state = GMON_PROF_ON;
}
else
{
/* stop */
profil(NULL, 0, 0, 0);
p->state = GMON_PROF_OFF;
}
}
void monstartup (u_long lowpc, u_long highpc)
{
register int o;
char *cp;
struct gmonparam *p = &_gmonparam;
/*
* round lowpc and highpc to multiples of the density we're using
* so the rest of the scaling (here and in gprof) stays in ints.
*/
p->lowpc = ROUNDDOWN(lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->highpc = ROUNDUP(highpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->textsize = p->highpc - p->lowpc;
p->kcountsize = p->textsize / HISTFRACTION;
p->hashfraction = HASHFRACTION;
p->log_hashfraction = -1;
/* The following test must be kept in sync with the corresponding
test in mcount.c. */
if ((HASHFRACTION & (HASHFRACTION - 1)) == 0) {
/* if HASHFRACTION is a power of two, mcount can use shifting
instead of integer division. Precompute shift amount. */
p->log_hashfraction = ffs(p->hashfraction * sizeof(*p->froms)) - 1;
}
p->fromssize = p->textsize / HASHFRACTION;
p->tolimit = p->textsize * ARCDENSITY / 100;
if (p->tolimit < MINARCS)
p->tolimit = MINARCS;
else if (p->tolimit > MAXARCS)
p->tolimit = MAXARCS;
p->tossize = p->tolimit * sizeof(struct tostruct);
cp = calloc (p->kcountsize + p->fromssize + p->tossize, 1);
if (! cp)
{
ERR("monstartup: out of memory\n");
p->tos = NULL;
p->state = GMON_PROF_ERROR;
return;
}
p->tos = (struct tostruct *)cp;
cp += p->tossize;
p->kcount = (HISTCOUNTER *)cp;
cp += p->kcountsize;
p->froms = (ARCINDEX *)cp;
p->tos[0].link = 0;
o = p->highpc - p->lowpc;
if (p->kcountsize < (u_long) o)
{
#ifndef hp300
s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1;
#else
/* avoid floating point operations */
int quot = o / p->kcountsize;
if (quot >= 0x10000)
s_scale = 1;
else if (quot >= 0x100)
s_scale = 0x10000 / quot;
else if (o >= 0x800000)
s_scale = 0x1000000 / (o / (p->kcountsize >> 8));
else
s_scale = 0x1000000 / ((o << 8) / p->kcountsize);
#endif
} else
s_scale = SCALE_1_TO_1;
moncontrol(1);
}
/* Return frequency of ticks reported by profil. */
static int profile_frequency (void)
{
/*
* Discover the tick frequency of the machine if something goes wrong,
* we return 0, an impossible hertz.
*/
struct itimerval tim;
tim.it_interval.tv_sec = 0;
tim.it_interval.tv_usec = 1;
tim.it_value.tv_sec = 0;
tim.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tim, 0);
setitimer(ITIMER_REAL, 0, &tim);
if (tim.it_interval.tv_usec < 2)
return 0;
return (1000000 / tim.it_interval.tv_usec);
}
static void write_hist (int fd)
{
u_char tag = GMON_TAG_TIME_HIST;
struct gmon_hist_hdr thdr __attribute__ ((aligned (__alignof__ (char *))));
if (_gmonparam.kcountsize > 0)
{
struct iovec iov[3] =
{
{ &tag, sizeof (tag) },
{ &thdr, sizeof (struct gmon_hist_hdr) },
{ _gmonparam.kcount, _gmonparam.kcountsize }
};
*(char **) thdr.low_pc = (char *) _gmonparam.lowpc;
*(char **) thdr.high_pc = (char *) _gmonparam.highpc;
*(int32_t *) thdr.hist_size = (_gmonparam.kcountsize
/ sizeof (HISTCOUNTER));
*(int32_t *) thdr.prof_rate = profile_frequency ();
strncpy (thdr.dimen, "seconds", sizeof (thdr.dimen));
thdr.dimen_abbrev = 's';
writev (fd, iov, 3);
}
}
static void write_call_graph (int fd)
{
#define NARCS_PER_WRITEV 32
u_char tag = GMON_TAG_CG_ARC;
struct gmon_cg_arc_record raw_arc[NARCS_PER_WRITEV]
__attribute__ ((aligned (__alignof__ (char*))));
ARCINDEX from_index, to_index, from_len;
u_long frompc;
struct iovec iov[2 * NARCS_PER_WRITEV];
int nfilled;
for (nfilled = 0; nfilled < NARCS_PER_WRITEV; ++nfilled)
{
iov[2 * nfilled].iov_base = &tag;
iov[2 * nfilled].iov_len = sizeof (tag);
iov[2 * nfilled + 1].iov_base = &raw_arc[nfilled];
iov[2 * nfilled + 1].iov_len = sizeof (struct gmon_cg_arc_record);
}
nfilled = 0;
from_len = _gmonparam.fromssize / sizeof (*_gmonparam.froms);
for (from_index = 0; from_index < from_len; ++from_index)
{
if (_gmonparam.froms[from_index] == 0)
continue;
frompc = _gmonparam.lowpc;
frompc += (from_index * _gmonparam.hashfraction
* sizeof (*_gmonparam.froms));
for (to_index = _gmonparam.froms[from_index];
to_index != 0;
to_index = _gmonparam.tos[to_index].link)
{
struct arc
{
char *frompc;
char *selfpc;
int32_t count;
}
arc;
arc.frompc = (char *) frompc;
arc.selfpc = (char *) _gmonparam.tos[to_index].selfpc;
arc.count = _gmonparam.tos[to_index].count;
memcpy (raw_arc + nfilled, &arc, sizeof (raw_arc [0]));
if (++nfilled == NARCS_PER_WRITEV)
{
writev (fd, iov, 2 * nfilled);
nfilled = 0;
}
}
}
if (nfilled > 0)
writev (fd, iov, 2 * nfilled);
}
static void write_bb_counts (int fd)
{
struct __bb *grp;
u_char tag = GMON_TAG_BB_COUNT;
size_t ncounts;
size_t i;
struct iovec bbhead[2] =
{
{ &tag, sizeof (tag) },
{ &ncounts, sizeof (ncounts) }
};
struct iovec bbbody[8];
size_t nfilled;
for (i = 0; i < (sizeof (bbbody) / sizeof (bbbody[0])); i += 2)
{
bbbody[i].iov_len = sizeof (grp->addresses[0]);
bbbody[i + 1].iov_len = sizeof (grp->counts[0]);
}
/* Write each group of basic-block info (all basic-blocks in a
compilation unit form a single group). */
for (grp = __bb_head; grp; grp = grp->next)
{
ncounts = grp->ncounts;
writev (fd, bbhead, 2);
for (nfilled = i = 0; i < ncounts; ++i)
{
if (nfilled > (sizeof (bbbody) / sizeof (bbbody[0])) - 2)
{
writev (fd, bbbody, nfilled);
nfilled = 0;
}
bbbody[nfilled++].iov_base = (char *) &grp->addresses[i];
bbbody[nfilled++].iov_base = &grp->counts[i];
}
if (nfilled > 0)
writev (fd, bbbody, nfilled);
}
}
static void write_gmon (void)
{
struct gmon_hdr ghdr __attribute__ ((aligned (__alignof__ (int))));
int fd = -1;
char *env;
#ifndef O_NOFOLLOW
# define O_NOFOLLOW 0
#endif
env = getenv ("GMON_OUT_PREFIX");
if (env != NULL
#if 0
&& !__libc_enable_secure
#endif
)
{
size_t len = strlen (env);
char buf[len + 20];
sprintf (buf, "%s.%u", env, getpid ());
fd = open (buf, O_CREAT|O_TRUNC|O_WRONLY|O_NOFOLLOW, 0666);
}
if (fd == -1)
{
fd = open ("gmon.out", O_CREAT|O_TRUNC|O_WRONLY|O_NOFOLLOW, 0666);
if (fd < 0)
{
char buf[300];
int errnum = errno;
fprintf (stderr, "_mcleanup: gmon.out: %s\n",
strerror_r (errnum, buf, sizeof buf));
return;
}
}
/* write gmon.out header: */
memset (&ghdr, '\0', sizeof (struct gmon_hdr));
memcpy (&ghdr.cookie[0], GMON_MAGIC, sizeof (ghdr.cookie));
*(int32_t *) ghdr.version = GMON_VERSION;
write (fd, &ghdr, sizeof (struct gmon_hdr));
/* write PC histogram: */
write_hist (fd);
/* write call-graph: */
write_call_graph (fd);
/* write basic-block execution counts: */
write_bb_counts (fd);
close (fd);
}
void write_profiling (void)
{
int save = _gmonparam.state;
_gmonparam.state = GMON_PROF_OFF;
if (save == GMON_PROF_ON)
write_gmon ();
_gmonparam.state = save;
}
void _mcleanup (void)
{
moncontrol (0);
if (_gmonparam.state != GMON_PROF_ERROR)
write_gmon ();
/* free the memory. */
if (_gmonparam.tos != NULL)
free (_gmonparam.tos);
}
#ifndef SIGPROF
/* Enable statistical profiling, writing samples of the PC into at most
SIZE bytes of SAMPLE_BUFFER; every processor clock tick while profiling
is enabled, the system examines the user PC and increments
SAMPLE_BUFFER[((PC - OFFSET) / 2) * SCALE / 65536]. If SCALE is zero,
disable profiling. Returns zero on success, -1 on error. */
int profil (u_short *sample_buffer, size_t size, size_t offset, u_int scale)
{
if (scale == 0)
/* Disable profiling. */
return 0;
__set_errno (ENOSYS);
return -1;
}
#else
static u_short *samples;
static size_t nsamples;
static size_t pc_offset;
static u_int pc_scale;
static inline void profil_count (void *pc)
{
size_t i = (pc - pc_offset - (void *) 0) / 2;
if (sizeof (unsigned long long int) > sizeof (size_t))
i = (unsigned long long int) i * pc_scale / 65536;
else
i = i / 65536 * pc_scale + i % 65536 * pc_scale / 65536;
if (i < nsamples)
++samples[i];
}
/* Get the machine-dependent definition of `profil_counter', the signal
handler for SIGPROF. It calls `profil_count' (above) with the PC of the
interrupted code. */
#include <bits/profil-counter.h>
/* Enable statistical profiling, writing samples of the PC into at most
SIZE bytes of SAMPLE_BUFFER; every processor clock tick while profiling
is enabled, the system examines the user PC and increments
SAMPLE_BUFFER[((PC - OFFSET) / 2) * SCALE / 65536]. If SCALE is zero,
disable profiling. Returns zero on success, -1 on error. */
int profil (u_short *sample_buffer, size_t size, size_t offset, u_int scale)
{
static struct sigaction oact;
static struct itimerval otimer;
struct sigaction act;
struct itimerval timer;
if (sample_buffer == NULL)
{
/* Disable profiling. */
if (samples == NULL)
/* Wasn't turned on. */
return 0;
if (setitimer (ITIMER_PROF, &otimer, NULL) < 0)
return -1;
samples = NULL;
return sigaction (SIGPROF, &oact, NULL);
}
if (samples)
{
/* Was already turned on. Restore old timer and signal handler
first. */
if (setitimer (ITIMER_PROF, &otimer, NULL) < 0
|| sigaction (SIGPROF, &oact, NULL) < 0)
return -1;
}
samples = sample_buffer;
nsamples = size / sizeof *samples;
pc_offset = offset;
pc_scale = scale;
act.sa_handler = (__sighandler_t) &profil_counter;
act.sa_flags = SA_RESTART;
__sigfillset (&act.sa_mask);
if (sigaction (SIGPROF, &act, &oact) < 0)
return -1;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 1;
timer.it_interval = timer.it_value;
return setitimer (ITIMER_PROF, &timer, &otimer);
}
#endif
/* This file provides the machine-dependent definitions of the _MCOUNT_DECL
and MCOUNT macros. */
#include <bits/machine-gmon.h>
#include <bits/atomicity.h>
/*
* mcount is called on entry to each function compiled with the profiling
* switch set. _mcount(), which is declared in a machine-dependent way
* with _MCOUNT_DECL, does the actual work and is either inlined into a
* C routine or called by an assembly stub. In any case, this magic is
* taken care of by the MCOUNT definition in <machine/profile.h>.
*
* _mcount updates data structures that represent traversals of the
* program's call graph edges. frompc and selfpc are the return
* address and function address that represents the given call graph edge.
*
* Note: the original BSD code used the same variable (frompcindex) for
* both frompcindex and frompc. Any reasonable, modern compiler will
* perform this optimization.
*/
_MCOUNT_DECL(frompc, selfpc) /* _mcount; may be static, inline, etc */
{
register ARCINDEX *frompcindex;
register struct tostruct *top, *prevtop;
register struct gmonparam *p;
register ARCINDEX toindex;
int i;
p = &_gmonparam;
/*
* check that we are profiling
* and that we aren't recursively invoked.
*/
if (! compare_and_swap (&p->state, GMON_PROF_ON, GMON_PROF_BUSY))
return;
/*
* check that frompcindex is a reasonable pc value.
* for example: signal catchers get called from the stack,
* not from text space. too bad.
*/
frompc -= p->lowpc;
if (frompc > p->textsize)
goto done;
/* The following test used to be
if (p->log_hashfraction >= 0)
But we can simplify this if we assume the profiling data
is always initialized by the functions in gmon.c. But
then it is possible to avoid a runtime check and use the
smae `if' as in gmon.c. So keep these tests in sync. */
if ((HASHFRACTION & (HASHFRACTION - 1)) == 0) {
/* avoid integer divide if possible: */
i = frompc >> p->log_hashfraction;
} else {
i = frompc / (p->hashfraction * sizeof(*p->froms));
}
frompcindex = &p->froms[i];
toindex = *frompcindex;
if (toindex == 0) {
/*
* first time traversing this arc
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit)
/* halt further profiling */
goto overflow;
*frompcindex = toindex;
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = 0;
goto done;
}
top = &p->tos[toindex];
if (top->selfpc == selfpc) {
/*
* arc at front of chain; usual case.
*/
top->count++;
goto done;
}
/*
* have to go looking down chain for it.
* top points to what we are looking at,
* prevtop points to previous top.
* we know it is not at the head of the chain.
*/
for (; /* goto done */; ) {
if (top->link == 0) {
/*
* top is end of the chain and none of the chain
* had top->selfpc == selfpc.
* so we allocate a new tostruct
* and link it to the head of the chain.
*/
toindex = ++p->tos[0].link;
if (toindex >= p->tolimit)
goto overflow;
top = &p->tos[toindex];
top->selfpc = selfpc;
top->count = 1;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
/*
* otherwise, check the next arc on the chain.
*/
prevtop = top;
top = &p->tos[top->link];
if (top->selfpc == selfpc) {
/*
* there it is.
* increment its count
* move it to the head of the chain.
*/
top->count++;
toindex = prevtop->link;
prevtop->link = top->link;
top->link = *frompcindex;
*frompcindex = toindex;
goto done;
}
}
done:
p->state = GMON_PROF_ON;
return;
overflow:
p->state = GMON_PROF_ERROR;
return;
}
/*
* Actual definition of mcount function. Defined in <machine/profile.h>,
* which is included by <sys/gmon.h>.
*/
MCOUNT
#endif
| {
"content_hash": "3ab450aabe9c29a5ef6b4595e4ab7d3a",
"timestamp": "",
"source": "github",
"line_count": 613,
"max_line_length": 79,
"avg_line_length": 24.766721044045678,
"alnum_prop": 0.6190883941509683,
"repo_name": "easion/os_sdk",
"id": "a3444a28ed7cdb06730bdbd200172eee4e009e46",
"size": "16782",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "libc/uclibc/sysdeps/linux/common/gmon.c",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "980392"
},
{
"name": "Awk",
"bytes": "1743"
},
{
"name": "Bison",
"bytes": "113274"
},
{
"name": "C",
"bytes": "60384056"
},
{
"name": "C++",
"bytes": "6888586"
},
{
"name": "CSS",
"bytes": "3092"
},
{
"name": "Component Pascal",
"bytes": "295471"
},
{
"name": "D",
"bytes": "275403"
},
{
"name": "Erlang",
"bytes": "130334"
},
{
"name": "Groovy",
"bytes": "15362"
},
{
"name": "JavaScript",
"bytes": "437486"
},
{
"name": "Logos",
"bytes": "6575"
},
{
"name": "Makefile",
"bytes": "145054"
},
{
"name": "Max",
"bytes": "4350"
},
{
"name": "Nu",
"bytes": "1315315"
},
{
"name": "Objective-C",
"bytes": "209666"
},
{
"name": "PHP",
"bytes": "246706"
},
{
"name": "Perl",
"bytes": "1767429"
},
{
"name": "Prolog",
"bytes": "1387207"
},
{
"name": "Python",
"bytes": "14909"
},
{
"name": "R",
"bytes": "46561"
},
{
"name": "Ruby",
"bytes": "290155"
},
{
"name": "Scala",
"bytes": "184297"
},
{
"name": "Shell",
"bytes": "5748626"
},
{
"name": "TeX",
"bytes": "346362"
},
{
"name": "XC",
"bytes": "6266"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LYtest.Helpers
{
interface IUniqueIdGen<T>
{
T GetNext();
}
class UniqueIntGen : IUniqueIdGen<int>
{
private int _id = 0;
public int GetNext()
{
return _id++;
}
}
}
| {
"content_hash": "2d80ad9959c5becef04a60a1bf328d46",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 42,
"avg_line_length": 15.666666666666666,
"alnum_prop": 0.574468085106383,
"repo_name": "DeKoyre/b8",
"id": "2194761143ebe445db9f1a46f3b2679b85ac9bd0",
"size": "378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LYtest/Helpers/UniqueIdGen.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "287870"
},
{
"name": "Lex",
"bytes": "3113"
},
{
"name": "Yacc",
"bytes": "6985"
}
],
"symlink_target": ""
} |
package org.smoothbuild.bytecode.type.exc;
import org.smoothbuild.bytecode.hashed.Hash;
public class DecodeCatIllegalKindExc extends DecodeCatExc {
public DecodeCatIllegalKindExc(Hash hash, byte marker) {
super("Cannot decode category at %s. It has illegal CategoryKind marker = %s."
.formatted(hash, marker));
}
}
| {
"content_hash": "85a739dc091fa225e8272d10557c9a45",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 82,
"avg_line_length": 33.3,
"alnum_prop": 0.7567567567567568,
"repo_name": "mikosik/smooth-build",
"id": "ea6fe5cea09121c8ba6576a4742dac00fc17116c",
"size": "333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/smoothbuild/bytecode/type/exc/DecodeCatIllegalKindExc.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "2349"
},
{
"name": "Java",
"bytes": "1512436"
},
{
"name": "Shell",
"bytes": "150"
}
],
"symlink_target": ""
} |
Enforces unbound methods are called with their expected scope.
Warns when a method is used outside of a method call.
Class functions don't preserve the class scope when passed as standalone variables.
If your function does not access `this`, [you can annotate it with `this: void`](https://www.typescriptlang.org/docs/handbook/2/functions.html#declaring-this-in-a-function), or consider using an arrow function instead.
If you're working with `jest`, you can use [`eslint-plugin-jest`'s version of this rule](https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/unbound-method.md) to lint your test files, which knows when it's ok to pass an unbound method to `expect` calls.
## Rule Details
Examples of code for this rule
<!--tabs-->
### ❌ Incorrect
```ts
class MyClass {
public log(): void {
console.log(this);
}
}
const instance = new MyClass();
// This logs the global scope (`window`/`global`), not the class instance
const myLog = instance.log;
myLog();
// This log might later be called with an incorrect scope
const { log } = instance;
// arith.double may refer to `this` internally
const arith = {
double(x: number): number {
return x * 2;
},
};
const { double } = arith;
```
### ✅ Correct
```ts
class MyClass {
public logUnbound(): void {
console.log(this);
}
public logBound = () => console.log(this);
}
const instance = new MyClass();
// logBound will always be bound with the correct scope
const { logBound } = instance;
logBound();
// .bind and lambdas will also add a correct scope
const dotBindLog = instance.logBound.bind(instance);
const innerLog = () => instance.logBound();
// arith.double explicitly declares that it does not refer to `this` internally
const arith = {
double(this: void, x: number): number {
return x * 2;
},
};
const { double } = arith;
```
## Options
The rule accepts an options object with the following property:
- `ignoreStatic` to not check whether `static` methods are correctly bound
### `ignoreStatic`
Examples of **correct** code for this rule with `{ ignoreStatic: true }`:
```ts
class OtherClass {
static log() {
console.log(OtherClass);
}
}
// With `ignoreStatic`, statics are assumed to not rely on a particular scope
const { log } = OtherClass;
log();
```
## Example
```json
{
"@typescript-eslint/unbound-method": [
"error",
{
"ignoreStatic": true
}
]
}
```
## When Not To Use It
If your code intentionally waits to bind methods after use, such as by passing a `scope: this` along with the method, you can disable this rule.
If you're wanting to use `toBeCalled` and similar matches in `jest` tests, you can disable this rule for your test files in favor of [`eslint-plugin-jest`'s version of this rule](https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/unbound-method.md).
| {
"content_hash": "b1d5f4f39094213fe3aacf4072564aa4",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 276,
"avg_line_length": 25.166666666666668,
"alnum_prop": 0.701289647960962,
"repo_name": "ChromeDevTools/devtools-frontend",
"id": "9f71738f5a9147d87617d3b4df61c1c20f12219d",
"size": "2893",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "node_modules/@typescript-eslint/eslint-plugin/docs/rules/unbound-method.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "615241"
},
{
"name": "Dart",
"bytes": "205"
},
{
"name": "HTML",
"bytes": "317251"
},
{
"name": "JavaScript",
"bytes": "1401177"
},
{
"name": "LLVM",
"bytes": "1918"
},
{
"name": "Makefile",
"bytes": "687"
},
{
"name": "Python",
"bytes": "133111"
},
{
"name": "Shell",
"bytes": "1122"
},
{
"name": "TypeScript",
"bytes": "15230731"
},
{
"name": "WebAssembly",
"bytes": "921"
}
],
"symlink_target": ""
} |
package org.apache.dubbo.common.serialize.avro;
import org.apache.dubbo.common.serialize.model.Person;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.core.IsNull.nullValue;
public class AvroObjectInputOutputTest {
private AvroObjectInput avroObjectInput;
private AvroObjectOutput avroObjectOutput;
private PipedOutputStream pos;
private PipedInputStream pis;
@BeforeEach
public void setup() throws IOException {
pis = new PipedInputStream();
pos = new PipedOutputStream();
pis.connect(pos);
avroObjectOutput = new AvroObjectOutput(pos);
avroObjectInput = new AvroObjectInput(pis);
}
@AfterEach
public void clean() throws IOException {
if (pos != null) {
pos.close();
pos = null;
}
if (pis != null) {
pis.close();
pis = null;
}
}
@Test
public void testWriteReadBool() throws IOException, InterruptedException {
avroObjectOutput.writeBool(true);
avroObjectOutput.flushBuffer();
pos.close();
boolean result = avroObjectInput.readBool();
assertThat(result, is(true));
}
@Test
public void testWriteReadByte() throws IOException {
avroObjectOutput.writeByte((byte) 'a');
avroObjectOutput.flushBuffer();
pos.close();
Byte result = avroObjectInput.readByte();
assertThat(result, is((byte) 'a'));
}
@Test
public void testWriteReadBytes() throws IOException {
avroObjectOutput.writeBytes("123456".getBytes());
avroObjectOutput.flushBuffer();
pos.close();
byte[] result = avroObjectInput.readBytes();
assertThat(result, is("123456".getBytes()));
}
@Test
public void testWriteReadShort() throws IOException {
avroObjectOutput.writeShort((short) 1);
avroObjectOutput.flushBuffer();
pos.close();
short result = avroObjectInput.readShort();
assertThat(result, is((short) 1));
}
@Test
public void testWriteReadInt() throws IOException {
avroObjectOutput.writeInt(1);
avroObjectOutput.flushBuffer();
pos.close();
Integer result = avroObjectInput.readInt();
assertThat(result, is(1));
}
@Test
public void testReadDouble() throws IOException {
avroObjectOutput.writeDouble(3.14d);
avroObjectOutput.flushBuffer();
pos.close();
Double result = avroObjectInput.readDouble();
assertThat(result, is(3.14d));
}
@Test
public void testReadLong() throws IOException {
avroObjectOutput.writeLong(10L);
avroObjectOutput.flushBuffer();
pos.close();
Long result = avroObjectInput.readLong();
assertThat(result, is(10L));
}
@Test
public void testWriteReadFloat() throws IOException {
avroObjectOutput.writeFloat(1.66f);
avroObjectOutput.flushBuffer();
pos.close();
Float result = avroObjectInput.readFloat();
assertThat(result, is(1.66F));
}
@Test
public void testWriteReadUTF() throws IOException {
avroObjectOutput.writeUTF("wording");
avroObjectOutput.flushBuffer();
pos.close();
String result = avroObjectInput.readUTF();
assertThat(result, is("wording"));
}
@Test
public void testWriteReadObject() throws IOException, ClassNotFoundException {
Person p = new Person();
p.setAge(30);
p.setName("abc");
avroObjectOutput.writeObject(p);
avroObjectOutput.flushBuffer();
pos.close();
Person result = avroObjectInput.readObject(Person.class);
assertThat(result, not(nullValue()));
assertThat(result.getName(), is("abc"));
assertThat(result.getAge(), is(30));
}
@Test
public void testWriteReadObjectWithoutClass() throws IOException, ClassNotFoundException {
Person p = new Person();
p.setAge(30);
p.setName("abc");
avroObjectOutput.writeObject(p);
avroObjectOutput.flushBuffer();
pos.close();
//这里会丢失所有信息
Object result = avroObjectInput.readObject();
assertThat(result, not(nullValue()));
// assertThat(result.getName(), is("abc"));
// assertThat(result.getAge(), is(30));
}
}
| {
"content_hash": "7ec59c205a48d2a7f8e3584a78c15d14",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 94,
"avg_line_length": 27.07182320441989,
"alnum_prop": 0.6148979591836735,
"repo_name": "fengyie007/dubbo",
"id": "431b29f0830230474738e1a49d34767374a8c27c",
"size": "5734",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "dubbo-serialization/dubbo-serialization-test/src/test/java/org/apache/dubbo/common/serialize/avro/AvroObjectInputOutputTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2002"
},
{
"name": "Java",
"bytes": "10570613"
},
{
"name": "JavaScript",
"bytes": "3258"
},
{
"name": "Lex",
"bytes": "2076"
},
{
"name": "Mustache",
"bytes": "29337"
},
{
"name": "Shell",
"bytes": "15510"
},
{
"name": "Thrift",
"bytes": "5293"
}
],
"symlink_target": ""
} |
{% load i18n %}
{% load devicetags %}
<div class="modal fade" id="{{ modalname }}" role="dialog" aria-labelledby="{{ modalname }}Label" aria-hidden="true">
<div class="modal-dialog {% block cssClasses %}{% endblock %}">
<div class="modal-content">
<div class="modal-header">
{% block modalHeader %}{% endblock %}
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
{% block modalBody %}{% endblock %}
</div>
<div class="modal-footer">
{% block modalFooter %}{% endblock %}
</div>
</div>
</div>
</div> | {
"content_hash": "a1a7c68b9fc9c9e8e9545c261657d4dc",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 117,
"avg_line_length": 38.63157894736842,
"alnum_prop": 0.5095367847411444,
"repo_name": "MPIB/Lagerregal",
"id": "c158b4ad123bd80737bde9404eb61bd9dd8578d6",
"size": "734",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "templates/snippets/modals/base.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "3809"
},
{
"name": "HTML",
"bytes": "214898"
},
{
"name": "JavaScript",
"bytes": "6698"
},
{
"name": "Makefile",
"bytes": "1162"
},
{
"name": "Python",
"bytes": "640679"
}
],
"symlink_target": ""
} |
# frozen_string_literal: true
require "cases/helper"
require "models/post"
if supports_optimizer_hints?
class Mysql2OptimzerHintsTest < ActiveRecord::Mysql2TestCase
fixtures :posts
def test_optimizer_hints
assert_sql(%r{\ASELECT /\*\+ NO_RANGE_OPTIMIZATION\(posts index_posts_on_author_id\) \*/}) do
posts = Post.optimizer_hints("NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id)")
posts = posts.select(:id).where(author_id: [0, 1])
assert_includes posts.explain, "| index | index_posts_on_author_id | index_posts_on_author_id |"
end
end
def test_optimizer_hints_with_count_subquery
assert_sql(%r{\ASELECT /\*\+ NO_RANGE_OPTIMIZATION\(posts index_posts_on_author_id\) \*/}) do
posts = Post.optimizer_hints("NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id)")
posts = posts.select(:id).where(author_id: [0, 1]).limit(5)
assert_equal 5, posts.count
end
end
def test_optimizer_hints_is_sanitized
assert_sql(%r{\ASELECT /\*\+ NO_RANGE_OPTIMIZATION\(posts index_posts_on_author_id\) \*/}) do
posts = Post.optimizer_hints("/*+ NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id) */")
posts = posts.select(:id).where(author_id: [0, 1])
assert_includes posts.explain, "| index | index_posts_on_author_id | index_posts_on_author_id |"
end
assert_sql(%r{\ASELECT /\*\+ `posts`\.\*, \*/}) do
posts = Post.optimizer_hints("**// `posts`.*, //**")
posts = posts.select(:id).where(author_id: [0, 1])
assert_equal({ "id" => 1 }, posts.first.as_json)
end
end
def test_optimizer_hints_with_unscope
assert_sql(%r{\ASELECT `posts`\.`id`}) do
posts = Post.optimizer_hints("/*+ NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id) */")
posts = posts.select(:id).where(author_id: [0, 1])
posts.unscope(:optimizer_hints).load
end
end
def test_optimizer_hints_with_or
assert_sql(%r{\ASELECT /\*\+ NO_RANGE_OPTIMIZATION\(posts index_posts_on_author_id\) \*/}) do
Post.optimizer_hints("NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id)")
.or(Post.all).load
end
queries = capture_sql do
Post.optimizer_hints("NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id)")
.or(Post.optimizer_hints("NO_ICP(posts)")).load
end
assert_equal 1, queries.length
assert_includes queries.first, "NO_RANGE_OPTIMIZATION(posts index_posts_on_author_id)"
assert_not_includes queries.first, "NO_ICP(posts)"
queries = capture_sql do
Post.all.or(Post.optimizer_hints("NO_ICP(posts)")).load
end
assert_equal 1, queries.length
assert_not_includes queries.first, "NO_ICP(posts)"
end
end
end
| {
"content_hash": "79df8e86b7212864338781728660b749",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 104,
"avg_line_length": 40.608695652173914,
"alnum_prop": 0.6370449678800857,
"repo_name": "tgxworld/rails",
"id": "d043b3c72604f6e7f6047af9dcebea3c5f0c3801",
"size": "2802",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "activerecord/test/cases/adapters/mysql2/optimizer_hints_test.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "44804"
},
{
"name": "CoffeeScript",
"bytes": "24543"
},
{
"name": "HTML",
"bytes": "478094"
},
{
"name": "JavaScript",
"bytes": "132672"
},
{
"name": "Ruby",
"bytes": "13904535"
},
{
"name": "SCSS",
"bytes": "979"
},
{
"name": "Shell",
"bytes": "4531"
},
{
"name": "Yacc",
"bytes": "1003"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
namespace BaselineSolution.Framework.Response
{
public abstract class BaseResponse<T>
{
private List<Message> _messages;
private IEnumerable<T> _values;
protected BaseResponse()
{
}
protected BaseResponse(T value)
{
Values = Values.Append(value);
}
protected BaseResponse(IEnumerable<T> values)
{
Values = values;
}
public List<Message> Messages
{
get { return _messages ?? (_messages = new List<Message>()); }
set { _messages = value; }
}
public IEnumerable<T> Values
{
get => _values ?? (_values = new List<T>());
private set => _values = value;
}
}
}
| {
"content_hash": "abfa83b977fbcc3979c8742fe46897f5",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 74,
"avg_line_length": 22.289473684210527,
"alnum_prop": 0.5182998819362455,
"repo_name": "Adconsulting/BaseSolution",
"id": "df8491355c480ead4903e43bf78e954187f32d49",
"size": "849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BaselineSolution.Framework/Response/BaseResponse.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "114"
},
{
"name": "C#",
"bytes": "645373"
},
{
"name": "CSS",
"bytes": "20422"
},
{
"name": "JavaScript",
"bytes": "259724"
}
],
"symlink_target": ""
} |
title: "Filters"
description: "Filters help you reduce alert fatigue by controlling which events acted on by Sensu handlers. Read the reference doc to learn about filters, use Sensu's built-in filters, and create your own filters."
weight: 10
version: "5.11"
product: "Sensu Go"
platformContent: false
menu:
sensu-go-5.11:
parent: reference
---
- [Built-in filters](#built-in-filters)
- [Building filter expressions](#building-filter-expressions)
- [Specification](#filter-specification)
- [Examples](#filter-examples)
- [Handling production events](#handling-production-events)
- [Handling non-production events](#handling-non-production-events)
- [Handling state change only](#handling-state-change-only)
- [Handling repeated events](#handling-repeated-events)
- [Handling events during office hours only](#handling-events-during-office-hours-only)
## How do Sensu filters work?
Sensu filters are applied when **event handlers** are configured to use one or
more filters. Prior to executing a handler, the Sensu backend will apply any
filters configured for the handler to the **event** data. If the event is not
removed by the filter(s), the handler will be executed. The
filter analysis flow performs these steps:
* When the Sensu backend is processing an event, it will check for the definition
of a `handler` (or `handlers`). Prior to executing each handler, the Sensu
server will first apply any configured `filters` for the handler.
* If multiple `filters` are configured for a handler, they are executed
sequentially.
* Filter `expressions` are compared with event data.
* Filters can be inclusive (only matching events are handled) or exclusive
(matching events are not handled).
* As soon as a filter removes an event, no further
analysis is performed and the event handler will not be executed.
_NOTE: Filters specified in a **handler set** definition have no effect. Filters must
be specified in individual handler definitions._
### Inclusive and exclusive filtering
Filters can be _inclusive_ `"action": "allow"` (replaces `"negate": false` in
Sensu 1) or _exclusive_ `"action": "deny"` (replaces `"negate": true` in Sensu
1). Configuring a handler to use multiple _inclusive_ filters is the equivalent
of using an `AND` query operator (only handle events if they match
_inclusive_ filter `x AND y AND z`). Configuring a handler to use multiple
_exclusive_ filters is the equivalent of using an `OR` operator (only
handle events if they don’t match `x OR y OR z`).
* **Inclusive filtering**: by setting the filter definition attribute `"action":
"allow"`, only events that match the defined filter expressions are handled.
* **Exclusive filtering**: by setting the filter definition attribute `"action":
"deny"`, events are only handled if they do not match the defined filter
expressions.
### Filter expression comparison
Filter expressions are compared directly with their event data counterparts. For
inclusive filter definitions (like `"action": "allow"`), matching expressions
will result in the filter returning a `true` value; for exclusive filter
definitions (like `"action": "deny"`), matching expressions will result in the
filter returning a `false` value, and the event will not pass through the
filter. Filters that return a true value will continue to be processed via
additional filters (if defined), mutators (if defined), and handlers.
### Filter expression evaluation
When more complex conditional logic is needed than direct filter expression
comparison, Sensu filters provide support for expression evaluation using
[Otto](https://github.com/robertkrimen/otto). Otto is an ECMAScript 5 (JavaScript) VM,
and evaluates javascript expressions that are provided in the filter.
There are some caveats to using Otto; most notably, the regular expressions
specified in ECMAScript 5 do not all work. See the Otto README for more details.
### Filter assets
Sensu filters can have assets that are included in their execution context.
When valid assets are associated with a filter, Sensu evaluates any
files it finds that have a ".js" extension before executing a filter. The
result of evaluating the scripts is cached for a given asset set, for the
sake of performance. For an example of how to implement a filter as an asset, see the [guide on reducing alert fatigue][alert-fatigue].
## Built-in filters
Sensu includes built-in filters to help you customize event pipelines for metrics and alerts.
To start using built-in filters, see the guides to [sending Slack alerts][4] and [planning maintenances][5].
### Built-in filter: only incidents
The incidents filter is included in every installation of the [Sensu backend][8].
You can use the incidents filter to allow only high priority events through a Sensu pipeline.
For example, you can use the incidents filter to reduce noise when sending notifications to Slack.
When applied to a handler, the incidents filter allows only warning (`"status": 1`), critical (`"status": 2`), and resolution events to be processed.
To use the incidents filter, include the `is_incident` filter in the handler configuration `filters` array:
{{< language-toggle >}}
{{< highlight yml >}}
type: Handler
api_version: core/v2
metadata:
name: slack
namespace: default
spec:
command: sensu-slack-handler --channel '#monitoring'
env_vars:
- SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
filters:
- is_incident
handlers: []
runtime_assets: []
timeout: 0
type: pipe
{{< /highlight >}}
{{< highlight json >}}
{
"type": "Handler",
"api_version": "core/v2",
"metadata": {
"name": "slack",
"namespace": "default"
},
"spec": {
"command": "sensu-slack-handler --channel '#monitoring'",
"env_vars": [
"SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
],
"filters": [
"is_incident"
],
"handlers": [],
"runtime_assets": [],
"timeout": 0,
"type": "pipe"
}
}
{{< /highlight >}}
{{< /language-toggle >}}
The `is_incident` filter applies the following filtering logic:
| status | allow | discard | | | | |
| ----- | ----- | ------- | --- | --- | --- | --- |
| 0 | |{{< cross >}}| | | | |
| 1 |{{< check >}} | | | | | |
| 2 |{{< check >}} | | | | | |
| other | |{{< cross >}}| | | | |
| 1 --> 0 or 2 --> 0<br>(resolution event) |{{< check >}} | | | | | |
### Built-in filter: allow silencing
[Sensu silencing][6] lets you suppress execution of event handlers on an on-demand basis, giving you the ability to quiet incoming alerts and [plan maintenances][5].
To allow silencing for an event handler, add the `not_silenced` filter to the handler configuration `filters` array:
{{< language-toggle >}}
{{< highlight yml >}}
type: Handler
api_version: core/v2
metadata:
name: slack
namespace: default
spec:
command: sensu-slack-handler --channel '#monitoring'
env_vars:
- SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
filters:
- is_incident
- not_silenced
handlers: []
runtime_assets: []
timeout: 0
type: pipe
{{< /highlight >}}
{{< highlight json >}}
{
"type": "Handler",
"api_version": "core/v2",
"metadata": {
"name": "slack",
"namespace": "default"
},
"spec": {
"command": "sensu-slack-handler --channel '#monitoring'",
"env_vars": [
"SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"
],
"filters": [
"is_incident",
"not_silenced"
],
"handlers": [],
"runtime_assets": [],
"timeout": 0,
"type": "pipe"
}
}
{{< /highlight >}}
{{< /language-toggle >}}
When applied to a handler configuration, the `not_silenced` filter silences events that include the `silenced` attribute. The handler in the example above uses both the silencing and [incidents][7] filters, preventing low priority and silenced events from being sent to Slack.
### Built-in filter: has metrics
The metrics filter is included in every installation of the [Sensu backend][8].
When applied to a handler, the metrics filter allows only events containing [Sensu metrics][9] to be processed.
You can use the metrics filter to prevent handlers that require metrics from failing in case of an error in metric collection.
To use the metrics filter, include the `has_metrics` filter in the handler configuration `filters` array:
{{< language-toggle >}}
{{< highlight yml >}}
type: Handler
api_version: core/v2
metadata:
name: influx-db
namespace: default
spec:
command: sensu-influxdb-handler -d sensu
env_vars:
- INFLUXDB_ADDR=http://influxdb.default.svc.cluster.local:8086
- INFLUXDB_USER=sensu
- INFLUXDB_PASSWORD=password
filters:
- has_metrics
handlers: []
runtime_assets: []
timeout: 0
type: pipe
{{< /highlight >}}
{{< highlight json >}}
{
"type": "Handler",
"api_version": "core/v2",
"metadata": {
"name": "influx-db",
"namespace": "default"
},
"spec": {
"command": "sensu-influxdb-handler -d sensu",
"env_vars": [
"INFLUXDB_ADDR=http://influxdb.default.svc.cluster.local:8086",
"INFLUXDB_USER=sensu",
"INFLUXDB_PASSWORD=password"
],
"filters": [
"has_metrics"
],
"handlers": [],
"runtime_assets": [],
"timeout": 0,
"type": "pipe"
}
}
{{< /highlight >}}
{{< /language-toggle >}}
When applied to a handler configuration, the `has_metrics` filter allows only events that include a [`metrics` scope][9].
## Building filter expressions
You can write custom filter expressions as [Sensu query expressions][27] using the event data attributes described in this section.
For more information about event attributes, see the [event reference][28].
### Syntax quick reference
<table>
<thead>
<tr>
<th>operator</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>===</code> / <code>!==</code></td>
<td>Identity operator / Nonidentity operator</td>
</tr>
<tr>
<td><code>==</code> / <code>!=</code></td>
<td>Equality operator / Inequality operator</td>
</tr>
<tr>
<td><code>&&</code> / <code>||</code></td>
<td>Logical AND / Logical OR</td>
</tr>
<tr>
<td><code><</code> / <code>></code></td>
<td>Less than / Greater than</td>
</tr>
<tr>
<td><code><=</code> / <code>>=</code></td>
<td>Less than or equal to / Greater than or equal to</td>
</tr>
</tbody>
</table>
### Event attributes available to filters
| attribute | type | description |
| ------------------- | ------- | ----------- |
`event.has_check` | boolean | Returns true if the event contains check data
`event.has_metrics` | boolean | Returns true if the event contains metrics
`event.is_incident` | boolean | Returns true for critical alerts (status `2`), warnings (status `1`), and resolution events (status `0` transitioning from status `1` or `2`)
`event.is_resolution` | boolean | Returns true if the event status is OK (`0`) and the previous event was of a non-zero status
`event.is_silenced` | boolean | Returns true if the event matches an active silencing entry
`event.timestamp` | integer | Time that the event occurred in seconds since the Unix epoch
### Check attributes available to filters
| attribute | type | description |
| ---------------------------------- | ------- | ----------- |
`event.check.annotations` | map | Custom [annotations][19] applied to the check
`event.check.command` | string | The command executed by the check
`event.check.cron` | string | [Check execution schedule][21] using cron syntax
`event.check.discard_output` | boolean | If the check is configured to discard check output from event data
`event.check.duration` | float | Command execution time in seconds
`event.check.env_vars` | array | Environment variables used with command execution
`event.check.executed` | integer | Time that the check was executed in seconds since the Unix epoch
`event.check.handlers` | array | Sensu event [handlers][22] assigned to the check
`event.check.high_flap_threshold` | integer | The check's flap detection high threshold in percent state change
`event.check.history` | array | [Check status history][20] for the last 21 check executions
`event.check.hooks` | array | [Check hook][12] execution data
`event.check.interval` | integer | The check execution frequency in seconds
`event.check.issued` | integer | Time that the check request was issued in seconds since the Unix epoch
`event.check.labels` | map | Custom [labels][19] applied to the check
`event.check.last_ok` | integer | The last time that the check returned an OK status (`0`) in seconds since the Unix epoch
`event.check.low_flap_threshold` | integer | The check's flap detection low threshold in percent state change
`event.check.max_output_size` | integer | Maximum size, in bytes, of stored check outputs
`event.check.name` | string | Check name
`event.check.occurrences` | integer | The [number of preceding events][29] with the same status as the current event
`event.check.occurrences_watermark` | integer | For resolution events, the [number of preceding events][29] with a non-OK status
`event.check.output` | string | The output from the execution of the check command
`event.check.output_metric_format` | string | The [metric format][13] generated by the check command: `nagios_perfdata`, `graphite_plaintext`, `influxdb_line`, or `opentsdb_line`
`event.check.output_metric_handlers` | array | Sensu metric [handlers][22] assigned to the check
`event.check.proxy_entity_name` | string | The entity name, used to create a [proxy entity][14] for an external resource
`event.check.proxy_requests` | map | [Proxy request][15] configuration
`event.check.publish` | boolean | If the check is scheduled automatically
`event.check.round_robin` | boolean | If the check is configured to be executed in a [round-robin style][16]
`event.check.runtime_assets` | array | Sensu [assets][17] used by the check
`event.check.state` | string | The state of the check: `passing` (status `0`), `failing` (status other than `0`), or `flapping`
`event.check.status` | integer | Exit status code produced by the check: `0` (OK), `1` (warning), `2` (critical), or other status (unknown or custom status)
`event.check.stdin` | boolean | If the Sensu agent writes JSON-serialized entity and check data to the command process’ STDIN
`event.check.subscriptions` | array | Subscriptions that the check belongs to
`event.check.timeout` | integer | The check execution duration timeout in seconds
`event.check.total_state_change` | integer | The total state change percentage for the check’s history
`event.check.ttl` | integer | The time to live (TTL) in seconds until the event is considered stale
`event.metrics.handlers` | array | Sensu metric [handlers][22] assigned to the check
`event.metrics.points` | array | [Metric data points][23] including a name, timestamp, value, and tags
### Entity attributes available to filters
| attribute | type | description |
| ------------------------------------ | ------- | ----------- |
`event.entity.annotations` | map | Custom [annotations][24] assigned to the entity
`event.entity.deregister` | boolean | If the agent entity should be removed when it stops sending [keepalive messages][26]
`event.entity.deregistration` | map | A map containing a handler name, for use when an entity is deregistered
`event.entity.entity_class` | string | The entity type: usually `agent` or `proxy`
`event.entity.labels` | map | Custom [labels][24] assigned to the entity
`event.entity.last_seen` | integer | Timestamp the entity was last seen, in seconds since the Unix epoch
`event.entity.name` | string | Entity name
`event.entity.redact` | array | List of items to redact from log messages
`event.entity.subscriptions` | array | List of subscriptions assigned to the entity
`event.entity.system` | map | Information about the [entity's system][18]
`event.entity.system.arch` | string | The entity's system architecture
`event.entity.system.hostname` | string | The entity's hostname
`event.entity.system.network` | map | The entity's network interface list
`event.entity.system.os` | string | The entity’s operating system
`event.entity.system.platform` | string | The entity’s operating system distribution
`event.entity.system.platform_family` | string | The entity’s operating system family
`event.entity.system.platform_version` | string | The entity’s operating system version
`event.entity.user` | string | Sensu [RBAC][25] username used by the agent entity
## Filter specification
### Top-level attributes
type |
-------------|------
description | Top-level attribute specifying the [`sensuctl create`][sc] resource type. Filters should always be of type `EventFilter`.
required | Required for filter definitions in `wrapped-json` or `yaml` format for use with [`sensuctl create`][sc].
type | String
example | {{< highlight shell >}}"type": "EventFilter"{{< /highlight >}}
api_version |
-------------|------
description | Top-level attribute specifying the Sensu API group and version. For filters in this version of Sensu, this attribute should always be `core/v2`.
required | Required for filter definitions in `wrapped-json` or `yaml` format for use with [`sensuctl create`][sc].
type | String
example | {{< highlight shell >}}"api_version": "core/v2"{{< /highlight >}}
metadata |
-------------|------
description | Top-level collection of metadata about the filter, including the `name` and `namespace` as well as custom `labels` and `annotations`. The `metadata` map is always at the top level of the filter definition. This means that in `wrapped-json` and `yaml` formats, the `metadata` scope occurs outside the `spec` scope. See the [metadata attributes reference][11] for details.
required | Required for filter definitions in `wrapped-json` or `yaml` format for use with [`sensuctl create`][sc].
type | Map of key-value pairs
example | {{< highlight shell >}}
"metadata": {
"name": "filter-weekdays-only",
"namespace": "default",
"labels": {
"region": "us-west-1"
},
"annotations": {
"slack-channel" : "#monitoring"
}
}
{{< /highlight >}}
spec |
-------------|------
description | Top-level map that includes the filter [spec attributes][sp].
required | Required for filter definitions in `wrapped-json` or `yaml` format for use with [`sensuctl create`][sc].
type | Map of key-value pairs
example | {{< highlight shell >}}
"spec": {
"action": "allow",
"expressions": [
"event.entity.namespace == 'production'"
],
"runtime_assets": []
}
{{< /highlight >}}
### Spec attributes
action |
-------------|------
description | Action to take with the event if the filter expressions match. _NOTE: see [Inclusive and exclusive filtering][1] for more information._
required | true
type | String
allowed values | `allow`, `deny`
example | {{< highlight shell >}}"action": "allow"{{< /highlight >}}
expressions |
-------------|------
description | Filter expressions to be compared with event data. Note that event metadata can be referenced without including the `metadata` scope, for example: `event.entity.namespace`.
required | true
type | Array
example | {{< highlight shell >}}"expressions": [
"event.check.team == 'ops'"
]
{{< /highlight >}}
runtime_assets | |
---------------|------
description | Assets to be applied to the filter's execution context. JavaScript files in the lib directory of the asset will be evaluated.
required | false
type | Array of String
default | []
example | {{< highlight shell >}}"runtime_assets": ["underscore"]{{< /highlight >}}
### Metadata attributes
| name | |
-------------|------
description | A unique string used to identify the filter. Filter names cannot contain special characters or spaces (validated with Go regex [`\A[\w\.\-]+\z`](https://regex101.com/r/zo9mQU/2)). Each filter must have a unique name within its namespace.
required | true
type | String
example | {{< highlight shell >}}"name": "filter-weekdays-only"{{< /highlight >}}
| namespace | |
-------------|------
description | The Sensu [RBAC namespace][10] that this filter belongs to.
required | false
type | String
default | `default`
example | {{< highlight shell >}}"namespace": "production"{{< /highlight >}}
| labels | |
-------------|------
description | Custom attributes you can use to create meaningful collections that can be selected with [API filtering][api-filter] and [sensuctl filtering][sensuctl-filter]. Overusing labels can impact Sensu's internal performance, so we recommend moving complex, non-identifying metadata to annotations.
required | false
type | Map of key-value pairs. Keys can contain only letters, numbers, and underscores, but must start with a letter. Values can be any valid UTF-8 string.
default | `null`
example | {{< highlight shell >}}"labels": {
"environment": "development",
"region": "us-west-2"
}{{< /highlight >}}
| annotations | |
-------------|------
description | Non-identifying metadata that's meaningful to people or external tools interacting with Sensu.<br><br>In contrast to labels, annotations cannot be used in [API filtering][api-filter] or [sensuctl filtering][sensuctl-filter] and do not impact Sensu's internal performance.
required | false
type | Map of key-value pairs. Keys and values can be any valid UTF-8 string.
default | `null`
example | {{< highlight shell >}} "annotations": {
"managed-by": "ops",
"playbook": "www.example.url"
}{{< /highlight >}}
## Filter Examples
### Minimum required filter attributes
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
name: filter_minimum
namespace: default
spec:
action: allow
expressions:
- event.check.occurrences == 1
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "filter_minimum",
"namespace": "default"
},
"spec": {
"action": "allow",
"expressions": [
"event.check.occurrences == 1"
]
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Handling production events
The following filter allows only events with a custom entity label `"environment": "production"` to be handled.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
name: production_filter
namespace: default
spec:
action: allow
expressions:
- event.entity.labels['environment'] == 'production'
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "production_filter",
"namespace": "default"
},
"spec": {
"action": "allow",
"expressions": [
"event.entity.labels['environment'] == 'production'"
]
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Handling non-production events
The following filter discards events with a custom entity label `"environment": "production"`, allowing only events without an `environment` label or events with `environment` set to something other than `production` to be handled.
Note that `action` is `deny`, making this an exclusive filter; if evaluation
returns false, the event is handled.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
name: not_production
namespace: default
spec:
action: deny
expressions:
- event.entity.labels['environment'] == 'production'
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "not_production",
"namespace": "default"
},
"spec": {
"action": "deny",
"expressions": [
"event.entity.labels['environment'] == 'production'"
]
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Handling state change only
Some teams migrating to Sensu have asked about reproducing the behavior of their
old monitoring system which alerts only on state change. This
`state_change_only` inclusive filter provides such.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
annotations: null
labels: null
name: state_change_only
namespace: default
spec:
action: allow
expressions:
- event.check.occurrences == 1
runtime_assets: []
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "state_change_only",
"namespace": "default",
"labels": null,
"annotations": null
},
"spec": {
"action": "allow",
"expressions": [
"event.check.occurrences == 1"
],
"runtime_assets": []
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Handling repeated events
The following example filter definition, entitled `filter_interval_60_hourly`,
will match event data with a check `interval` of `60` seconds, and an
`occurrences` value of `1` (the first occurrence) -OR- any `occurrences`
value that is evenly divisible by 60 via a [modulo
operator](https://en.wikipedia.org/wiki/Modulo_operation) calculation
(calculating the remainder after dividing `occurrences` by 60).
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
annotations: null
labels: null
name: filter_interval_60_hourly
namespace: default
spec:
action: allow
expressions:
- event.check.interval == 60
- event.check.occurrences == 1 || event.check.occurrences % 60 == 0
runtime_assets: []
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "filter_interval_60_hourly",
"namespace": "default",
"labels": null,
"annotations": null
},
"spec": {
"action": "allow",
"expressions": [
"event.check.interval == 60",
"event.check.occurrences == 1 || event.check.occurrences % 60 == 0"
],
"runtime_assets": []
}
}
{{< /highlight >}}
{{< /language-toggle >}}
The next example will apply the same logic as the previous example, but for
checks with a 30 second `interval`.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
annotations: null
labels: null
name: filter_interval_30_hourly
namespace: default
spec:
action: allow
expressions:
- event.check.interval == 30
- event.check.occurrences == 1 || event.check.occurrences % 120 == 0
runtime_assets: []
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "filter_interval_30_hourly",
"namespace": "default",
"labels": null,
"annotations": null
},
"spec": {
"action": "allow",
"expressions": [
"event.check.interval == 30",
"event.check.occurrences == 1 || event.check.occurrences % 120 == 0"
],
"runtime_assets": []
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Handling events during office hours only
This filter evaluates the event timestamp to determine if the event occurred
between 9 AM and 5 PM UTC on a weekday. Remember that `action` is equal to
`allow`, so this is an inclusive filter. If evaluation returns false, the event
will not be handled.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
annotations: null
labels: null
name: nine_to_fiver
namespace: default
spec:
action: allow
expressions:
- weekday(event.timestamp) >= 1 && weekday(event.timestamp) <= 5
- hour(event.timestamp) >= 9 && hour(event.timestamp) <= 17
runtime_assets: []
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "nine_to_fiver",
"namespace": "default",
"labels": null,
"annotations": null
},
"spec": {
"action": "allow",
"expressions": [
"weekday(event.timestamp) >= 1 && weekday(event.timestamp) <= 5",
"hour(event.timestamp) >= 9 && hour(event.timestamp) <= 17"
],
"runtime_assets": []
}
}
{{< /highlight >}}
{{< /language-toggle >}}
### Using JavaScript libraries with Sensu filters
You can include JavaScript libraries in their filter execution context with
assets. For instance, assuming you've packaged underscore.js into a Sensu
asset, you could then use functions from the underscore library for filter
expressions.
{{< language-toggle >}}
{{< highlight yml >}}
type: EventFilter
api_version: core/v2
metadata:
annotations: null
labels: null
name: deny_if_failure_in_history
namespace: default
spec:
action: deny
expressions:
- _.reduce(event.check.history, function(memo, h) { return (memo || h.status !=
0); })
runtime_assets:
- underscore
{{< /highlight >}}
{{< highlight json >}}
{
"type": "EventFilter",
"api_version": "core/v2",
"metadata": {
"name": "deny_if_failure_in_history",
"namespace": "default",
"labels": null,
"annotations": null
},
"spec": {
"action": "deny",
"expressions": [
"_.reduce(event.check.history, function(memo, h) { return (memo || h.status != 0); })"
],
"runtime_assets": ["underscore"]
}
}
{{< /highlight >}}
{{< /language-toggle >}}
[1]: #inclusive-and-exclusive-filtering
[2]: #when-attributes
[3]: ../../reference/sensuctl/#time-windows
[4]: ../../guides/send-slack-alerts
[5]: ../../guides/plan-maintenance/
[6]: ../silencing
[7]: #built-in-filter-only-incidents
[8]: ../backend
[9]: ../events
[10]: ../rbac#namespaces
[11]: #metadata-attributes
[sc]: ../../sensuctl/reference#creating-resources
[sp]: #spec-attributes
[12]: ../hooks
[13]: ../../guides/extract-metrics-with-checks
[14]: ../checks#using-a-proxy-check-to-monitor-a-proxy-entity
[15]: ../checks#using-a-proxy-check-to-monitor-multiple-proxy-entities
[16]: ../checks#round-robin-checks
[17]: ../assets
[18]: ../entities#system-attributes
[19]: ../checks/#metadata-attributes
[20]: ../events/#history-attributes
[21]: ../checks#check-scheduling
[22]: ../handlers
[23]: ../events#metric-attributes
[24]: ../entities#metadata-attributes
[25]: ../rbac#default-roles
[26]: ../agent#keepalive-monitoring
[27]: ../sensu-query-expressions
[28]: ../events#event-format
[api-filter]: ../../api/overview#filtering
[sensuctl-filter]: ../../sensuctl/reference#filtering
[29]: ../events#occurrences-and-occurrences-watermark
[alert-fatigue]: ../../guides/reduce-alert-fatigue/
| {
"content_hash": "51ee01d9846bcd4bad618daaa86a67cf",
"timestamp": "",
"source": "github",
"line_count": 886,
"max_line_length": 386,
"avg_line_length": 35.465011286681715,
"alnum_prop": 0.6655209725669913,
"repo_name": "sensu/sensu-docs",
"id": "13d9c9059fcb0f37bcda6cf2e1f92ed531cb16de",
"size": "31440",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "archived/sensu-go/5.11/reference/filters.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "123020"
},
{
"name": "JavaScript",
"bytes": "61971"
},
{
"name": "Procfile",
"bytes": "14"
},
{
"name": "Python",
"bytes": "3764"
},
{
"name": "Ruby",
"bytes": "4422"
},
{
"name": "SCSS",
"bytes": "32403"
},
{
"name": "Shell",
"bytes": "30924"
}
],
"symlink_target": ""
} |
package org.apache.ambari.server.controller;
public class RootServiceHostComponentRequest extends RootServiceComponentRequest{
private String hostName;
public RootServiceHostComponentRequest(String serviceName, String hostName, String componentName) {
super(serviceName, componentName);
this.hostName = hostName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
}
| {
"content_hash": "e22941904761a3bcb01c652c93a22027",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 101,
"avg_line_length": 22.666666666666668,
"alnum_prop": 0.7626050420168067,
"repo_name": "sekikn/ambari",
"id": "cebe6173751c5254e42b36a80a2215c28a56ee87",
"size": "1281",
"binary": false,
"copies": "3",
"ref": "refs/heads/trunk",
"path": "ambari-server/src/main/java/org/apache/ambari/server/controller/RootServiceHostComponentRequest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22734"
},
{
"name": "C",
"bytes": "109499"
},
{
"name": "C#",
"bytes": "182799"
},
{
"name": "CSS",
"bytes": "616806"
},
{
"name": "CoffeeScript",
"bytes": "4323"
},
{
"name": "Dockerfile",
"bytes": "8117"
},
{
"name": "HTML",
"bytes": "3725781"
},
{
"name": "Handlebars",
"bytes": "1594385"
},
{
"name": "Java",
"bytes": "26670585"
},
{
"name": "JavaScript",
"bytes": "14647486"
},
{
"name": "Jinja",
"bytes": "147938"
},
{
"name": "Less",
"bytes": "303080"
},
{
"name": "Makefile",
"bytes": "2407"
},
{
"name": "PHP",
"bytes": "149648"
},
{
"name": "PLpgSQL",
"bytes": "298247"
},
{
"name": "PowerShell",
"bytes": "2047735"
},
{
"name": "Python",
"bytes": "7226684"
},
{
"name": "R",
"bytes": "1457"
},
{
"name": "Shell",
"bytes": "350773"
},
{
"name": "TSQL",
"bytes": "42351"
},
{
"name": "Vim Script",
"bytes": "5813"
},
{
"name": "sed",
"bytes": "1133"
}
],
"symlink_target": ""
} |
package kafka.api;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.collect.Maps;
import kafka.common.TopicAndPartition;
import kafka.consumer.ConsumerConfigs;
import kafka.utils.NonThreadSafe;
@NonThreadSafe
public class FetchRequestBuilder {
private AtomicInteger correlationId = new AtomicInteger(0);
private short versionId = FetchRequestReader.CurrentVersion;
private String clientId = ConsumerConfigs.DefaultClientId;
private int replicaId = Requests.OrdinaryConsumerId;
private int maxWait = FetchRequestReader.DefaultMaxWait;
private int minBytes = FetchRequestReader.DefaultMinBytes;
private Map<TopicAndPartition, PartitionFetchInfo> requestMap = Maps.newHashMap();
public FetchRequestBuilder addFetch(String topic, int partition, long offset, int fetchSize) {
requestMap.put(new TopicAndPartition(topic, partition), new PartitionFetchInfo(offset, fetchSize));
return this;
}
public FetchRequestBuilder clientId(String clientId) {
this.clientId = clientId;
return this;
}
/**
* Only for internal use. Clients shouldn't set replicaId.
*/
public FetchRequestBuilder replicaId(int replicaId) {
this.replicaId = replicaId;
return this;
}
public FetchRequestBuilder maxWait(int maxWait) {
this.maxWait = maxWait;
return this;
}
public FetchRequestBuilder minBytes(int minBytes) {
this.minBytes = minBytes;
return this;
}
public FetchRequest build() {
FetchRequest fetchRequest = new FetchRequest(versionId, correlationId.getAndIncrement(), clientId, replicaId, maxWait, minBytes, requestMap);
requestMap.clear();
return fetchRequest;
}
}
| {
"content_hash": "b1e74402ffff8d0a309fb953fdc34cfb",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 149,
"avg_line_length": 32.63636363636363,
"alnum_prop": 0.7264623955431755,
"repo_name": "lemonJun/Jkafka",
"id": "5fca0092cbcf50f33b70a2900a47837faf396fe6",
"size": "1795",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jkafka-core/src/main/java/kafka/api/FetchRequestBuilder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "118"
},
{
"name": "Java",
"bytes": "3488646"
},
{
"name": "JavaScript",
"bytes": "97"
}
],
"symlink_target": ""
} |
package com.hcl.appscan.sdk.scanners.mobile;
public interface MAConstants {
String APPLICATION_FILE_ID = "ApplicationFileId"; //$NON-NLS-1$
String MA = "Mobile Analyzer"; //$NON-NLS-1$
String MOBILE_ANALYZER = "MobileAnalyzer"; //$NON-NLS-1$
//Errors
String ERROR_SUBMITTING_FILE = "error.submitting.file"; //$NON-NLS-1$
}
| {
"content_hash": "86bc5e8dda979fbfa5d91a3ee099aa33",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 70,
"avg_line_length": 24.857142857142858,
"alnum_prop": 0.6810344827586207,
"repo_name": "AppSecDev/appscan-sdk",
"id": "575b85711bfe6966143f83b0dab862e0b16d0fe9",
"size": "522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/hcl/appscan/sdk/scanners/mobile/MAConstants.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "124071"
}
],
"symlink_target": ""
} |
/// <reference no-default-lib="true"/>
interface ErrorOptions {
cause?: unknown;
}
interface Error {
cause?: unknown;
}
interface ErrorConstructor {
new (message?: string, options?: ErrorOptions): Error;
(message?: string, options?: ErrorOptions): Error;
}
interface EvalErrorConstructor {
new (message?: string, options?: ErrorOptions): EvalError;
(message?: string, options?: ErrorOptions): EvalError;
}
interface RangeErrorConstructor {
new (message?: string, options?: ErrorOptions): RangeError;
(message?: string, options?: ErrorOptions): RangeError;
}
interface ReferenceErrorConstructor {
new (message?: string, options?: ErrorOptions): ReferenceError;
(message?: string, options?: ErrorOptions): ReferenceError;
}
interface SyntaxErrorConstructor {
new (message?: string, options?: ErrorOptions): SyntaxError;
(message?: string, options?: ErrorOptions): SyntaxError;
}
interface TypeErrorConstructor {
new (message?: string, options?: ErrorOptions): TypeError;
(message?: string, options?: ErrorOptions): TypeError;
}
interface URIErrorConstructor {
new (message?: string, options?: ErrorOptions): URIError;
(message?: string, options?: ErrorOptions): URIError;
}
interface AggregateErrorConstructor {
new (
errors: Iterable<any>,
message?: string,
options?: ErrorOptions
): AggregateError;
(
errors: Iterable<any>,
message?: string,
options?: ErrorOptions
): AggregateError;
}
| {
"content_hash": "128461511c8b9db106de2fb181363042",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 67,
"avg_line_length": 24.661290322580644,
"alnum_prop": 0.6893394375408763,
"repo_name": "LivelyKernel/lively4-core",
"id": "4b16e09121d45866ed7f1962de011527f73e1e1b",
"size": "2339",
"binary": false,
"copies": "7",
"ref": "refs/heads/gh-pages",
"path": "src/external/typescript/lib/lib.es2022.error.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "144422"
},
{
"name": "HTML",
"bytes": "589346"
},
{
"name": "JavaScript",
"bytes": "4554338"
}
],
"symlink_target": ""
} |
using Bokeh
plotfile("display.html")
x = linspace(0, 2pi)
# plot returns a Plot object
myplot = plot(x, sin(x))
# which can then be displayed with
showplot(myplot)
# if you wish to generate a plot but not display it, you can use genplot
genplot(myplot)
# you can also specify the filename directly to genplot:
genplot(myplot, "display1.html")
# underneither genplot there's renderplot which returns the actual html
html = renderplot(myplot)
println(html[1:100], "...")
# however bokeh.jl also keeps a reference to the current plot, which you can access
plot(x, cos(x))
showplot(curplot())
# for convienience there's a shorthand for this:
showplot()
# Note: in this example, we've generated display.html and opened it in the browser
# 3 times, however probably all three plots will show the final plot,
# that's because the browser is too slow for julia which has generated the last version of
# display.html before the browser has time to opening it the first two times
# (or so I assume????) | {
"content_hash": "ba8221f861d01260ed396473d10ee608",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 90,
"avg_line_length": 30.333333333333332,
"alnum_prop": 0.7502497502497503,
"repo_name": "spencerlyon2/Bokeh.jl",
"id": "d07e9d47fc05c6aa00dae9dfae9dc26cf53ce40e",
"size": "1001",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "test/test-cases/display.jl",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "805"
},
{
"name": "JavaScript",
"bytes": "653"
},
{
"name": "Julia",
"bytes": "43410"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>passive-sts-feature</artifactId>
<version>4.4.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.identity.sts.passive.ui.feature</artifactId>
<packaging>pom</packaging>
<name>Passive STS UI Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the bundles required for Front-end functionality of Passive STS</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.sts.passive.ui</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.identity</groupId>
<artifactId>org.wso2.carbon.identity.sts.passive.stub</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>4-p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.identity.sts.passive.ui</id>
<propertiesFile>../../etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:console
</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false
</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>org.wso2.carbon.identity:org.wso2.carbon.identity.sts.passive.ui
</bundleDef>
<bundleDef>org.wso2.carbon.identity:org.wso2.carbon.identity.sts.passive.stub
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core:${carbon.kernel.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.identity.application.authentication.framework.server:${carbon.identity.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.identity.application.mgt.server:${carbon.identity.version}</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "86b967cefedd7966825eef4e211894b1",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 201,
"avg_line_length": 47.03409090909091,
"alnum_prop": 0.5462672143029718,
"repo_name": "cdwijayarathna/carbon-identity",
"id": "2013633538d2578e508a2df374fa2261b69b6f97",
"size": "4139",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "features/passive-sts/org.wso2.carbon.identity.sts.passive.ui.feature/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "97558"
},
{
"name": "HTML",
"bytes": "89563"
},
{
"name": "Java",
"bytes": "10125395"
},
{
"name": "JavaScript",
"bytes": "245863"
},
{
"name": "PLSQL",
"bytes": "47991"
},
{
"name": "Thrift",
"bytes": "338"
},
{
"name": "XSLT",
"bytes": "951"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="zh">
<head>
<!-- Generated by javadoc (1.8.0_25) on Thu Nov 19 15:55:26 CST 2015 -->
<title>com.guangchiguangchi.littlebee.models 类分层结构</title>
<meta name="date" content="2015-11-19">
<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="com.guangchiguangchi.littlebee.models \u7C7B\u5206\u5C42\u7ED3\u6784";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li>类</li>
<li class="navBarCell1Rev">树</li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-files/index-1.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/guangchiguangchi/littlebee/controllers/package-tree.html">上一个</a></li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/guangchiguangchi/littlebee/models/package-tree.html" target="_top">框架</a></li>
<li><a href="package-tree.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">所有类</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 class="title">程序包com.guangchiguangchi.littlebee.models的分层结构</h1>
<span class="packageHierarchyLabel">程序包分层结构:</span>
<ul class="horizontal">
<li><a href="../../../../overview-tree.html">所有程序包</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="类分层结构">类分层结构</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">com.jfinal.plugin.activerecord.Model<M> (implements java.io.Serializable)
<ul>
<li type="circle">com.guangchiguangchi.littlebee.models.<a href="../../../../com/guangchiguangchi/littlebee/models/LogsModel.html" title="com.guangchiguangchi.littlebee.models中的类"><span class="typeNameLink">LogsModel</span></a></li>
<li type="circle">com.guangchiguangchi.littlebee.models.<a href="../../../../com/guangchiguangchi/littlebee/models/ProjectModel.html" title="com.guangchiguangchi.littlebee.models中的类"><span class="typeNameLink">ProjectModel</span></a></li>
<li type="circle">com.guangchiguangchi.littlebee.models.<a href="../../../../com/guangchiguangchi/littlebee/models/TasksModel.html" title="com.guangchiguangchi.littlebee.models中的类"><span class="typeNameLink">TasksModel</span></a></li>
<li type="circle">com.guangchiguangchi.littlebee.models.<a href="../../../../com/guangchiguangchi/littlebee/models/UserModel.html" title="com.guangchiguangchi.littlebee.models中的类"><span class="typeNameLink">UserModel</span></a></li>
</ul>
</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="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li>类</li>
<li class="navBarCell1Rev">树</li>
<li><a href="../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../index-files/index-1.html">索引</a></li>
<li><a href="../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../com/guangchiguangchi/littlebee/controllers/package-tree.html">上一个</a></li>
<li>下一个</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?com/guangchiguangchi/littlebee/models/package-tree.html" target="_top">框架</a></li>
<li><a href="package-tree.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">所有类</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": "a2b0934bfe1b900ce35bf549433f6c96",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 238,
"avg_line_length": 36.352112676056336,
"alnum_prop": 0.6321193335916312,
"repo_name": "guangchiguangchi/little-bee",
"id": "796097e9627cc8effda3f795705ceb828efef45a",
"size": "5442",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/com/guangchiguangchi/littlebee/models/package-tree.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "34745"
},
{
"name": "Java",
"bytes": "41288"
},
{
"name": "JavaScript",
"bytes": "21742"
},
{
"name": "Shell",
"bytes": "282"
}
],
"symlink_target": ""
} |
package org.apache.commons.validator;
/**
* Contains validation methods for different unit tests.
*
* @version $Revision: 1649191 $
*/
public class ParameterValidatorImpl {
/**
* ValidatorParameter is valid.
*
*/
public static boolean validateParameter(
final java.lang.Object bean,
final org.apache.commons.validator.Form form,
final org.apache.commons.validator.Field field,
final org.apache.commons.validator.Validator validator,
final org.apache.commons.validator.ValidatorAction action,
final org.apache.commons.validator.ValidatorResults results,
final java.util.Locale locale)
throws Exception {
return true;
}
}
| {
"content_hash": "bf4c5e8ec66297371d4fa68c8923155d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 68,
"avg_line_length": 31.037037037037038,
"alnum_prop": 0.5930787589498807,
"repo_name": "ManfredTremmel/gwt-commons-validator",
"id": "1c8d12ce7879defcdc46e132afb59d87ced7902a",
"size": "1640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/apache/commons/validator/ParameterValidatorImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "41910"
},
{
"name": "Java",
"bytes": "1353882"
},
{
"name": "Shell",
"bytes": "157"
}
],
"symlink_target": ""
} |
include $(TOPDIR)/rules.mk
LUCI_TITLE:=Roaring Penguin PPPoE Server
LUCI_DEPENDS:=+luci-compat +rp-pppoe-server
include ../../luci.mk
# call BuildPackage - OpenWrt buildroot signature
| {
"content_hash": "61df3ac54613025013fe3d39e7522f4b",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 49,
"avg_line_length": 23.375,
"alnum_prop": 0.7593582887700535,
"repo_name": "openwrt/luci",
"id": "b4edfc9499a5d978046090b0651646e08caa4cbd",
"size": "339",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "applications/luci-app-rp-pppoe-server/Makefile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1711167"
},
{
"name": "C#",
"bytes": "42820"
},
{
"name": "CMake",
"bytes": "1240"
},
{
"name": "CSS",
"bytes": "200239"
},
{
"name": "HTML",
"bytes": "461848"
},
{
"name": "Java",
"bytes": "49574"
},
{
"name": "JavaScript",
"bytes": "2183494"
},
{
"name": "Lex",
"bytes": "7173"
},
{
"name": "Lua",
"bytes": "1113329"
},
{
"name": "Makefile",
"bytes": "144335"
},
{
"name": "Perl",
"bytes": "57773"
},
{
"name": "Python",
"bytes": "1165"
},
{
"name": "Shell",
"bytes": "86593"
},
{
"name": "Terra",
"bytes": "499"
},
{
"name": "UnrealScript",
"bytes": "71672"
},
{
"name": "Visual Basic .NET",
"bytes": "33030"
},
{
"name": "Yacc",
"bytes": "17409"
}
],
"symlink_target": ""
} |
require File.expand_path("../boot", __FILE__)
require "rails/all"
require "csv"
require "securerandom"
require "elasticsearch/rails/instrumentation"
require "elasticsearch/rails/lograge"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module AccessCalServer
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = "UTC"
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
config.i18n.available_locales = [:en, :es]
config.i18n.default_locale = :en
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
# Use sidekiq for job queue management
config.active_job.queue_adapter = :sidekiq
config.middleware.insert_before 0, "Rack::Cors", debug: true, logger: (-> { Rails.logger }) do
allow do
origins "*"
resource(
"/cors",
headers: :any,
methods: [:post],
credentials: true,
max_age: 0
)
resource(
"*",
headers: :any,
methods: [:get, :post, :delete, :put, :options, :head],
max_age: 0
)
end
end
end
end
| {
"content_hash": "363320be83f9048828ba4dc6617db932",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 99,
"avg_line_length": 33.574074074074076,
"alnum_prop": 0.655819084390513,
"repo_name": "allaboardapps/access-cal-server",
"id": "7890f9dbef8c82f8f74163d824d1bbc0c9a9b402",
"size": "1813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/application.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1271"
},
{
"name": "CoffeeScript",
"bytes": "29"
},
{
"name": "HTML",
"bytes": "7155"
},
{
"name": "JavaScript",
"bytes": "61"
},
{
"name": "Ruby",
"bytes": "301376"
}
],
"symlink_target": ""
} |
package org.apache.storm.cluster;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.apache.storm.generated.Assignment;
import org.apache.storm.generated.ClusterWorkerHeartbeat;
import org.apache.storm.generated.Credentials;
import org.apache.storm.generated.ErrorInfo;
import org.apache.storm.generated.ExecutorInfo;
import org.apache.storm.generated.LogConfig;
import org.apache.storm.generated.NimbusSummary;
import org.apache.storm.generated.NodeInfo;
import org.apache.storm.generated.PrivateWorkerKey;
import org.apache.storm.generated.ProfileRequest;
import org.apache.storm.generated.StormBase;
import org.apache.storm.generated.SupervisorInfo;
import org.apache.storm.generated.WorkerTokenServiceType;
import org.apache.storm.nimbus.NimbusInfo;
public interface IStormClusterState {
List<String> assignments(Runnable callback);
/**
* Get the assignment based on storm id from local backend.
*
* @param stormId topology id
* @param callback callback function
* @return {@link Assignment}
*/
Assignment assignmentInfo(String stormId, Runnable callback);
/**
* Get the assignment based on storm id from remote state store, eg: ZK.
*
* @param stormId topology id
* @param callback callback function
* @return {@link Assignment}
*/
Assignment remoteAssignmentInfo(String stormId, Runnable callback);
/**
* Get all the topologies assignments mapping stormId -> Assignment from local backend.
*
* @return stormId -> Assignment mapping
*/
Map<String, Assignment> assignmentsInfo();
/**
* Sync the remote state store assignments to local backend, used when master gains leadership, see {@link LeaderListenerCallback}
*
* @param remote assigned assignments for a specific {@link IStormClusterState} instance, usually a supervisor/node.
*/
void syncRemoteAssignments(Map<String, byte[]> remote);
/**
* Flag to indicate if the assignments synced successfully, see {@link #syncRemoteAssignments(Map)}.
*
* @return true if is synced successfully
*/
boolean isAssignmentsBackendSynchronized();
/**
* Mark the assignments as synced successfully, see {@link #isAssignmentsBackendSynchronized()}
*/
void setAssignmentsBackendSynchronized();
VersionedData<Assignment> assignmentInfoWithVersion(String stormId, Runnable callback);
Integer assignmentVersion(String stormId, Runnable callback) throws Exception;
List<String> blobstoreInfo(String blobKey);
List<NimbusSummary> nimbuses();
void addNimbusHost(String nimbusId, NimbusSummary nimbusSummary);
List<String> activeStorms();
/**
* Get a storm base for a topology
*
* @param stormId the id of the topology
* @param callback something to call if the data changes (best effort)
* @return the StormBase or null if it is not alive.
*/
StormBase stormBase(String stormId, Runnable callback);
/**
* Get storm id from passed name, null if the name doesn't exist on cluster.
*
* @param stormName storm name
* @return storm id
*/
String stormId(String stormName);
/**
* Sync all the active storm ids of the cluster, used now when master gains leadership.
*
* @param ids stormName -> stormId mapping
*/
void syncRemoteIds(Map<String, String> ids);
ClusterWorkerHeartbeat getWorkerHeartbeat(String stormId, String node, Long port);
List<ProfileRequest> getWorkerProfileRequests(String stormId, NodeInfo nodeInfo);
List<ProfileRequest> getTopologyProfileRequests(String stormId);
void setWorkerProfileRequest(String stormId, ProfileRequest profileRequest);
void deleteTopologyProfileRequests(String stormId, ProfileRequest profileRequest);
Map<ExecutorInfo, ExecutorBeat> executorBeats(String stormId, Map<List<Long>, NodeInfo> executorNodePort);
List<String> supervisors(Runnable callback);
SupervisorInfo supervisorInfo(String supervisorId); // returns nil if doesn't exist
void setupHeatbeats(String stormId, Map<String, Object> topoConf);
void teardownHeartbeats(String stormId);
void teardownTopologyErrors(String stormId);
List<String> heartbeatStorms();
List<String> errorTopologies();
/**
* @deprecated: In Storm 2.0. Retained for enabling transition from 1.x. Will be removed soon.
*/
@Deprecated
List<String> backpressureTopologies();
/**
* Get leader info from state store, which was written when a master gains leadership.
* <p>Caution: it can not be used for fencing and is only for informational purposes because we use ZK as our
* backend now, which could have a overdue info of nodes.
*
* @param callback callback func
* @return {@link NimbusInfo}
*/
NimbusInfo getLeader(Runnable callback);
void setTopologyLogConfig(String stormId, LogConfig logConfig, Map<String, Object> topoConf);
LogConfig topologyLogConfig(String stormId, Runnable cb);
void workerHeartbeat(String stormId, String node, Long port, ClusterWorkerHeartbeat info);
void removeWorkerHeartbeat(String stormId, String node, Long port);
void supervisorHeartbeat(String supervisorId, SupervisorInfo info);
/**
* @deprecated: In Storm 2.0. Retained for enabling transition from 1.x. Will be removed soon.
*/
@Deprecated
boolean topologyBackpressure(String stormId, long timeoutMs, Runnable callback);
/**
* @deprecated: In Storm 2.0. Retained for enabling transition from 1.x. Will be removed soon.
*/
@Deprecated
void setupBackpressure(String stormId, Map<String, Object> topoConf);
/**
* @deprecated: In Storm 2.0. Retained for enabling transition from 1.x. Will be removed soon.
*/
@Deprecated
void removeBackpressure(String stormId);
/**
* @deprecated: In Storm 2.0. Retained for enabling transition from 1.x. Will be removed soon.
*/
@Deprecated
void removeWorkerBackpressure(String stormId, String node, Long port);
void activateStorm(String stormId, StormBase stormBase, Map<String, Object> topoConf);
void updateStorm(String stormId, StormBase newElems);
void removeStormBase(String stormId);
void setAssignment(String stormId, Assignment info, Map<String, Object> topoConf);
void setupBlob(String key, NimbusInfo nimbusInfo, Integer versionInfo);
List<String> activeKeys();
List<String> blobstore(Runnable callback);
void removeStorm(String stormId);
void removeBlobstoreKey(String blobKey);
void removeKeyVersion(String blobKey);
void reportError(String stormId, String componentId, String node, Long port, Throwable error);
void setupErrors(String stormId, Map<String, Object> topoConf);
List<ErrorInfo> errors(String stormId, String componentId);
ErrorInfo lastError(String stormId, String componentId);
void setCredentials(String stormId, Credentials creds, Map<String, Object> topoConf);
Credentials credentials(String stormId, Runnable callback);
void disconnect();
/**
* Get a private key used to validate a token is correct. This is expected to be called from a privileged daemon, and the ACLs should be
* set up to only allow nimbus and these privileged daemons access to these private keys.
*
* @param type the type of service the key is for.
* @param topologyId the topology id the key is for.
* @param keyVersion the version of the key this is for.
* @return the private key or null if it could not be found.
*/
PrivateWorkerKey getPrivateWorkerKey(WorkerTokenServiceType type, String topologyId, long keyVersion);
/**
* Store a new version of a private key. This is expected to only ever be called from nimbus. All ACLs however need to be setup to
* allow the given services access to the stored information.
*
* @param type the type of service this key is for.
* @param topologyId the topology this key is for
* @param keyVersion the version of the key this is for.
* @param key the key to store.
*/
void addPrivateWorkerKey(WorkerTokenServiceType type, String topologyId, long keyVersion, PrivateWorkerKey key);
/**
* Get the next key version number that should be used for this topology id. This is expected to only ever be called from nimbus, but it
* is acceptable if the ACLs are setup so that it can work from a privileged daemon for the given service.
*
* @param type the type of service this is for.
* @param topologyId the topology id this is for.
* @return the next version number. It should be 0 for a new topology id/service combination.
*/
long getNextPrivateWorkerKeyVersion(WorkerTokenServiceType type, String topologyId);
/**
* Remove all keys for the given topology that have expired. The number of keys should be small enough that doing an exhaustive scan of
* them all is acceptable as there is no guarantee that expiration time and version number are related. This should be for all service
* types. This is expected to only ever be called from nimbus and some ACLs may be setup so being called from other daemons will cause
* it to fail.
*
* @param topologyId the id of the topology to scan.
*/
void removeExpiredPrivateWorkerKeys(String topologyId);
/**
* Remove all of the worker keys for a given topology. Used to clean up after a topology finishes. This is expected to only ever be
* called from nimbus and ideally should only ever work from nimbus.
*
* @param topologyId the topology to clean up after.
*/
void removeAllPrivateWorkerKeys(String topologyId);
/**
* Get a list of all topologyIds that currently have private worker keys stored, of any kind. This is expected to only ever be called
* from nimbus.
*
* @return the list of topology ids with any kind of private worker key stored.
*/
Set<String> idsOfTopologiesWithPrivateWorkerKeys();
/**
* Get all of the supervisors with the ID as the key.
*/
default Map<String, SupervisorInfo> allSupervisorInfo() {
return allSupervisorInfo(null);
}
/**
* @param callback be alerted if the list of supervisors change
* @return All of the supervisors with the ID as the key
*/
default Map<String, SupervisorInfo> allSupervisorInfo(Runnable callback) {
Map<String, SupervisorInfo> ret = new HashMap<>();
for (String id : supervisors(callback)) {
ret.put(id, supervisorInfo(id));
}
return ret;
}
/**
* Get a topology ID from the name of a topology
*
* @param topologyName the name of the topology to look for
* @return the id of the topology or null if it is not alive.
*/
default Optional<String> getTopoId(final String topologyName) {
return Optional.ofNullable(stormId(topologyName));
}
default Map<String, StormBase> topologyBases() {
Map<String, StormBase> stormBases = new HashMap<>();
for (String topologyId : activeStorms()) {
StormBase base = stormBase(topologyId, null);
if (base != null) { //rece condition with delete
stormBases.put(topologyId, base);
}
}
return stormBases;
}
}
| {
"content_hash": "5f3c4794d6a18cd72c9001d35d35c521",
"timestamp": "",
"source": "github",
"line_count": 315,
"max_line_length": 140,
"avg_line_length": 36.70793650793651,
"alnum_prop": 0.7062181094871574,
"repo_name": "srdo/storm",
"id": "5627997363f50c09f0f62085f115452e621644ba",
"size": "12347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "storm-client/src/jvm/org/apache/storm/cluster/IStormClusterState.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "53871"
},
{
"name": "CSS",
"bytes": "12597"
},
{
"name": "Clojure",
"bytes": "494628"
},
{
"name": "Fancy",
"bytes": "6234"
},
{
"name": "FreeMarker",
"bytes": "3512"
},
{
"name": "HTML",
"bytes": "187245"
},
{
"name": "Java",
"bytes": "11668041"
},
{
"name": "JavaScript",
"bytes": "74069"
},
{
"name": "M4",
"bytes": "1522"
},
{
"name": "Makefile",
"bytes": "1302"
},
{
"name": "PowerShell",
"bytes": "3405"
},
{
"name": "Python",
"bytes": "954624"
},
{
"name": "Ruby",
"bytes": "15777"
},
{
"name": "Shell",
"bytes": "23774"
},
{
"name": "Thrift",
"bytes": "31552"
},
{
"name": "XSLT",
"bytes": "1365"
}
],
"symlink_target": ""
} |
package fake
import (
unversioned "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned"
restclient "k8s.io/kubernetes/pkg/client/restclient"
core "k8s.io/kubernetes/pkg/client/testing/core"
)
type FakeCertificates struct {
*core.Fake
}
func (c *FakeCertificates) CertificateSigningRequests() unversioned.CertificateSigningRequestInterface {
return &FakeCertificateSigningRequests{c}
}
// RESTClient returns a RESTClient that is used to communicate
// with API server by this client implementation.
func (c *FakeCertificates) RESTClient() restclient.Interface {
var ret *restclient.RESTClient
return ret
}
| {
"content_hash": "843bfd0f6a944abc4822eba752be9651",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 112,
"avg_line_length": 27.666666666666668,
"alnum_prop": 0.8072289156626506,
"repo_name": "djosborne/kubernetes",
"id": "92cf1449a10b69af56e1ce8a13641fe3692ee0b7",
"size": "1233",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "pkg/client/clientset_generated/internalclientset/typed/certificates/unversioned/fake/fake_certificates_client.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "978"
},
{
"name": "Go",
"bytes": "45215338"
},
{
"name": "HTML",
"bytes": "2251615"
},
{
"name": "Makefile",
"bytes": "71415"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "Protocol Buffer",
"bytes": "573593"
},
{
"name": "Python",
"bytes": "916099"
},
{
"name": "SaltStack",
"bytes": "54088"
},
{
"name": "Shell",
"bytes": "1529498"
}
],
"symlink_target": ""
} |
package util
import (
"context"
"errors"
"fmt"
"net"
"strconv"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/tools/record"
helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
utilsysctl "k8s.io/kubernetes/pkg/util/sysctl"
utilnet "k8s.io/utils/net"
"k8s.io/klog/v2"
)
const (
// IPv4ZeroCIDR is the CIDR block for the whole IPv4 address space
IPv4ZeroCIDR = "0.0.0.0/0"
// IPv6ZeroCIDR is the CIDR block for the whole IPv6 address space
IPv6ZeroCIDR = "::/0"
)
var (
// ErrAddressNotAllowed indicates the address is not allowed
ErrAddressNotAllowed = errors.New("address not allowed")
// ErrNoAddresses indicates there are no addresses for the hostname
ErrNoAddresses = errors.New("No addresses for hostname")
)
// isValidEndpoint checks that the given host / port pair are valid endpoint
func isValidEndpoint(host string, port int) bool {
return host != "" && port > 0
}
// BuildPortsToEndpointsMap builds a map of portname -> all ip:ports for that
// portname. Explode Endpoints.Subsets[*] into this structure.
func BuildPortsToEndpointsMap(endpoints *v1.Endpoints) map[string][]string {
portsToEndpoints := map[string][]string{}
for i := range endpoints.Subsets {
ss := &endpoints.Subsets[i]
for i := range ss.Ports {
port := &ss.Ports[i]
for i := range ss.Addresses {
addr := &ss.Addresses[i]
if isValidEndpoint(addr.IP, int(port.Port)) {
portsToEndpoints[port.Name] = append(portsToEndpoints[port.Name], net.JoinHostPort(addr.IP, strconv.Itoa(int(port.Port))))
}
}
}
}
return portsToEndpoints
}
// IsZeroCIDR checks whether the input CIDR string is either
// the IPv4 or IPv6 zero CIDR
func IsZeroCIDR(cidr string) bool {
if cidr == IPv4ZeroCIDR || cidr == IPv6ZeroCIDR {
return true
}
return false
}
// IsProxyableIP checks if a given IP address is permitted to be proxied
func IsProxyableIP(ip string) error {
netIP := net.ParseIP(ip)
if netIP == nil {
return ErrAddressNotAllowed
}
return isProxyableIP(netIP)
}
func isProxyableIP(ip net.IP) error {
if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() {
return ErrAddressNotAllowed
}
return nil
}
// Resolver is an interface for net.Resolver
type Resolver interface {
LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
}
// IsProxyableHostname checks if the IP addresses for a given hostname are permitted to be proxied
func IsProxyableHostname(ctx context.Context, resolv Resolver, hostname string) error {
resp, err := resolv.LookupIPAddr(ctx, hostname)
if err != nil {
return err
}
if len(resp) == 0 {
return ErrNoAddresses
}
for _, host := range resp {
if err := isProxyableIP(host.IP); err != nil {
return err
}
}
return nil
}
// GetLocalAddrs returns a list of all network addresses on the local system
func GetLocalAddrs() ([]net.IP, error) {
var localAddrs []net.IP
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return nil, err
}
localAddrs = append(localAddrs, ip)
}
return localAddrs, nil
}
// ShouldSkipService checks if a given service should skip proxying
func ShouldSkipService(svcName types.NamespacedName, service *v1.Service) bool {
// if ClusterIP is "None" or empty, skip proxying
if !helper.IsServiceIPSet(service) {
klog.V(3).Infof("Skipping service %s due to clusterIP = %q", svcName, service.Spec.ClusterIP)
return true
}
// Even if ClusterIP is set, ServiceTypeExternalName services don't get proxied
if service.Spec.Type == v1.ServiceTypeExternalName {
klog.V(3).Infof("Skipping service %s due to Type=ExternalName", svcName)
return true
}
return false
}
// GetNodeAddresses return all matched node IP addresses based on given cidr slice.
// Some callers, e.g. IPVS proxier, need concrete IPs, not ranges, which is why this exists.
// NetworkInterfacer is injected for test purpose.
// We expect the cidrs passed in is already validated.
// Given an empty input `[]`, it will return `0.0.0.0/0` and `::/0` directly.
// If multiple cidrs is given, it will return the minimal IP sets, e.g. given input `[1.2.0.0/16, 0.0.0.0/0]`, it will
// only return `0.0.0.0/0`.
// NOTE: GetNodeAddresses only accepts CIDRs, if you want concrete IPs, e.g. 1.2.3.4, then the input should be 1.2.3.4/32.
func GetNodeAddresses(cidrs []string, nw NetworkInterfacer) (sets.String, error) {
uniqueAddressList := sets.NewString()
if len(cidrs) == 0 {
uniqueAddressList.Insert(IPv4ZeroCIDR)
uniqueAddressList.Insert(IPv6ZeroCIDR)
return uniqueAddressList, nil
}
// First round of iteration to pick out `0.0.0.0/0` or `::/0` for the sake of excluding non-zero IPs.
for _, cidr := range cidrs {
if IsZeroCIDR(cidr) {
uniqueAddressList.Insert(cidr)
}
}
itfs, err := nw.Interfaces()
if err != nil {
return nil, fmt.Errorf("error listing all interfaces from host, error: %v", err)
}
// Second round of iteration to parse IPs based on cidr.
for _, cidr := range cidrs {
if IsZeroCIDR(cidr) {
continue
}
_, ipNet, _ := net.ParseCIDR(cidr)
for _, itf := range itfs {
addrs, err := nw.Addrs(&itf)
if err != nil {
return nil, fmt.Errorf("error getting address from interface %s, error: %v", itf.Name, err)
}
for _, addr := range addrs {
if addr == nil {
continue
}
ip, _, err := net.ParseCIDR(addr.String())
if err != nil {
return nil, fmt.Errorf("error parsing CIDR for interface %s, error: %v", itf.Name, err)
}
if ipNet.Contains(ip) {
if utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv6ZeroCIDR) {
uniqueAddressList.Insert(ip.String())
}
if !utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv4ZeroCIDR) {
uniqueAddressList.Insert(ip.String())
}
}
}
}
}
if uniqueAddressList.Len() == 0 {
return nil, fmt.Errorf("no addresses found for cidrs %v", cidrs)
}
return uniqueAddressList, nil
}
// LogAndEmitIncorrectIPVersionEvent logs and emits incorrect IP version event.
func LogAndEmitIncorrectIPVersionEvent(recorder record.EventRecorder, fieldName, fieldValue, svcNamespace, svcName string, svcUID types.UID) {
errMsg := fmt.Sprintf("%s in %s has incorrect IP version", fieldValue, fieldName)
klog.Errorf("%s (service %s/%s).", errMsg, svcNamespace, svcName)
if recorder != nil {
recorder.Eventf(
&v1.ObjectReference{
Kind: "Service",
Name: svcName,
Namespace: svcNamespace,
UID: svcUID,
}, v1.EventTypeWarning, "KubeProxyIncorrectIPVersion", errMsg)
}
}
// FilterIncorrectIPVersion filters out the incorrect IP version case from a slice of IP strings.
func FilterIncorrectIPVersion(ipStrings []string, isIPv6Mode bool) ([]string, []string) {
return filterWithCondition(ipStrings, isIPv6Mode, utilnet.IsIPv6String)
}
// FilterIncorrectCIDRVersion filters out the incorrect IP version case from a slice of CIDR strings.
func FilterIncorrectCIDRVersion(ipStrings []string, isIPv6Mode bool) ([]string, []string) {
return filterWithCondition(ipStrings, isIPv6Mode, utilnet.IsIPv6CIDRString)
}
func filterWithCondition(strs []string, expectedCondition bool, conditionFunc func(string) bool) ([]string, []string) {
var corrects, incorrects []string
for _, str := range strs {
if conditionFunc(str) != expectedCondition {
incorrects = append(incorrects, str)
} else {
corrects = append(corrects, str)
}
}
return corrects, incorrects
}
// AppendPortIfNeeded appends the given port to IP address unless it is already in
// "ipv4:port" or "[ipv6]:port" format.
func AppendPortIfNeeded(addr string, port int32) string {
// Return if address is already in "ipv4:port" or "[ipv6]:port" format.
if _, _, err := net.SplitHostPort(addr); err == nil {
return addr
}
// Simply return for invalid case. This should be caught by validation instead.
ip := net.ParseIP(addr)
if ip == nil {
return addr
}
// Append port to address.
if ip.To4() != nil {
return fmt.Sprintf("%s:%d", addr, port)
}
return fmt.Sprintf("[%s]:%d", addr, port)
}
// ShuffleStrings copies strings from the specified slice into a copy in random
// order. It returns a new slice.
func ShuffleStrings(s []string) []string {
if s == nil {
return nil
}
shuffled := make([]string, len(s))
perm := utilrand.Perm(len(s))
for i, j := range perm {
shuffled[j] = s[i]
}
return shuffled
}
// EnsureSysctl sets a kernel sysctl to a given numeric value.
func EnsureSysctl(sysctl utilsysctl.Interface, name string, newVal int) error {
if oldVal, _ := sysctl.GetSysctl(name); oldVal != newVal {
if err := sysctl.SetSysctl(name, newVal); err != nil {
return fmt.Errorf("can't set sysctl %s to %d: %v", name, newVal, err)
}
klog.V(1).Infof("Changed sysctl %q: %d -> %d", name, oldVal, newVal)
}
return nil
}
| {
"content_hash": "939601ccd525b4b7aa02305c3605e322",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 142,
"avg_line_length": 30.076923076923077,
"alnum_prop": 0.701768041810297,
"repo_name": "klaus1982/kubernetes",
"id": "d7f94345e2dde54311391ed06cc720e8ec591a0a",
"size": "9562",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/proxy/util/utils.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "20004663"
},
{
"name": "HTML",
"bytes": "1193990"
},
{
"name": "Makefile",
"bytes": "47403"
},
{
"name": "Nginx",
"bytes": "1013"
},
{
"name": "Python",
"bytes": "68276"
},
{
"name": "SaltStack",
"bytes": "46705"
},
{
"name": "Shell",
"bytes": "1169155"
}
],
"symlink_target": ""
} |
<?php
class Mage_Connect_Channel_Generator extends Mage_Xml_Generator
{
protected $_file = 'channel.xml';
protected $_generator = null;
public function __construct($file='')
{
if ($file) {
$this->_file = $file;
}
return $this;
}
public function getFile()
{
return $this->_file;
}
public function getGenerator()
{
if (is_null($this->_generator)) {
$this->_generator = new Mage_Xml_Generator();
}
return $this->_generator;
}
/**
* @param array $content
*/
public function save($content)
{
$xmlContent = $this->getGenerator()
->arrayToXml($content)
->save($this->getFile());
return $this;
}
}
| {
"content_hash": "ef4d782b0c477f9248bbf063079734f0",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 63,
"avg_line_length": 20.575,
"alnum_prop": 0.48724179829890646,
"repo_name": "almadaocta/lordbike-production",
"id": "2a18a52814bdba46d285db4523dec0b2adfa76f6",
"size": "1802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "downloader/lib/Mage/Connect/Channel/Generator.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "20744"
},
{
"name": "ApacheConf",
"bytes": "6510"
},
{
"name": "Batchfile",
"bytes": "1053"
},
{
"name": "C",
"bytes": "25531"
},
{
"name": "CSS",
"bytes": "2695575"
},
{
"name": "HTML",
"bytes": "7607119"
},
{
"name": "JavaScript",
"bytes": "4942446"
},
{
"name": "Makefile",
"bytes": "266"
},
{
"name": "PHP",
"bytes": "111927807"
},
{
"name": "Perl",
"bytes": "1124"
},
{
"name": "PowerShell",
"bytes": "1042"
},
{
"name": "Roff",
"bytes": "1009"
},
{
"name": "Ruby",
"bytes": "298"
},
{
"name": "Shell",
"bytes": "2118"
},
{
"name": "XSLT",
"bytes": "2135"
}
],
"symlink_target": ""
} |
/* fileDriver.h - common header file for file driver
*/
#ifndef FILE_DRIVER_HPP
#define FILE_DRIVER_HPP
#ifndef windows_platform
#include <dirent.h>
#endif
#include "rods.h"
#include "rcConnect.h"
#include "objInfo.h"
#include "msParam.h"
// =-=-=-=-=-=-=-
#include "irods_error.hpp"
#include "irods_first_class_object.hpp"
irods::error fileCreate( rsComm_t*, irods::first_class_object_ptr );
irods::error fileOpen( rsComm_t*, irods::first_class_object_ptr );
irods::error fileRead( rsComm_t*, irods::first_class_object_ptr, void*, int );
irods::error fileWrite( rsComm_t*, irods::first_class_object_ptr, void*, int );
irods::error fileClose( rsComm_t*, irods::first_class_object_ptr );
irods::error fileUnlink( rsComm_t*, irods::first_class_object_ptr );
irods::error fileStat( rsComm_t*, irods::first_class_object_ptr, struct stat* );
irods::error fileLseek( rsComm_t*, irods::first_class_object_ptr, long long, int );
irods::error fileMkdir( rsComm_t*, irods::first_class_object_ptr );
irods::error fileChmod( rsComm_t*, irods::first_class_object_ptr, int );
irods::error fileRmdir( rsComm_t*, irods::first_class_object_ptr );
irods::error fileOpendir( rsComm_t*, irods::first_class_object_ptr );
irods::error fileClosedir( rsComm_t*, irods::first_class_object_ptr );
irods::error fileReaddir( rsComm_t*, irods::first_class_object_ptr, struct rodsDirent** );
irods::error fileRename( rsComm_t*, irods::first_class_object_ptr, const std::string& );
irods::error fileGetFsFreeSpace( rsComm_t*, irods::first_class_object_ptr );
irods::error fileTruncate( rsComm_t*, irods::first_class_object_ptr );
irods::error fileStageToCache( rsComm_t*, irods::first_class_object_ptr, const std::string& );
irods::error fileSyncToArch( rsComm_t*, irods::first_class_object_ptr, const std::string& );
irods::error fileRegistered( rsComm_t* _comm, irods::first_class_object_ptr _object );
irods::error fileUnregistered( rsComm_t* _comm, irods::first_class_object_ptr _object );
irods::error fileModified( rsComm_t* _comm, irods::first_class_object_ptr _object );
irods::error fileNotify( rsComm_t* _comm, irods::first_class_object_ptr _object , const std::string& );
#endif /* FILE_DRIVER_H */
| {
"content_hash": "1efcd544b3d441e2a58641aa11c52bfa",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 103,
"avg_line_length": 47.56521739130435,
"alnum_prop": 0.7271480804387569,
"repo_name": "janiheikkinen/irods",
"id": "12b747a71d0a8dd411c6b0a3ff17c9279cefd283",
"size": "2346",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "iRODS/server/drivers/include/fileDriver.hpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "438371"
},
{
"name": "C++",
"bytes": "8162401"
},
{
"name": "CMake",
"bytes": "854"
},
{
"name": "CSS",
"bytes": "3246"
},
{
"name": "FORTRAN",
"bytes": "6804"
},
{
"name": "HTML",
"bytes": "27675"
},
{
"name": "JavaScript",
"bytes": "5231"
},
{
"name": "Lex",
"bytes": "3088"
},
{
"name": "Makefile",
"bytes": "75630"
},
{
"name": "Objective-C",
"bytes": "1160"
},
{
"name": "PLSQL",
"bytes": "3241"
},
{
"name": "Pascal",
"bytes": "20991"
},
{
"name": "Perl",
"bytes": "281394"
},
{
"name": "Python",
"bytes": "779176"
},
{
"name": "R",
"bytes": "10664"
},
{
"name": "Rebol",
"bytes": "159165"
},
{
"name": "Ruby",
"bytes": "5914"
},
{
"name": "Shell",
"bytes": "205324"
},
{
"name": "Yacc",
"bytes": "17441"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.