text stringlengths 2 1.04M | meta dict |
|---|---|
var Groups = require.main.require('./src/groups');
var async = require.main.require('async');
var db = require.main.require('./src/database');
var privileges = require.main.require('./src/privileges');
var posts = require.main.require('./src/posts');
(function () {
Groups.getLatestMemberPosts = function (groupName, max, uid, callback) {
async.waterfall([
function (next) {
Groups.getMembers(groupName, 0, -1, next);
},
function (uids, next) {
if (!Array.isArray(uids) || !uids.length) {
return callback(null, []);
}
var keys = uids.map(function (uid) {
return 'uid:' + uid + ':posts';
});
db.getSortedSetRevRange(keys, 0, max - 1, next);
},
function (pids, next) {
privileges.posts.filter('read', pids, uid, next);
},
function (pids, next) {
posts.getPostSummaryByPids(pids, uid, {stripTags: false}, next);
}
], callback);
};
return Groups;
})(module.exports)
| {
"content_hash": "fd37a283b92c5670e5e3e8afc3919a19",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 80,
"avg_line_length": 35.06060606060606,
"alnum_prop": 0.5108038029386344,
"repo_name": "revir/nodebb-theme-v2mm",
"id": "e11b26d5bbf7a264307647cf00c205194a6b58af",
"size": "1157",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/groups.js",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "39435"
},
{
"name": "CoffeeScript",
"bytes": "9692"
},
{
"name": "JavaScript",
"bytes": "42433"
},
{
"name": "Smarty",
"bytes": "118650"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.9.1</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.apache.jclouds.provider</groupId>
<artifactId>ultradns-ws</artifactId>
<name>jclouds ultradns-ws provider</name>
<description>jclouds components to access UltraDNS Web Services API</description>
<packaging>bundle</packaging>
<properties>
<test.ultradns-ws.endpoint>https://ultra-api.ultradns.com:8443/UltraDNS_WS/v01</test.ultradns-ws.endpoint>
<test.ultradns-ws.api-version>v01</test.ultradns-ws.api-version>
<test.ultradns-ws.build-version />
<test.ultradns-ws.identity />
<test.ultradns-ws.credential />
<jclouds.osgi.export>org.jclouds.ultradns.ws*;version="${project.version}"</jclouds.osgi.export>
<jclouds.osgi.import>org.jclouds*;version="${project.version}",*</jclouds.osgi.import>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.jclouds.driver</groupId>
<artifactId>jclouds-slf4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>integration</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<!-- to prevent live tests from clashing with eachother -->
<threadCount>1</threadCount>
<systemPropertyVariables>
<test.ultradns-ws.endpoint>${test.ultradns-ws.endpoint}</test.ultradns-ws.endpoint>
<test.ultradns-ws.api-version>${test.ultradns-ws.api-version}</test.ultradns-ws.api-version>
<test.ultradns-ws.build-version>${test.ultradns-ws.build-version}</test.ultradns-ws.build-version>
<test.ultradns-ws.identity>${test.ultradns-ws.identity}</test.ultradns-ws.identity>
<test.ultradns-ws.credential>${test.ultradns-ws.credential}</test.ultradns-ws.credential>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
| {
"content_hash": "f52046fab52237e1bb8058e0fb80be02",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 201,
"avg_line_length": 39.4375,
"alnum_prop": 0.6465927099841522,
"repo_name": "yanzhijun/jclouds-aliyun",
"id": "e005ecf90cd097ade67848ccedafbbfe6d440aef",
"size": "4417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "providers/ultradns-ws/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "12999"
},
{
"name": "CSS",
"bytes": "10692"
},
{
"name": "Clojure",
"bytes": "99051"
},
{
"name": "Emacs Lisp",
"bytes": "852"
},
{
"name": "HTML",
"bytes": "381689"
},
{
"name": "Java",
"bytes": "19478047"
},
{
"name": "JavaScript",
"bytes": "7110"
},
{
"name": "Shell",
"bytes": "121121"
}
],
"symlink_target": ""
} |
package dbconn.jaxws;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name = "info_boxResponse", namespace = "http://dbconn/")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "info_boxResponse", namespace = "http://dbconn/")
public class Info_boxResponse {
@XmlElement(name = "return", namespace = "")
private String _return;
/**
*
* @return
* returns String
*/
public String getReturn() {
return this._return;
}
/**
*
* @param _return
* the value for the _return property
*/
public void setReturn(String _return) {
this._return = _return;
}
}
| {
"content_hash": "57fbc9002d77de22fd5c56ac4961b815",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 72,
"avg_line_length": 23.805555555555557,
"alnum_prop": 0.6569428238039673,
"repo_name": "codewithus/Open-Domain-Question-Answering",
"id": "91273f3e87d1b9cfa73254a92286a8f35f4aeabe",
"size": "857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Connect_MongolabDB/src/dbconn/jaxws/Info_boxResponse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3486"
},
{
"name": "HTML",
"bytes": "1780"
},
{
"name": "Java",
"bytes": "108805"
}
],
"symlink_target": ""
} |
angular.module('MassAutoComplete', [])
.directive('massAutocomplete', ["$timeout", "$window", "$document", "$q", function ($timeout, $window, $document, $q) {
'use strict';
return {
restrict: "A",
scope: { options: '&massAutocomplete' },
transclude: true,
template:
'<span ng-transclude></span>' +
'<div class="ac-container" ng-show="show_autocomplete && results.length > 0" style="position:absolute;">' +
'<ul class="ac-menu">' +
'<li ng-repeat="result in results" ng-if="$index > 0" ' +
'class="ac-menu-item" ng-class="$index == selected_index ? \'ac-state-focus\': \'\'">' +
'<a href ng-click="apply_selection($index)" ng-bind-html="result.label"></a>' +
'</li>' +
'</ul>' +
'</div>',
link: function (scope, element) {
scope.container = angular.element(element[0].getElementsByClassName('ac-container')[0]);
},
controller: ["$scope", function ($scope) {
var that = this;
var KEYS = {
TAB: 9,
ESC: 27,
ENTER: 13,
UP: 38,
DOWN: 40
};
var EVENTS = {
KEYDOWN: 'keydown',
RESIZE: 'resize',
BLUR: 'blur'
};
var bound_events = {};
bound_events[EVENTS.BLUR] = null;
bound_events[EVENTS.KEYDOWN] = null;
bound_events[EVENTS.RESIZE] = null;
var _user_options = $scope.options() || {};
var user_options = {
debounce_position: _user_options.debounce_position || 150,
debounce_attach: _user_options.debounce_attach || 300,
debounce_suggest: _user_options.debounce_suggest || 200,
debounce_blur: _user_options.debounce_blur || 150
};
var current_element,
current_model,
current_options,
previous_value,
value_watch,
last_selected_value;
$scope.show_autocomplete = false;
// Debounce - taken from underscore
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function _position_autocomplete() {
var rect = current_element[0].getBoundingClientRect(),
scrollTop = $document[0].body.scrollTop || $document[0].documentElement.scrollTop || $window.pageYOffset,
scrollLeft = $document[0].body.scrollLeft || $document[0].documentElement.scrollLeft || $window.pageXOffset,
container = $scope.container[0];
/*container.style.top = rect.top + rect.height + scrollTop + 'px';*/
container.style.top = rect.height + 'px';
/*container.style.left = rect.left + scrollLeft + 'px';*/
container.style.width = rect.width + 'px';
}
var position_autocomplete = debounce(_position_autocomplete, user_options.debounce_position);
// Attach autocomplete behaviour to an input element.
function _attach(ngmodel, target_element, options) {
// Element is already attached.
if (current_element === target_element) return;
// Safe: clear previously attached elements.
if (current_element) that.detach();
// The element is still the active element.
if (target_element[0] !== $document[0].activeElement) return;
options.on_attach && options.on_attach();
current_element = target_element;
current_model = ngmodel;
current_options = options;
previous_value = ngmodel.$viewValue;
$scope.results = [];
$scope.selected_index = -1;
bind_element();
value_watch = $scope.$watch(
function () {
return ngmodel.$modelValue;
},
function (nv, ov) {
// Prevent suggestion cycle when the value is the last value selected.
// When selecting from the menu the ng-model is updated and this watch
// is triggered. This causes another suggestion cycle that will provide as
// suggestion the value that is currently selected - this is unnecessary.
if (nv === last_selected_value)
return;
_position_autocomplete();
suggest(nv, current_element);
}
);
}
that.attach = debounce(_attach, user_options.debounce_attach);
function _suggest(term, target_element) {
$scope.selected_index = 0;
$scope.waiting_for_suggestion = true;
if (typeof(term) === 'string' && term.length > 0) {
$q.when(current_options.suggest(term),
function suggest_succeeded(suggestions) {
// Make sure the suggestion we are processing is of the current element.
// When using remote sources for example, a suggestion cycnle might be
// triggered at a later time (When a different field is in focus).
if (!current_element || current_element !== target_element)
return;
if (suggestions && suggestions.length > 0) {
// Add the original term as the first value to enable the user
// to return to his original expression after suggestions were made.
$scope.results = [{ value: term, label: ''}].concat(suggestions);
$scope.show_autocomplete = true;
if (current_options.auto_select_first)
set_selection(1);
} else {
$scope.results = [];
}
},
function suggest_failed(error) {
$scope.show_autocomplete = false;
current_options.on_error && current_options.on_error(error);
}
).finally(function suggest_finally() {
$scope.waiting_for_suggestion = false;
});
} else {
$scope.waiting_for_suggestion = false;
$scope.show_autocomplete = false;
$scope.$apply();
}
}
var suggest = debounce(_suggest, user_options.debounce_suggest);
// Trigger end of editing and remove all attachments made by
// this directive to the input element.
that.detach = function () {
if (current_element) {
var value = current_element.val();
update_model_value(value);
current_options.on_detach && current_options.on_detach(value);
current_element.unbind(EVENTS.KEYDOWN, bound_events[EVENTS.KEYDOWN]);
current_element.unbind(EVENTS.BLUR, bound_events[EVENTS.BLUR]);
}
// Clear references and events.
$scope.show_autocomplete = false;
angular.element($window).unbind(EVENTS.RESIZE, bound_events[EVENTS.RESIZE]);
value_watch && value_watch();
$scope.selected_index = $scope.results = undefined;
current_model = current_element = previous_value = undefined;
};
// Update angular's model view value.
// It is important that before triggering hooks the model's view
// value will be synced with the visible value to the user. This will
// allow the consumer controller to rely on its local ng-model.
function update_model_value(value) {
if (current_model.$modelValue !== value) {
current_model.$setViewValue(value);
current_model.$render();
}
}
// Set the current selection while navigating through the menu.
function set_selection(i) {
// We use value instead of setting the model's view value
// because we watch the model value and setting it will trigger
// a new suggestion cycle.
var selected = $scope.results[i];
current_element.val(selected.value);
$scope.selected_index = i;
return selected;
}
// Apply and accept the current selection made from the menu.
// When selecting from the menu directly (using click or touch) the
// selection is directly applied.
$scope.apply_selection = function (i) {
current_element[0].focus();
if (!$scope.show_autocomplete || i > $scope.results.length || i < 0)
return;
var selected = set_selection(i);
last_selected_value = selected.value;
update_model_value(selected.value);
$scope.show_autocomplete = false;
current_options.on_select && current_options.on_select(selected);
};
function bind_element() {
angular.element($window).bind(EVENTS.RESIZE, position_autocomplete);
bound_events[EVENTS.BLUR] = function () {
// Detach the element from the auto complete when input loses focus.
// Focus is lost when a selection is made from the auto complete menu
// using the mouse (or touch). In that case we don't want to detach so
// we wait several ms for the input to regain focus.
$timeout(function() {
if (!current_element || current_element[0] !== $document[0].activeElement)
that.detach();
}, user_options.debounce_blur);
};
current_element.bind(EVENTS.BLUR, bound_events[EVENTS.BLUR]);
bound_events[EVENTS.KEYDOWN] = function (e) {
// Reserve key combinations with shift for different purposes.
if (e.shiftKey) return;
switch (e.keyCode) {
// Close the menu if it's open. Or, undo changes made to the value
// if the menu is closed.
case KEYS.ESC:
if ($scope.show_autocomplete) {
$scope.show_autocomplete = false;
$scope.$apply();
} else {
current_element.val(previous_value);
}
break;
// Select an element and close the menu. Or, if a selection is
// unavailable let the event propagate.
case KEYS.ENTER:
// Accept a selection only if results exist, the menu is
// displayed and the results are valid (no current request
// for new suggestions is active).
if ($scope.show_autocomplete &&
$scope.selected_index > 0 &&
!$scope.waiting_for_suggestion) {
$scope.apply_selection($scope.selected_index);
// When selecting an item from the AC list the focus is set on
// the input element. So the enter will cause a keypress event
// on the input itself. Since this enter is not intended for the
// input but for the AC result we prevent propagation to parent
// elements because this event is not of their concern. We cannot
// prevent events from firing when the event was registered on
// the input itself.
e.stopPropagation();
e.preventDefault();
}
$scope.show_autocomplete = false;
$scope.$apply();
break;
// Navigate the menu when it's open. When it's not open fall back
// to default behavior.
case KEYS.TAB:
if (!$scope.show_autocomplete)
break;
e.preventDefault();
/* falls through */
// Open the menu when results exists but are not displayed. Or,
// select the next element when the menu is open. When reaching
// bottom wrap to top.
case KEYS.DOWN:
if ($scope.results.length > 0) {
if ($scope.show_autocomplete) {
set_selection($scope.selected_index + 1 > $scope.results.length - 1 ? 0 : $scope.selected_index + 1);
} else {
$scope.show_autocomplete = true;
$scope.selected_index = 0;
}
$scope.$apply();
}
break;
// Navigate up in the menu. When reaching the top wrap to bottom.
case KEYS.UP:
if ($scope.show_autocomplete) {
e.preventDefault();
set_selection($scope.selected_index - 1 >= 0 ? $scope.selected_index - 1 : $scope.results.length - 1);
$scope.$apply();
}
break;
}
};
current_element.bind(EVENTS.KEYDOWN, bound_events[EVENTS.KEYDOWN]);
}
$scope.$on('$destroy', function () {
that.detach();
$scope.container.remove();
});
}]
};
}])
.directive('massAutocompleteItem', function () {
'use strict';
return {
restrict: "A",
require: ["^massAutocomplete", "ngModel"],
scope: {'massAutocompleteItem' : "&"},
link: function (scope, element, attrs, required) {
// Prevent html5/browser auto completion.
attrs.$set('autocomplete', 'off');
element.bind('focus', function () {
var options = scope.massAutocompleteItem();
if (!options)
throw "Invalid options";
required[0].attach(required[1], element, options);
});
}
};
}); | {
"content_hash": "54eeabb915f689d076a5a9b82e592af3",
"timestamp": "",
"source": "github",
"line_count": 345,
"max_line_length": 120,
"avg_line_length": 38.857971014492755,
"alnum_prop": 0.5634044457705505,
"repo_name": "trentniemeyer/CustomizedCalaca",
"id": "4c832cdb0964b31984fe43eca8ed3d4983eca21c",
"size": "13406",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "js/massautocomplete.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7833"
},
{
"name": "HTML",
"bytes": "16786"
},
{
"name": "JavaScript",
"bytes": "51181"
}
],
"symlink_target": ""
} |
module RackCloud
end
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../../datapathy/lib"))
require 'datapathy'
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../../../../personal/resourceful/lib"))
require 'resourceful'
require 'json'
require File.join(File.dirname(__FILE__), 'datapathy', 'adapter')
require File.join(File.dirname(__FILE__), 'rackcloud', 'models', 'server')
require 'yaml'
config = YAML.load_file(File.expand_path("~/.rackcloud.yml"))
user, key = config["user"], config["key"]
Datapathy.default_adapter = RackCloud::DatapathyRackCloudAdapter.new(:user => user, :key => key)
| {
"content_hash": "067ff3e10bc812a6a29aa223ef8d58df",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 102,
"avg_line_length": 31.55,
"alnum_prop": 0.6925515055467512,
"repo_name": "paul/rackcloud",
"id": "4ef4cea284a1f5f95cb8cbfa099948618a79ecea",
"size": "632",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/rackcloud.rb",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package cgeo.geocaching.utils;
import androidx.annotation.NonNull;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RxOkHttpUtils {
private RxOkHttpUtils() {
// Do not instantiate
}
/**
* Create a Single for running a cancellable request.
*
* @param client the client to use for this request
* @param request the request
* @return a Single containing the response or an IOException
*/
public static Single<Response> request(final OkHttpClient client, final Request request) {
return Single.create(singleEmitter -> {
final Call call = client.newCall(request);
final AtomicBoolean completed = new AtomicBoolean(false);
singleEmitter.setDisposable(Disposable.fromRunnable(() -> {
if (!completed.get()) {
call.cancel();
}
}));
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull final Call call, @NonNull final IOException e) {
completed.set(true);
singleEmitter.onError(e);
}
@Override
public void onResponse(@NonNull final Call call, @NonNull final Response response) throws IOException {
completed.set(true);
singleEmitter.onSuccess(response);
}
});
});
}
}
| {
"content_hash": "75b8f33a09de10731d516781c55254b9",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 119,
"avg_line_length": 31.796296296296298,
"alnum_prop": 0.6092020966802563,
"repo_name": "matej116/cgeo",
"id": "991da6ebe38542e6a6a9a0caad6bb9f0bb3f79df",
"size": "1717",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "main/src/cgeo/geocaching/utils/RxOkHttpUtils.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3556803"
},
{
"name": "Java",
"bytes": "5546219"
},
{
"name": "Shell",
"bytes": "8245"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.hbase.master.procedure;
import java.io.IOException;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.InvalidFamilyOperationException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.RegionInfo;
import org.apache.hadoop.hbase.client.TableDescriptor;
import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
import org.apache.hadoop.hbase.procedure2.ProcedureStateSerializer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.hadoop.hbase.shaded.com.google.protobuf.UnsafeByteOperations;
import org.apache.hadoop.hbase.shaded.protobuf.ProtobufUtil;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos;
import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProcedureProtos.DeleteColumnFamilyState;
/**
* The procedure to delete a column family from an existing table.
*/
@InterfaceAudience.Private
public class DeleteColumnFamilyProcedure
extends AbstractStateMachineTableProcedure<DeleteColumnFamilyState> {
private static final Log LOG = LogFactory.getLog(DeleteColumnFamilyProcedure.class);
private TableDescriptor unmodifiedTableDescriptor;
private TableName tableName;
private byte [] familyName;
private boolean hasMob;
private List<RegionInfo> regionInfoList;
private Boolean traceEnabled;
public DeleteColumnFamilyProcedure() {
super();
this.unmodifiedTableDescriptor = null;
this.regionInfoList = null;
this.traceEnabled = null;
}
public DeleteColumnFamilyProcedure(final MasterProcedureEnv env, final TableName tableName,
final byte[] familyName) {
this(env, tableName, familyName, null);
}
public DeleteColumnFamilyProcedure(final MasterProcedureEnv env, final TableName tableName,
final byte[] familyName, final ProcedurePrepareLatch latch) {
super(env, latch);
this.tableName = tableName;
this.familyName = familyName;
this.unmodifiedTableDescriptor = null;
this.regionInfoList = null;
this.traceEnabled = null;
}
@Override
protected Flow executeFromState(final MasterProcedureEnv env, DeleteColumnFamilyState state)
throws InterruptedException {
if (isTraceEnabled()) {
LOG.trace(this + " execute state=" + state);
}
try {
switch (state) {
case DELETE_COLUMN_FAMILY_PREPARE:
prepareDelete(env);
setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PRE_OPERATION);
break;
case DELETE_COLUMN_FAMILY_PRE_OPERATION:
preDelete(env, state);
setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR);
break;
case DELETE_COLUMN_FAMILY_UPDATE_TABLE_DESCRIPTOR:
updateTableDescriptor(env);
setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT);
break;
case DELETE_COLUMN_FAMILY_DELETE_FS_LAYOUT:
deleteFromFs(env);
setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_POST_OPERATION);
break;
case DELETE_COLUMN_FAMILY_POST_OPERATION:
postDelete(env, state);
setNextState(DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS);
break;
case DELETE_COLUMN_FAMILY_REOPEN_ALL_REGIONS:
if (env.getAssignmentManager().isTableEnabled(getTableName())) {
addChildProcedure(env.getAssignmentManager()
.createReopenProcedures(getRegionInfoList(env)));
}
return Flow.NO_MORE_STATE;
default:
throw new UnsupportedOperationException(this + " unhandled state=" + state);
}
} catch (IOException e) {
if (isRollbackSupported(state)) {
setFailure("master-delete-columnfamily", e);
} else {
LOG.warn("Retriable error trying to delete the column family " + getColumnFamilyName() +
" from table " + tableName + " (in state=" + state + ")", e);
}
}
return Flow.HAS_MORE_STATE;
}
@Override
protected void rollbackState(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
throws IOException {
if (state == DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PREPARE ||
state == DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PRE_OPERATION) {
// nothing to rollback, pre is just table-state checks.
// We can fail if the table does not exist or is not disabled.
// TODO: coprocessor rollback semantic is still undefined.
return;
}
// The procedure doesn't have a rollback. The execution will succeed, at some point.
throw new UnsupportedOperationException("unhandled state=" + state);
}
@Override
protected boolean isRollbackSupported(final DeleteColumnFamilyState state) {
switch (state) {
case DELETE_COLUMN_FAMILY_PRE_OPERATION:
case DELETE_COLUMN_FAMILY_PREPARE:
return true;
default:
return false;
}
}
@Override
protected void completionCleanup(final MasterProcedureEnv env) {
releaseSyncLatch();
}
@Override
protected DeleteColumnFamilyState getState(final int stateId) {
return DeleteColumnFamilyState.valueOf(stateId);
}
@Override
protected int getStateId(final DeleteColumnFamilyState state) {
return state.getNumber();
}
@Override
protected DeleteColumnFamilyState getInitialState() {
return DeleteColumnFamilyState.DELETE_COLUMN_FAMILY_PREPARE;
}
@Override
protected void serializeStateData(ProcedureStateSerializer serializer)
throws IOException {
super.serializeStateData(serializer);
MasterProcedureProtos.DeleteColumnFamilyStateData.Builder deleteCFMsg =
MasterProcedureProtos.DeleteColumnFamilyStateData.newBuilder()
.setUserInfo(MasterProcedureUtil.toProtoUserInfo(getUser()))
.setTableName(ProtobufUtil.toProtoTableName(tableName))
.setColumnfamilyName(UnsafeByteOperations.unsafeWrap(familyName));
if (unmodifiedTableDescriptor != null) {
deleteCFMsg
.setUnmodifiedTableSchema(ProtobufUtil.toTableSchema(unmodifiedTableDescriptor));
}
serializer.serialize(deleteCFMsg.build());
}
@Override
protected void deserializeStateData(ProcedureStateSerializer serializer)
throws IOException {
super.deserializeStateData(serializer);
MasterProcedureProtos.DeleteColumnFamilyStateData deleteCFMsg =
serializer.deserialize(MasterProcedureProtos.DeleteColumnFamilyStateData.class);
setUser(MasterProcedureUtil.toUserInfo(deleteCFMsg.getUserInfo()));
tableName = ProtobufUtil.toTableName(deleteCFMsg.getTableName());
familyName = deleteCFMsg.getColumnfamilyName().toByteArray();
if (deleteCFMsg.hasUnmodifiedTableSchema()) {
unmodifiedTableDescriptor = ProtobufUtil.toTableDescriptor(deleteCFMsg.getUnmodifiedTableSchema());
}
}
@Override
public void toStringClassDetails(StringBuilder sb) {
sb.append(getClass().getSimpleName());
sb.append(" (table=");
sb.append(tableName);
sb.append(", columnfamily=");
if (familyName != null) {
sb.append(getColumnFamilyName());
} else {
sb.append("Unknown");
}
sb.append(")");
}
@Override
public TableName getTableName() {
return tableName;
}
@Override
public TableOperationType getTableOperationType() {
return TableOperationType.EDIT;
}
/**
* Action before any real action of deleting column family.
* @param env MasterProcedureEnv
* @throws IOException
*/
private void prepareDelete(final MasterProcedureEnv env) throws IOException {
// Checks whether the table is allowed to be modified.
checkTableModifiable(env);
// In order to update the descriptor, we need to retrieve the old descriptor for comparison.
unmodifiedTableDescriptor = env.getMasterServices().getTableDescriptors().get(tableName);
if (unmodifiedTableDescriptor == null) {
throw new IOException("TableDescriptor missing for " + tableName);
}
if (!unmodifiedTableDescriptor.hasColumnFamily(familyName)) {
throw new InvalidFamilyOperationException("Family '" + getColumnFamilyName()
+ "' does not exist, so it cannot be deleted");
}
if (unmodifiedTableDescriptor.getColumnFamilyCount() == 1) {
throw new InvalidFamilyOperationException("Family '" + getColumnFamilyName()
+ "' is the only column family in the table, so it cannot be deleted");
}
// whether mob family
hasMob = unmodifiedTableDescriptor.getColumnFamily(familyName).isMobEnabled();
}
/**
* Action before deleting column family.
* @param env MasterProcedureEnv
* @param state the procedure state
* @throws IOException
* @throws InterruptedException
*/
private void preDelete(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
throws IOException, InterruptedException {
runCoprocessorAction(env, state);
}
/**
* Remove the column family from the file system and update the table descriptor
*/
private void updateTableDescriptor(final MasterProcedureEnv env) throws IOException {
// Update table descriptor
LOG.info("DeleteColumn. Table = " + tableName + " family = " + getColumnFamilyName());
TableDescriptor htd = env.getMasterServices().getTableDescriptors().get(tableName);
if (!htd.hasColumnFamily(familyName)) {
// It is possible to reach this situation, as we could already delete the column family
// from table descriptor, but the master failover happens before we complete this state.
// We should be able to handle running this function multiple times without causing problem.
return;
}
env.getMasterServices().getTableDescriptors().add(
TableDescriptorBuilder.newBuilder(htd).removeColumnFamily(familyName).build());
}
/**
* Restore back to the old descriptor
* @param env MasterProcedureEnv
* @throws IOException
**/
private void restoreTableDescriptor(final MasterProcedureEnv env) throws IOException {
env.getMasterServices().getTableDescriptors().add(unmodifiedTableDescriptor);
// Make sure regions are opened after table descriptor is updated.
//reOpenAllRegionsIfTableIsOnline(env);
// TODO: NUKE ROLLBACK!!!!
}
/**
* Remove the column family from the file system
**/
private void deleteFromFs(final MasterProcedureEnv env) throws IOException {
MasterDDLOperationHelper.deleteColumnFamilyFromFileSystem(env, tableName,
getRegionInfoList(env), familyName, hasMob);
}
/**
* Action after deleting column family.
* @param env MasterProcedureEnv
* @param state the procedure state
* @throws IOException
* @throws InterruptedException
*/
private void postDelete(final MasterProcedureEnv env, final DeleteColumnFamilyState state)
throws IOException, InterruptedException {
runCoprocessorAction(env, state);
}
/**
* The procedure could be restarted from a different machine. If the variable is null, we need to
* retrieve it.
* @return traceEnabled
*/
private Boolean isTraceEnabled() {
if (traceEnabled == null) {
traceEnabled = LOG.isTraceEnabled();
}
return traceEnabled;
}
private String getColumnFamilyName() {
return Bytes.toString(familyName);
}
/**
* Coprocessor Action.
* @param env MasterProcedureEnv
* @param state the procedure state
* @throws IOException
* @throws InterruptedException
*/
private void runCoprocessorAction(final MasterProcedureEnv env,
final DeleteColumnFamilyState state) throws IOException, InterruptedException {
final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost();
if (cpHost != null) {
switch (state) {
case DELETE_COLUMN_FAMILY_PRE_OPERATION:
cpHost.preDeleteColumnFamilyAction(tableName, familyName, getUser());
break;
case DELETE_COLUMN_FAMILY_POST_OPERATION:
cpHost.postCompletedDeleteColumnFamilyAction(tableName, familyName, getUser());
break;
default:
throw new UnsupportedOperationException(this + " unhandled state=" + state);
}
}
}
private List<RegionInfo> getRegionInfoList(final MasterProcedureEnv env) throws IOException {
if (regionInfoList == null) {
regionInfoList = env.getAssignmentManager().getRegionStates()
.getRegionsOfTable(getTableName());
}
return regionInfoList;
}
}
| {
"content_hash": "ed9c2240dc642890a7441fbc64a67518",
"timestamp": "",
"source": "github",
"line_count": 355,
"max_line_length": 105,
"avg_line_length": 35.540845070422534,
"alnum_prop": 0.7273519854165016,
"repo_name": "JingchengDu/hbase",
"id": "fd9937834a6319734bb383fbd5a1d634915fccdf",
"size": "13423",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteColumnFamilyProcedure.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "351"
},
{
"name": "Batchfile",
"bytes": "25288"
},
{
"name": "C",
"bytes": "28534"
},
{
"name": "C++",
"bytes": "56085"
},
{
"name": "CMake",
"bytes": "13186"
},
{
"name": "CSS",
"bytes": "35785"
},
{
"name": "Groovy",
"bytes": "12548"
},
{
"name": "HTML",
"bytes": "17275"
},
{
"name": "Java",
"bytes": "31868492"
},
{
"name": "JavaScript",
"bytes": "2694"
},
{
"name": "Makefile",
"bytes": "1359"
},
{
"name": "PHP",
"bytes": "8385"
},
{
"name": "Perl",
"bytes": "383739"
},
{
"name": "Protocol Buffer",
"bytes": "278993"
},
{
"name": "Python",
"bytes": "109656"
},
{
"name": "Ruby",
"bytes": "547382"
},
{
"name": "Scala",
"bytes": "442815"
},
{
"name": "Shell",
"bytes": "181569"
},
{
"name": "Thrift",
"bytes": "41524"
},
{
"name": "XSLT",
"bytes": "6764"
}
],
"symlink_target": ""
} |
package org.apache.activemq.test;
import java.io.File;
import java.lang.reflect.Array;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;
import junit.framework.TestCase;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Useful base class for unit test cases
*
*
*/
public abstract class TestSupport extends TestCase {
private static final Logger LOG = LoggerFactory.getLogger(TestSupport.class);
protected ConnectionFactory connectionFactory;
protected boolean topic = true;
public TestSupport() {
super();
}
public TestSupport(String name) {
super(name);
}
/**
* Creates an ActiveMQMessage.
*
* @return ActiveMQMessage
*/
protected ActiveMQMessage createMessage() {
return new ActiveMQMessage();
}
/**
* Creates a destination.
*
* @param subject - topic or queue name.
* @return Destination - either an ActiveMQTopic or ActiveMQQUeue.
*/
protected Destination createDestination(String subject) {
if (topic) {
return new ActiveMQTopic(subject);
} else {
return new ActiveMQQueue(subject);
}
}
/**
* Tests if firstSet and secondSet are equal.
*
* @param messsage - string to be displayed when the assertion fails.
* @param firstSet[] - set of messages to be compared with its counterpart
* in the secondset.
* @param secondSet[] - set of messages to be compared with its counterpart
* in the firstset.
* @throws JMSException
*/
protected void assertTextMessagesEqual(Message[] firstSet, Message[] secondSet) throws JMSException {
assertTextMessagesEqual("", firstSet, secondSet);
}
/**
* Tests if firstSet and secondSet are equal.
*
* @param messsage - string to be displayed when the assertion fails.
* @param firstSet[] - set of messages to be compared with its counterpart
* in the secondset.
* @param secondSet[] - set of messages to be compared with its counterpart
* in the firstset.
*/
protected void assertTextMessagesEqual(String messsage, Message[] firstSet, Message[] secondSet) throws JMSException {
assertEquals("Message count does not match: " + messsage, firstSet.length, secondSet.length);
for (int i = 0; i < secondSet.length; i++) {
TextMessage m1 = (TextMessage)firstSet[i];
TextMessage m2 = (TextMessage)secondSet[i];
assertTextMessageEqual("Message " + (i + 1) + " did not match : ", m1, m2);
}
}
/**
* Tests if m1 and m2 are equal.
*
* @param m1 - message to be compared with m2.
* @param m2 - message to be compared with m1.
* @throws JMSException
*/
protected void assertEquals(TextMessage m1, TextMessage m2) throws JMSException {
assertEquals("", m1, m2);
}
/**
* Tests if m1 and m2 are equal.
*
* @param message - string to be displayed when the assertion fails.
* @param m1 - message to be compared with m2.
* @param m2 - message to be compared with m1.
*/
protected void assertTextMessageEqual(String message, TextMessage m1, TextMessage m2) throws JMSException {
assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null);
if (m1 == null) {
return;
}
assertEquals(message, m1.getText(), m2.getText());
}
/**
* Tests if m1 and m2 are equal.
*
* @param m1 - message to be compared with m2.
* @param m2 - message to be compared with m1.
* @throws JMSException
*/
protected void assertEquals(Message m1, Message m2) throws JMSException {
assertEquals("", m1, m2);
}
/**
* Tests if m1 and m2 are equal.
*
* @param message - error message.
* @param m1 - message to be compared with m2.
* @param m2 -- message to be compared with m1.
*/
protected void assertEquals(String message, Message m1, Message m2) throws JMSException {
assertFalse(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1 == null ^ m2 == null);
if (m1 == null) {
return;
}
assertTrue(message + ": expected {" + m1 + "}, but was {" + m2 + "}", m1.getClass() == m2.getClass());
if (m1 instanceof TextMessage) {
assertTextMessageEqual(message, (TextMessage)m1, (TextMessage)m2);
} else {
assertEquals(message, m1, m2);
}
}
/**
* Test if base directory contains spaces
*/
protected void assertBaseDirectoryContainsSpaces() {
assertFalse("Base directory cannot contain spaces.", new File(System.getProperty("basedir", ".")).getAbsoluteFile().toString().contains(" "));
}
/**
* Creates an ActiveMQConnectionFactory.
*
* @return ActiveMQConnectionFactory
* @throws Exception
*/
protected ConnectionFactory createConnectionFactory() throws Exception {
return new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
}
/**
* Factory method to create a new connection.
*
* @return connection
* @throws Exception
*/
protected Connection createConnection() throws Exception {
return getConnectionFactory().createConnection();
}
/**
* Creates an ActiveMQ connection factory.
*
* @return connectionFactory
* @throws Exception
*/
public ConnectionFactory getConnectionFactory() throws Exception {
if (connectionFactory == null) {
connectionFactory = createConnectionFactory();
assertTrue("Should have created a connection factory!", connectionFactory != null);
}
return connectionFactory;
}
/**
* Returns the consumer subject.
*
* @return String
*/
protected String getConsumerSubject() {
return getSubject();
}
/**
* Returns the producer subject.
*
* @return String
*/
protected String getProducerSubject() {
return getSubject();
}
/**
* Returns the subject.
*
* @return String
*/
protected String getSubject() {
return getClass().getName() + "." + getName();
}
protected void assertArrayEqual(String message, Object[] expected, Object[] actual) {
assertEquals(message + ". Array length", expected.length, actual.length);
for (int i = 0; i < expected.length; i++) {
assertEquals(message + ". element: " + i, expected[i], actual[i]);
}
}
protected void assertPrimitiveArrayEqual(String message, Object expected, Object actual) {
int length = Array.getLength(expected);
assertEquals(message + ". Array length", length, Array.getLength(actual));
for (int i = 0; i < length; i++) {
assertEquals(message + ". element: " + i, Array.get(expected, i), Array.get(actual, i));
}
}
}
| {
"content_hash": "6b09e4a10ef73ea56dd42d9cb2659a0b",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 147,
"avg_line_length": 30.736625514403293,
"alnum_prop": 0.6161467398580801,
"repo_name": "chirino/activemq",
"id": "6acb807b99b163748dd0b6763db09f19e7b5dce0",
"size": "8272",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "activemq-broker/src/test/java/org/apache/activemq/test/TestSupport.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17712"
},
{
"name": "C#",
"bytes": "27536"
},
{
"name": "C++",
"bytes": "17404"
},
{
"name": "CSS",
"bytes": "34997"
},
{
"name": "HTML",
"bytes": "158883"
},
{
"name": "Java",
"bytes": "25304453"
},
{
"name": "JavaScript",
"bytes": "438641"
},
{
"name": "PHP",
"bytes": "3665"
},
{
"name": "Perl",
"bytes": "4128"
},
{
"name": "Protocol Buffer",
"bytes": "13867"
},
{
"name": "Python",
"bytes": "14547"
},
{
"name": "Ruby",
"bytes": "6594"
},
{
"name": "Scala",
"bytes": "302023"
},
{
"name": "Shell",
"bytes": "87001"
}
],
"symlink_target": ""
} |
package org.springframework.core.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.meta.When;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotationUtilsTests.ExtendsBaseClassWithGenericAnnotatedMethod;
import org.springframework.core.annotation.AnnotationUtilsTests.ImplementsInterfaceWithGenericAnnotatedMethod;
import org.springframework.core.annotation.AnnotationUtilsTests.WebController;
import org.springframework.core.annotation.AnnotationUtilsTests.WebMapping;
import org.springframework.core.testfixture.stereotype.Component;
import org.springframework.core.testfixture.stereotype.Indexed;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.Nullable;
import org.springframework.util.MultiValueMap;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.springframework.core.annotation.AnnotatedElementUtils.findAllMergedAnnotations;
import static org.springframework.core.annotation.AnnotatedElementUtils.findMergedAnnotation;
import static org.springframework.core.annotation.AnnotatedElementUtils.getAllAnnotationAttributes;
import static org.springframework.core.annotation.AnnotatedElementUtils.getAllMergedAnnotations;
import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedAnnotation;
import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedAnnotationAttributes;
import static org.springframework.core.annotation.AnnotatedElementUtils.getMetaAnnotationTypes;
import static org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation;
import static org.springframework.core.annotation.AnnotatedElementUtils.hasMetaAnnotationTypes;
import static org.springframework.core.annotation.AnnotatedElementUtils.isAnnotated;
import static org.springframework.core.annotation.AnnotationUtilsTests.asArray;
/**
* Unit tests for {@link AnnotatedElementUtils}.
*
* @author Sam Brannen
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @since 4.0.3
* @see AnnotationUtilsTests
* @see MultipleComposedAnnotationsOnSingleAnnotatedElementTests
* @see ComposedRepeatableAnnotationsTests
*/
class AnnotatedElementUtilsTests {
private static final String TX_NAME = Transactional.class.getName();
@Nested
class ConventionBasedAnnotationAttributeOverrideTests {
@Test
void getMergedAnnotationAttributesWithConventionBasedComposedAnnotation() {
Class<?> element = ConventionBasedComposedContextConfigClass.class;
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").containsExactly("explicitDeclaration");
assertThat(attributes.getStringArray("value")).as("value").containsExactly("explicitDeclaration");
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
/**
* This test should never pass, simply because Spring does not support a hybrid
* approach for annotation attribute overrides with transitive implicit aliases.
* See SPR-13554 for details.
* <p>Furthermore, if you choose to execute this test, it can fail for either
* the first test class or the second one (with different exceptions), depending
* on the order in which the JVM returns the attribute methods via reflection.
*/
@Disabled("Permanently disabled but left in place for illustrative purposes")
@Test
void getMergedAnnotationAttributesWithHalfConventionBasedAndHalfAliasedComposedAnnotation() {
for (Class<?> clazz : asList(HalfConventionBasedAndHalfAliasedComposedContextConfigClassV1.class,
HalfConventionBasedAndHalfAliasedComposedContextConfigClassV2.class)) {
getMergedAnnotationAttributesWithHalfConventionBasedAndHalfAliasedComposedAnnotation(clazz);
}
}
private void getMergedAnnotationAttributesWithHalfConventionBasedAndHalfAliasedComposedAnnotation(Class<?> clazz) {
String name = ContextConfig.class.getName();
String simpleName = clazz.getSimpleName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(clazz, name);
assertThat(attributes).as("Should find @ContextConfig on " + simpleName).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations for class [" + simpleName + "]")
.containsExactly("explicitDeclaration");
assertThat(attributes.getStringArray("value")).as("value for class [" + simpleName + "]")
.containsExactly("explicitDeclaration");
// Verify contracts between utility methods:
assertThat(isAnnotated(clazz, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesWithInvalidConventionBasedComposedAnnotation() {
Class<?> element = InvalidConventionBasedComposedContextConfigClass.class;
assertThatExceptionOfType(AnnotationConfigurationException.class).isThrownBy(() ->
getMergedAnnotationAttributes(element, ContextConfig.class))
.withMessageContaining("Different @AliasFor mirror values for annotation")
.withMessageContaining("attribute 'locations' and its alias 'value'")
.withMessageContaining("values of [{requiredLocationsDeclaration}] and [{duplicateDeclaration}]");
}
@Test
void findMergedAnnotationAttributesWithSingleElementOverridingAnArrayViaConvention() {
assertComponentScanAttributes(ConventionBasedSinglePackageComponentScanClass.class, "com.example.app.test");
}
@Test
void findMergedAnnotationWithLocalAliasesThatConflictWithAttributesInMetaAnnotationByConvention() {
Class<?> element = SpringAppConfigClass.class;
ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class);
assertThat(contextConfig).as("Should find @ContextConfig on " + element).isNotNull();
assertThat(contextConfig.locations()).as("locations for " + element).isEmpty();
// 'value' in @SpringAppConfig should not override 'value' in @ContextConfig
assertThat(contextConfig.value()).as("value for " + element).isEmpty();
assertThat(contextConfig.classes()).as("classes for " + element).containsExactly(Number.class);
}
@Test
void findMergedAnnotationWithSingleElementOverridingAnArrayViaConvention() throws Exception {
assertWebMapping(WebController.class.getMethod("postMappedWithPathAttribute"));
}
}
@Test
void getMetaAnnotationTypesOnNonAnnotatedClass() {
assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class).isEmpty()).isTrue();
assertThat(getMetaAnnotationTypes(NonAnnotatedClass.class, TransactionalComponent.class.getName()).isEmpty()).isTrue();
}
@Test
void getMetaAnnotationTypesOnClassWithMetaDepth1() {
Set<String> names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class);
assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class));
names = getMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName());
assertThat(names).isEqualTo(names(Transactional.class, Component.class, Indexed.class));
}
@Test
void getMetaAnnotationTypesOnClassWithMetaDepth2() {
Set<String> names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class);
assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class));
names = getMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName());
assertThat(names).isEqualTo(names(TransactionalComponent.class, Transactional.class, Component.class, Indexed.class));
}
private Set<String> names(Class<?>... classes) {
return stream(classes).map(Class::getName).collect(toSet());
}
@Test
void hasMetaAnnotationTypesOnNonAnnotatedClass() {
assertThat(hasMetaAnnotationTypes(NonAnnotatedClass.class, TX_NAME)).isFalse();
}
@Test
void hasMetaAnnotationTypesOnClassWithMetaDepth0() {
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isFalse();
}
@Test
void hasMetaAnnotationTypesOnClassWithMetaDepth1() {
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(hasMetaAnnotationTypes(TransactionalComponentClass.class, Component.class.getName())).isTrue();
}
@Test
void hasMetaAnnotationTypesOnClassWithMetaDepth2() {
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(hasMetaAnnotationTypes(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isFalse();
}
@Test
void isAnnotatedOnNonAnnotatedClass() {
assertThat(isAnnotated(NonAnnotatedClass.class, Transactional.class)).isFalse();
}
@Test
void isAnnotatedOnClassWithMetaDepth() {
assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class)).as("isAnnotated() does not search the class hierarchy.").isFalse();
assertThat(isAnnotated(TransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(isAnnotated(TransactionalComponentClass.class, Component.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue();
}
@Test
void isAnnotatedForPlainTypes() {
assertThat(isAnnotated(Order.class, Documented.class)).isTrue();
assertThat(isAnnotated(NonNullApi.class, Documented.class)).isTrue();
assertThat(isAnnotated(NonNullApi.class, Nonnull.class)).isTrue();
assertThat(isAnnotated(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue();
}
@Test
void isAnnotatedWithNameOnNonAnnotatedClass() {
assertThat(isAnnotated(NonAnnotatedClass.class, TX_NAME)).isFalse();
}
@Test
void isAnnotatedWithNameOnClassWithMetaDepth() {
assertThat(isAnnotated(TransactionalComponentClass.class, TransactionalComponent.class.getName())).isTrue();
assertThat(isAnnotated(SubTransactionalComponentClass.class, TransactionalComponent.class.getName())).as("isAnnotated() does not search the class hierarchy.").isFalse();
assertThat(isAnnotated(TransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(isAnnotated(TransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, TX_NAME)).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, Component.class.getName())).isTrue();
assertThat(isAnnotated(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class.getName())).isTrue();
}
@Test
void hasAnnotationOnNonAnnotatedClass() {
assertThat(hasAnnotation(NonAnnotatedClass.class, Transactional.class)).isFalse();
}
@Test
void hasAnnotationOnClassWithMetaDepth() {
assertThat(hasAnnotation(TransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(hasAnnotation(SubTransactionalComponentClass.class, TransactionalComponent.class)).isTrue();
assertThat(hasAnnotation(TransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(hasAnnotation(TransactionalComponentClass.class, Component.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Transactional.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, Component.class)).isTrue();
assertThat(hasAnnotation(ComposedTransactionalComponentClass.class, ComposedTransactionalComponent.class)).isTrue();
}
@Test
void hasAnnotationForPlainTypes() {
assertThat(hasAnnotation(Order.class, Documented.class)).isTrue();
assertThat(hasAnnotation(NonNullApi.class, Documented.class)).isTrue();
assertThat(hasAnnotation(NonNullApi.class, Nonnull.class)).isTrue();
assertThat(hasAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class)).isTrue();
}
@Test
void getAllAnnotationAttributesOnNonAnnotatedClass() {
assertThat(getAllAnnotationAttributes(NonAnnotatedClass.class, TX_NAME)).isNull();
}
@Test
void getAllAnnotationAttributesOnClassWithLocalAnnotation() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(TxConfig.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on TxConfig").isNotNull();
assertThat(attributes.get("value")).as("value for TxConfig").isEqualTo(asList("TxConfig"));
}
@Test
void getAllAnnotationAttributesOnClassWithLocalComposedAnnotationAndInheritedAnnotation() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(SubClassWithInheritedAnnotation.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on SubClassWithInheritedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("composed2", "transactionManager"));
}
@Test
void getAllAnnotationAttributesFavorsInheritedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(SubSubClassWithInheritedAnnotation.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("transactionManager"));
}
@Test
void getAllAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes( SubSubClassWithInheritedComposedAnnotation.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on SubSubClassWithInheritedComposedAnnotation").isNotNull();
assertThat(attributes.get("qualifier")).isEqualTo(asList("composed1"));
}
/**
* If the "value" entry contains both "DerivedTxConfig" AND "TxConfig", then
* the algorithm is accidentally picking up shadowed annotations of the same
* type within the class hierarchy. Such undesirable behavior would cause the
* logic in {@code org.springframework.context.annotation.ProfileCondition}
* to fail.
*/
@Test
void getAllAnnotationAttributesOnClassWithLocalAnnotationThatShadowsAnnotationFromSuperclass() {
// See org.springframework.core.env.EnvironmentSystemIntegrationTests#mostSpecificDerivedClassDrivesEnvironment_withDevEnvAndDerivedDevConfigClass
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(DerivedTxConfig.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on DerivedTxConfig").isNotNull();
assertThat(attributes.get("value")).as("value for DerivedTxConfig").isEqualTo(asList("DerivedTxConfig"));
}
/**
* Note: this functionality is required by {@code org.springframework.context.annotation.ProfileCondition}.
*/
@Test
void getAllAnnotationAttributesOnClassWithMultipleComposedAnnotations() {
// See org.springframework.core.env.EnvironmentSystemIntegrationTests
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(TxFromMultipleComposedAnnotations.class, TX_NAME);
assertThat(attributes).as("Annotation attributes map for @Transactional on TxFromMultipleComposedAnnotations").isNotNull();
assertThat(attributes.get("value")).as("value for TxFromMultipleComposedAnnotations.").isEqualTo(asList("TxInheritedComposed", "TxComposed"));
}
@Test
void getAllAnnotationAttributesOnLangType() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
NonNullApi.class, Nonnull.class.getName());
assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull();
assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS));
}
@Test
void getAllAnnotationAttributesOnJavaxType() {
MultiValueMap<String, Object> attributes = getAllAnnotationAttributes(
ParametersAreNonnullByDefault.class, Nonnull.class.getName());
assertThat(attributes).as("Annotation attributes map for @Nonnull on NonNullApi").isNotNull();
assertThat(attributes.get("when")).as("value for NonNullApi").isEqualTo(asList(When.ALWAYS));
}
@Test
void getMergedAnnotationAttributesOnClassWithLocalAnnotation() {
Class<?> element = TxConfig.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Annotation attributes for @Transactional on TxConfig").isNotNull();
assertThat(attributes.getString("value")).as("value for TxConfig").isEqualTo("TxConfig");
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesOnClassWithLocalAnnotationThatShadowsAnnotationFromSuperclass() {
Class<?> element = DerivedTxConfig.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Annotation attributes for @Transactional on DerivedTxConfig").isNotNull();
assertThat(attributes.getString("value")).as("value for DerivedTxConfig").isEqualTo("DerivedTxConfig");
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesOnMetaCycleAnnotatedClassWithMissingTargetMetaAnnotation() {
AnnotationAttributes attributes = getMergedAnnotationAttributes(MetaCycleAnnotatedClass.class, TX_NAME);
assertThat(attributes).as("Should not find annotation attributes for @Transactional on MetaCycleAnnotatedClass").isNull();
}
@Test
void getMergedAnnotationAttributesFavorsLocalComposedAnnotationOverInheritedAnnotation() {
Class<?> element = SubClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubClassWithInheritedAnnotation").isNotNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubClassWithInheritedAnnotation.").isTrue();
}
@Test
void getMergedAnnotationAttributesFavorsInheritedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
Class<?> element = SubSubClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedAnnotation").isNotNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedAnnotation.").isFalse();
}
@Test
void getMergedAnnotationAttributesFavorsInheritedComposedAnnotationsOverMoreLocallyDeclaredComposedAnnotations() {
Class<?> element = SubSubClassWithInheritedComposedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("AnnotationAttributes for @Transactional on SubSubClassWithInheritedComposedAnnotation.").isNotNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
assertThat(attributes.getBoolean("readOnly")).as("readOnly flag for SubSubClassWithInheritedComposedAnnotation.").isFalse();
}
@Test
void getMergedAnnotationAttributesFromInterfaceImplementedBySuperclass() {
Class<?> element = ConcreteClassWithInheritedAnnotation.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should not find @Transactional on ConcreteClassWithInheritedAnnotation").isNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isFalse();
}
@Test
void getMergedAnnotationAttributesOnInheritedAnnotationInterface() {
Class<?> element = InheritedAnnotationInterface.class;
String name = TX_NAME;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesOnNonInheritedAnnotationInterface() {
Class<?> element = NonInheritedAnnotationInterface.class;
String name = Order.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull();
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesWithAliasedComposedAnnotation() {
Class<?> element = AliasedComposedContextConfigClass.class;
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml"));
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml"));
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesWithAliasedValueComposedAnnotation() {
Class<?> element = AliasedValueComposedContextConfigClass.class;
String name = ContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(asArray("test.xml"));
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(asArray("test.xml"));
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesWithImplicitAliasesInMetaAnnotationOnComposedAnnotation() {
Class<?> element = ComposedImplicitAliasesContextConfigClass.class;
String name = ImplicitAliasesContextConfig.class.getName();
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, name);
String[] expected = asArray("A.xml", "B.xml");
assertThat(attributes).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("groovyScripts")).as("groovyScripts").isEqualTo(expected);
assertThat(attributes.getStringArray("xmlFiles")).as("xmlFiles").isEqualTo(expected);
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected);
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected);
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationWithAliasedValueComposedAnnotation() {
assertGetMergedAnnotation(AliasedValueComposedContextConfigClass.class, "test.xml");
}
@Test
void getMergedAnnotationWithImplicitAliasesForSameAttributeInComposedAnnotation() {
assertGetMergedAnnotation(ImplicitAliasesContextConfigClass1.class, "foo.xml");
assertGetMergedAnnotation(ImplicitAliasesContextConfigClass2.class, "bar.xml");
assertGetMergedAnnotation(ImplicitAliasesContextConfigClass3.class, "baz.xml");
}
@Test
void getMergedAnnotationWithTransitiveImplicitAliases() {
assertGetMergedAnnotation(TransitiveImplicitAliasesContextConfigClass.class, "test.groovy");
}
@Test
void getMergedAnnotationWithTransitiveImplicitAliasesWithSingleElementOverridingAnArrayViaAliasFor() {
assertGetMergedAnnotation(SingleLocationTransitiveImplicitAliasesContextConfigClass.class, "test.groovy");
}
@Test
void getMergedAnnotationWithTransitiveImplicitAliasesWithSkippedLevel() {
assertGetMergedAnnotation(TransitiveImplicitAliasesWithSkippedLevelContextConfigClass.class, "test.xml");
}
@Test
void getMergedAnnotationWithTransitiveImplicitAliasesWithSkippedLevelWithSingleElementOverridingAnArrayViaAliasFor() {
assertGetMergedAnnotation(SingleLocationTransitiveImplicitAliasesWithSkippedLevelContextConfigClass.class, "test.xml");
}
private void assertGetMergedAnnotation(Class<?> element, String... expected) {
String name = ContextConfig.class.getName();
ContextConfig contextConfig = getMergedAnnotation(element, ContextConfig.class);
assertThat(contextConfig).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(contextConfig.locations()).as("locations").isEqualTo(expected);
assertThat(contextConfig.value()).as("value").isEqualTo(expected);
Object[] expecteds = new Class<?>[0];
assertThat(contextConfig.classes()).as("classes").isEqualTo(expecteds);
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationWithImplicitAliasesInMetaAnnotationOnComposedAnnotation() {
Class<?> element = ComposedImplicitAliasesContextConfigClass.class;
String name = ImplicitAliasesContextConfig.class.getName();
ImplicitAliasesContextConfig config = getMergedAnnotation(element, ImplicitAliasesContextConfig.class);
String[] expected = asArray("A.xml", "B.xml");
assertThat(config).as("Should find @ImplicitAliasesContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(config.groovyScripts()).as("groovyScripts").isEqualTo(expected);
assertThat(config.xmlFiles()).as("xmlFiles").isEqualTo(expected);
assertThat(config.locations()).as("locations").isEqualTo(expected);
assertThat(config.value()).as("value").isEqualTo(expected);
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationWithImplicitAliasesWithDefaultsInMetaAnnotationOnComposedAnnotation() {
Class<?> element = ImplicitAliasesWithDefaultsClass.class;
String name = AliasesWithDefaults.class.getName();
AliasesWithDefaults annotation = getMergedAnnotation(element, AliasesWithDefaults.class);
assertThat(annotation).as("Should find @AliasesWithDefaults on " + element.getSimpleName()).isNotNull();
assertThat(annotation.a1()).as("a1").isEqualTo("ImplicitAliasesWithDefaults");
assertThat(annotation.a2()).as("a2").isEqualTo("ImplicitAliasesWithDefaults");
// Verify contracts between utility methods:
assertThat(isAnnotated(element, name)).isTrue();
}
@Test
void getMergedAnnotationAttributesWithShadowedAliasComposedAnnotation() {
Class<?> element = ShadowedAliasComposedContextConfigClass.class;
AnnotationAttributes attributes = getMergedAnnotationAttributes(element, ContextConfig.class);
String[] expected = asArray("test.xml");
assertThat(attributes).as("Should find @ContextConfig on " + element.getSimpleName()).isNotNull();
assertThat(attributes.getStringArray("locations")).as("locations").isEqualTo(expected);
assertThat(attributes.getStringArray("value")).as("value").isEqualTo(expected);
}
@Test
void findMergedAnnotationAttributesOnInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(InheritedAnnotationInterface.class, Transactional.class);
assertThat(attributes).as("Should find @Transactional on InheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnSubInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubInheritedAnnotationInterface.class, Transactional.class);
assertThat(attributes).as("Should find @Transactional on SubInheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnSubSubInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubInheritedAnnotationInterface.class, Transactional.class);
assertThat(attributes).as("Should find @Transactional on SubSubInheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(NonInheritedAnnotationInterface.class, Order.class);
assertThat(attributes).as("Should find @Order on NonInheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnSubNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubNonInheritedAnnotationInterface.class, Order.class);
assertThat(attributes).as("Should find @Order on SubNonInheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnSubSubNonInheritedAnnotationInterface() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(SubSubNonInheritedAnnotationInterface.class, Order.class);
assertThat(attributes).as("Should find @Order on SubSubNonInheritedAnnotationInterface").isNotNull();
}
@Test
void findMergedAnnotationAttributesInheritedFromInterfaceMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleFromInterface");
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Order.class);
assertThat(attributes).as("Should find @Order on ConcreteClassWithInheritedAnnotation.handleFromInterface() method").isNotNull();
}
@Test
void findMergedAnnotationAttributesInheritedFromAbstractMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handle");
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class);
assertThat(attributes).as("Should find @Transactional on ConcreteClassWithInheritedAnnotation.handle() method").isNotNull();
}
@Test
void findMergedAnnotationAttributesInheritedFromBridgedMethod() throws NoSuchMethodException {
Method method = ConcreteClassWithInheritedAnnotation.class.getMethod("handleParameterized", String.class);
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, Transactional.class);
assertThat(attributes).as("Should find @Transactional on bridged ConcreteClassWithInheritedAnnotation.handleParameterized()").isNotNull();
}
/**
* Bridge/bridged method setup code copied from
* {@link org.springframework.core.BridgeMethodResolverTests#withGenericParameter()}.
* @since 4.2
*/
@Test
void findMergedAnnotationAttributesFromBridgeMethod() {
Method[] methods = StringGenericParameter.class.getMethods();
Method bridgeMethod = null;
Method bridgedMethod = null;
for (Method method : methods) {
if ("getFor".equals(method.getName()) && !method.getParameterTypes()[0].equals(Integer.class)) {
if (method.getReturnType().equals(Object.class)) {
bridgeMethod = method;
}
else {
bridgedMethod = method;
}
}
}
assertThat(bridgeMethod != null && bridgeMethod.isBridge()).isTrue();
boolean condition = bridgedMethod != null && !bridgedMethod.isBridge();
assertThat(condition).isTrue();
AnnotationAttributes attributes = findMergedAnnotationAttributes(bridgeMethod, Order.class);
assertThat(attributes).as("Should find @Order on StringGenericParameter.getFor() bridge method").isNotNull();
}
@Test
void findMergedAnnotationAttributesOnClassWithMetaAndLocalTxConfig() {
AnnotationAttributes attributes = findMergedAnnotationAttributes(MetaAndLocalTxConfigClass.class, Transactional.class);
assertThat(attributes).as("Should find @Transactional on MetaAndLocalTxConfigClass").isNotNull();
assertThat(attributes.getString("qualifier")).as("TX qualifier for MetaAndLocalTxConfigClass.").isEqualTo("localTxMgr");
}
@Test
void findAndSynthesizeAnnotationAttributesOnClassWithAttributeAliasesInTargetAnnotation() {
String qualifier = "aliasForQualifier";
// 1) Find and merge AnnotationAttributes from the annotation hierarchy
AnnotationAttributes attributes = findMergedAnnotationAttributes(
AliasedTransactionalComponentClass.class, AliasedTransactional.class);
assertThat(attributes).as("@AliasedTransactional on AliasedTransactionalComponentClass.").isNotNull();
// 2) Synthesize the AnnotationAttributes back into the target annotation
AliasedTransactional annotation = AnnotationUtils.synthesizeAnnotation(attributes,
AliasedTransactional.class, AliasedTransactionalComponentClass.class);
assertThat(annotation).isNotNull();
// 3) Verify that the AnnotationAttributes and synthesized annotation are equivalent
assertThat(attributes.getString("value")).as("TX value via attributes.").isEqualTo(qualifier);
assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo(qualifier);
assertThat(attributes.getString("qualifier")).as("TX qualifier via attributes.").isEqualTo(qualifier);
assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo(qualifier);
}
@Test
void findMergedAnnotationAttributesOnClassWithAttributeAliasInComposedAnnotationAndNestedAnnotationsInTargetAnnotation() {
AnnotationAttributes attributes = assertComponentScanAttributes(TestComponentScanClass.class, "com.example.app.test");
Filter[] excludeFilters = attributes.getAnnotationArray("excludeFilters", Filter.class);
assertThat(excludeFilters).isNotNull();
List<String> patterns = stream(excludeFilters).map(Filter::pattern).collect(toList());
assertThat(patterns).isEqualTo(asList("*Test", "*Tests"));
}
/**
* This test ensures that {@link AnnotationUtils#postProcessAnnotationAttributes}
* uses {@code ObjectUtils.nullSafeEquals()} to check for equality between annotation
* attributes since attributes may be arrays.
*/
@Test
void findMergedAnnotationAttributesOnClassWithBothAttributesOfAnAliasPairDeclared() {
assertComponentScanAttributes(ComponentScanWithBasePackagesAndValueAliasClass.class, "com.example.app.test");
}
/**
* @since 5.2.1
* @see <a href="https://github.com/spring-projects/spring-framework/issues/23767">#23767</a>
*/
@Test
void findMergedAnnotationAttributesOnMethodWithComposedMetaTransactionalAnnotation() throws Exception {
Method method = getClass().getDeclaredMethod("composedTransactionalMethod");
AnnotationAttributes attributes = findMergedAnnotationAttributes(method, AliasedTransactional.class);
assertThat(attributes).as("Should find @AliasedTransactional on " + method).isNotNull();
assertThat(attributes.getString("value")).as("TX qualifier for " + method).isEqualTo("anotherTransactionManager");
assertThat(attributes.getString("qualifier")).as("TX qualifier for " + method).isEqualTo("anotherTransactionManager");
}
/**
* @since 5.2.1
* @see <a href="https://github.com/spring-projects/spring-framework/issues/23767">#23767</a>
*/
@Test
void findMergedAnnotationOnMethodWithComposedMetaTransactionalAnnotation() throws Exception {
Method method = getClass().getDeclaredMethod("composedTransactionalMethod");
AliasedTransactional annotation = findMergedAnnotation(method, AliasedTransactional.class);
assertThat(annotation).as("Should find @AliasedTransactional on " + method).isNotNull();
assertThat(annotation.value()).as("TX qualifier for " + method).isEqualTo("anotherTransactionManager");
assertThat(annotation.qualifier()).as("TX qualifier for " + method).isEqualTo("anotherTransactionManager");
}
/**
* @since 5.2.1
* @see <a href="https://github.com/spring-projects/spring-framework/issues/23767">#23767</a>
*/
@Test
void findMergedAnnotationAttributesOnClassWithComposedMetaTransactionalAnnotation() throws Exception {
Class<?> clazz = ComposedTransactionalClass.class;
AnnotationAttributes attributes = findMergedAnnotationAttributes(clazz, AliasedTransactional.class);
assertThat(attributes).as("Should find @AliasedTransactional on " + clazz).isNotNull();
assertThat(attributes.getString("value")).as("TX qualifier for " + clazz).isEqualTo("anotherTransactionManager");
assertThat(attributes.getString("qualifier")).as("TX qualifier for " + clazz).isEqualTo("anotherTransactionManager");
}
/**
* @since 5.2.1
* @see <a href="https://github.com/spring-projects/spring-framework/issues/23767">#23767</a>
*/
@Test
void findMergedAnnotationOnClassWithComposedMetaTransactionalAnnotation() throws Exception {
Class<?> clazz = ComposedTransactionalClass.class;
AliasedTransactional annotation = findMergedAnnotation(clazz, AliasedTransactional.class);
assertThat(annotation).as("Should find @AliasedTransactional on " + clazz).isNotNull();
assertThat(annotation.value()).as("TX qualifier for " + clazz).isEqualTo("anotherTransactionManager");
assertThat(annotation.qualifier()).as("TX qualifier for " + clazz).isEqualTo("anotherTransactionManager");
}
@Test
void findMergedAnnotationAttributesWithSingleElementOverridingAnArrayViaAliasFor() {
assertComponentScanAttributes(AliasForBasedSinglePackageComponentScanClass.class, "com.example.app.test");
}
private AnnotationAttributes assertComponentScanAttributes(Class<?> element, String... expected) {
AnnotationAttributes attributes = findMergedAnnotationAttributes(element, ComponentScan.class);
assertThat(attributes).as("Should find @ComponentScan on " + element).isNotNull();
assertThat(attributes.getStringArray("value")).as("value: ").isEqualTo(expected);
assertThat(attributes.getStringArray("basePackages")).as("basePackages: ").isEqualTo(expected);
return attributes;
}
private AnnotationAttributes findMergedAnnotationAttributes(AnnotatedElement element, Class<? extends Annotation> annotationType) {
return AnnotatedElementUtils.findMergedAnnotationAttributes(element, annotationType.getName(), false, false);
}
@Test
void findMergedAnnotationWithAttributeAliasesInTargetAnnotation() {
Class<?> element = AliasedTransactionalComponentClass.class;
AliasedTransactional annotation = findMergedAnnotation(element, AliasedTransactional.class);
assertThat(annotation).as("@AliasedTransactional on " + element).isNotNull();
assertThat(annotation.value()).as("TX value via synthesized annotation.").isEqualTo("aliasForQualifier");
assertThat(annotation.qualifier()).as("TX qualifier via synthesized annotation.").isEqualTo("aliasForQualifier");
}
@Test
void findMergedAnnotationForMultipleMetaAnnotationsWithClashingAttributeNames() {
String[] xmlLocations = asArray("test.xml");
String[] propFiles = asArray("test.properties");
Class<?> element = AliasedComposedContextConfigAndTestPropSourceClass.class;
ContextConfig contextConfig = findMergedAnnotation(element, ContextConfig.class);
assertThat(contextConfig).as("@ContextConfig on " + element).isNotNull();
assertThat(contextConfig.locations()).as("locations").isEqualTo(xmlLocations);
assertThat(contextConfig.value()).as("value").isEqualTo(xmlLocations);
// Synthesized annotation
TestPropSource testPropSource = AnnotationUtils.findAnnotation(element, TestPropSource.class);
assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles);
assertThat(testPropSource.value()).as("value").isEqualTo(propFiles);
// Merged annotation
testPropSource = findMergedAnnotation(element, TestPropSource.class);
assertThat(testPropSource).as("@TestPropSource on " + element).isNotNull();
assertThat(testPropSource.locations()).as("locations").isEqualTo(propFiles);
assertThat(testPropSource.value()).as("value").isEqualTo(propFiles);
}
@Test
void findMergedAnnotationWithSingleElementOverridingAnArrayViaAliasFor() throws Exception {
assertWebMapping(WebController.class.getMethod("getMappedWithValueAttribute"));
assertWebMapping(WebController.class.getMethod("getMappedWithPathAttribute"));
}
private void assertWebMapping(AnnotatedElement element) {
WebMapping webMapping = findMergedAnnotation(element, WebMapping.class);
assertThat(webMapping).isNotNull();
assertThat(webMapping.value()).as("value attribute: ").isEqualTo(asArray("/test"));
assertThat(webMapping.path()).as("path attribute: ").isEqualTo(asArray("/test"));
}
@Test
void javaLangAnnotationTypeViaFindMergedAnnotation() throws Exception {
Constructor<?> deprecatedCtor = Date.class.getConstructor(String.class);
assertThat(findMergedAnnotation(deprecatedCtor, Deprecated.class)).isEqualTo(deprecatedCtor.getAnnotation(Deprecated.class));
assertThat(findMergedAnnotation(Date.class, Deprecated.class)).isEqualTo(Date.class.getAnnotation(Deprecated.class));
}
@Test
void javaxAnnotationTypeViaFindMergedAnnotation() throws Exception {
assertThat(findMergedAnnotation(ResourceHolder.class, Resource.class)).isEqualTo(ResourceHolder.class.getAnnotation(Resource.class));
assertThat(findMergedAnnotation(SpringAppConfigClass.class, Resource.class)).isEqualTo(SpringAppConfigClass.class.getAnnotation(Resource.class));
}
@Test
void javaxMetaAnnotationTypeViaFindMergedAnnotation() throws Exception {
assertThat(findMergedAnnotation(ParametersAreNonnullByDefault.class, Nonnull.class)).isEqualTo(ParametersAreNonnullByDefault.class.getAnnotation(Nonnull.class));
assertThat(findMergedAnnotation(ResourceHolder.class, Nonnull.class)).isEqualTo(ParametersAreNonnullByDefault.class.getAnnotation(Nonnull.class));
}
@Test
void nullableAnnotationTypeViaFindMergedAnnotation() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
assertThat(findMergedAnnotation(method, Resource.class)).isEqualTo(method.getAnnotation(Resource.class));
}
@Test
void getAllMergedAnnotationsOnClassWithInterface() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
Set<Transactional> allMergedAnnotations = getAllMergedAnnotations(method, Transactional.class);
assertThat(allMergedAnnotations.isEmpty()).isTrue();
}
@Test
void findAllMergedAnnotationsOnClassWithInterface() throws Exception {
Method method = TransactionalServiceImpl.class.getMethod("doIt");
Set<Transactional> allMergedAnnotations = findAllMergedAnnotations(method, Transactional.class);
assertThat(allMergedAnnotations).hasSize(1);
}
@Test // SPR-16060
void findMethodAnnotationFromGenericInterface() throws Exception {
Method method = ImplementsInterfaceWithGenericAnnotatedMethod.class.getMethod("foo", String.class);
Order order = findMergedAnnotation(method, Order.class);
assertThat(order).isNotNull();
}
@Test // SPR-17146
void findMethodAnnotationFromGenericSuperclass() throws Exception {
Method method = ExtendsBaseClassWithGenericAnnotatedMethod.class.getMethod("foo", String.class);
Order order = findMergedAnnotation(method, Order.class);
assertThat(order).isNotNull();
}
@Test // gh-22655
void forAnnotationsCreatesCopyOfArrayOnEachCall() {
AnnotatedElement element = AnnotatedElementUtils.forAnnotations(ForAnnotationsClass.class.getDeclaredAnnotations());
// Trigger the NPE as originally reported in the bug
AnnotationsScanner.getDeclaredAnnotations(element, false);
AnnotationsScanner.getDeclaredAnnotations(element, false);
// Also specifically test we get different instances
assertThat(element.getDeclaredAnnotations()).isNotSameAs(element.getDeclaredAnnotations());
}
@Test // gh-22703
void getMergedAnnotationOnThreeDeepMetaWithValue() {
ValueAttribute annotation = AnnotatedElementUtils.getMergedAnnotation(
ValueAttributeMetaMetaClass.class, ValueAttribute.class);
assertThat(annotation.value()).containsExactly("FromValueAttributeMeta");
}
// -------------------------------------------------------------------------
@MetaCycle3
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@interface MetaCycle1 {
}
@MetaCycle1
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
@interface MetaCycle2 {
}
@MetaCycle2
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MetaCycle3 {
}
@MetaCycle3
static class MetaCycleAnnotatedClass {
}
// -------------------------------------------------------------------------
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@interface Transactional {
String value() default "";
String qualifier() default "transactionManager";
boolean readOnly() default false;
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@interface AliasedTransactional {
@AliasFor("qualifier")
String value() default "";
@AliasFor("value")
String qualifier() default "";
}
@AliasedTransactional
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface MyAliasedTransactional {
@AliasFor(annotation = AliasedTransactional.class, attribute = "value")
String value() default "defaultTransactionManager";
}
@MyAliasedTransactional("anotherTransactionManager")
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@interface ComposedMyAliasedTransactional {
}
@Transactional(qualifier = "composed1")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@interface InheritedComposed {
}
@Transactional(qualifier = "composed2", readOnly = true)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Composed {
}
@Transactional
@Retention(RetentionPolicy.RUNTIME)
@interface TxComposedWithOverride {
String qualifier() default "txMgr";
}
@Transactional("TxInheritedComposed")
@Retention(RetentionPolicy.RUNTIME)
@interface TxInheritedComposed {
}
@Transactional("TxComposed")
@Retention(RetentionPolicy.RUNTIME)
@interface TxComposed {
}
@Transactional
@Component
@Retention(RetentionPolicy.RUNTIME)
@interface TransactionalComponent {
}
@TransactionalComponent
@Retention(RetentionPolicy.RUNTIME)
@interface ComposedTransactionalComponent {
}
@AliasedTransactional(value = "aliasForQualifier")
@Component
@Retention(RetentionPolicy.RUNTIME)
@interface AliasedTransactionalComponent {
}
@TxComposedWithOverride
// Override default "txMgr" from @TxComposedWithOverride with "localTxMgr"
@Transactional(qualifier = "localTxMgr")
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MetaAndLocalTxConfig {
}
/**
* Mock of {@code org.springframework.test.context.TestPropertySource}.
*/
@Retention(RetentionPolicy.RUNTIME)
@interface TestPropSource {
@AliasFor("locations")
String[] value() default {};
@AliasFor("value")
String[] locations() default {};
}
/**
* Mock of {@code org.springframework.test.context.ContextConfiguration}.
*/
@Retention(RetentionPolicy.RUNTIME)
@interface ContextConfig {
@AliasFor("locations")
String[] value() default {};
@AliasFor("value")
String[] locations() default {};
Class<?>[] classes() default {};
}
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface ConventionBasedComposedContextConfig {
// Do NOT use @AliasFor here until Spring 6.1
// @AliasFor(annotation = ContextConfig.class)
String[] locations() default {};
}
@ContextConfig(value = "duplicateDeclaration")
@Retention(RetentionPolicy.RUNTIME)
@interface InvalidConventionBasedComposedContextConfig {
// Do NOT use @AliasFor here until Spring 6.1
// @AliasFor(annotation = ContextConfig.class)
String[] locations();
}
/**
* This hybrid approach for annotation attribute overrides with transitive implicit
* aliases is unsupported. See SPR-13554 for details.
*/
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface HalfConventionBasedAndHalfAliasedComposedContextConfig {
String[] locations() default {};
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xmlConfigFiles() default {};
}
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface AliasedComposedContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xmlConfigFiles();
}
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface AliasedValueComposedContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "value")
String[] locations();
}
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface ImplicitAliasesContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] groovyScripts() default {};
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xmlFiles() default {};
// intentionally omitted: attribute = "locations"
@AliasFor(annotation = ContextConfig.class)
String[] locations() default {};
// intentionally omitted: attribute = "locations" (SPR-14069)
@AliasFor(annotation = ContextConfig.class)
String[] value() default {};
}
@ImplicitAliasesContextConfig(xmlFiles = {"A.xml", "B.xml"})
@Retention(RetentionPolicy.RUNTIME)
@interface ComposedImplicitAliasesContextConfig {
}
@Retention(RetentionPolicy.RUNTIME)
@interface AliasesWithDefaults {
@AliasFor("a2")
String a1() default "AliasesWithDefaults";
@AliasFor("a1")
String a2() default "AliasesWithDefaults";
}
@Retention(RetentionPolicy.RUNTIME)
@AliasesWithDefaults
@interface ImplicitAliasesWithDefaults {
@AliasFor(annotation = AliasesWithDefaults.class, attribute = "a1")
String b1() default "ImplicitAliasesWithDefaults";
@AliasFor(annotation = AliasesWithDefaults.class, attribute = "a2")
String b2() default "ImplicitAliasesWithDefaults";
}
@ImplicitAliasesContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface TransitiveImplicitAliasesContextConfig {
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "xmlFiles")
String[] xml() default {};
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "groovyScripts")
String[] groovy() default {};
}
@ImplicitAliasesContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface SingleLocationTransitiveImplicitAliasesContextConfig {
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "xmlFiles")
String xml() default "";
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "groovyScripts")
String groovy() default "";
}
@ImplicitAliasesContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface TransitiveImplicitAliasesWithSkippedLevelContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xml() default {};
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "groovyScripts")
String[] groovy() default {};
}
@ImplicitAliasesContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface SingleLocationTransitiveImplicitAliasesWithSkippedLevelContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String xml() default "";
@AliasFor(annotation = ImplicitAliasesContextConfig.class, attribute = "groovyScripts")
String groovy() default "";
}
/**
* Although the configuration declares an explicit value for 'value' and
* requires a value for the aliased 'locations', this does not result in
* an error since 'locations' effectively <em>shadows</em> the 'value'
* attribute (which cannot be set via the composed annotation anyway).
*
* If 'value' were not shadowed, such a declaration would not make sense.
*/
@ContextConfig(value = "duplicateDeclaration")
@Retention(RetentionPolicy.RUNTIME)
@interface ShadowedAliasComposedContextConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xmlConfigFiles();
}
@ContextConfig(locations = "shadowed.xml")
@TestPropSource(locations = "test.properties")
@Retention(RetentionPolicy.RUNTIME)
@interface AliasedComposedContextConfigAndTestPropSource {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] xmlConfigFiles() default "default.xml";
}
/**
* Mock of {@code org.springframework.boot.test.SpringApplicationConfiguration}.
*/
@ContextConfig
@Retention(RetentionPolicy.RUNTIME)
@interface SpringAppConfig {
@AliasFor(annotation = ContextConfig.class, attribute = "locations")
String[] locations() default {};
// Do NOT use @AliasFor(annotation = ...) here until Spring 6.1
// @AliasFor(annotation = ContextConfig.class, attribute = "classes")
@AliasFor("value")
Class<?>[] classes() default {};
// Do NOT use @AliasFor(annotation = ...) here until Spring 6.1
// @AliasFor(annotation = ContextConfig.class, attribute = "classes")
@AliasFor("classes")
Class<?>[] value() default {};
}
/**
* Mock of {@code org.springframework.context.annotation.ComponentScan}
*/
@Retention(RetentionPolicy.RUNTIME)
@interface ComponentScan {
@AliasFor("basePackages")
String[] value() default {};
// Intentionally no alias declaration for "value"
String[] basePackages() default {};
Filter[] excludeFilters() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface Filter {
String pattern();
}
@ComponentScan(excludeFilters = {@Filter(pattern = "*Test"), @Filter(pattern = "*Tests")})
@Retention(RetentionPolicy.RUNTIME)
@interface TestComponentScan {
@AliasFor(attribute = "basePackages", annotation = ComponentScan.class)
String[] packages();
}
@ComponentScan
@Retention(RetentionPolicy.RUNTIME)
@interface ConventionBasedSinglePackageComponentScan {
// Do NOT use @AliasFor here until Spring 6.1
// @AliasFor(annotation = ComponentScan.class)
String basePackages();
}
@ComponentScan
@Retention(RetentionPolicy.RUNTIME)
@interface AliasForBasedSinglePackageComponentScan {
@AliasFor(attribute = "basePackages", annotation = ComponentScan.class)
String pkg();
}
// -------------------------------------------------------------------------
static class NonAnnotatedClass {
}
@TransactionalComponent
static class TransactionalComponentClass {
}
static class SubTransactionalComponentClass extends TransactionalComponentClass {
}
@ComposedTransactionalComponent
static class ComposedTransactionalComponentClass {
}
@AliasedTransactionalComponent
static class AliasedTransactionalComponentClass {
}
@ComposedMyAliasedTransactional
void composedTransactionalMethod() {
}
@ComposedMyAliasedTransactional
static class ComposedTransactionalClass {
}
@Transactional
static class ClassWithInheritedAnnotation {
}
@Composed
static class SubClassWithInheritedAnnotation extends ClassWithInheritedAnnotation {
}
static class SubSubClassWithInheritedAnnotation extends SubClassWithInheritedAnnotation {
}
@InheritedComposed
static class ClassWithInheritedComposedAnnotation {
}
@Composed
static class SubClassWithInheritedComposedAnnotation extends ClassWithInheritedComposedAnnotation {
}
static class SubSubClassWithInheritedComposedAnnotation extends SubClassWithInheritedComposedAnnotation {
}
@MetaAndLocalTxConfig
static class MetaAndLocalTxConfigClass {
}
@Transactional("TxConfig")
static class TxConfig {
}
@Transactional("DerivedTxConfig")
static class DerivedTxConfig extends TxConfig {
}
@TxInheritedComposed
@TxComposed
static class TxFromMultipleComposedAnnotations {
}
@Transactional
interface InterfaceWithInheritedAnnotation {
@Order
void handleFromInterface();
}
static abstract class AbstractClassWithInheritedAnnotation<T> implements InterfaceWithInheritedAnnotation {
@Transactional
public abstract void handle();
@Transactional
public void handleParameterized(T t) {
}
}
static class ConcreteClassWithInheritedAnnotation extends AbstractClassWithInheritedAnnotation<String> {
@Override
public void handle() {
}
@Override
public void handleParameterized(String s) {
}
@Override
public void handleFromInterface() {
}
}
public interface GenericParameter<T> {
T getFor(Class<T> cls);
}
@SuppressWarnings("unused")
private static class StringGenericParameter implements GenericParameter<String> {
@Order
@Override
public String getFor(Class<String> cls) {
return "foo";
}
public String getFor(Integer integer) {
return "foo";
}
}
@Transactional
public interface InheritedAnnotationInterface {
}
public interface SubInheritedAnnotationInterface extends InheritedAnnotationInterface {
}
public interface SubSubInheritedAnnotationInterface extends SubInheritedAnnotationInterface {
}
@Order
public interface NonInheritedAnnotationInterface {
}
public interface SubNonInheritedAnnotationInterface extends NonInheritedAnnotationInterface {
}
public interface SubSubNonInheritedAnnotationInterface extends SubNonInheritedAnnotationInterface {
}
@ConventionBasedComposedContextConfig(locations = "explicitDeclaration")
static class ConventionBasedComposedContextConfigClass {
}
@InvalidConventionBasedComposedContextConfig(locations = "requiredLocationsDeclaration")
static class InvalidConventionBasedComposedContextConfigClass {
}
@HalfConventionBasedAndHalfAliasedComposedContextConfig(xmlConfigFiles = "explicitDeclaration")
static class HalfConventionBasedAndHalfAliasedComposedContextConfigClassV1 {
}
@HalfConventionBasedAndHalfAliasedComposedContextConfig(locations = "explicitDeclaration")
static class HalfConventionBasedAndHalfAliasedComposedContextConfigClassV2 {
}
@AliasedComposedContextConfig(xmlConfigFiles = "test.xml")
static class AliasedComposedContextConfigClass {
}
@AliasedValueComposedContextConfig(locations = "test.xml")
static class AliasedValueComposedContextConfigClass {
}
@ImplicitAliasesContextConfig("foo.xml")
static class ImplicitAliasesContextConfigClass1 {
}
@ImplicitAliasesContextConfig(locations = "bar.xml")
static class ImplicitAliasesContextConfigClass2 {
}
@ImplicitAliasesContextConfig(xmlFiles = "baz.xml")
static class ImplicitAliasesContextConfigClass3 {
}
@ImplicitAliasesWithDefaults
static class ImplicitAliasesWithDefaultsClass {
}
@TransitiveImplicitAliasesContextConfig(groovy = "test.groovy")
static class TransitiveImplicitAliasesContextConfigClass {
}
@SingleLocationTransitiveImplicitAliasesContextConfig(groovy = "test.groovy")
static class SingleLocationTransitiveImplicitAliasesContextConfigClass {
}
@TransitiveImplicitAliasesWithSkippedLevelContextConfig(xml = "test.xml")
static class TransitiveImplicitAliasesWithSkippedLevelContextConfigClass {
}
@SingleLocationTransitiveImplicitAliasesWithSkippedLevelContextConfig(xml = "test.xml")
static class SingleLocationTransitiveImplicitAliasesWithSkippedLevelContextConfigClass {
}
@ComposedImplicitAliasesContextConfig
static class ComposedImplicitAliasesContextConfigClass {
}
@ShadowedAliasComposedContextConfig(xmlConfigFiles = "test.xml")
static class ShadowedAliasComposedContextConfigClass {
}
@AliasedComposedContextConfigAndTestPropSource(xmlConfigFiles = "test.xml")
static class AliasedComposedContextConfigAndTestPropSourceClass {
}
@ComponentScan(value = "com.example.app.test", basePackages = "com.example.app.test")
static class ComponentScanWithBasePackagesAndValueAliasClass {
}
@TestComponentScan(packages = "com.example.app.test")
static class TestComponentScanClass {
}
@ConventionBasedSinglePackageComponentScan(basePackages = "com.example.app.test")
static class ConventionBasedSinglePackageComponentScanClass {
}
@AliasForBasedSinglePackageComponentScan(pkg = "com.example.app.test")
static class AliasForBasedSinglePackageComponentScanClass {
}
@SpringAppConfig(Number.class)
static class SpringAppConfigClass {
}
@Resource(name = "x")
@ParametersAreNonnullByDefault
static class ResourceHolder {
}
interface TransactionalService {
@Transactional
@Nullable
Object doIt();
}
class TransactionalServiceImpl implements TransactionalService {
@Override
@Nullable
public Object doIt() {
return null;
}
}
@Deprecated
@ComponentScan
class ForAnnotationsClass {
}
@Retention(RetentionPolicy.RUNTIME)
@interface ValueAttribute {
String[] value();
}
@Retention(RetentionPolicy.RUNTIME)
@ValueAttribute("FromValueAttributeMeta")
@interface ValueAttributeMeta {
@AliasFor("alias")
String[] value() default {};
@AliasFor("value")
String[] alias() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@ValueAttributeMeta("FromValueAttributeMetaMeta")
@interface ValueAttributeMetaMeta {
}
@ValueAttributeMetaMeta
static class ValueAttributeMetaMetaClass {
}
}
| {
"content_hash": "f6dcd2c66827ee9667e6576e6f4b7fb8",
"timestamp": "",
"source": "github",
"line_count": 1556,
"max_line_length": 171,
"avg_line_length": 39.830976863753214,
"alnum_prop": 0.7981831969924327,
"repo_name": "spring-projects/spring-framework",
"id": "c70c576559b5b3de97496e2011d10704c20c85b4",
"size": "62598",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "32003"
},
{
"name": "CSS",
"bytes": "1019"
},
{
"name": "Dockerfile",
"bytes": "257"
},
{
"name": "FreeMarker",
"bytes": "30820"
},
{
"name": "Groovy",
"bytes": "6902"
},
{
"name": "HTML",
"bytes": "1203"
},
{
"name": "Java",
"bytes": "43939386"
},
{
"name": "JavaScript",
"bytes": "280"
},
{
"name": "Kotlin",
"bytes": "571613"
},
{
"name": "PLpgSQL",
"bytes": "305"
},
{
"name": "Python",
"bytes": "254"
},
{
"name": "Ruby",
"bytes": "1060"
},
{
"name": "Shell",
"bytes": "5374"
},
{
"name": "Smarty",
"bytes": "700"
},
{
"name": "XSLT",
"bytes": "2945"
}
],
"symlink_target": ""
} |
package org.sosy_lab.java_smt.solvers.smtinterpol;
import de.uni_freiburg.informatik.ultimate.logic.FunctionSymbol;
import de.uni_freiburg.informatik.ultimate.logic.Script;
import de.uni_freiburg.informatik.ultimate.logic.Sort;
import de.uni_freiburg.informatik.ultimate.logic.Term;
import de.uni_freiburg.informatik.ultimate.logic.Theory;
import java.util.Collection;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import org.sosy_lab.java_smt.api.BooleanFormula;
import org.sosy_lab.java_smt.basicimpl.AbstractBooleanFormulaManager;
class SmtInterpolBooleanFormulaManager
extends AbstractBooleanFormulaManager<Term, Sort, Script, FunctionSymbol> {
// We use the Theory directly here because the methods there perform simplifications
// that we could not use otherwise.
private final Theory theory;
SmtInterpolBooleanFormulaManager(SmtInterpolFormulaCreator creator) {
super(creator);
theory = getFormulaCreator().getEnv().getTheory();
}
@Override
public Term makeVariableImpl(String varName) {
return formulaCreator.makeVariable(formulaCreator.getBoolType(), varName);
}
@Override
public Term makeBooleanImpl(boolean pValue) {
Term t;
if (pValue) {
t = theory.mTrue;
} else {
t = theory.mFalse;
}
return t;
}
@Override
public Term equivalence(Term t1, Term t2) {
assert t1.getTheory().getBooleanSort() == t1.getSort()
&& t2.getTheory().getBooleanSort() == t2.getSort()
: "Cannot make equivalence of non-boolean terms:\nTerm 1:\n"
+ t1.toStringDirect()
+ "\nTerm 2:\n"
+ t2.toStringDirect();
return theory.equals(t1, t2);
}
@Override
public boolean isTrue(Term t) {
return t.getTheory().mTrue == t;
}
@Override
public boolean isFalse(Term t) {
return t.getTheory().mFalse == t;
}
@Override
public Term ifThenElse(Term condition, Term t1, Term t2) {
return theory.ifthenelse(condition, t1, t2);
}
@Override
public Term not(Term pBits) {
return theory.not(pBits);
}
@Override
public Term and(Term pBits1, Term pBits2) {
return theory.and(pBits1, pBits2);
}
@Override
protected Term andImpl(Collection<Term> pParams) {
// SMTInterpol does all simplifications itself
return theory.and(pParams.toArray(new Term[0]));
}
@Override
public Collector<BooleanFormula, ?, BooleanFormula> toConjunction() {
return Collectors.collectingAndThen(Collectors.toList(), this::and);
}
@Override
public Term or(Term pBits1, Term pBits2) {
return theory.or(pBits1, pBits2);
}
@Override
protected Term orImpl(Collection<Term> pParams) {
// SMTInterpol does all simplifications itself
return theory.or(pParams.toArray(new Term[0]));
}
@Override
public Collector<BooleanFormula, ?, BooleanFormula> toDisjunction() {
return Collectors.collectingAndThen(Collectors.toList(), this::or);
}
@Override
public Term xor(Term pBits1, Term pBits2) {
return theory.xor(pBits1, pBits2);
}
@Override
protected Term implication(Term bits1, Term bits2) {
return theory.implies(bits1, bits2);
}
}
| {
"content_hash": "be1996c8a1c035f297a892ccfc35a4ad",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 86,
"avg_line_length": 27.789473684210527,
"alnum_prop": 0.7095959595959596,
"repo_name": "sosy-lab/java-smt",
"id": "9887a1b67835f9e5bb249ec3deb68b66202ce945",
"size": "3408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/sosy_lab/java_smt/solvers/smtinterpol/SmtInterpolBooleanFormulaManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "228119"
},
{
"name": "Dockerfile",
"bytes": "1150"
},
{
"name": "HTML",
"bytes": "494"
},
{
"name": "Java",
"bytes": "2405454"
},
{
"name": "Jinja",
"bytes": "291"
},
{
"name": "Python",
"bytes": "4291"
},
{
"name": "SMT",
"bytes": "625967"
},
{
"name": "Shell",
"bytes": "19780"
},
{
"name": "XSLT",
"bytes": "5693"
}
],
"symlink_target": ""
} |
namespace swift {
namespace markup {
class MarkupContext;
class MarkupASTNode;
class Paragraph;
class ParamField;
class ReturnsField;
class ThrowsField;
/// The basic structure of a doc comment attached to a Swift
/// declaration.
struct CommentParts {
Optional<const Paragraph *> Brief;
ArrayRef<const MarkupASTNode *> BodyNodes;
ArrayRef<ParamField *> ParamFields;
Optional<const ReturnsField *> ReturnsField;
Optional<const ThrowsField *> ThrowsField;
bool isEmpty() const {
return !Brief.hasValue() &&
!ReturnsField.hasValue() &&
!ThrowsField.hasValue() &&
BodyNodes.empty() &&
ParamFields.empty();
}
bool hasFunctionDocumentation() const {
return !ParamFields.empty() ||
ReturnsField.hasValue() ||
ThrowsField.hasValue();
}
};
#define MARKUP_AST_NODE(Id, Parent) class Id;
#define ABSTRACT_MARKUP_AST_NODE(Id, Parent) class Id;
#define MARKUP_AST_NODE_RANGE(Id, FirstId, LastId)
#include "swift/Markup/ASTNodes.def"
enum class ASTNodeKind : uint8_t {
#define MARKUP_AST_NODE(Id, Parent) Id,
#define ABSTRACT_MARKUP_AST_NODE(Id, Parent)
#define MARKUP_AST_NODE_RANGE(Id, FirstId, LastId) \
First_##Id = FirstId, Last_##Id = LastId,
#include "swift/Markup/ASTNodes.def"
};
class alignas(void *) MarkupASTNode {
MarkupASTNode(const MarkupASTNode &) = delete;
void operator=(const MarkupASTNode &) = delete;
protected:
ASTNodeKind Kind;
public:
MarkupASTNode(ASTNodeKind Kind) : Kind(Kind) {}
ASTNodeKind getKind() const { return Kind; }
void *operator new(size_t Bytes, MarkupContext &MC,
unsigned alignment = alignof(MarkupASTNode));
void *operator new(size_t Bytes, void *Mem) {
assert(Mem);
return Mem;
}
ArrayRef<MarkupASTNode *> getChildren();
ArrayRef<const MarkupASTNode *> getChildren() const;
void *operator new(size_t Bytes) = delete;
void operator delete(void *Data) = delete;
};
#pragma mark Markdown Nodes
class Document final : public MarkupASTNode,
private llvm::TrailingObjects<Document, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
Document(ArrayRef<MarkupASTNode*> Children);
public:
static Document *create(MarkupContext &MC,
ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Document;
}
};
class BlockQuote final : public MarkupASTNode,
private llvm::TrailingObjects<BlockQuote, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
BlockQuote(ArrayRef<MarkupASTNode *> Children);
public:
static BlockQuote *create(MarkupContext &MC, ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::BlockQuote;
}
};
class List final : public MarkupASTNode,
private llvm::TrailingObjects<List, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
bool Ordered;
List(ArrayRef<MarkupASTNode *> Children, bool IsOrdered);
public:
static List *create(MarkupContext &MC, ArrayRef<MarkupASTNode *> Items,
bool IsOrdered);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
void setChildren(ArrayRef<MarkupASTNode *> NewChildren) {
assert(NewChildren.size() <= NumChildren);
std::copy(NewChildren.begin(), NewChildren.end(),
getTrailingObjects<MarkupASTNode *>());
NumChildren = NewChildren.size();
}
bool isOrdered() const {
return Ordered;
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::List;
}
};
class Item final : public MarkupASTNode,
private llvm::TrailingObjects<Item, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
Item(ArrayRef<MarkupASTNode *> Children);
public:
static Item *create(MarkupContext &MC, ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Item;
}
};
class CodeBlock final : public MarkupASTNode {
StringRef LiteralContent;
StringRef Language;
CodeBlock(StringRef LiteralContent, StringRef Language)
: MarkupASTNode(ASTNodeKind::CodeBlock),
LiteralContent(LiteralContent),
Language(Language) {}
public:
static CodeBlock *create(MarkupContext &MC, StringRef LiteralContent,
StringRef Language);
StringRef getLiteralContent() const { return LiteralContent; };
StringRef getLanguage() const { return Language; };
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::CodeBlock;
}
};
class HTML final : public MarkupASTNode {
StringRef LiteralContent;
HTML(StringRef LiteralContent)
: MarkupASTNode(ASTNodeKind::HTML),
LiteralContent(LiteralContent) {}
public:
static HTML *create(MarkupContext &MC, StringRef LiteralContent);
StringRef getLiteralContent() const { return LiteralContent; };
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::HTML;
}
};
class Paragraph final : public MarkupASTNode,
private llvm::TrailingObjects<Paragraph, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
Paragraph(ArrayRef<MarkupASTNode *> Children);
public:
static Paragraph *create(MarkupContext &MC,
ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Paragraph;
}
};
class Header final : public MarkupASTNode,
private llvm::TrailingObjects<Header, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
unsigned Level;
Header(unsigned Level, ArrayRef<MarkupASTNode *> Children);
public:
static Header *create(MarkupContext &MC, unsigned Level,
ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
unsigned getLevel() const {
return Level;
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Header;
}
};
class HRule final : public MarkupASTNode {
HRule() : MarkupASTNode(ASTNodeKind::HRule) {}
public:
static HRule *create(MarkupContext &MC);
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::HRule;
}
};
class InlineContent : public MarkupASTNode {
public:
InlineContent(ASTNodeKind Kind) : MarkupASTNode(Kind) {}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() >= ASTNodeKind::First_Inline &&
N->getKind() <= ASTNodeKind::Last_Inline;
}
};
class Text final : public InlineContent {
StringRef LiteralContent;
Text(StringRef LiteralContent)
: InlineContent(ASTNodeKind::Text),
LiteralContent(LiteralContent) {}
public:
static Text *create(MarkupContext &MC, StringRef LiteralContent);
StringRef getLiteralContent() const { return LiteralContent; };
void setLiteralContent(StringRef LC) {
LiteralContent = LC;
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
StringRef str() const {
return LiteralContent;
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Text;
}
};
class SoftBreak final : public InlineContent {
SoftBreak() : InlineContent(ASTNodeKind::SoftBreak) {}
public:
static SoftBreak *create(MarkupContext &MC);
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
StringRef str() const {
return "\n";
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::SoftBreak;
}
};
class LineBreak final : public InlineContent {
LineBreak() : InlineContent(ASTNodeKind::LineBreak) {}
public:
static LineBreak *create(MarkupContext &MC);
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
StringRef str() const {
return "\n";
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::LineBreak;
}
};
class Code final : public InlineContent {
StringRef LiteralContent;
Code(StringRef LiteralContent)
: InlineContent(ASTNodeKind::Code),
LiteralContent(LiteralContent) {}
public:
static Code *create(MarkupContext &MC, StringRef LiteralContent);
StringRef getLiteralContent() const { return LiteralContent; };
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
StringRef str() const {
return LiteralContent;
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Code;
}
};
class InlineHTML final : public InlineContent {
StringRef LiteralContent;
InlineHTML(StringRef LiteralContent)
: InlineContent(ASTNodeKind::InlineHTML),
LiteralContent(LiteralContent) {}
public:
static InlineHTML *create(MarkupContext &MC, StringRef LiteralContent);
StringRef getLiteralContent() const { return LiteralContent; };
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
StringRef str() const {
return LiteralContent;
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::InlineHTML;
}
};
class Emphasis final : public InlineContent,
private llvm::TrailingObjects<Emphasis, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
Emphasis(ArrayRef<MarkupASTNode *> Children);
public:
static Emphasis *create(MarkupContext &MC,
ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Emphasis;
}
};
class Strong final : public InlineContent,
private llvm::TrailingObjects<Strong, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
Strong(ArrayRef<MarkupASTNode *> Children);
public:
static Strong *create(MarkupContext &MC,
ArrayRef<MarkupASTNode *> Children);
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Strong;
}
};
class Link final : public InlineContent,
private llvm::TrailingObjects<Link, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
StringRef Destination;
Link(StringRef Destination, ArrayRef<MarkupASTNode *> Children);
public:
static Link *create(MarkupContext &MC,
StringRef Destination,
ArrayRef<MarkupASTNode *> Children);
StringRef getDestination() const { return Destination; }
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Link;
}
};
class Image final : public InlineContent,
private llvm::TrailingObjects<Image, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
// FIXME: Hyperlink destinations can't be wrapped - use a Line
StringRef Destination;
Optional<StringRef> Title;
Image(StringRef Destination, Optional<StringRef> Title,
ArrayRef<MarkupASTNode *> Children);
public:
static Image *create(MarkupContext &MC,
StringRef Destination,
Optional<StringRef> Title,
ArrayRef<MarkupASTNode *> Children);
StringRef getDestination() const { return Destination; }
bool hasTitle() const {
return Title.hasValue();
}
StringRef getTitle() const {
return StringRef(Title.getValue());
}
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::Image;
}
};
#pragma mark Private Extensions
class PrivateExtension : public MarkupASTNode {
protected:
PrivateExtension(ASTNodeKind Kind)
: MarkupASTNode(Kind) {}
public:
ArrayRef<const MarkupASTNode *> getChildren() const {
return {};
}
ArrayRef<MarkupASTNode *> getChildren() {
return {};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() >= ASTNodeKind::First_Private &&
N->getKind() <= ASTNodeKind::Last_Private;
}
};
class ParamField final : public PrivateExtension,
private llvm::TrailingObjects<ParamField, MarkupASTNode *> {
friend TrailingObjects;
size_t NumChildren;
StringRef Name;
// Parameter fields can contain a substructure describing a
// function or closure parameter.
llvm::Optional<CommentParts> Parts;
ParamField(StringRef Name, ArrayRef<MarkupASTNode *> Children);
public:
static ParamField *create(MarkupContext &MC, StringRef Name,
ArrayRef<MarkupASTNode *> Children);
StringRef getName() const {
return Name;
}
llvm::Optional<CommentParts> getParts() const {
return Parts;
}
void setParts(CommentParts P) {
Parts = P;
}
bool isClosureParameter() const {
if (!Parts.hasValue())
return false;
return Parts.getValue().hasFunctionDocumentation();
}
ArrayRef<MarkupASTNode *> getChildren() {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
ArrayRef<const MarkupASTNode *> getChildren() const {
return {getTrailingObjects<MarkupASTNode *>(), NumChildren};
}
static bool classof(const MarkupASTNode *N) {
return N->getKind() == ASTNodeKind::ParamField;
}
};
#define MARKUP_SIMPLE_FIELD(Id, Keyword, XMLKind) \
class Id final : public PrivateExtension, \
private llvm::TrailingObjects<Id, MarkupASTNode *> { \
friend TrailingObjects; \
\
size_t NumChildren; \
\
Id(ArrayRef<MarkupASTNode *> Children);\
\
public: \
static Id *create(MarkupContext &MC, ArrayRef<MarkupASTNode *> Children); \
\
ArrayRef<MarkupASTNode *> getChildren() { \
return {getTrailingObjects<MarkupASTNode *>(), NumChildren}; \
} \
\
ArrayRef<const MarkupASTNode *> getChildren() const { \
return {getTrailingObjects<MarkupASTNode *>(), NumChildren}; \
} \
\
static bool classof(const MarkupASTNode *N) { \
return N->getKind() == ASTNodeKind::Id; \
} \
};
#include "swift/Markup/SimpleFields.def"
class MarkupASTWalker {
public:
void walk(const MarkupASTNode *Node) {
enter(Node);
switch(Node->getKind()) {
#define MARKUP_AST_NODE(Id, Parent) \
case ASTNodeKind::Id: \
visit##Id(static_cast<const Id*>(Node)); \
break;
#define ABSTRACT_MARKUP_AST_NODE(Id, Parent)
#define MARKUP_AST_NODE_RANGE(Id, FirstId, LastId)
#include "swift/Markup/ASTNodes.def"
}
if (shouldVisitChildrenOf(Node))
for (auto Child : Node->getChildren())
walk(Child);
exit(Node);
}
virtual bool shouldVisitChildrenOf(const MarkupASTNode *Node) {
return true;
}
virtual void enter(const MarkupASTNode *Node) {}
virtual void exit(const MarkupASTNode *Node) {}
#define MARKUP_AST_NODE(Id, Parent) \
virtual void visit##Id(const Id *Node) {}
#define ABSTRACT_MARKUP_AST_NODE(Id, Parent)
#define MARKUP_AST_NODE_RANGE(Id, FirstId, LastId)
#include "swift/Markup/ASTNodes.def"
virtual ~MarkupASTWalker() = default;
};
MarkupASTNode *createSimpleField(MarkupContext &MC, StringRef Tag,
ArrayRef<MarkupASTNode *> Children);
bool isAFieldTag(StringRef Tag);
void dump(const MarkupASTNode *Node, llvm::raw_ostream &OS, unsigned indent = 0);
void printInlinesUnder(const MarkupASTNode *Node, llvm::raw_ostream &OS,
bool PrintDecorators = false);
} // namespace markup
} // namespace swift
#endif // SWIFT_MARKUP_AST_H
| {
"content_hash": "55b6193bee8fa35c7068203ad784b3f3",
"timestamp": "",
"source": "github",
"line_count": 715,
"max_line_length": 83,
"avg_line_length": 25.834965034965034,
"alnum_prop": 0.6869315721091381,
"repo_name": "johnno1962d/swift",
"id": "e8d0ae756401f8166fe9e5b2116d841f1bb6e983",
"size": "19196",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "include/swift/Markup/AST.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "2024"
},
{
"name": "C",
"bytes": "49755"
},
{
"name": "C++",
"bytes": "19221541"
},
{
"name": "CMake",
"bytes": "247115"
},
{
"name": "D",
"bytes": "1686"
},
{
"name": "DTrace",
"bytes": "1857"
},
{
"name": "Emacs Lisp",
"bytes": "34021"
},
{
"name": "LLVM",
"bytes": "49912"
},
{
"name": "Makefile",
"bytes": "1841"
},
{
"name": "Objective-C",
"bytes": "184594"
},
{
"name": "Objective-C++",
"bytes": "156991"
},
{
"name": "Perl",
"bytes": "2219"
},
{
"name": "Python",
"bytes": "386980"
},
{
"name": "Ruby",
"bytes": "2091"
},
{
"name": "Shell",
"bytes": "130030"
},
{
"name": "Swift",
"bytes": "12594303"
},
{
"name": "VimL",
"bytes": "11829"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: james
* Date: 20/03/2014
* Time: 23:29
*/
namespace Swifty\Spotify;
class APITest extends \PHPUnit_Framework_TestCase {
/**
* test the basic setters and getters
*/
public function testSettersAndGetters()
{
$lib = new API('lookup',1);
$version = 1;
$service = 'lookup';
$url = 'http://example.com';
$endpoint = 'test';
$this->assertInstanceOf('Swifty\Spotify\API', $lib->setApiVersion($version));
$this->assertInstanceOf('Swifty\Spotify\API', $lib->setService($service));
$this->assertInstanceOf('Swifty\Spotify\API', $lib->setUrl($url));
$this->assertInstanceOf('Swifty\Spotify\API', $lib->setEndpoint($endpoint));
$this->assertEquals($service, $lib->getService());
$this->assertEquals($version, $lib->getApiVersion());
$this->assertEquals($url, $lib->getUrl());
$this->assertEquals($endpoint, $lib->getEndpoint());
}
/**
* test to add, remove and get parameter methods
*/
public function testParams()
{
$lib = new API('lookup',1);
$this->assertInstanceOf('Swifty\Spotify\API', $lib->addParam('uri','test'));
$this->assertInstanceOf('Swifty\Spotify\API', $lib->addParam('user','fred'));
//check getParams is an array with both the params we added
$this->assertEquals(array('uri'=>'test','user'=>'fred'), $lib->getParams());
//test removing a param
$this->assertInstanceOf('Swifty\Spotify\API', $lib->removeParam('uri'));
//test element is missing from array after removeParam
$this->assertEquals(array('user'=>'fred'), $lib->getParams());
}
}
| {
"content_hash": "453727890306c0c7e66080d85cd38a9f",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 85,
"avg_line_length": 30.120689655172413,
"alnum_prop": 0.5975958786491128,
"repo_name": "irvingswiftj/spotifyLib",
"id": "0249f1e3805504a447cccc302cfab2376046304a",
"size": "1747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/APITest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "30628"
}
],
"symlink_target": ""
} |
require 'set'
class CalendarDate < ActiveRecord::Base
extend ScheduleFu::Finder
has_many :event_dates, :class_name=>'CalendarEventDate', :readonly => true
has_many :events, :through => :event_dates
validates_presence_of :value
validates_inclusion_of :weekday, :in => 0..6
validates_inclusion_of :monthday, :in => 1..31
validates_inclusion_of :monthweek, :in => 0..4
validates_inclusion_of :month, :in => 1..12
before_validation :derive_date_parts, :on => :create
scope :by_dates, lambda {|*args| {:conditions => conditions_for_date_finders(*args)}}
scope :by_values, lambda{|*args| {:conditions => ["value in (?)", args]}}
def self.find_by_value(value)
find(:first, :conditions => { :value => value })
end
def self.create_for_dates(start_date = nil, end_date = nil)
start_date ||= Date.today
end_date ||= 5.years.since(start_date)
range = start_date..end_date
existing_dates = Set.new
self.by_dates(range).each {|d| existing_dates << d.value }
range.each do |date|
begin
self.create(:value => date) unless existing_dates.include?(date)
rescue; end
end
end
def self.create_for_date(date)
self.create_for_dates(date, date)
end
@@create_lock = Mutex.new
def self.get_and_create_dates(range)
range = range.first.to_date..range.last.to_date
dates = self.by_dates(range)
if dates.size < range.to_a.size
CalendarDate.create_for_dates(range.first, range.last)
Thread.new do
start_date = 1.year.ago(range.first).to_date
end_date = 1.year.since(range.last).to_date
@@create_lock.synchronize do
CalendarDate.create_for_dates(start_date, end_date)
end
end
dates = self.by_dates(range)
end
dates
end
private
def derive_date_parts
self.weekday = value.wday
self.monthday = value.mday
self.monthweek = (monthday - 1) / 7
date = value
self.month = date.month
days_until_next_month = 0
while date = date.next
days_until_next_month += 1
break if date.month != self.month
end
if days_until_next_month <= 7
self.lastweek = true
end
end
end
| {
"content_hash": "df0f0eda437acd4601df48ad5287d6e3",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 87,
"avg_line_length": 28.776315789473685,
"alnum_prop": 0.6401463191586648,
"repo_name": "angelic/schedule_fu",
"id": "023f0cfdd865d78311c0c2cb2d597958b7291917",
"size": "2187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/calendar_date.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "67190"
}
],
"symlink_target": ""
} |
/* Make GCC agree with types.h. */
#undef SIZE_TYPE
#undef PTRDIFF_TYPE
#define SIZE_TYPE "unsigned int"
#define PTRDIFF_TYPE "int"
#undef TARGET_OS_CPP_BUILTINS
#define TARGET_OS_CPP_BUILTINS() \
do \
{ \
if (!c_dialect_cxx () && !flag_iso) \
{ \
builtin_define ("hppa"); \
builtin_define_std ("PWB"); \
} \
builtin_define ("__pro__"); \
builtin_assert ("system=pro"); \
} \
while (0)
/* Like the default, except no -lg. */
#undef LIB_SPEC
#define LIB_SPEC "%{!p:%{!pg:-lc}}%{p: -L/lib/libp/ -lc}%{pg: -L/lib/libp/ -lc}"
/* hpux8 and later have C++ compatible include files, so do not
pretend they are `extern "C"'. */
#define NO_IMPLICIT_EXTERN_C
/* We don't want a crt0.o to get linked in automatically, we want the
linker script to pull it in. */
#undef STARTFILE_SPEC
#define STARTFILE_SPEC ""
/* We need to override the following two macros defined in elfos.h since
the .comm directive has a different syntax and it can't be used for
local common symbols. */
#undef ASM_OUTPUT_ALIGNED_COMMON
#define ASM_OUTPUT_ALIGNED_COMMON(FILE, NAME, SIZE, ALIGN) \
pa_asm_output_aligned_common (FILE, NAME, SIZE, ALIGN)
#undef ASM_OUTPUT_ALIGNED_LOCAL
#define ASM_OUTPUT_ALIGNED_LOCAL(FILE, NAME, SIZE, ALIGN) \
pa_asm_output_aligned_local (FILE, NAME, SIZE, ALIGN)
| {
"content_hash": "c0f1cc0f27d9ce8d0ec3a466f18d12a8",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 80,
"avg_line_length": 29.91304347826087,
"alnum_prop": 0.6366279069767442,
"repo_name": "shaotuanchen/sunflower_exp",
"id": "7d5fc79a26dcb03b884475ddfc52388e9cdec3b5",
"size": "2142",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "tools/source/gcc-4.2.4/gcc/config/pa/pa-pro-end.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "459993"
},
{
"name": "Awk",
"bytes": "6562"
},
{
"name": "Batchfile",
"bytes": "9028"
},
{
"name": "C",
"bytes": "50326113"
},
{
"name": "C++",
"bytes": "2040239"
},
{
"name": "CSS",
"bytes": "2355"
},
{
"name": "Clarion",
"bytes": "2484"
},
{
"name": "Coq",
"bytes": "61440"
},
{
"name": "DIGITAL Command Language",
"bytes": "69150"
},
{
"name": "Emacs Lisp",
"bytes": "186910"
},
{
"name": "Fortran",
"bytes": "5364"
},
{
"name": "HTML",
"bytes": "2171356"
},
{
"name": "JavaScript",
"bytes": "27164"
},
{
"name": "Logos",
"bytes": "159114"
},
{
"name": "M",
"bytes": "109006"
},
{
"name": "M4",
"bytes": "100614"
},
{
"name": "Makefile",
"bytes": "5409865"
},
{
"name": "Mercury",
"bytes": "702"
},
{
"name": "Module Management System",
"bytes": "56956"
},
{
"name": "OCaml",
"bytes": "253115"
},
{
"name": "Objective-C",
"bytes": "57800"
},
{
"name": "Papyrus",
"bytes": "3298"
},
{
"name": "Perl",
"bytes": "70992"
},
{
"name": "Perl 6",
"bytes": "693"
},
{
"name": "PostScript",
"bytes": "3440120"
},
{
"name": "Python",
"bytes": "40729"
},
{
"name": "Redcode",
"bytes": "1140"
},
{
"name": "Roff",
"bytes": "3794721"
},
{
"name": "SAS",
"bytes": "56770"
},
{
"name": "SRecode Template",
"bytes": "540157"
},
{
"name": "Shell",
"bytes": "1560436"
},
{
"name": "Smalltalk",
"bytes": "10124"
},
{
"name": "Standard ML",
"bytes": "1212"
},
{
"name": "TeX",
"bytes": "385584"
},
{
"name": "WebAssembly",
"bytes": "52904"
},
{
"name": "Yacc",
"bytes": "510934"
}
],
"symlink_target": ""
} |
namespace llvm {
class ModuleSummaryIndex;
class Module;
namespace object {
class ObjectFile;
/// This class is used to read just the module summary index related
/// sections out of the given object (which may contain a single module's
/// bitcode or be a combined index bitcode file). It builds a ModuleSummaryIndex
/// object.
class ModuleSummaryIndexObjectFile : public SymbolicFile {
std::unique_ptr<ModuleSummaryIndex> Index;
public:
ModuleSummaryIndexObjectFile(MemoryBufferRef Object,
std::unique_ptr<ModuleSummaryIndex> I);
~ModuleSummaryIndexObjectFile() override;
// TODO: Walk through GlobalValueMap entries for symbols.
// However, currently these interfaces are not used by any consumers.
void moveSymbolNext(DataRefImpl &Symb) const override {
llvm_unreachable("not implemented");
}
std::error_code printSymbolName(raw_ostream &OS,
DataRefImpl Symb) const override {
llvm_unreachable("not implemented");
return std::error_code();
}
uint32_t getSymbolFlags(DataRefImpl Symb) const override {
llvm_unreachable("not implemented");
return 0;
}
basic_symbol_iterator symbol_begin() const override {
llvm_unreachable("not implemented");
return basic_symbol_iterator(BasicSymbolRef());
}
basic_symbol_iterator symbol_end() const override {
llvm_unreachable("not implemented");
return basic_symbol_iterator(BasicSymbolRef());
}
const ModuleSummaryIndex &getIndex() const {
return const_cast<ModuleSummaryIndexObjectFile *>(this)->getIndex();
}
ModuleSummaryIndex &getIndex() { return *Index; }
std::unique_ptr<ModuleSummaryIndex> takeIndex();
static inline bool classof(const Binary *v) {
return v->isModuleSummaryIndex();
}
/// \brief Finds and returns bitcode embedded in the given object file, or an
/// error code if not found.
static ErrorOr<MemoryBufferRef> findBitcodeInObject(const ObjectFile &Obj);
/// \brief Finds and returns bitcode in the given memory buffer (which may
/// be either a bitcode file or a native object file with embedded bitcode),
/// or an error code if not found.
static ErrorOr<MemoryBufferRef>
findBitcodeInMemBuffer(MemoryBufferRef Object);
/// \brief Parse module summary index in the given memory buffer.
/// Return new ModuleSummaryIndexObjectFile instance containing parsed module
/// summary/index.
static Expected<std::unique_ptr<ModuleSummaryIndexObjectFile>>
create(MemoryBufferRef Object);
};
}
/// Parse the module summary index out of an IR file and return the module
/// summary index object if found, or nullptr if not.
Expected<std::unique_ptr<ModuleSummaryIndex>>
getModuleSummaryIndexForFile(StringRef Path);
}
#endif
| {
"content_hash": "d369d1c2880f1e6dc7d66bbde76f170b",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 80,
"avg_line_length": 35.883116883116884,
"alnum_prop": 0.7343467245747376,
"repo_name": "ensemblr/llvm-project-boilerplate",
"id": "6205927039dcd7684a2e3db1c4c5cf023d94915b",
"size": "3439",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "include/llvm/include/llvm/Object/ModuleSummaryIndexObjectFile.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "32"
},
{
"name": "AppleScript",
"bytes": "1429"
},
{
"name": "Assembly",
"bytes": "15649629"
},
{
"name": "Awk",
"bytes": "1747037"
},
{
"name": "Batchfile",
"bytes": "34481"
},
{
"name": "Brainfuck",
"bytes": "284"
},
{
"name": "C",
"bytes": "85584624"
},
{
"name": "C#",
"bytes": "20737"
},
{
"name": "C++",
"bytes": "168418524"
},
{
"name": "CMake",
"bytes": "1174816"
},
{
"name": "CSS",
"bytes": "49900"
},
{
"name": "Cuda",
"bytes": "414703"
},
{
"name": "Emacs Lisp",
"bytes": "110018"
},
{
"name": "Forth",
"bytes": "1490"
},
{
"name": "Fortran",
"bytes": "356707"
},
{
"name": "GAP",
"bytes": "6167"
},
{
"name": "Go",
"bytes": "132137"
},
{
"name": "HTML",
"bytes": "1751124"
},
{
"name": "JavaScript",
"bytes": "141512"
},
{
"name": "LLVM",
"bytes": "62219250"
},
{
"name": "Limbo",
"bytes": "7437"
},
{
"name": "Logos",
"bytes": "1572537943"
},
{
"name": "Lua",
"bytes": "86606"
},
{
"name": "M",
"bytes": "2008"
},
{
"name": "M4",
"bytes": "109560"
},
{
"name": "Makefile",
"bytes": "616437"
},
{
"name": "Mathematica",
"bytes": "7845"
},
{
"name": "Matlab",
"bytes": "53817"
},
{
"name": "Mercury",
"bytes": "1194"
},
{
"name": "Mirah",
"bytes": "1079943"
},
{
"name": "OCaml",
"bytes": "407143"
},
{
"name": "Objective-C",
"bytes": "5910944"
},
{
"name": "Objective-C++",
"bytes": "1720450"
},
{
"name": "OpenEdge ABL",
"bytes": "690534"
},
{
"name": "PHP",
"bytes": "15986"
},
{
"name": "POV-Ray SDL",
"bytes": "19471"
},
{
"name": "Perl",
"bytes": "591927"
},
{
"name": "PostScript",
"bytes": "845774"
},
{
"name": "Protocol Buffer",
"bytes": "20013"
},
{
"name": "Python",
"bytes": "1895427"
},
{
"name": "QMake",
"bytes": "15580"
},
{
"name": "RenderScript",
"bytes": "741"
},
{
"name": "Roff",
"bytes": "94555"
},
{
"name": "Rust",
"bytes": "200"
},
{
"name": "Scheme",
"bytes": "2654"
},
{
"name": "Shell",
"bytes": "1144090"
},
{
"name": "Smalltalk",
"bytes": "144607"
},
{
"name": "SourcePawn",
"bytes": "1544"
},
{
"name": "Standard ML",
"bytes": "2841"
},
{
"name": "Tcl",
"bytes": "8285"
},
{
"name": "TeX",
"bytes": "320484"
},
{
"name": "Vim script",
"bytes": "17239"
},
{
"name": "Yacc",
"bytes": "163484"
}
],
"symlink_target": ""
} |
using BooksServiceSample.Models;
using System;
using System.Collections.Generic;
namespace BooksServiceSample.Services
{
public interface IBookChaptersService
{
void Add(BookChapter bookChapter);
void AddRange(IEnumerable<BookChapter> chapters);
IEnumerable<BookChapter> GetAll();
BookChapter Find(Guid id);
BookChapter Remove(Guid id);
void Update(BookChapter bookChapter);
}
}
| {
"content_hash": "986ccf463164576dc52e2266b4174807",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 57,
"avg_line_length": 27.5625,
"alnum_prop": 0.7120181405895691,
"repo_name": "ProfessionalCSharp/ProfessionalCSharp7",
"id": "23566a444b5809f86aa1e662f4c46d705d319f03",
"size": "443",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "API/Sync/BooksServiceSample/BookServices/Services/IBookChaptersService.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "210"
},
{
"name": "Batchfile",
"bytes": "21458"
},
{
"name": "C#",
"bytes": "1710305"
},
{
"name": "CSS",
"bytes": "8195"
},
{
"name": "Dockerfile",
"bytes": "439"
},
{
"name": "HTML",
"bytes": "199109"
},
{
"name": "JavaScript",
"bytes": "214593"
},
{
"name": "TypeScript",
"bytes": "9812"
}
],
"symlink_target": ""
} |
#include "config.h"
#if defined(POLARSSL_CIPHER_C)
#include "polarssl/cipher_wrap.h"
#if defined(POLARSSL_AES_C)
#include "polarssl/aes.h"
#endif
#if defined(POLARSSL_CAMELLIA_C)
#include "polarssl/camellia.h"
#endif
#if defined(POLARSSL_DES_C)
#include "polarssl/des.h"
#endif
#if defined(POLARSSL_BLOWFISH_C)
#include "polarssl/blowfish.h"
#endif
#include <stdlib.h>
#if defined(POLARSSL_AES_C)
int aes_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return aes_crypt_cbc( (aes_context *) ctx, operation, length, iv, input, output );
}
int aes_crypt_cfb128_wrap( void *ctx, operation_t operation, size_t length,
size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CFB)
return aes_crypt_cfb128( (aes_context *) ctx, operation, length, iv_off, iv, input, output );
#else
((void) ctx);
((void) operation);
((void) length);
((void) iv_off);
((void) iv);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int aes_crypt_ctr_wrap( void *ctx, size_t length,
size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CTR)
return aes_crypt_ctr( (aes_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output );
#else
((void) ctx);
((void) length);
((void) nc_off);
((void) nonce_counter);
((void) stream_block);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int aes_setkey_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return aes_setkey_dec( (aes_context *) ctx, key, key_length );
}
int aes_setkey_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return aes_setkey_enc( (aes_context *) ctx, key, key_length );
}
static void * aes_ctx_alloc( void )
{
return malloc( sizeof( aes_context ) );
}
static void aes_ctx_free( void *ctx )
{
free( ctx );
}
const cipher_base_t aes_info = {
POLARSSL_CIPHER_ID_AES,
aes_crypt_cbc_wrap,
aes_crypt_cfb128_wrap,
aes_crypt_ctr_wrap,
aes_setkey_enc_wrap,
aes_setkey_dec_wrap,
aes_ctx_alloc,
aes_ctx_free
};
const cipher_info_t aes_128_cbc_info = {
POLARSSL_CIPHER_AES_128_CBC,
POLARSSL_MODE_CBC,
128,
"AES-128-CBC",
16,
16,
&aes_info
};
const cipher_info_t aes_192_cbc_info = {
POLARSSL_CIPHER_AES_192_CBC,
POLARSSL_MODE_CBC,
192,
"AES-192-CBC",
16,
16,
&aes_info
};
const cipher_info_t aes_256_cbc_info = {
POLARSSL_CIPHER_AES_256_CBC,
POLARSSL_MODE_CBC,
256,
"AES-256-CBC",
16,
16,
&aes_info
};
#if defined(POLARSSL_CIPHER_MODE_CFB)
const cipher_info_t aes_128_cfb128_info = {
POLARSSL_CIPHER_AES_128_CFB128,
POLARSSL_MODE_CFB,
128,
"AES-128-CFB128",
16,
16,
&aes_info
};
const cipher_info_t aes_192_cfb128_info = {
POLARSSL_CIPHER_AES_192_CFB128,
POLARSSL_MODE_CFB,
192,
"AES-192-CFB128",
16,
16,
&aes_info
};
const cipher_info_t aes_256_cfb128_info = {
POLARSSL_CIPHER_AES_256_CFB128,
POLARSSL_MODE_CFB,
256,
"AES-256-CFB128",
16,
16,
&aes_info
};
#endif /* POLARSSL_CIPHER_MODE_CFB */
#if defined(POLARSSL_CIPHER_MODE_CTR)
const cipher_info_t aes_128_ctr_info = {
POLARSSL_CIPHER_AES_128_CTR,
POLARSSL_MODE_CTR,
128,
"AES-128-CTR",
16,
16,
&aes_info
};
const cipher_info_t aes_192_ctr_info = {
POLARSSL_CIPHER_AES_192_CTR,
POLARSSL_MODE_CTR,
192,
"AES-192-CTR",
16,
16,
&aes_info
};
const cipher_info_t aes_256_ctr_info = {
POLARSSL_CIPHER_AES_256_CTR,
POLARSSL_MODE_CTR,
256,
"AES-256-CTR",
16,
16,
&aes_info
};
#endif /* POLARSSL_CIPHER_MODE_CTR */
#endif
#if defined(POLARSSL_CAMELLIA_C)
int camellia_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return camellia_crypt_cbc( (camellia_context *) ctx, operation, length, iv, input, output );
}
int camellia_crypt_cfb128_wrap( void *ctx, operation_t operation, size_t length,
size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CFB)
return camellia_crypt_cfb128( (camellia_context *) ctx, operation, length, iv_off, iv, input, output );
#else
((void) ctx);
((void) operation);
((void) length);
((void) iv_off);
((void) iv);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int camellia_crypt_ctr_wrap( void *ctx, size_t length,
size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CTR)
return camellia_crypt_ctr( (camellia_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output );
#else
((void) ctx);
((void) length);
((void) nc_off);
((void) nonce_counter);
((void) stream_block);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int camellia_setkey_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return camellia_setkey_dec( (camellia_context *) ctx, key, key_length );
}
int camellia_setkey_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return camellia_setkey_enc( (camellia_context *) ctx, key, key_length );
}
static void * camellia_ctx_alloc( void )
{
return malloc( sizeof( camellia_context ) );
}
static void camellia_ctx_free( void *ctx )
{
free( ctx );
}
const cipher_base_t camellia_info = {
POLARSSL_CIPHER_ID_CAMELLIA,
camellia_crypt_cbc_wrap,
camellia_crypt_cfb128_wrap,
camellia_crypt_ctr_wrap,
camellia_setkey_enc_wrap,
camellia_setkey_dec_wrap,
camellia_ctx_alloc,
camellia_ctx_free
};
const cipher_info_t camellia_128_cbc_info = {
POLARSSL_CIPHER_CAMELLIA_128_CBC,
POLARSSL_MODE_CBC,
128,
"CAMELLIA-128-CBC",
16,
16,
&camellia_info
};
const cipher_info_t camellia_192_cbc_info = {
POLARSSL_CIPHER_CAMELLIA_192_CBC,
POLARSSL_MODE_CBC,
192,
"CAMELLIA-192-CBC",
16,
16,
&camellia_info
};
const cipher_info_t camellia_256_cbc_info = {
POLARSSL_CIPHER_CAMELLIA_256_CBC,
POLARSSL_MODE_CBC,
256,
"CAMELLIA-256-CBC",
16,
16,
&camellia_info
};
#if defined(POLARSSL_CIPHER_MODE_CFB)
const cipher_info_t camellia_128_cfb128_info = {
POLARSSL_CIPHER_CAMELLIA_128_CFB128,
POLARSSL_MODE_CFB,
128,
"CAMELLIA-128-CFB128",
16,
16,
&camellia_info
};
const cipher_info_t camellia_192_cfb128_info = {
POLARSSL_CIPHER_CAMELLIA_192_CFB128,
POLARSSL_MODE_CFB,
192,
"CAMELLIA-192-CFB128",
16,
16,
&camellia_info
};
const cipher_info_t camellia_256_cfb128_info = {
POLARSSL_CIPHER_CAMELLIA_256_CFB128,
POLARSSL_MODE_CFB,
256,
"CAMELLIA-256-CFB128",
16,
16,
&camellia_info
};
#endif /* POLARSSL_CIPHER_MODE_CFB */
#if defined(POLARSSL_CIPHER_MODE_CTR)
const cipher_info_t camellia_128_ctr_info = {
POLARSSL_CIPHER_CAMELLIA_128_CTR,
POLARSSL_MODE_CTR,
128,
"CAMELLIA-128-CTR",
16,
16,
&camellia_info
};
const cipher_info_t camellia_192_ctr_info = {
POLARSSL_CIPHER_CAMELLIA_192_CTR,
POLARSSL_MODE_CTR,
192,
"CAMELLIA-192-CTR",
16,
16,
&camellia_info
};
const cipher_info_t camellia_256_ctr_info = {
POLARSSL_CIPHER_CAMELLIA_256_CTR,
POLARSSL_MODE_CTR,
256,
"CAMELLIA-256-CTR",
16,
16,
&camellia_info
};
#endif /* POLARSSL_CIPHER_MODE_CTR */
#endif
#if defined(POLARSSL_DES_C)
int des_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return des_crypt_cbc( (des_context *) ctx, operation, length, iv, input, output );
}
int des3_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return des3_crypt_cbc( (des3_context *) ctx, operation, length, iv, input, output );
}
int des_crypt_cfb128_wrap( void *ctx, operation_t operation, size_t length,
size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output )
{
((void) ctx);
((void) operation);
((void) length);
((void) iv_off);
((void) iv);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
int des_crypt_ctr_wrap( void *ctx, size_t length,
size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
((void) ctx);
((void) length);
((void) nc_off);
((void) nonce_counter);
((void) stream_block);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
int des_setkey_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des_setkey_dec( (des_context *) ctx, key );
}
int des_setkey_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des_setkey_enc( (des_context *) ctx, key );
}
int des3_set2key_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des3_set2key_dec( (des3_context *) ctx, key );
}
int des3_set2key_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des3_set2key_enc( (des3_context *) ctx, key );
}
int des3_set3key_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des3_set3key_dec( (des3_context *) ctx, key );
}
int des3_set3key_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
((void) key_length);
return des3_set3key_enc( (des3_context *) ctx, key );
}
static void * des_ctx_alloc( void )
{
return malloc( sizeof( des_context ) );
}
static void * des3_ctx_alloc( void )
{
return malloc( sizeof( des3_context ) );
}
static void des_ctx_free( void *ctx )
{
free( ctx );
}
const cipher_base_t des_info = {
POLARSSL_CIPHER_ID_DES,
des_crypt_cbc_wrap,
des_crypt_cfb128_wrap,
des_crypt_ctr_wrap,
des_setkey_enc_wrap,
des_setkey_dec_wrap,
des_ctx_alloc,
des_ctx_free
};
const cipher_info_t des_cbc_info = {
POLARSSL_CIPHER_DES_CBC,
POLARSSL_MODE_CBC,
POLARSSL_KEY_LENGTH_DES,
"DES-CBC",
8,
8,
&des_info
};
const cipher_base_t des_ede_info = {
POLARSSL_CIPHER_ID_DES,
des3_crypt_cbc_wrap,
des_crypt_cfb128_wrap,
des_crypt_ctr_wrap,
des3_set2key_enc_wrap,
des3_set2key_dec_wrap,
des3_ctx_alloc,
des_ctx_free
};
const cipher_info_t des_ede_cbc_info = {
POLARSSL_CIPHER_DES_EDE_CBC,
POLARSSL_MODE_CBC,
POLARSSL_KEY_LENGTH_DES_EDE,
"DES-EDE-CBC",
8,
8,
&des_ede_info
};
const cipher_base_t des_ede3_info = {
POLARSSL_CIPHER_ID_DES,
des3_crypt_cbc_wrap,
des_crypt_cfb128_wrap,
des_crypt_ctr_wrap,
des3_set3key_enc_wrap,
des3_set3key_dec_wrap,
des3_ctx_alloc,
des_ctx_free
};
const cipher_info_t des_ede3_cbc_info = {
POLARSSL_CIPHER_DES_EDE3_CBC,
POLARSSL_MODE_CBC,
POLARSSL_KEY_LENGTH_DES_EDE3,
"DES-EDE3-CBC",
8,
8,
&des_ede3_info
};
#endif
#if defined(POLARSSL_BLOWFISH_C)
int blowfish_crypt_cbc_wrap( void *ctx, operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return blowfish_crypt_cbc( (blowfish_context *) ctx, operation, length, iv, input, output );
}
int blowfish_crypt_cfb64_wrap( void *ctx, operation_t operation, size_t length,
size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CFB)
return blowfish_crypt_cfb64( (blowfish_context *) ctx, operation, length, iv_off, iv, input, output );
#else
((void) ctx);
((void) operation);
((void) length);
((void) iv_off);
((void) iv);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int blowfish_crypt_ctr_wrap( void *ctx, size_t length,
size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
#if defined(POLARSSL_CIPHER_MODE_CTR)
return blowfish_crypt_ctr( (blowfish_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output );
#else
((void) ctx);
((void) length);
((void) nc_off);
((void) nonce_counter);
((void) stream_block);
((void) input);
((void) output);
return POLARSSL_ERR_CIPHER_FEATURE_UNAVAILABLE;
#endif
}
int blowfish_setkey_dec_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return blowfish_setkey( (blowfish_context *) ctx, key, key_length );
}
int blowfish_setkey_enc_wrap( void *ctx, const unsigned char *key, unsigned int key_length )
{
return blowfish_setkey( (blowfish_context *) ctx, key, key_length );
}
static void * blowfish_ctx_alloc( void )
{
return malloc( sizeof( blowfish_context ) );
}
static void blowfish_ctx_free( void *ctx )
{
free( ctx );
}
const cipher_base_t blowfish_info = {
POLARSSL_CIPHER_ID_BLOWFISH,
blowfish_crypt_cbc_wrap,
blowfish_crypt_cfb64_wrap,
blowfish_crypt_ctr_wrap,
blowfish_setkey_enc_wrap,
blowfish_setkey_dec_wrap,
blowfish_ctx_alloc,
blowfish_ctx_free
};
const cipher_info_t blowfish_cbc_info = {
POLARSSL_CIPHER_BLOWFISH_CBC,
POLARSSL_MODE_CBC,
128,
"BLOWFISH-CBC",
8,
8,
&blowfish_info
};
#if defined(POLARSSL_CIPHER_MODE_CFB)
const cipher_info_t blowfish_cfb64_info = {
POLARSSL_CIPHER_BLOWFISH_CFB64,
POLARSSL_MODE_CFB,
128,
"BLOWFISH-CFB64",
8,
8,
&blowfish_info
};
#endif /* POLARSSL_CIPHER_MODE_CFB */
#if defined(POLARSSL_CIPHER_MODE_CTR)
const cipher_info_t blowfish_ctr_info = {
POLARSSL_CIPHER_BLOWFISH_CTR,
POLARSSL_MODE_CTR,
128,
"BLOWFISH-CTR",
8,
8,
&blowfish_info
};
#endif /* POLARSSL_CIPHER_MODE_CTR */
#endif /* POLARSSL_BLOWFISH_C */
#if defined(POLARSSL_CIPHER_NULL_CIPHER)
static void * null_ctx_alloc( void )
{
return (void *) 1;
}
static void null_ctx_free( void *ctx )
{
((void) ctx);
}
const cipher_base_t null_base_info = {
POLARSSL_CIPHER_ID_NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
null_ctx_alloc,
null_ctx_free
};
const cipher_info_t null_cipher_info = {
POLARSSL_CIPHER_NULL,
POLARSSL_MODE_NULL,
0,
"NULL",
1,
1,
&null_base_info
};
#endif /* defined(POLARSSL_CIPHER_NULL_CIPHER) */
#endif
| {
"content_hash": "eb28572b722e4294edd33009ff2a6440",
"timestamp": "",
"source": "github",
"line_count": 684,
"max_line_length": 107,
"avg_line_length": 22.450292397660817,
"alnum_prop": 0.6408569940088564,
"repo_name": "redfern314/uplink",
"id": "08adbb55639655a06c31170c90246c01ba2f14e9",
"size": "16423",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "device/Middlewares/Third_Party/PolarSSL/library/cipher_wrap.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "943956"
},
{
"name": "C",
"bytes": "34250844"
},
{
"name": "C++",
"bytes": "663798"
},
{
"name": "CSS",
"bytes": "139339"
},
{
"name": "JavaScript",
"bytes": "503263"
},
{
"name": "Makefile",
"bytes": "22045"
},
{
"name": "Objective-C",
"bytes": "1804"
},
{
"name": "Perl",
"bytes": "22806"
},
{
"name": "Prolog",
"bytes": "1856"
},
{
"name": "Python",
"bytes": "798"
},
{
"name": "Shell",
"bytes": "23522"
},
{
"name": "Tcl",
"bytes": "72"
}
],
"symlink_target": ""
} |
package io.github.exaberries.boa.command;
import java.util.ArrayList;
import io.github.exaberries.boa.fixture.Fixture;
import io.github.exaberries.boa.show.CueData;
public class FixtureAttributeCommand implements Command {
private ArrayList<Fixture> fixtures;
private CueData data;
public FixtureAttributeCommand(ArrayList<Fixture> fixtures, CueData data) {
this.fixtures = fixtures;
this.data = data;
}
public ArrayList<Fixture> getFixtures() {
return fixtures;
}
public CueData getData() {
return data;
}
} | {
"content_hash": "329f3309a73d1b6c1295ffbfab43c679",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 76,
"avg_line_length": 22.166666666666668,
"alnum_prop": 0.7706766917293233,
"repo_name": "ExaBerries/litan",
"id": "7ff62736f8f2352d3336be2693fc068fcc56d379",
"size": "532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/github/exaberries/boa/command/FixtureAttributeCommand.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5988"
},
{
"name": "Java",
"bytes": "109411"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ac649602ae2cea01c4cfd2e5dc1a0502",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "04950f09f8b16afe2963398d227b649c8d959dc9",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malvales/Malvaceae/Hibiscus/Hibiscus cucurbitaceus/Hibiscus cucurbitaceus cucurbitaceus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
name "ohai"
default_version "master"
source git: "https://github.com/opscode/ohai.git"
relative_path "ohai"
dependency "ruby"
dependency "rubygems"
dependency "bundler"
build do
env = with_standard_compiler_flags(with_embedded_path)
bundle "install --without development", env: env
gem "build ohai.gemspec", env: env
gem "install ohai*.gem" \
" --no-ri --no-rdoc", env: env
end
| {
"content_hash": "87f906713955cb105fdae3a99489adc6",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 56,
"avg_line_length": 19.9,
"alnum_prop": 0.7010050251256281,
"repo_name": "3ofcoins/chef-omnibus-software",
"id": "00265da4918b897dbd988ee7a9a34441705658cc",
"size": "1047",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/software/ohai.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "829"
},
{
"name": "C++",
"bytes": "1257"
},
{
"name": "HTML",
"bytes": "999"
},
{
"name": "Ruby",
"bytes": "211438"
},
{
"name": "Shell",
"bytes": "1241"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('realtime', '0060_auto_20180506_1815'),
]
operations = [
migrations.CreateModel(
name='EarthquakeMigration',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('migrated', models.BooleanField(default=False)),
('has_shake_grid_in_raw_file', models.BooleanField(default=False)),
('has_shake_grid_in_media_file', models.BooleanField(default=False)),
('has_shake_grid_in_database', models.BooleanField(default=False)),
('has_mmi_in_raw_file', models.BooleanField(default=False)),
('has_mmi_in_media_file', models.BooleanField(default=False)),
('has_mmi_in_database', models.BooleanField(default=False)),
('shake_grid_migrated', models.BooleanField(default=False)),
('mmi_migrated', models.BooleanField(default=False)),
('event', models.ForeignKey(related_name='migration_state', to='realtime.Earthquake')),
],
),
migrations.CreateModel(
name='FloodMigration',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('migrated', models.BooleanField(default=False)),
('has_hazard_in_raw_file', models.BooleanField(default=False)),
('has_hazard_in_media_file', models.BooleanField(default=False)),
('has_hazard_in_database', models.BooleanField(default=False)),
('has_impact_in_raw_file', models.BooleanField(default=False)),
('has_impact_in_media_file', models.BooleanField(default=False)),
('has_impact_in_database', models.BooleanField(default=False)),
('hazard_migrated', models.BooleanField(default=False)),
('impact_migrated', models.BooleanField(default=False)),
('event', models.ForeignKey(related_name='migration_state', to='realtime.Flood')),
],
),
]
| {
"content_hash": "bccf342c4c592c74767efb1a67c53f8c",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 114,
"avg_line_length": 50.84444444444444,
"alnum_prop": 0.5926573426573427,
"repo_name": "AIFDR/inasafe-django",
"id": "99ac40a424be58c1d010254467e884b6e100af11",
"size": "2312",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "django_project/realtime/migrations/0061_earthquakemigration_floodmigration.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "196369"
},
{
"name": "HTML",
"bytes": "93481"
},
{
"name": "JavaScript",
"bytes": "346781"
},
{
"name": "Makefile",
"bytes": "9201"
},
{
"name": "Python",
"bytes": "285851"
},
{
"name": "Shell",
"bytes": "2169"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang>
<head><meta name="generator" content="Hexo 3.9.0">
<!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="UTF-8">
<!-- responsive -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>迷宫算法的更正 [ Bingo ]</title>
<link rel="apple-touch-icon" sizes="57x57" href="./img/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="./img/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="./img/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="./img/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="./img/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="./img/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="./img/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="./img/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="./img/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="./img/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="./img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="./img/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="./img/favicon-16x16.png">
<link rel="manifest" href="./img/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="./img/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!-- katex -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css" integrity="sha384-TEMocfGvRuD1rIAacqrknm5BQZ7W7uWitoih+jMNFXQIbNl16bO8OZmylH/Vi/Ei" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.js" integrity="sha384-jmxIlussZWB7qCuB+PgKG1uLjjxbVVIayPJwi6cG6Zb4YKq0JIw+OMnkkEC7kYCq" crossorigin="anonymous"></script>
<!-- highlight -->
<link rel="stylesheet" href="/highlight/styles/monokai-sublime.css">
<script src="/highlight/highlight.pack.js"></script>
<!-- highlight line-number -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.3.0/highlightjs-line-numbers.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script>hljs.initLineNumbersOnLoad();</script>
<!-- theme css -->
<!-- stylesheets list from config.yml -->
<link rel="stylesheet" href="/css/elenore/css/elenore.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/css/animate.min.css">
<link rel="stylesheet" href="/css/basic.css">
<link rel="stylesheet" href="/css/floekr.css"><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</head>
<body>
<!-- hexo-inject:begin --><!-- hexo-inject:end --><!-- Navigation Bar -->
<nav id="navbar" class="navbar is-white is-fixed-top">
<div id="specialShadow" class="el-special-shadow"></div>
<div class="container">
<!-- left side, always visible -->
<div class="navbar-brand">
<a class="navbar-item" href="/">
<!-- <strong>Bingo</strong> -->
<i class="fa fa-lg fa-home"></i>
</a>
<!-- toggles the menu on touch devices -->
<div id="navbarBurger" class="navbar-burger burger" data-target="navMenu">
<span></span>
<span></span>
<span></span>
</div>
</div>
<!-- menu -->
<div id="navMenu" class="navbar-menu">
<div class="navbar-end">
<a href="/" class="navbar-item">HOME</a>
<a href="/projects" class="navbar-item">PROJECTS</a>
<a href="/about" class="navbar-item">ABOUT</a>
</div>
</div>
</div>
</nav>
<!-- index hero -->
<div class="hero is-large has-background-fixed" id="indexHero">
<div class="hero-body">
<div class="container has-text-centered">
<p id="titleContent">
Bingo, <span>Computer Graphics</span> & <span>Game Developer</span>
</p>
</div>
</div>
</div>
<!-- articles and about me -->
<!-- in the future -->
<section class="section">
<div class="container">
<div class="columns">
<div class="column is-four-fifths">
<div class="card is-white is-hover" id="postCard">
<div class="card-header">
<h3 class="card-header-title">迷宫算法的更正</h3>
</div>
<div class="card-content">
<p><blockquote>
<p>P74页中倒数第二行的else if</p>
</blockquote>
<pre><code class="cpp">if(next_row == EXIT_ROW && next_col == EXIT_COL)
found = TRUE;
else if(!maze[next_row][next_col] && !mark[nextRow][next_col]){
// do something...
}
</code></pre>
</p><p>此处的else if我认为可以更正为if,那么最后一个结点也可以入栈,或者为了性能起见,将stack.push()的在第一步if中添加上也可。个人更倾向于第二种做法。</p>
<p>即(<a href="https://github.com/BentleyBlanks/t3DataStructures/blob/master/t3DataStructures/LinearList/t3Maze.cpp" target="_blank" rel="noopener">t3DataStructures.t3Maze</a>中就是这样做的)</p>
<pre><code class="cpp">if(next_row == EXIT_ROW && next_col == EXIT_COL){
stack.push(row, col, dir);
found = TRUE;
}
else if(!maze[next_row][next_col] && !mark[next_row][next_col]){
// do something...
}
</code></pre>
<p></p>
</div>
</div>
</div>
<div class="column">
<div class="is-sticky">
<div class="card is-white is-hover is-hidden-mobile">
<div class="card-content">
<aside class="menu">
<p class="menu-label">
DESCRIPTION
</p>
<p id="pageDescription">对书中的代码进行小幅修正以确保栈数据正常</p>
</aside>
</div>
</div>
<br>
<div class="card is-white is-hover is-hidden-mobile">
<div class="card-content">
<aside class="menu">
<p class="menu-label">
Archives
</p>
<ul class="menu-list">
<li><a>2016</a></li>
<li>
<a>2017</a>
</li>
<li>
<a class="is-active">2018</a>
<ul>
<li><a>September</a></li>
<li><a>August</a></li>
<li><a>July</a></li>
</ul>
</li>
</ul>
</aside>
</div>
</div>
<br>
<div class="card is-white is-hover is-hidden-mobile">
<div class="card-content">
<aside class="menu">
<p class="menu-label">
Tags
</p>
<ul class="menu-list">
<li><a>Game</a></li>
<li>
<a class="is-active">Renderer</a>
</li>
<li><a>C++</a></li>
<li><a>Math</a></li>
</ul>
</aside>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Footer -->
<footer class="footer is-medium" id="footerStyle">
<div class="container">
<nav class="level is-mobile">
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered">
<img src="https://yellowdi.github.io/Elenore/images/elenore-icon-outlined.png" alt="Elenore logo" width="50">
</div>
<div class="level-item has-text-centered">
<img src="https://raw.githubusercontent.com/hexojs/logo/master/hexo-logo-avatar-transparent-background.png" alt="Hexo logo" width="50">
</div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
<div class="level-item has-text-centered"></div>
</nav>
<div class="columns has-text-centered">
<div class="column">
Theme Floekr developed By <a href="https://github.com/BentleyBlanks">Bingo</a>. Powered by <a href="https://yellowdi.github.io/Elenore">Elenore</a> and <a href="https://hexo.io/">Hexo</a>
</div>
</div>
</div>
</footer>
<!-- scripts list from theme config.yml -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" language="javascript"></script>
<script src="/js/wow.min.js" language="javascript"></script>
<script src="/js/floekr.js" language="javascript"></script><!-- hexo-inject:begin --><!-- hexo-inject:end -->
</body>
</html>
| {
"content_hash": "85d28fb7a5f4a981a4e9a9133e1d6b40",
"timestamp": "",
"source": "github",
"line_count": 278,
"max_line_length": 205,
"avg_line_length": 33.92446043165467,
"alnum_prop": 0.5833951860884318,
"repo_name": "BentleyBlanks/bentleyblanks.github.io",
"id": "97d677306cc77030e89e8118df5a11f3b0b8cbc3",
"size": "9654",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2015/08/13/2015-08-14-corrections/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "454260"
},
{
"name": "HTML",
"bytes": "18654553"
},
{
"name": "JavaScript",
"bytes": "3264"
}
],
"symlink_target": ""
} |
package googlemaps
import (
"fmt"
"net/url"
"github.com/zquestz/s/providers"
)
func init() {
providers.AddProvider("googlemaps", &Provider{})
}
// Provider merely implements the Provider interface.
type Provider struct{}
// BuildURI generates a search URL for Google Maps.
func (p *Provider) BuildURI(q string) string {
return fmt.Sprintf("https://www.google.com/maps/search/?api=1&query=%s", url.QueryEscape(q))
}
// Tags returns the tags relevant to this provider.
func (p *Provider) Tags() []string {
return []string{}
}
| {
"content_hash": "2627dda1d3007bbec4e6740b3b5a170e",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 93,
"avg_line_length": 21.44,
"alnum_prop": 0.7145522388059702,
"repo_name": "zquestz/s",
"id": "013443e3587fd7e2540dc76691b9afc4c260dd0a",
"size": "536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "providers/googlemaps/googlemaps.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "511"
},
{
"name": "Go",
"bytes": "219580"
},
{
"name": "Makefile",
"bytes": "1027"
}
],
"symlink_target": ""
} |
package org.nohope.jaxb2.plugin.validation;
import org.nohope.jaxb2.plugin.Jaxb2PluginTestSupport.BuildFailureValidator;
import org.xml.sax.SAXParseException;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:ketoth.xupack@gmail.com">Ketoth Xupack</a>
* @since 2013-10-17 17:10
*/
class ParseExceptionValidator implements BuildFailureValidator {
private final String message;
ParseExceptionValidator(final String message) {
this.message = message;
}
public static ParseExceptionValidator message(final String message) {
return new ParseExceptionValidator(message);
}
@Override
public void validate(final Exception e) {
assertTrue(e instanceof IllegalStateException);
assertNotNull(e.getCause());
assertNotNull(e.getCause() instanceof SAXParseException);
assertEquals(message, e.getCause().getMessage());
}
}
| {
"content_hash": "70daf621dd90f3c57875dc97dbdf8701",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 76,
"avg_line_length": 30.266666666666666,
"alnum_prop": 0.7323788546255506,
"repo_name": "no-hope/java-toolkit",
"id": "849f9fe1efdc12c58fe3485f598bb47d02796e34",
"size": "908",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "projects/jaxb2-plugins/src/test/java/org/nohope/jaxb2/plugin/validation/ParseExceptionValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "11307"
},
{
"name": "CSS",
"bytes": "3499"
},
{
"name": "Groovy",
"bytes": "10647"
},
{
"name": "HTML",
"bytes": "2998"
},
{
"name": "Java",
"bytes": "1009082"
},
{
"name": "JavaScript",
"bytes": "1839"
},
{
"name": "Shell",
"bytes": "2078"
}
],
"symlink_target": ""
} |
/**
* @fileoverview Rule to flag assignment of the exception parameter
* @author Stephen Murray <spmurrayzzz>
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "problem",
docs: {
description: "disallow reassigning exceptions in `catch` clauses",
recommended: true,
url: "https://eslint.org/docs/rules/no-ex-assign"
},
schema: [],
messages: {
unexpected: "Do not assign to the exception parameter."
}
},
create(context) {
/**
* Finds and reports references that are non initializer and writable.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
astUtils.getModifyingReferences(variable.references).forEach(reference => {
context.report({ node: reference.identifier, messageId: "unexpected" });
});
}
return {
CatchClause(node) {
context.getDeclaredVariables(node).forEach(checkVariable);
}
};
}
};
| {
"content_hash": "c4107e04f1c0b88327fa3c45c3303c5e",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 88,
"avg_line_length": 26.745098039215687,
"alnum_prop": 0.4941348973607038,
"repo_name": "platinumazure/eslint",
"id": "cd56c94af7587cb39d1e95a9558e239832ffb07a",
"size": "1364",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "lib/rules/no-ex-assign.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "8120"
},
{
"name": "JavaScript",
"bytes": "7870254"
}
],
"symlink_target": ""
} |
All prices (listing, booking, bankwire, refund, ...) are stored in cents and in the default app currency
defined by `cocorico.currency` parameter.
Entities decimal prices are accessed though `getXXXDecimal` methods.
## VAT
Listing price fixing can be set with or without VAT included depending on the parameter `cocorico.include_vat` value.
If it's setted to true then:
- listing price fixing include VAT
- all other prices like booking, bank wire, ... include also VAT
If it's setted to false then:
- listing price fixing don't include VAT
- Most of asker relative prices are displayed including VAT
- Most of offerer relative prices are displayed excluding VAT
## Fees
The platform can take fees on each transactions.
Fees rate are defined by the parameters `cocorico.fee_as_asker` and `cocorico.fee_as_offerer` parameter.
The administrator can choose to change the fee rate of each user as asker and as offerer.
## Refund
There are two type of cancellation policies **Flexible** and **Strict**.
Each policy define how asker will be refunded according to when he make a cancelation.
These rules are defined by the parameter `cocorico.booking.cancelation_policy`.
Example:
- Initial amounts:
- Booking amount excl fees = 95€
- Asker fees = 10€
- Offerer fees = 5€
- Amount payed by asker = 110€
- Amount refunded is 100%: Offerer fees payed by asker are refunded to asker.
- Amount refunded to asker = 95€ * 1 + 5€ = 100€
- Amount transferred to offerer wallet = 95€ * (1 - 1) = 0€
- Fees taken by the platform = 10€
- Amount refunded is 50%: No fees refunded
- Amount refunded to asker = 95€ * 0.5 = 47.50€
- Amount transferred to offerer wallet = 95€ * (1 - 0.5) = 47.50€
- Fees taken by the platform = 15€
- Amount refunded is 0%: No fees refunded
- Amount refunded to asker = 95€ * 0 = 0€
- Amount transferred to offerer wallet = 95€ * (1 - 0) = 95€
- Fees taken by the platform = 15€
| {
"content_hash": "8cbb45cc5432fad51026fc5a74be3579",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 117,
"avg_line_length": 33.610169491525426,
"alnum_prop": 0.7044881492687847,
"repo_name": "Cocolabs-SAS/cocorico",
"id": "21c18eac13444bc6db0291f2514e9c5d2af9101e",
"size": "2033",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/prices.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1146"
},
{
"name": "CSS",
"bytes": "385801"
},
{
"name": "Gherkin",
"bytes": "86110"
},
{
"name": "JavaScript",
"bytes": "247866"
},
{
"name": "PHP",
"bytes": "1764805"
},
{
"name": "Shell",
"bytes": "3717"
},
{
"name": "Twig",
"bytes": "649524"
}
],
"symlink_target": ""
} |
enum GameEnemyLevel {
GameEnemyLevelEasy,
GameEnemyLevelMedium,
GameEnemyLevelHard
};
@interface GameEnemy : GameTank
{
NSUInteger wallSensor;
NSUInteger leftSensor;
NSUInteger rightSensor;
NSUInteger turretSensorWallContact;
GameEnemyLevel level;
NSUInteger inaccuracyAngle;
float turretRotationSpeed;
b2Fixture *turretSensorFixture;
b2Body *turretSensorBody;
float moveTurretTo;
float actionDelay;
float retargetDelay;
float checkMineDelay;
float inaccuracy;
float inaccuracyDelay;
BOOL inactive;
BOOL friendly;
NSMutableArray *tanksInRange;
GameTank *targetTank;
}
- (void)tick:(ccTime)dt;
- (void)setLevel:(GameEnemyLevel)aLevel;
- (GameEnemyLevel)getLevel;
@property (assign) BOOL inactive;
@property (assign) BOOL friendly;
@end
| {
"content_hash": "5c4fd2e3875a25a7c40649c8911e29ce",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 40,
"avg_line_length": 20.095238095238095,
"alnum_prop": 0.7227488151658767,
"repo_name": "johndpope/FinalFighter-mac",
"id": "315eb3ca9fad61cdc961889fd44301a06637a545",
"size": "930",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FinalFighter-mac/Source/GameEnemy.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "263643"
},
{
"name": "C++",
"bytes": "977718"
},
{
"name": "CMake",
"bytes": "6592"
},
{
"name": "Matlab",
"bytes": "1875"
},
{
"name": "Objective-C",
"bytes": "1466178"
},
{
"name": "Objective-C++",
"bytes": "162622"
},
{
"name": "PHP",
"bytes": "14077"
},
{
"name": "Shell",
"bytes": "764"
}
],
"symlink_target": ""
} |
package org.apache.arrow.vector;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Map;
import org.apache.arrow.memory.ArrowBuf;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.vector.complex.MapVector;
import org.apache.arrow.vector.complex.StructVector;
import org.apache.arrow.vector.complex.impl.UnionMapReader;
import org.apache.arrow.vector.complex.impl.UnionMapWriter;
import org.apache.arrow.vector.complex.reader.FieldReader;
import org.apache.arrow.vector.complex.writer.BaseWriter.ListWriter;
import org.apache.arrow.vector.types.Types.MinorType;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.FieldType;
import org.apache.arrow.vector.util.JsonStringArrayList;
import org.apache.arrow.vector.util.TransferPair;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class TestMapVector {
private BufferAllocator allocator;
@Before
public void init() {
allocator = new DirtyRootAllocator(Long.MAX_VALUE, (byte) 100);
}
@After
public void terminate() throws Exception {
allocator.close();
}
public <T> T getResultKey(Map<?, T> resultStruct) {
assertTrue(resultStruct.containsKey(MapVector.KEY_NAME));
return resultStruct.get(MapVector.KEY_NAME);
}
public <T> T getResultValue(Map<?, T> resultStruct) {
assertTrue(resultStruct.containsKey(MapVector.VALUE_NAME));
return resultStruct.get(MapVector.VALUE_NAME);
}
@Test
public void testBasicOperation() {
int count = 5;
try (MapVector mapVector = MapVector.empty("map", allocator, false)) {
mapVector.allocateNew();
UnionMapWriter mapWriter = mapVector.getWriter();
for (int i = 0; i < count; i++) {
mapWriter.startMap();
for (int j = 0; j < i + 1; j++) {
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(j);
mapWriter.value().integer().writeInt(j);
mapWriter.endEntry();
}
mapWriter.endMap();
}
mapWriter.setValueCount(count);
UnionMapReader mapReader = mapVector.getReader();
for (int i = 0; i < count; i++) {
mapReader.setPosition(i);
for (int j = 0; j < i + 1; j++) {
mapReader.next();
assertEquals("record: " + i, j, mapReader.key().readLong().longValue());
assertEquals(j, mapReader.value().readInteger().intValue());
}
}
}
}
@Test
public void testBasicOperationNulls() {
int count = 6;
try (MapVector mapVector = MapVector.empty("map", allocator, false)) {
mapVector.allocateNew();
UnionMapWriter mapWriter = mapVector.getWriter();
for (int i = 0; i < count; i++) {
// i == 1 is a NULL
if (i != 1) {
mapWriter.setPosition(i);
mapWriter.startMap();
// i == 3 is an empty map
if (i != 3) {
for (int j = 0; j < i + 1; j++) {
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(j);
// i == 5 maps to a NULL value
if (i != 5) {
mapWriter.value().integer().writeInt(j);
}
mapWriter.endEntry();
}
}
mapWriter.endMap();
}
}
mapWriter.setValueCount(count);
UnionMapReader mapReader = mapVector.getReader();
for (int i = 0; i < count; i++) {
mapReader.setPosition(i);
if (i == 1) {
assertFalse(mapReader.isSet());
} else {
if (i == 3) {
JsonStringArrayList<?> result = (JsonStringArrayList<?>) mapReader.readObject();
assertTrue(result.isEmpty());
} else {
for (int j = 0; j < i + 1; j++) {
mapReader.next();
assertEquals("record: " + i, j, mapReader.key().readLong().longValue());
if (i == 5) {
assertFalse(mapReader.value().isSet());
} else {
assertEquals(j, mapReader.value().readInteger().intValue());
}
}
}
}
}
}
}
@Test
public void testCopyFrom() throws Exception {
try (MapVector inVector = MapVector.empty("input", allocator, false);
MapVector outVector = MapVector.empty("output", allocator, false)) {
UnionMapWriter writer = inVector.getWriter();
writer.allocate();
// populate input vector with the following records
// {1 -> 11, 2 -> 22, 3 -> 33}
// null
// {2 -> null}
writer.setPosition(0); // optional
writer.startMap();
writer.startEntry();
writer.key().bigInt().writeBigInt(1);
writer.value().bigInt().writeBigInt(11);
writer.endEntry();
writer.startEntry();
writer.key().bigInt().writeBigInt(2);
writer.value().bigInt().writeBigInt(22);
writer.endEntry();
writer.startEntry();
writer.key().bigInt().writeBigInt(3);
writer.value().bigInt().writeBigInt(33);
writer.endEntry();
writer.endMap();
writer.setPosition(2);
writer.startMap();
writer.startEntry();
writer.key().bigInt().writeBigInt(2);
writer.endEntry();
writer.endMap();
writer.setValueCount(3);
// copy values from input to output
outVector.allocateNew();
for (int i = 0; i < 3; i++) {
outVector.copyFrom(i, i, inVector);
}
outVector.setValueCount(3);
// assert the output vector is correct
FieldReader reader = outVector.getReader();
assertTrue("shouldn't be null", reader.isSet());
reader.setPosition(1);
assertFalse("should be null", reader.isSet());
reader.setPosition(2);
assertTrue("shouldn't be null", reader.isSet());
/* index 0 */
Object result = outVector.getObject(0);
ArrayList<?> resultSet = (ArrayList<?>) result;
assertEquals(3, resultSet.size());
Map<?, ?> resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(1L, getResultKey(resultStruct));
assertEquals(11L, getResultValue(resultStruct));
resultStruct = (Map<?, ?>) resultSet.get(1);
assertEquals(2L, getResultKey(resultStruct));
assertEquals(22L, getResultValue(resultStruct));
resultStruct = (Map<?, ?>) resultSet.get(2);
assertEquals(3L, getResultKey(resultStruct));
assertEquals(33L, getResultValue(resultStruct));
/* index 1 */
result = outVector.getObject(1);
assertNull(result);
/* index 2 */
result = outVector.getObject(2);
resultSet = (ArrayList<?>) result;
assertEquals(1, resultSet.size());
resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(2L, getResultKey(resultStruct));
assertFalse(resultStruct.containsKey(MapVector.VALUE_NAME));
}
}
@Test
public void testSplitAndTransfer() throws Exception {
try (MapVector mapVector = MapVector.empty("sourceVector", allocator, false)) {
/* Explicitly add the map child vectors */
FieldType type = new FieldType(false, ArrowType.Struct.INSTANCE, null, null);
AddOrGetResult<StructVector> addResult = mapVector.addOrGetVector(type);
FieldType keyType = new FieldType(false, MinorType.BIGINT.getType(), null, null);
FieldType valueType = FieldType.nullable(MinorType.FLOAT8.getType());
addResult.getVector().addOrGet(MapVector.KEY_NAME, keyType, BigIntVector.class);
addResult.getVector().addOrGet(MapVector.VALUE_NAME, valueType, Float8Vector.class);
UnionMapWriter mapWriter = mapVector.getWriter();
/* allocate memory */
mapWriter.allocate();
/* populate data */
mapWriter.setPosition(0);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(10);
mapWriter.value().float8().writeFloat8(1.0);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(11);
mapWriter.value().float8().writeFloat8(1.1);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(12);
mapWriter.value().float8().writeFloat8(1.2);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setPosition(1);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(13);
mapWriter.value().float8().writeFloat8(1.3);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(14);
mapWriter.value().float8().writeFloat8(1.4);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setPosition(2);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(15);
mapWriter.value().float8().writeFloat8(1.5);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(16);
mapWriter.value().float8().writeFloat8(1.6);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(17);
mapWriter.value().float8().writeFloat8(1.7);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(18);
mapWriter.value().float8().writeFloat8(1.8);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setPosition(3);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(19);
mapWriter.value().float8().writeFloat8(1.9);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setPosition(4);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(20);
mapWriter.value().float8().writeFloat8(2.0);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(21);
mapWriter.value().float8().writeFloat8(2.1);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(22);
mapWriter.value().float8().writeFloat8(2.2);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(23);
mapWriter.value().float8().writeFloat8(2.3);
mapWriter.endEntry();
mapWriter.endMap();
mapVector.setValueCount(5);
assertEquals(4, mapVector.getLastSet());
/* get offset buffer */
final ArrowBuf offsetBuffer = mapVector.getOffsetBuffer();
/* get dataVector */
StructVector dataVector = (StructVector) mapVector.getDataVector();
/* check the vector output */
int index = 0;
int offset = 0;
Map<?, ?> result = null;
/* index 0 */
assertFalse(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(0), Integer.toString(offset));
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(10L, getResultKey(result));
assertEquals(1.0, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(11L, getResultKey(result));
assertEquals(1.1, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(12L, getResultKey(result));
assertEquals(1.2, getResultValue(result));
/* index 1 */
index++;
assertFalse(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(3), Integer.toString(offset));
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(13L, getResultKey(result));
assertEquals(1.3, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(14L, getResultKey(result));
assertEquals(1.4, getResultValue(result));
/* index 2 */
index++;
assertFalse(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(5), Integer.toString(offset));
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(15L, getResultKey(result));
assertEquals(1.5, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(16L, getResultKey(result));
assertEquals(1.6, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(17L, getResultKey(result));
assertEquals(1.7, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(18L, getResultKey(result));
assertEquals(1.8, getResultValue(result));
/* index 3 */
index++;
assertFalse(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(9), Integer.toString(offset));
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(19L, getResultKey(result));
assertEquals(1.9, getResultValue(result));
/* index 4 */
index++;
assertFalse(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(10), Integer.toString(offset));
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(20L, getResultKey(result));
assertEquals(2.0, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(21L, getResultKey(result));
assertEquals(2.1, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(22L, getResultKey(result));
assertEquals(2.2, getResultValue(result));
offset++;
result = (Map<?, ?>) dataVector.getObject(offset);
assertEquals(23L, getResultKey(result));
assertEquals(2.3, getResultValue(result));
/* index 5 */
index++;
assertTrue(mapVector.isNull(index));
offset = offsetBuffer.getInt(index * MapVector.OFFSET_WIDTH);
assertEquals(Integer.toString(14), Integer.toString(offset));
/* do split and transfer */
try (MapVector toVector = MapVector.empty("toVector", allocator, false)) {
TransferPair transferPair = mapVector.makeTransferPair(toVector);
int[][] transferLengths = {{0, 2}, {3, 1}, {4, 1}};
for (final int[] transferLength : transferLengths) {
int start = transferLength[0];
int splitLength = transferLength[1];
int dataLength1 = 0;
int dataLength2 = 0;
int offset1 = 0;
int offset2 = 0;
transferPair.splitAndTransfer(start, splitLength);
/* get offsetBuffer of toVector */
final ArrowBuf toOffsetBuffer = toVector.getOffsetBuffer();
/* get dataVector of toVector */
StructVector dataVector1 = (StructVector) toVector.getDataVector();
for (int i = 0; i < splitLength; i++) {
dataLength1 = offsetBuffer.getInt((start + i + 1) * MapVector.OFFSET_WIDTH) -
offsetBuffer.getInt((start + i) * MapVector.OFFSET_WIDTH);
dataLength2 = toOffsetBuffer.getInt((i + 1) * MapVector.OFFSET_WIDTH) -
toOffsetBuffer.getInt(i * MapVector.OFFSET_WIDTH);
assertEquals("Different data lengths at index: " + i + " and start: " + start,
dataLength1, dataLength2);
offset1 = offsetBuffer.getInt((start + i) * MapVector.OFFSET_WIDTH);
offset2 = toOffsetBuffer.getInt(i * MapVector.OFFSET_WIDTH);
for (int j = 0; j < dataLength1; j++) {
assertEquals("Different data at indexes: " + offset1 + " and " + offset2,
dataVector.getObject(offset1), dataVector1.getObject(offset2));
offset1++;
offset2++;
}
}
}
}
}
}
@Test
public void testMapWithListValue() throws Exception {
try (MapVector mapVector = MapVector.empty("sourceVector", allocator, false)) {
UnionMapWriter mapWriter = mapVector.getWriter();
ListWriter valueWriter;
/* allocate memory */
mapWriter.allocate();
/* the dataVector that backs a listVector will also be a
* listVector for this test.
*/
/* write one or more maps index 0 */
mapWriter.setPosition(0);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(1);
valueWriter = mapWriter.value().list();
valueWriter.startList();
valueWriter.bigInt().writeBigInt(50);
valueWriter.bigInt().writeBigInt(100);
valueWriter.bigInt().writeBigInt(200);
valueWriter.endList();
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(2);
valueWriter = mapWriter.value().list();
valueWriter.startList();
valueWriter.bigInt().writeBigInt(75);
valueWriter.bigInt().writeBigInt(125);
valueWriter.bigInt().writeBigInt(150);
valueWriter.bigInt().writeBigInt(175);
valueWriter.endList();
mapWriter.endEntry();
mapWriter.endMap();
/* write one or more maps at index 1 */
mapWriter.setPosition(1);
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(3);
valueWriter = mapWriter.value().list();
valueWriter.startList();
valueWriter.bigInt().writeBigInt(10);
valueWriter.endList();
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(4);
valueWriter = mapWriter.value().list();
valueWriter.startList();
valueWriter.bigInt().writeBigInt(15);
valueWriter.bigInt().writeBigInt(20);
valueWriter.endList();
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(5);
valueWriter = mapWriter.value().list();
valueWriter.startList();
valueWriter.bigInt().writeBigInt(25);
valueWriter.bigInt().writeBigInt(30);
valueWriter.bigInt().writeBigInt(35);
valueWriter.endList();
mapWriter.endEntry();
mapWriter.endMap();
assertEquals(1, mapVector.getLastSet());
mapWriter.setValueCount(2);
assertEquals(2, mapVector.getValueCount());
// Get mapVector element at index 0
Object result = mapVector.getObject(0);
ArrayList<?> resultSet = (ArrayList<?>) result;
// 2 map entries at index 0
assertEquals(2, resultSet.size());
// First Map entry
Map<?, ?> resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(1L, getResultKey(resultStruct));
ArrayList<Long> list = (ArrayList<Long>) getResultValue(resultStruct);
assertEquals(3, list.size()); // value is a list with 3 elements
assertEquals(new Long(50), list.get(0));
assertEquals(new Long(100), list.get(1));
assertEquals(new Long(200), list.get(2));
// Second Map entry
resultStruct = (Map<?, ?>) resultSet.get(1);
list = (ArrayList<Long>) getResultValue(resultStruct);
assertEquals(4, list.size()); // value is a list with 4 elements
assertEquals(new Long(75), list.get(0));
assertEquals(new Long(125), list.get(1));
assertEquals(new Long(150), list.get(2));
assertEquals(new Long(175), list.get(3));
// Get mapVector element at index 1
result = mapVector.getObject(1);
resultSet = (ArrayList<?>) result;
// First Map entry
resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(3L, getResultKey(resultStruct));
list = (ArrayList<Long>) getResultValue(resultStruct);
assertEquals(1, list.size()); // value is a list with 1 element
assertEquals(new Long(10), list.get(0));
// Second Map entry
resultStruct = (Map<?, ?>) resultSet.get(1);
assertEquals(4L, getResultKey(resultStruct));
list = (ArrayList<Long>) getResultValue(resultStruct);
assertEquals(2, list.size()); // value is a list with 1 element
assertEquals(new Long(15), list.get(0));
assertEquals(new Long(20), list.get(1));
// Third Map entry
resultStruct = (Map<?, ?>) resultSet.get(2);
assertEquals(5L, getResultKey(resultStruct));
list = (ArrayList<Long>) getResultValue(resultStruct);
assertEquals(3, list.size()); // value is a list with 1 element
assertEquals(new Long(25), list.get(0));
assertEquals(new Long(30), list.get(1));
assertEquals(new Long(35), list.get(2));
/* check underlying bitVector */
assertFalse(mapVector.isNull(0));
assertFalse(mapVector.isNull(1));
/* check underlying offsets */
final ArrowBuf offsetBuffer = mapVector.getOffsetBuffer();
/* mapVector has 2 entries at index 0 and 3 entries at index 1 */
assertEquals(0, offsetBuffer.getInt(0 * MapVector.OFFSET_WIDTH));
assertEquals(2, offsetBuffer.getInt(1 * MapVector.OFFSET_WIDTH));
assertEquals(5, offsetBuffer.getInt(2 * MapVector.OFFSET_WIDTH));
}
}
@Test
public void testClearAndReuse() {
try (final MapVector vector = MapVector.empty("map", allocator, false)) {
vector.allocateNew();
UnionMapWriter mapWriter = vector.getWriter();
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(1);
mapWriter.value().integer().writeInt(11);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(2);
mapWriter.value().integer().writeInt(22);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setValueCount(2);
Object result = vector.getObject(0);
ArrayList<?> resultSet = (ArrayList<?>) result;
Map<?, ?> resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(1L, getResultKey(resultStruct));
assertEquals(11, getResultValue(resultStruct));
result = vector.getObject(1);
resultSet = (ArrayList<?>) result;
resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(2L, getResultKey(resultStruct));
assertEquals(22, getResultValue(resultStruct));
// Clear and release the buffers to trigger a realloc when adding next value
vector.clear();
mapWriter = new UnionMapWriter(vector);
// The map vector should reuse a buffer when reallocating the offset buffer
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(3);
mapWriter.value().integer().writeInt(33);
mapWriter.endEntry();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(4);
mapWriter.value().integer().writeInt(44);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.startMap();
mapWriter.startEntry();
mapWriter.key().bigInt().writeBigInt(5);
mapWriter.value().integer().writeInt(55);
mapWriter.endEntry();
mapWriter.endMap();
mapWriter.setValueCount(2);
result = vector.getObject(0);
resultSet = (ArrayList<?>) result;
resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(3L, getResultKey(resultStruct));
assertEquals(33, getResultValue(resultStruct));
resultStruct = (Map<?, ?>) resultSet.get(1);
assertEquals(4L, getResultKey(resultStruct));
assertEquals(44, getResultValue(resultStruct));
result = vector.getObject(1);
resultSet = (ArrayList<?>) result;
resultStruct = (Map<?, ?>) resultSet.get(0);
assertEquals(5L, getResultKey(resultStruct));
assertEquals(55, getResultValue(resultStruct));
}
}
}
| {
"content_hash": "47a0b008e8cc7aa949fbc5177088d4ef",
"timestamp": "",
"source": "github",
"line_count": 687,
"max_line_length": 92,
"avg_line_length": 35.082969432314414,
"alnum_prop": 0.6284125798688905,
"repo_name": "xhochy/arrow",
"id": "3b85ed6fe6986e931cd1a84f53a5292d2bbad37a",
"size": "24902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/vector/src/test/java/org/apache/arrow/vector/TestMapVector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "73655"
},
{
"name": "Awk",
"bytes": "3709"
},
{
"name": "Batchfile",
"bytes": "24676"
},
{
"name": "C",
"bytes": "881567"
},
{
"name": "C#",
"bytes": "699719"
},
{
"name": "C++",
"bytes": "14541996"
},
{
"name": "CMake",
"bytes": "560347"
},
{
"name": "Dockerfile",
"bytes": "100165"
},
{
"name": "Emacs Lisp",
"bytes": "1916"
},
{
"name": "FreeMarker",
"bytes": "2244"
},
{
"name": "Go",
"bytes": "848212"
},
{
"name": "HTML",
"bytes": "6152"
},
{
"name": "Java",
"bytes": "4713332"
},
{
"name": "JavaScript",
"bytes": "102300"
},
{
"name": "Julia",
"bytes": "235105"
},
{
"name": "Lua",
"bytes": "8771"
},
{
"name": "M4",
"bytes": "11095"
},
{
"name": "MATLAB",
"bytes": "36600"
},
{
"name": "Makefile",
"bytes": "57687"
},
{
"name": "Meson",
"bytes": "48356"
},
{
"name": "Objective-C",
"bytes": "17680"
},
{
"name": "Objective-C++",
"bytes": "12128"
},
{
"name": "PLpgSQL",
"bytes": "56995"
},
{
"name": "Perl",
"bytes": "3799"
},
{
"name": "Python",
"bytes": "3135304"
},
{
"name": "R",
"bytes": "533584"
},
{
"name": "Ruby",
"bytes": "1084485"
},
{
"name": "Rust",
"bytes": "3969176"
},
{
"name": "Shell",
"bytes": "380070"
},
{
"name": "Thrift",
"bytes": "142033"
},
{
"name": "TypeScript",
"bytes": "1157087"
}
],
"symlink_target": ""
} |
package org.pac4j.vertx.handler.impl;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import org.pac4j.core.config.Config;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.vertx.auth.Pac4jAuthProvider;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Version of the Pac4j authentication handler which auto-deploys a CallbackHandler on the relative URL derived from
* the path of the callback URL specified in the Clients object held within the Config object supplied in the
* constructor.
*
* There is no requirement to use this handler rather than a RequiresAuthenticationHandler (and indeed where the same
* callback URL is being potentially used for multiple authentication handlers it may muddy the waters) but it is supplied
* as a convenience to anyone wanting to perform very simple indirect authentications.
*
* If there is a desire to use the same callback for multiple indirect authentications, it is recommended to explicitly
* deploy a CallbackHandler for clarity.
*
* @author Jeremy Prime
* @since 2.0.0
*/
public class CallbackDeployingPac4jAuthHandler extends RequiresAuthenticationHandler {
private final Logger LOG = LoggerFactory.getLogger(CallbackDeployingPac4jAuthHandler.class);
// Consider coalescing the manager options into the handler options and then generating the manageroptions from them
public CallbackDeployingPac4jAuthHandler(final Vertx vertx,
final Config config,
final Router router,
final Pac4jAuthProvider authProvider,
final Pac4jAuthHandlerOptions options) {
super(vertx, config, authProvider, options);
// Other null checks performed by parent class
CommonHelper.assertNotNull("router", router);
CommonHelper.assertNotBlank("callbackUrl", config.getClients().getCallbackUrl());
final URI uri;
try {
uri = new URI(config.getClients().getCallbackUrl());
} catch (URISyntaxException e) {
LOG.error(e.getStackTrace().toString());
throw toTechnicalException(e);
}
// Start manager verticle
router.route(HttpMethod.GET, uri.getPath()).handler(authResultHandler(vertx, config, options));
}
private Handler<RoutingContext> authResultHandler(final Vertx vertx, final Config config, Pac4jAuthHandlerOptions options) {
return new CallbackHandler(vertx, config);
}
}
| {
"content_hash": "d8835fa92a82f5e0c32a6f6ae4e319fd",
"timestamp": "",
"source": "github",
"line_count": 64,
"max_line_length": 128,
"avg_line_length": 43.296875,
"alnum_prop": 0.7091302778780224,
"repo_name": "HendrikLanghammer/vertx-pac4j",
"id": "e42179e3b2ce2632ccd2157ab5096fd17d177aa0",
"size": "3372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/pac4j/vertx/handler/impl/CallbackDeployingPac4jAuthHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "21"
},
{
"name": "Java",
"bytes": "90584"
}
],
"symlink_target": ""
} |
package winter.config.model;
import org.testng.Assert;
import org.testng.annotations.Test;
public class PropertyTest {
@Test
public void getConstructorType_byte() {
Property property = new Property(5, Property.PrimitiveType.BYTE);
Assert.assertEquals(property.getConstructorType(), Byte.TYPE);
}
@Test
public void getConstructorType_int() {
Property property = new Property(5, Property.PrimitiveType.INTEGER);
Assert.assertEquals(property.getConstructorType(), Integer.TYPE);
}
@Test
public void getConstructorType_long() {
Property property = new Property(5, Property.PrimitiveType.LONG);
Assert.assertEquals(property.getConstructorType(), Long.TYPE);
}
@Test
public void getConstructorType_float() {
Property property = new Property(4.2, Property.PrimitiveType.FLOAT);
Assert.assertEquals(property.getConstructorType(), Float.TYPE);
}
@Test
public void getConstructorType_double() {
Property property = new Property(4.2, Property.PrimitiveType.DOUBLE);
Assert.assertEquals(property.getConstructorType(), Double.TYPE);
}
@Test
public void getConstructorType_string() {
Property property = new Property("yo", Property.PrimitiveType.STRING);
Assert.assertEquals(property.getConstructorType(), String.class);
}
@Test
public void getConstructorType_enum() {
Parameter property = new Enum(E.E1);
Assert.assertEquals(property.getConstructorType(), E.class);
}
@Test
public void toString_int() {
Property property = new Property(5, Property.PrimitiveType.INTEGER);
Assert.assertEquals(property.toString(), "[int:5]");
}
@Test
public void toString_long() {
Property property = new Property(5, Property.PrimitiveType.LONG);
Assert.assertEquals(property.toString(), "[long:5]");
}
@Test
public void toString_string() {
Property property = new Property("yo", Property.PrimitiveType.STRING);
Assert.assertEquals(property.toString(), "[class java.lang.String:yo]");
}
@Test
public void toString_enum() {
Parameter property = new Enum(E.E1);
Assert.assertEquals(property.toString(), "[class winter.config.model.PropertyTest$E:E1]");
}
enum E{
E1;
}
} | {
"content_hash": "c19e65e5543cb0d4c2e4c1914afaf7d7",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 98,
"avg_line_length": 30.46153846153846,
"alnum_prop": 0.6683501683501684,
"repo_name": "aviadbd/winter",
"id": "890199c72ee4797e7995bfdd1752435a84ac01e0",
"size": "2376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/winter/config/model/PropertyTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "62980"
}
],
"symlink_target": ""
} |
title: warbloggers
author: alba
layout: post
permalink: /2003/03/24/warbloggers/
categories:
- web
tags:
- web
---
[warbloggers][1]
[1]: http://www.washingtonpost.com/wp-dyn/articles/A12179-2003Mar22.html "'Webloggers,' Signing On as War Correspondents (washingtonpost.com)" | {
"content_hash": "4743065227642d9395b46800e574d6c7",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 143,
"avg_line_length": 23.333333333333332,
"alnum_prop": 0.7428571428571429,
"repo_name": "ericalba/ericalba.github.io",
"id": "a01cb0633bf41446ccd246c981222b99a7dc75bb",
"size": "284",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2003-03-24-warbloggers.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16266"
},
{
"name": "HTML",
"bytes": "26450"
},
{
"name": "Ruby",
"bytes": "6932"
}
],
"symlink_target": ""
} |
@interface VoucherServer () <NSNetServiceDelegate>
@property (copy, nonatomic) NSString *displayName;
@property (copy, nonatomic) NSString *uniqueSharedId;
@property (assign, nonatomic) BOOL isAdvertising;
@property (assign, nonatomic) BOOL shouldBeAdvertising;
@property (assign, nonatomic) BOOL isConnectedToClient;
// Advertising
@property (copy, nonatomic) VoucherServerRequestHandler requestHandler;
@property (strong, nonatomic) NSNetService *server;
@property (copy, nonatomic) NSString *registeredServerName;
@property (copy, nonatomic) NSString *serviceName;
@end
@implementation VoucherServer
- (instancetype)initWithUniqueSharedId:(NSString *)uniqueSharedId displayName:(NSString *)displayName
{
self = [super init];
if (self) {
self.uniqueSharedId = uniqueSharedId;
NSString *appString = [self.uniqueSharedId stringByReplacingOccurrencesOfString:@"." withString:@"_"];
self.serviceName = [NSString stringWithFormat:kVoucherServiceNameFormat, appString];
if (displayName.length == 0) {
displayName = [UIDevice currentDevice].name;
}
self.displayName = displayName;
}
return self;
}
- (instancetype)initWithUniqueSharedId:(NSString *)uniqueSharedId
{
return [self initWithUniqueSharedId:uniqueSharedId displayName:nil];
}
- (void)dealloc
{
[self stop];
}
- (void)startAdvertisingWithRequestHandler:(VoucherServerRequestHandler)requestHandler
{
if (self.server != nil) {
[self stopAdvertising];
}
self.shouldBeAdvertising = YES;
self.requestHandler = requestHandler;
self.server = [[NSNetService alloc] initWithDomain:@"local"
type:self.serviceName
name:self.displayName];
self.server.includesPeerToPeer = YES;
self.server.delegate = self;
[self.server publishWithOptions:NSNetServiceListenForConnections];
}
- (void)stop
{
[self disconnectClient];
[self stopAdvertising];
self.requestHandler = nil;
}
- (void)stopAdvertising
{
self.shouldBeAdvertising = NO;
if (self.server != nil) {
[self.server stop];
self.server.delegate = nil;
self.server = nil;
}
self.registeredServerName = nil;
self.isAdvertising = NO;
}
- (void)disconnectClient
{
[self closeStreams];
}
- (void)closeStreams
{
[super closeStreams];
self.isConnectedToClient = NO;
}
- (void)openStreams
{
[super openStreams];
self.isConnectedToClient = YES;
}
#pragma mark - Overall Events
- (void)handleReceivedData:(NSData *)data
{
// We send/receive information as a NSDictionary written out
// as NSData, so convert from NSData --> NSDictionary
NSDictionary *dict = (NSDictionary *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
[self handleIncomingRequestDictionary:dict];
}
- (void)handleIncomingRequestDictionary:(NSDictionary *)requestDict
{
NSLog(@"Received request: \n%@", requestDict);
NSString *displayName = requestDict[@"displayName"];
if (self.requestHandler) {
__weak VoucherServer *_weakSelf = self;
self.requestHandler(displayName, ^(NSData * authData, NSError * error) {
NSAssert(error == nil, @"Error handling not yet implemented");
NSDictionary *responseDict = nil;
if (authData.length) {
// App has granted us some data
responseDict = @{@"authData" : authData, @"displayName" : _weakSelf.displayName};
} else {
// Don't send back any response data, except our display name
responseDict = @{@"displayName" : _weakSelf.displayName};
}
NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:responseDict];
[_weakSelf sendData:responseData];
});
}
}
- (void)handleStreamEnd:(NSStream *)stream
{
[super handleStreamEnd:stream];
NSLog(@"Encountered unexpected stream end on VoucherServer, restarting server");
// An unexpected error occurred here, so
// restart server (is this the right move here?)
[self startAdvertisingWithRequestHandler:self.requestHandler];
}
#pragma mark - NSNetServiceDelegate
- (void)netServiceDidPublish:(NSNetService *)sender
{
assert(sender == self.server);
self.isAdvertising = YES;
self.registeredServerName = self.server.name;
NSLog(@"Advertising Voucher Server as: '%@'", self.registeredServerName);
}
- (void)netService:(NSNetService *)sender didAcceptConnectionWithInputStream:(NSInputStream *)inputStream outputStream:(NSOutputStream *)outputStream
{
// Due to a bug <rdar://problem/15626440>, this method is called on some unspecified
// queue rather than the queue associated with the net service (which in this case
// is the main queue). Work around this by bouncing to the main queue.
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
assert(sender == self.server);
#pragma unused(sender)
assert(inputStream != nil);
assert(outputStream != nil);
assert( (self.inputStream != nil) == (self.outputStream != nil) ); // should either have both or neither
if (self.inputStream != nil) {
// We already have a connection, reject this one
[inputStream open];
[inputStream close];
[outputStream open];
[outputStream close];
} else {
// Latch the input and output sterams and kick off an open.
self.inputStream = inputStream;
self.outputStream = outputStream;
[self openStreams];
}
}];
}
- (void)netService:(NSNetService *)sender didNotPublish:(NSDictionary *)errorDict
// This is called when the server stops of its own accord. The only reason
// that might happen is if the Bonjour registration fails when we reregister
// the server, and that's hard to trigger because we use auto-rename. I've
// left an assert here so that, if this does happen, we can figure out why it
// happens and then decide how best to handle it.
{
assert(sender == self.server);
self.isAdvertising = NO;
// This will also get called if, while the server is published, the app
// (iOS) goes to the background, then comes back.
// This fails with a NSNetServicesUnknownError (-72000). For Voucher,
// we want to get the server back up and running, if we already thought
// we were
#pragma unused(sender)
NSNetServicesError errorCode = [errorDict[NSNetServicesErrorCode] integerValue];
NSLog(@"Voucher Server stopped publishing, due to error: %ld", (long)errorCode);
if (errorCode == NSNetServicesUnknownError) {
if (self.shouldBeAdvertising) {
NSLog(@"Restarting Voucher Server...");
[self startAdvertisingWithRequestHandler:self.requestHandler];
}
}
}
#pragma mark - Setters
- (void)setIsAdvertising:(BOOL)isAdvertising
{
if (_isAdvertising == isAdvertising) {
return;
}
_isAdvertising = isAdvertising;
if ([self.delegate respondsToSelector:@selector(voucherServer:didUpdateAdvertising:)]) {
[self.delegate voucherServer:self didUpdateAdvertising:_isAdvertising];
}
}
- (void)setIsConnectedToClient:(BOOL)isConnectedToClient
{
if (_isConnectedToClient == isConnectedToClient) {
return;
}
_isConnectedToClient = isConnectedToClient;
if ([self.delegate respondsToSelector:@selector(voucherServer:didUpdateConnectionToClient:)]) {
[self.delegate voucherServer:self didUpdateConnectionToClient:_isConnectedToClient];
}
}
@end
| {
"content_hash": "6eacc81cb4e0a34d2ac5181aa1ea00e5",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 149,
"avg_line_length": 32.17573221757322,
"alnum_prop": 0.6775032509752926,
"repo_name": "almas73/Voucher",
"id": "5225c8f0959c7100db95e2282672c1bf8cf55fc1",
"size": "7939",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Voucher/Server/VoucherServer.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "31316"
},
{
"name": "Ruby",
"bytes": "1698"
},
{
"name": "Swift",
"bytes": "12649"
}
],
"symlink_target": ""
} |
namespace EF读写分离.Model
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("AuthTokenControlCenter")]
public partial class AuthTokenControlCenter
{
[Key]
public long ATCCID { get; set; }
[Required]
[StringLength(128)]
public string Appid { get; set; }
[StringLength(128)]
public string Secretid { get; set; }
public int? TokenType { get; set; }
[Required]
[StringLength(1024)]
public string Token { get; set; }
public DateTime TokenExpires { get; set; }
[StringLength(1024)]
public string RefreshToken { get; set; }
public DateTime? RefreshTokenExpires { get; set; }
}
}
| {
"content_hash": "086b5eacbad40ed65679e998c5b27fe9",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 58,
"avg_line_length": 24.885714285714286,
"alnum_prop": 0.6211251435132032,
"repo_name": "luoyefeiwu/Jerry",
"id": "7a734870bcc72bd1fc3362cd784d960e625d9387",
"size": "879",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Jerry/架构/EF读写分离/Model/AuthTokenControlCenter.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "501"
},
{
"name": "C#",
"bytes": "1167568"
},
{
"name": "CSS",
"bytes": "3981"
},
{
"name": "HTML",
"bytes": "15588"
},
{
"name": "JavaScript",
"bytes": "167484"
},
{
"name": "PowerShell",
"bytes": "309813"
}
],
"symlink_target": ""
} |
"""
Fork of pynxos library from network to code and mzbenami
Reimplemented by ktbyers to support XML-RPC in addition to JSON-RPC
"""
from __future__ import unicode_literals
class NXAPIError(Exception):
"""Generic NXAPI exception."""
pass
class NXAPICommandError(NXAPIError):
def __init__(self, command, message):
self.command = command
self.message = message
def __repr__(self):
return 'The command "{}" gave the error "{}".'.format(
self.command, self.message
)
__str__ = __repr__
class NXAPIConnectionError(NXAPIError):
"""HTTP Post Connection Error."""
pass
class NXAPIAuthError(NXAPIError):
"""HTTP Post Authentication Error."""
pass
class NXAPIPostError(NXAPIError):
"""Exception occurred during HTTP POST to NX-API."""
pass
class NXAPIXMLError(NXAPIError):
"""Exception occurred processing XML response from NX-API."""
pass
| {
"content_hash": "ab7b7a90b767737f9f8e2dda106bacdf",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 67,
"avg_line_length": 18.94,
"alnum_prop": 0.6568109820485745,
"repo_name": "spotify/napalm",
"id": "144e8ae1feda43a568831a1c5adc8d651cb2a950",
"size": "947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "napalm/nxapi_plumbing/errors.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "349372"
},
{
"name": "Ruby",
"bytes": "2509"
},
{
"name": "Smarty",
"bytes": "696"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Saving Private Ryan (1998)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0120815">Saving Private Ryan (1998)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Craig+Roush">Craig Roush</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>SAVING PRIVATE RYAN</PRE>
<P>Release Date: July 24, 1998
Starring: Tom Hanks, Tom Sizemore, Edward J. Burns, Jeremy Davies, Matt
Damon, Dennis Farina, Ted Danson, Harve Presnell
Directed by: Steven Spielberg
Distributed by: DreamWorks Pictures
MPAA Rating: R (intense prolonged realistically graphic sequences of war
violence, language)
URL: <A HREF="http://www.execpc.com/~kinnopio/reviews/1998/saving.htm">http://www.execpc.com/~kinnopio/reviews/1998/saving.htm</A></P>
<P>It's a dismal day on the northwestern coast of France: the skies are
heavily overcast, the seas are choppy, the winds are high. At the Dog
Green sector of Omaha Beach, things are particularly gruesome: tens of
thousands of American infantrymen push relentlessly toward the sand in
troop transports. Then the army of boats land, and the ramps drop, and
there's a split second where everyone gets their first look at France.
Then the German gunners fill the air with rifle fire and troops are cut
down by the hundreds - some before taking their first step. Others are
killed on the beaches, or in the water, but eventually - if only by
sheer numbers - the Allied invasion force at Normandy wins the day and
gets a small foothold in Nazi France. </P>
<P>Such is the opening scene in Steven Spielberg's latest epic masterpiece,
SAVING PRIVATE RYAN, a scene which some thought might have earned the
movie an NC-17 classification if the movie had been directed by any
other man. Such claims are not far off base, in the sense that Spielberg
incorporates an awesomely stunning amount of realism into his latest
product. The intense violence, largely concentrated to the first twenty
or thirty minutes, is a no-holds-barred look at the Great War. Men die
explicitly and and in utter chaos. At first glance, it would be easy to
earmark such a crass depiction as nothing but gratuitous violence. But
after only moments of viewing, Spielberg does the near-impossible. He
puts every member of the audience there at Dog Green on June 6, 1944. </P>
<P>Even after the opening-scene slaughter, everything remains authentic.
Mid-forties jargon, olive green uniforms, bulky grey helmets, original
automatic weapons, and more are all replicated in stunning detail and
attention to realism. On those terms, SAVING PRIVATE RYAN is to World
War II what TITANIC was to its namesake oceanliner. If there's anything
about the movie that Spielberg does the most, it's in creating an
authentic, believable, and complete atmosphere for the story. Tramping
around the French countryside night and day, everyone watching is in a
complete sense of awe at the time travel they have just undergone. This
benchmark statement of set and production design is accented and
furthered by the acting corps. </P>
<P>Tom Hanks (THAT THING YOU DO!), Tom Sizemore (THE RELIC), and Ed Burns
(SHE'S THE ONE) are the lead players in a squad of US Army Rangers with
the mission of locating Private James Ryan. Ryan has three brothers, all
of whom have already been killed, and the War Department, fearing a
scandal, gives Captain Miller (Hanks) and his team the job of finding
the remaining Ryan. Each and every member of the team is believable and
solid in nature, as the joke, laugh, cry, and suffer through war and its
facilities. Hanks is not outstanding but is wonderful as ever, exuding
an aura that only comes from a man who has two successive Best Actor
nominations. His lead is essential in this movie, and contributes
greatly to making SAVING PRIVATE RYAN Spielberg's finest film since
SCHINDLER'S LIST. In comparison to his last feature, AMISTAD, Spielberg
exchanges a more colorful set for a more action-filled script; this
works out for the better with a 170-minute running time. All-in-all, the
definitive must-see feature of the summer, and possibly the year.</P>
<P>FINAL AWARD FOR "SAVING PRIVATE RYAN": 4.0 stars - an excellent movie.</P>
<PRE>--
Craig Roush
<A HREF="mailto:kinnopio@execpc.com">kinnopio@execpc.com</A>
--
Kinnopio's Movie Reviews
<A HREF="http://www.execpc.com/~kinnopio">http://www.execpc.com/~kinnopio</A></PRE>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "dcdeee79ebb31436b36ebd803c7df076",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 203,
"avg_line_length": 62.741176470588236,
"alnum_prop": 0.765047815488468,
"repo_name": "xianjunzhengbackup/code",
"id": "26217935cd3970e86c96c74d0f5612ade6c449b3",
"size": "5333",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/13733.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
bool Loading::init()
{
if (!Layer::init())
{
return false;
}
m_index = 0;
auto window_width = Director::getInstance()->getVisibleSize().width;
auto window_height = Director::getInstance()->getVisibleSize().height;
// autoload resources plist
this->schedule(schedule_selector(Loading::loadResources), 0.2f);
Sprite* background = Sprite::create("LoadingSlider/sliderBackground.png");
Sprite* pogress = Sprite::create("LoadingSlider/sliderProgress.png");
Sprite* button = Sprite::create("LoadingSlider/sliderButton.png");
m_Slider = ControlSlider::create(background, pogress, button);
m_Slider->setScale(3.0f);
m_Slider->setPosition(Vec2(window_width*0.5, window_height*0.5));
m_Slider->setMaximumAllowedValue(1.2f);
m_Slider->setMinimumAllowedValue(0.0f);
m_Slider->setValue(0);
this->addChild(m_Slider);
this->schedule(schedule_selector(Loading::updateSlider), 0.2f);
return true;
}
Scene* Loading::createScene()
{
auto scene = Scene::create();
auto layer = Loading::create();
scene->addChild(layer);
return scene;
}
void Loading::loadResources(float t)
{
switch (m_index) {
case 0:
{
auto spriteFrameCache = SpriteFrameCache::getInstance();
spriteFrameCache->addSpriteFramesWithFile("paint/paint.plist");
}
break;
case 1:
//SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pictures/gatechoice.plist");
break;
case 2:
//SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pictures/Itemchoose.plist");
break;
case 3:
//SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pictures/gatescene0.plist");
break;
case 4:
//SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pictures/rubbish.plist");
break;
case 5:
//SpriteFrameCache::getInstance()->addSpriteFramesWithFile("pictures/test.plist");
break;
case 6:
// after load resources ,change to game scene
Director::getInstance()->replaceScene(GameScene::createScene(GameMode::Classical, 1));
break;
}
m_index++;
}
void Loading::updateSlider(float t)
{
float sliderValue = m_Slider->getValue();
sliderValue += 0.2f;
m_Slider->setValue(sliderValue);
}
| {
"content_hash": "2529ecbc37988ad79ff38cb5195033a2",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 90,
"avg_line_length": 25.76829268292683,
"alnum_prop": 0.7288215806909607,
"repo_name": "blighli/iPhone2015",
"id": "f5784db3607b0002099bc04753dcad8346ee371c",
"size": "2171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nb15110谭锦志/ios大作业/DropsGame/Classes/Loading/Loading.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "57551727"
},
{
"name": "C",
"bytes": "989362"
},
{
"name": "C++",
"bytes": "841211"
},
{
"name": "CMake",
"bytes": "17255"
},
{
"name": "CSS",
"bytes": "45762"
},
{
"name": "GLSL",
"bytes": "4840"
},
{
"name": "HTML",
"bytes": "147506"
},
{
"name": "JavaScript",
"bytes": "545537"
},
{
"name": "Makefile",
"bytes": "5543"
},
{
"name": "Metal",
"bytes": "2713"
},
{
"name": "Objective-C",
"bytes": "21892970"
},
{
"name": "Objective-C++",
"bytes": "263154"
},
{
"name": "Ruby",
"bytes": "1031"
},
{
"name": "Shell",
"bytes": "36609"
},
{
"name": "Swift",
"bytes": "194188"
}
],
"symlink_target": ""
} |
The MIT License (MIT)
Copyright (c) 2016 Felipe Soares
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
| {
"content_hash": "9837956335daf1bdccddb902b19eb355",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 78,
"avg_line_length": 51.42857142857143,
"alnum_prop": 0.8037037037037037,
"repo_name": "Felipe31/Ramalingam-Reps",
"id": "6993a07c735874372b2de94de055c2bc3b7423c4",
"size": "1080",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "140006"
},
{
"name": "C++",
"bytes": "2326"
},
{
"name": "Makefile",
"bytes": "1480"
},
{
"name": "R",
"bytes": "459"
}
],
"symlink_target": ""
} |
<?php if ( ! defined( 'ABSPATH' ) ) exit;
/**
* Class NF_MergeTags_Calcs
*/
final class NF_MergeTags_Calcs extends NF_Abstracts_MergeTags
{
protected $id = 'calcs';
protected $_default_group = FALSE;
public function __construct()
{
parent::__construct();
$this->title = __( 'Calculations', 'ninja-forms' );
add_filter( 'ninja_forms_calc_setting', array( $this, 'replace' ) );
}
public function __call($name, $arguments)
{
return $this->merge_tags[ $name ][ 'calc_value' ];
}
public function set_merge_tags( $key, $value, $round = 2 )
{
global $wp_locale;
$dec = $wp_locale->number_format['decimal_point'];
$sep = $wp_locale->number_format['thousands_sep'];
$callback = ( is_numeric( $key ) ) ? 'calc_' . $key : $key;
try {
$value = str_replace($sep, '', $value);
$value = str_replace($dec, '.', $value);
$calculated_value = Ninja_Forms()->eos()->solve( $value );
} catch( Exception $e ){
$calculated_value = FALSE;
}
$this->merge_tags[ $callback ] = array(
'id' => $key,
'tag' => "{calc:$key}",
// 'label' => __( '', 'ninja_forms' ),
'callback' => $callback,
'calc_value' => number_format( $calculated_value, $round, $dec, $sep )
);
$callback .= '2';
$this->merge_tags[ $callback ] = array(
'id' => $key,
'tag' => "{calc:$key:2}",
// 'label' => __( '', 'ninja_forms' ),
'callback' => $callback,
'calc_value' => number_format( $calculated_value, 2, $dec, $sep )
);
}
public function get_calc_value( $key )
{
return $this->merge_tags[ $key ][ 'calc_value' ];
}
} // END CLASS NF_MergeTags_Calcs
| {
"content_hash": "bace3e86a434b0dd7db09350aca88545",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 82,
"avg_line_length": 29.666666666666668,
"alnum_prop": 0.492776886035313,
"repo_name": "1001hz/wpnoonan",
"id": "87e95f194ca7c248088c97ec7189ab03d40af55f",
"size": "1869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/ninja-forms/includes/MergeTags/Calcs.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "616"
},
{
"name": "CSS",
"bytes": "1118696"
},
{
"name": "HTML",
"bytes": "17775"
},
{
"name": "JavaScript",
"bytes": "602452"
},
{
"name": "PHP",
"bytes": "2743716"
}
],
"symlink_target": ""
} |
package org.sakaiproject.component.section;
import java.io.Serializable;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import org.sakaiproject.section.api.coursemanagement.Course;
import org.sakaiproject.section.api.coursemanagement.CourseSection;
/**
* A detachable CourseSection for persistent storage.
*
* @author <a href="mailto:jholtzman@berkeley.edu">Josh Holtzman</a>
*
*/
public class CourseSectionImpl extends LearningContextImpl implements CourseSection, Comparable, Serializable {
private static final long serialVersionUID = 1L;
protected Course course;
protected String category;
protected Integer maxEnrollments;
protected List meetings;
/** Default constructor needed by hibernate */
public CourseSectionImpl() {}
/** Converts an arbitrary CourseSection into an instance of this class */
public CourseSectionImpl(CourseSection section) {
this.course = section.getCourse();
this.category = section.getCategory();
this.maxEnrollments = section.getMaxEnrollments();
this.meetings = section.getMeetings();
this.title = section.getTitle();
this.uuid = section.getUuid();
}
/**
* Convenience constructor to create a CourseSection with a single meeting.
*
* @param course
* @param title
* @param uuid
* @param category
* @param maxEnrollments
* @param location
* @param startTime
* @param endTime
* @param monday
* @param tuesday
* @param wednesday
* @param thursday
* @param friday
* @param saturday
* @param sunday
*/
public CourseSectionImpl(Course course, String title, String uuid, String category,
Integer maxEnrollments, String location, Time startTime,
Time endTime, boolean monday, boolean tuesday,
boolean wednesday, boolean thursday, boolean friday, boolean saturday,
boolean sunday) {
this.course = course;
this.title = title;
this.uuid = uuid;
this.category = category;
this.maxEnrollments = maxEnrollments;
this.meetings = new ArrayList();
MeetingImpl meeting = new MeetingImpl(location, startTime, endTime, monday, tuesday, wednesday, thursday, friday, saturday, sunday);
meetings.add(meeting);
}
public CourseSectionImpl(Course course, String title, String uuid, String category,
Integer maxEnrollments, List meetings) {
this.course = course;
this.title = title;
this.uuid = uuid;
this.category = category;
this.maxEnrollments = maxEnrollments;
this.meetings = meetings;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getMaxEnrollments() {
return maxEnrollments;
}
public void setMaxEnrollments(Integer maxEnrollments) {
this.maxEnrollments = maxEnrollments;
}
public List getMeetings() {
return meetings;
}
public void setMeetings(List meetings) {
this.meetings = meetings;
}
/**
* Compares CourseSectionImpls based on their category ID and title. Sections
* without a category are sorted last.
*/
public int compareTo(Object o) {
if(o == this) {
return 0;
}
if(o instanceof CourseSectionImpl) {
CourseSectionImpl other = (CourseSectionImpl)o;
if(this.category != null && other.category == null) {
return -1;
} else if(this.category == null && other.category != null) {
return 1;
}
if(this.category == null && other.category == null) {
return this.title.compareTo(other.title);
}
int categoryComparison = this.category.compareTo(other.category);
if(categoryComparison == 0) {
return this.title.compareTo(other.title);
} else {
return categoryComparison;
}
} else {
throw new ClassCastException("Can not compare CourseSectionImpl to " + o.getClass());
}
}
/**
* Standalone does not support the notion of enterprise-defined CourseSections.
*/
public String getEid() {
return null;
}
}
| {
"content_hash": "cc3c17bc0c37e05240bbb7abf24b7f04",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 134,
"avg_line_length": 27.83783783783784,
"alnum_prop": 0.6990291262135923,
"repo_name": "eemirtekin/Sakai-10.6-TR",
"id": "5d847b17a4762352ed8da8ec61901606662d3269",
"size": "5285",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "edu-services/sections-service/sections-impl/standalone/src/java/org/sakaiproject/component/section/CourseSectionImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "59098"
},
{
"name": "Batchfile",
"bytes": "6366"
},
{
"name": "C++",
"bytes": "6402"
},
{
"name": "CSS",
"bytes": "2616828"
},
{
"name": "ColdFusion",
"bytes": "146057"
},
{
"name": "HTML",
"bytes": "5982358"
},
{
"name": "Java",
"bytes": "49585098"
},
{
"name": "JavaScript",
"bytes": "6722774"
},
{
"name": "Lasso",
"bytes": "26436"
},
{
"name": "PHP",
"bytes": "223840"
},
{
"name": "PLSQL",
"bytes": "2163243"
},
{
"name": "Perl",
"bytes": "102776"
},
{
"name": "Python",
"bytes": "87575"
},
{
"name": "Ruby",
"bytes": "3606"
},
{
"name": "Shell",
"bytes": "33041"
},
{
"name": "SourcePawn",
"bytes": "2274"
},
{
"name": "XSLT",
"bytes": "607759"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenTK;
namespace BehaviourEngine.Example
{
public class Zombie : GameObject
{
public Vector2 Size = Vector2.One * 0.75f;
private Vector2 direction = -Vector2.UnitX;
public Vector2 Direction
{
get { return direction; }
set { direction = value; Flip(); }
}
public float Speed = 2f;
private Vector2 originalScale;
private Rigidbody2D rigidbody;
public Zombie()
{
this.Layer = (uint)CollisionLayer.Enemy;
this.Transform.Scale = Size;
originalScale = this.Transform.Scale;
Flip();
FSM fsm = new FSM();
//fsm.UpdateType = FSM.FSMUpdateType.FixedUpdate;
StateMove move = new StateMove(fsm, this);
fsm.AddState("move", move);
fsm.Init(move);
this.AddBehaviour(fsm);
BoxCollider2D collider = new BoxCollider2D(Size);
collider.CollisionEnter += OnCollisionEnter;
this.AddBehaviour(collider);
BoxCollider2DRenderer colliderRenderer = new BoxCollider2DRenderer();
colliderRenderer.RenderOffset = (int)RenderLayer.Collider;
this.AddBehaviour(colliderRenderer);
SpriteRenderer spriteRenderer = new SpriteRenderer(TextureManager.GetTexture("zombie"));
spriteRenderer.RenderOffset = (int)RenderLayer.Zombie;
this.AddBehaviour(spriteRenderer);
rigidbody = new Rigidbody2D();
this.AddBehaviour(rigidbody);
}
public void Die()
{
Pool<Zombie>.RecycleInstance(this, z => z.OnRecycle());
}
public void OnGet()
{
this.Active = true;
rigidbody.Velocity = Vector2.Zero;
}
public void OnRecycle()
{
this.Active = false;
rigidbody.Velocity = Vector2.Zero;
}
private void OnCollisionEnter(Collider2D other, HitState hitState)
{
if (other.Owner is Wall)
{
if (hitState.normal.X != 0f)
{
//Change Direction
direction.X *= -1f;
Flip();
}
}
}
private void Flip()
{
Vector2 scale = this.Transform.Scale;
if (Direction.X > 0f)
{
scale.X = +originalScale.X;
}
else
{
scale.X = -originalScale.X;
}
this.Transform.Scale = scale;
}
}
}
| {
"content_hash": "a487f401e315a11e16b60fe24298726d",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 100,
"avg_line_length": 27.386138613861387,
"alnum_prop": 0.5300072306579898,
"repo_name": "SaverioDiLazzaro/BehaviourEngine",
"id": "9bd7b1906bb0d054ac360b33bdb645f063230fa6",
"size": "2768",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BehaviourEngine/BehaviourEngine.Example/Prefabs/Zombie.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "115659"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zym_Recaptcha_Exception
*/
require_once 'Zym/Recaptcha/Exception.php';
/**
* @see Zym_Recaptcha_Response
*/
require_once 'Zym/Recaptcha/Response.php';
/**
* @author Jurrien Stutterheim
* @category Zym
* @package Zym_Recaptcha
* @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/)
* @license http://www.zym-project.com/license New BSD License
*/
class Zym_Recaptcha
{
/**
* API server url
*
* @var string
*/
const SERVER_API = 'http://api.recaptcha.net';
/**
* Secure API server url
*
* @var string
*/
const SERVER_API_SECURE = 'https://api-secure.recaptcha.net';
/**
* Verification server
*
* @var string
*/
const SERVER_VERIFY = 'api-verify.recaptcha.net';
/**
* Carriage return linefeed
*
* @var string
*/
const CRLF = "\r\n";
/**
* Private key
*
* @var string
*/
protected $_privateKey;
/**
* Remote IP address
*
* @var string
*/
protected $_remoteIp;
/**
* Constructor
*
* @param string $privateKey
* @param string $remoteIp
*/
public function __construct($privateKey, $remoteIp)
{
if (empty($privateKey)) {
throw new Zym_Recaptcha_Exception('No private key specified.');
}
if (empty($remoteIp)) {
throw new Zym_Recaptcha_Exception('No remote IP specified.');
}
$this->_privateKey = $privateKey;
$this->_remoteIp = $remoteIp;
}
/**
* Encodes the given data into a query string format
*
* @param $data - array of string elements to be encoded
* @return string - encoded request
*/
protected function _encodeQueryString($data)
{
$request = '';
foreach ($data as $key => $value) {
$request .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
$request = substr($request, 0, strlen($request) - 1);
return $request;
}
/**
* Submits an HTTP POST to a reCAPTCHA server
* @param string $host
* @param string $path
* @param array $data
* @param int port
* @return array response
*/
protected function _httpPost($host, $path, $data, $port = 80)
{
$requestData = $this->_encodeQueryString($data);
$httpRequest = 'POST ' . $path . ' HTTP/1.0' . self::CRLF;
$httpRequest .= 'Host: ' . $host . self::CRLF;
$httpRequest .= 'Content-Type: application/x-www-form-urlencoded;' . self::CRLF;
$httpRequest .= 'Content-Length: ' . strlen($requestData) . self::CLRF;
$httpRequest .= 'User-Agent: reCAPTCHA/PHP' . self::CLRF;
$httpRequest .= self::CRLF;
$httpRequest .= $requestData;
$response = '';
$errno = null;
$errstr = null;
$socket = @fsockopen($host, $port, $errno, $errstr, 10);
if (!$socket) {
$message = sprintf('Could not open socket. Error %s: "%s."', $errno, $errstr);
throw new Zym_Recaptcha_Exception($message);
}
fwrite($socket, $httpRequest);
while (!feof($socket)) {
$response .= fgets($socket, 1160);
}
fclose($socket);
$response = explode(self::CRLF . self::CRLF, $response, 2);
return $response;
}
/**
* Calls an HTTP POST function to verify if the user's guess was correct
*
* @param string $challenge
* @param string $response
* @param array $params
* @return Zym_Recaptcha_Response
*/
public function checkAnswer($challenge, $response, $params = array())
{
if (empty($challenge) || empty($response)) {
return new Zym_Recaptcha_Response(false, 'incorrect-captcha-sol');
}
$defaultParams = array('privatekey' => $this->_privateKey,
'remoteIp' => $this->_remoteIp,
'challenge' => $challenge,
'response' => $response);
$serverResponse = $this->_httpPost(self::SERVER_VERIFY, '/verify',
array_merge($defaultParams, $params));
$answers = explode("\n", $serverResponse[1]);
$valid = false;
$error = '';
if (trim($answers[0]) == 'true') {
$valid = true;
} else {
$error = $answers[1];
}
return new Zym_Recaptcha_Response($valid, $error);
}
/**
* gets a URL where the user can sign up for reCAPTCHA. If your application
* has a configuration page where you enter a key, you should provide a link
* using this function.
*
* @param string $domain The domain where the page is hosted
* @param string $appname The name of your application
* @return string
*/
public function getSignupUrl($domain = null, $appname = null)
{
return self::SERVER_API . '/getkey?' . $this->_encodeQueryString(array('domain' => $domain,
'app' => $appname));
}
} | {
"content_hash": "434785dea8905e1afa682789c59bc3ae",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 102,
"avg_line_length": 26.944162436548222,
"alnum_prop": 0.521665410700829,
"repo_name": "robinsk/zym",
"id": "e53cff16ac9fe28a66619c1bd144fd02790ad74e",
"size": "5679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deprecated/library/Zym/Recaptcha.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "617"
},
{
"name": "PHP",
"bytes": "1404140"
}
],
"symlink_target": ""
} |
package it.w0rd.filters;
import it.w0rd.api.auth.AuthenticationProvider;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import java.util.Base64;
public class AdminAuthFilterTest {
AdminAuthFilter adminAuthFilter;
FilterChain filterChain;
AuthenticationProvider authenticationProvider;
@Before
public void setUp() throws IOException, ServletException {
authenticationProvider = mock(AuthenticationProvider.class);
adminAuthFilter = new AdminAuthFilter(authenticationProvider);
filterChain = mock(FilterChain.class);
}
@Test
public void shouldBlockUsersWithoutAuthenticationOnAdminRoot() throws Throwable {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/");
MockHttpServletResponse response = new MockHttpServletResponse();
adminAuthFilter.doFilter(request, response, filterChain);
Mockito.verify(filterChain, times(0))
.doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class));
assertThat(response.getStatus(), equalTo(HttpServletResponse.SC_UNAUTHORIZED));
assertThat(response.getHeader("WWW-Authenticate"), equalTo("Basic"));
}
@Test
public void shouldBlockUsersWithoutAuthenticationOnAdminSomething() throws Throwable {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
adminAuthFilter.doFilter(request, response, filterChain);
Mockito.verify(filterChain, times(0))
.doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class));
assertThat(response.getStatus(), equalTo(HttpServletResponse.SC_UNAUTHORIZED));
assertThat(response.getHeader("WWW-Authenticate"), equalTo("Basic"));
}
@Test
public void shouldLetUsersWithCorrectCredentialsPass() throws Throwable {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/admin/");
final String user = "test";
final String password = "passwd";
final String authKey = new String(Base64.getEncoder().encode((user + ":" + password).getBytes()));
request.addHeader("Authorization", "Basic " + authKey);
Mockito.when(authenticationProvider.isAdministrator(Mockito.eq(user), Mockito.eq(password))).thenReturn(true);
MockHttpServletResponse response = new MockHttpServletResponse();
adminAuthFilter.doFilter(request, response, filterChain);
Mockito.verify(filterChain, times(1))
.doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class));
Mockito.verify(authenticationProvider, times(1)).isAdministrator(user, password);
assertThat(response.getStatus(), equalTo(HttpServletResponse.SC_OK));
}
@Test
public void shouldNotBlockOnNonAdminPage() throws Throwable {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/index.html");
MockHttpServletResponse response = new MockHttpServletResponse();
adminAuthFilter.doFilter(request, response, filterChain);
Mockito.verify(filterChain, times(1))
.doFilter(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class));
}
}
| {
"content_hash": "78cebffa0f0d53d9edb9b8a4b2ce2dfa",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 118,
"avg_line_length": 41.48936170212766,
"alnum_prop": 0.7415384615384616,
"repo_name": "Armandorev/url-shortener",
"id": "032e7052911bda52b48e012b59797e0082b2f94d",
"size": "3900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/it/w0rd/filters/AdminAuthFilterTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2906"
},
{
"name": "HTML",
"bytes": "1973"
},
{
"name": "Java",
"bytes": "52948"
},
{
"name": "JavaScript",
"bytes": "7089"
},
{
"name": "Shell",
"bytes": "116"
}
],
"symlink_target": ""
} |
package org.apache.webbeans.web.jetty9;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class JettySecurityFilter implements Filter
{
private static ThreadLocal<Principal> principal = new ThreadLocal<>();
public static Principal getPrincipal()
{
return principal.get();
}
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
// nothing to do
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
try
{
if (request instanceof HttpServletRequest)
{
Principal p = ((HttpServletRequest) request).getUserPrincipal();
if (p != null)
{
principal.set(p);
}
}
// continue with the request
chain.doFilter(request, response);
}
finally
{
if (principal.get() != null)
{
principal.remove();
}
}
}
@Override
public void destroy()
{
// nothing to do
}
}
| {
"content_hash": "8c90d569276fb4d24152079dfc5a8ee0",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 130,
"avg_line_length": 24.114754098360656,
"alnum_prop": 0.6070700203942896,
"repo_name": "apache/openwebbeans",
"id": "359294f416de9c731760b8039ed603986c7f93c8",
"size": "2272",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "webbeans-jetty9/src/main/java/org/apache/webbeans/web/jetty9/JettySecurityFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4590"
},
{
"name": "HTML",
"bytes": "1236"
},
{
"name": "Java",
"bytes": "4551763"
},
{
"name": "Shell",
"bytes": "10261"
}
],
"symlink_target": ""
} |
#ifndef Magnum_Trade_TextureData_h
#define Magnum_Trade_TextureData_h
/** @file
* @brief Class @ref Magnum::Trade::TextureData
*/
#include "Magnum/Array.h"
#include "Magnum/Sampler.h"
#include "Magnum/visibility.h"
namespace Magnum { namespace Trade {
/**
@brief Texture data
*/
class TextureData {
public:
/**
* @brief Texture type
*
* @see @ref type()
*/
enum class Type: UnsignedByte {
Texture1D, /**< One-dimensional texture */
Texture2D, /**< Two-dimensional texture */
Texture3D, /**< Three-dimensional texture */
Cube /**< Cube map texture */
};
/**
* @brief Constructor
* @param type Texture type
* @param minificationFilter Minification filter
* @param magnificationFilter Magnification filter
* @param mipmapFilter Mipmap filter
* @param wrapping Wrapping
* @param image Texture image ID
* @param importerState Importer-specific state
*/
TextureData(Type type, Sampler::Filter minificationFilter, Sampler::Filter magnificationFilter, Sampler::Mipmap mipmapFilter, Array3D<Sampler::Wrapping> wrapping, UnsignedInt image, const void* importerState = nullptr) noexcept: _type{type}, _minificationFilter{minificationFilter}, _magnificationFilter{magnificationFilter}, _mipmapFilter{mipmapFilter}, _wrapping{wrapping}, _image{image}, _importerState{importerState} {}
/** @brief Copying is not allowed */
TextureData(const TextureData&) = delete;
/** @brief Move constructor */
TextureData(TextureData&&) noexcept = default;
/** @brief Copying is not allowed */
TextureData& operator=(const TextureData&) = delete;
/** @brief Move assignment */
TextureData& operator=(TextureData&&) noexcept = default;
/** @brief Texture type */
Type type() const { return _type; }
/** @brief Minification filter */
Sampler::Filter minificationFilter() const { return _minificationFilter; }
/** @brief Magnification filter */
Sampler::Filter magnificationFilter() const { return _magnificationFilter; }
/** @brief Mipmap filter */
Sampler::Mipmap mipmapFilter() const { return _mipmapFilter; }
/** @brief Wrapping */
Array3D<Sampler::Wrapping> wrapping() const { return _wrapping; }
/**
* @brief Image ID
*
* ID of 1D, 2D or 3D image based on texture type. If type is
* @ref Type::Cube the function returns first of six consecutive
* IDs of cube map sides, ordered +X, -X, +Y, -Y, +Z, -Z.
* @see @ref type(), @ref AbstractImporter::image1D(),
* @ref AbstractImporter::image2D(), @ref AbstractImporter::image3D()
*/
UnsignedInt image() const { return _image; }
/**
* @brief Importer-specific state
*
* See @ref AbstractImporter::importerState() for more information.
*/
const void* importerState() const { return _importerState; }
private:
Type _type;
Sampler::Filter _minificationFilter, _magnificationFilter;
Sampler::Mipmap _mipmapFilter;
Array3D<Sampler::Wrapping> _wrapping;
UnsignedInt _image;
const void* _importerState;
};
/** @debugoperatorclassenum{Magnum::Trade::TextureData,Magnum::Trade::TextureData::Type} */
MAGNUM_EXPORT Debug& operator<<(Debug& debug, TextureData::Type value);
}}
#endif
| {
"content_hash": "8af45a40ad62a8142aa7e6aa593f48e9",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 431,
"avg_line_length": 35.36893203883495,
"alnum_prop": 0.6082898709854515,
"repo_name": "MiUishadow/magnum",
"id": "b942959b390ee9d95e2c34ecd568d617ee51878b",
"size": "4876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Magnum/Trade/TextureData.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "7448"
},
{
"name": "C",
"bytes": "720028"
},
{
"name": "C++",
"bytes": "6125526"
},
{
"name": "CMake",
"bytes": "307663"
},
{
"name": "CSS",
"bytes": "805"
},
{
"name": "GLSL",
"bytes": "47956"
},
{
"name": "HTML",
"bytes": "1181"
},
{
"name": "JavaScript",
"bytes": "2571"
},
{
"name": "Makefile",
"bytes": "852"
},
{
"name": "Objective-C",
"bytes": "11702"
},
{
"name": "Objective-C++",
"bytes": "3863"
},
{
"name": "Ruby",
"bytes": "935"
},
{
"name": "Shell",
"bytes": "12459"
}
],
"symlink_target": ""
} |
package org.dbmaintain.script.analyzer;
import org.apache.commons.lang.StringUtils;
import java.util.SortedSet;
/**
* @author Filip Neven
* @author Tim Ducheyne
* @since 6-feb-2009
*/
public class ScriptUpdatesFormatter {
/**
* @param scriptUpdates The script updates, not null
* @return An printable overview of the regular script updates
*/
public String formatScriptUpdates(SortedSet<ScriptUpdate> scriptUpdates) {
StringBuilder formattedUpdates = new StringBuilder();
int index = 0;
for (ScriptUpdate scriptUpdate : scriptUpdates) {
formattedUpdates.append(" ").append(++index).append(". ").append(StringUtils.capitalize(formatScriptUpdate(scriptUpdate))).append("\n");
}
return formattedUpdates.toString();
}
/**
* @param scriptUpdate The script update to format, not null
* @return A printable view of the given script update
*/
public String formatScriptUpdate(ScriptUpdate scriptUpdate) {
switch (scriptUpdate.getType()) {
case HIGHER_INDEX_SCRIPT_ADDED:
return "newly added indexed script: " + scriptUpdate.getScript().getFileName();
case REPEATABLE_SCRIPT_ADDED:
return "newly added repeatable script: " + scriptUpdate.getScript().getFileName();
case REPEATABLE_SCRIPT_UPDATED:
return "updated repeatable script: " + scriptUpdate.getScript().getFileName();
case REPEATABLE_SCRIPT_DELETED:
return "deleted repeatable script: " + scriptUpdate.getScript().getFileName();
case POSTPROCESSING_SCRIPT_ADDED:
return "newly added postprocessing script: " + scriptUpdate.getScript().getFileName();
case POSTPROCESSING_SCRIPT_UPDATED:
return "updated postprocessing script: " + scriptUpdate.getScript().getFileName();
case POSTPROCESSING_SCRIPT_DELETED:
return "deleted postprocessing script: " + scriptUpdate.getScript().getFileName();
case POSTPROCESSING_SCRIPT_FAILURE_RERUN:
return "re-run of failed postprocessing script: " + scriptUpdate.getScript().getFileName();
case INDEXED_SCRIPT_UPDATED:
return "updated indexed script: " + scriptUpdate.getScript().getFileName();
case INDEXED_SCRIPT_DELETED:
return "deleted indexed script: " + scriptUpdate.getScript().getFileName();
case LOWER_INDEX_NON_PATCH_SCRIPT_ADDED:
return "newly added script with a lower index: "
+ scriptUpdate.getScript().getFileName();
case LOWER_INDEX_PATCH_SCRIPT_ADDED:
return "newly added patch script with a lower index: "
+ scriptUpdate.getScript().getFileName();
case INDEXED_SCRIPT_RENAMED:
return "renamed indexed script " + scriptUpdate.getScript() + " into " + scriptUpdate.getRenamedToScript()
+ ", without changing the sequence of the scripts";
case INDEXED_SCRIPT_RENAMED_SCRIPT_SEQUENCE_CHANGED:
return "renamed indexed script " + scriptUpdate.getScript() + " into " + scriptUpdate.getRenamedToScript()
+ ", which changes the sequence of the scripts";
case REPEATABLE_SCRIPT_RENAMED:
return "renamed repeatable script " + scriptUpdate.getScript() + " into " + scriptUpdate.getRenamedToScript();
case POSTPROCESSING_SCRIPT_RENAMED:
return "renamed postprocessing script " + scriptUpdate.getScript() + " into " + scriptUpdate.getRenamedToScript();
}
throw new IllegalArgumentException("Invalid script update type " + scriptUpdate.getType());
}
}
| {
"content_hash": "f6e36a8aa2e97f39bd1ccaa0da47dc2d",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 149,
"avg_line_length": 50.973333333333336,
"alnum_prop": 0.6408579649489929,
"repo_name": "fcamblor/dbmaintain-maven-plugin",
"id": "3f22caf631f9f5189c8d404ac6be206a2c677dca",
"size": "4415",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "dbmaintain/src/main/java/org/dbmaintain/script/analyzer/ScriptUpdatesFormatter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Threading;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Common.Services;
using Common.Utilities;
using Common.Messages;
using Common.EndpointMappers;
namespace Common.Models
{
public static class ClusterExtensions
{
/// <summary>
/// Register our Middleware
/// </summary>
/// <param name="app"></param>
public static void UseCluster(this IApplicationBuilder app)
{
var endpointMapper = app.ApplicationServices.GetRequiredService<IEndpoints>();
endpointMapper.MapEndpoints(app);
}
/// <summary>
/// Add cluster dependencies and instantiate the cluster
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static Cluster AddCluster(this IServiceCollection services)
{
var workerStatus = new WorkerStatus<WorkerStatusMessage>();
var cluster = new Cluster(workerStatus);
services.AddSingleton<Cluster>(cluster);
services.AddSingleton<IWorkerStatus<WorkerStatusMessage>>(workerStatus);
services.AddTransient<IApiService, ApiService>();
services.AddTransient<IEndpoints, ClusterEndpoints>();
var serviceProvider = cluster.ServiceProvider = services.BuildServiceProvider();
var lifetime = serviceProvider.GetRequiredService<IApplicationLifetime>();
lifetime.ApplicationStarted.Register(cluster.Started);
lifetime.ApplicationStopping.Register(cluster.Stopping);
lifetime.ApplicationStopped.Register(cluster.Stopped);
return cluster;
}
}
/// <summary>
/// Basic cluster - inherit from BasicActor so that we can receive type messages (Tell)
/// </summary>
public class Cluster : BasicActor
{
private IWorkerStatus<WorkerStatusMessage> _workerStatus;
private IServiceProvider _serviceProvider { get; set; }
private ConcurrentDictionary<string, string> _availableNodes = new ConcurrentDictionary<string, string>();
private ConcurrentDictionary<Guid, object> _outbox = new ConcurrentDictionary<Guid, object>();
public IServiceProvider ServiceProvider { set { _serviceProvider = value; } }
private int _lastIndex = 0;
private long _perfCounter = 0;
private DateTime _startTime = DateTime.UtcNow;
public Cluster(IWorkerStatus<WorkerStatusMessage> workerStatus)
{
_workerStatus = workerStatus;
Receive<NodeReady>(n =>
_availableNodes.TryAdd(n.IpAddress, n.IpAddress)
);
Receive<NodeLeft>(n =>
{
string node;
_availableNodes.TryRemove(n.IpAddress, out node);
});
Receive<TaskComplete>(t =>
{
object task;
var success = _outbox.TryRemove(new Guid(t.TaskId), out task);
if (task == null)
{
// Why wasn't it found?
Console.WriteLine();
}
});
}
/// <summary>
/// Simple round-robin to get next node
/// </summary>
public string NextNode
{
get
{
if ((_availableNodes?.Count ?? 0) == 0)
{
return null;
}
if (_lastIndex == _availableNodes.Count - 1)
{
_lastIndex = 0;
}
else
{
_lastIndex++;
}
return _availableNodes.ElementAt(_lastIndex).Value;
}
}
public void Started()
{
var cancellationTokenSource = new CancellationTokenSource();
var firstRun = true;
TaskRepeater.Interval(TimeSpan.FromMilliseconds(50), () =>
{
if ((_availableNodes?.Count ?? 0) > 0)
{
if (firstRun)
{
_startTime = DateTime.UtcNow;
firstRun = false;
}
_perfCounter++;
var random = new Random();
var nodeHost = this.NextNode;
// Randomly choose what to send to the node(s)
if (!string.IsNullOrWhiteSpace(nodeHost))
{
// Randomly choose what to send to the waiting nodes.
if (random.Next(0, 1000) > 500)
{
TellNodeToProcessMarket(nodeHost);
}
else
{
TellNodeToStart(nodeHost);
}
}
TimeSpan span = DateTime.UtcNow - _startTime;
long msPerRequest = (int)span.TotalMilliseconds / _perfCounter;
Console.WriteLine(msPerRequest);
}
}, cancellationTokenSource.Token, true);
}
public void Stopping()
{
// Perform some cleanup?
}
public void Stopped()
{
// Perform some cleanup?
}
private void TellNodeToStart(string nodeHost)
{
try
{
var taskId = Guid.NewGuid().ToString();
var message = "start please";
var apiService = _serviceProvider.GetRequiredService<IApiService>();
var url = string.Format("http://{0}/api/worker/startJob/", nodeHost);
var startJob = new StartJob() { TaskId = taskId, MarketIdentity = message };
_outbox.TryAdd(new Guid(taskId), startJob);
apiService.PutOrPostToApi<StartJob, string>(url, startJob);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void TellNodeToProcessMarket(string nodeHost)
{
try
{
var taskId = Guid.NewGuid().ToString();
var apiService = _serviceProvider.GetRequiredService<IApiService>();
var url = string.Format("http://{0}/api/worker/processMarket/{1}", nodeHost, "process");
var processMarket = new ProcessMarket() { MarketIdentity = RandomHelper.RandMarket(), TaskId = taskId };
_outbox.TryAdd(new Guid(taskId), processMarket);
apiService.PutOrPostToApi<ProcessMarket, string>(url, processMarket);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
| {
"content_hash": "3d9e6593a2aaadc8c5f06c940b660f17",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 120,
"avg_line_length": 35.22,
"alnum_prop": 0.5239920499716071,
"repo_name": "long2know/distributed-actor-system",
"id": "ea6d2f80bfa37bfb0f56142bcd9b1a6c1b741a40",
"size": "7046",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Common/Models/Cluster.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "100201"
},
{
"name": "HTML",
"bytes": "19989"
}
],
"symlink_target": ""
} |
package fluentd
import (
"fmt"
"net"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"github.com/stretchr/testify/require"
"github.com/influxdata/telegraf/testutil"
)
// sampleJSON from fluentd version '0.14.9'
const sampleJSON = `
{
"plugins": [
{
"plugin_id": "object:f48698",
"plugin_category": "input",
"type": "dummy",
"config": {
"@type": "dummy",
"@log_level": "info",
"tag": "stdout.page.node",
"rate": "",
"dummy": "{\"hello\":\"world_from_first_dummy\"}",
"auto_increment_key": "id1"
},
"output_plugin": false,
"retry_count": null
},
{
"plugin_id": "object:e27138",
"plugin_category": "input",
"type": "dummy",
"config": {
"@type": "dummy",
"@log_level": "info",
"tag": "stdout.superproject.supercontainer",
"rate": "",
"dummy": "{\"hello\":\"world_from_second_dummy\"}",
"auto_increment_key": "id1"
},
"output_plugin": false,
"retry_count": null
},
{
"plugin_id": "object:d74060",
"plugin_category": "input",
"type": "monitor_agent",
"config": {
"@type": "monitor_agent",
"@log_level": "error",
"bind": "0.0.0.0",
"port": "24220"
},
"output_plugin": false,
"retry_count": null
},
{
"plugin_id": "object:11a5e2c",
"plugin_category": "output",
"type": "stdout",
"config": {
"@type": "stdout"
},
"output_plugin": true,
"retry_count": 0
},
{
"plugin_id": "object:11237ec",
"plugin_category": "output",
"type": "s3",
"config": {
"@type": "s3",
"@log_level": "info",
"aws_key_id": "xxxxxx",
"aws_sec_key": "xxxxxx",
"s3_bucket": "bucket",
"s3_endpoint": "http://mock:4567",
"path": "logs/%Y%m%d_%H/${tag[1]}/",
"time_slice_format": "%M",
"s3_object_key_format": "%{path}%{time_slice}_%{hostname}_%{index}_%{hex_random}.%{file_extension}",
"store_as": "gzip"
},
"output_plugin": true,
"buffer_queue_length": 0,
"retry_count": 0,
"buffer_total_queued_size": 0
},
{
"plugin_id": "object:output_td_1",
"plugin_category": "output",
"type": "tdlog",
"config": {
"@type": "tdlog",
"@id": "output_td",
"apikey": "xxxxxx",
"auto_create_table": ""
},
"output_plugin": true,
"buffer_queue_length": 0,
"buffer_total_queued_size": 0,
"retry_count": 0,
"emit_records": 0,
"emit_size": 0,
"emit_count": 0,
"write_count": 0,
"rollback_count": 0,
"slow_flush_count": 0,
"flush_time_count": 0,
"buffer_stage_length": 0,
"buffer_stage_byte_size": 0,
"buffer_queue_byte_size": 0,
"buffer_available_buffer_space_ratios": 0
},
{
"plugin_id": "object:output_td_2",
"plugin_category": "output",
"type": "tdlog",
"config": {
"@type": "tdlog",
"@id": "output_td",
"apikey": "xxxxxx",
"auto_create_table": ""
},
"output_plugin": true,
"buffer_queue_length": 0,
"buffer_total_queued_size": 0,
"retry_count": 0,
"rollback_count": 0,
"emit_records": 0,
"slow_flush_count": 0,
"buffer_available_buffer_space_ratios": 0
}
]
}
`
var (
zero float64
expectedOutput = []pluginData{
// {"object:f48698", "dummy", "input", nil, nil, nil},
// {"object:e27138", "dummy", "input", nil, nil, nil},
// {"object:d74060", "monitor_agent", "input", nil, nil, nil},
{"object:11a5e2c", "stdout", "output", &zero, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil},
{"object:11237ec", "s3", "output", &zero, &zero, &zero, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil},
{"object:output_td_1", "tdlog", "output", &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero, &zero},
{"object:output_td_2", "tdlog", "output", &zero, &zero, &zero, &zero, &zero, nil, nil, nil, &zero, nil, nil, nil, nil, &zero},
}
fluentdTest = &Fluentd{
Endpoint: "http://localhost:8081",
}
)
func Test_parse(t *testing.T) {
t.Log("Testing parser function")
t.Logf("JSON (%s) ", sampleJSON)
_, err := parse([]byte(sampleJSON))
if err != nil {
t.Error(err)
}
}
func Test_Gather(t *testing.T) {
t.Logf("Start HTTP mock (%s) with sampleJSON", fluentdTest.Endpoint)
ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, err := fmt.Fprintf(w, "%s", string(sampleJSON))
require.NoError(t, err)
}))
requestURL, err := url.Parse(fluentdTest.Endpoint)
require.NoError(t, err)
require.NotNil(t, requestURL)
ts.Listener, err = net.Listen("tcp", fmt.Sprintf("%s:%s", requestURL.Hostname(), requestURL.Port()))
require.NoError(t, err)
ts.Start()
defer ts.Close()
var acc testutil.Accumulator
err = fluentdTest.Gather(&acc)
if err != nil {
t.Error(err)
}
if !acc.HasMeasurement("fluentd") {
t.Errorf("acc.HasMeasurement: expected fluentd")
}
require.Equal(t, expectedOutput[0].PluginID, acc.Metrics[0].Tags["plugin_id"])
require.Equal(t, expectedOutput[0].PluginType, acc.Metrics[0].Tags["plugin_type"])
require.Equal(t, expectedOutput[0].PluginCategory, acc.Metrics[0].Tags["plugin_category"])
require.Equal(t, *expectedOutput[0].RetryCount, acc.Metrics[0].Fields["retry_count"])
require.Equal(t, expectedOutput[1].PluginID, acc.Metrics[1].Tags["plugin_id"])
require.Equal(t, expectedOutput[1].PluginType, acc.Metrics[1].Tags["plugin_type"])
require.Equal(t, expectedOutput[1].PluginCategory, acc.Metrics[1].Tags["plugin_category"])
require.Equal(t, *expectedOutput[1].RetryCount, acc.Metrics[1].Fields["retry_count"])
require.Equal(t, *expectedOutput[1].BufferQueueLength, acc.Metrics[1].Fields["buffer_queue_length"])
require.Equal(t, *expectedOutput[1].BufferTotalQueuedSize, acc.Metrics[1].Fields["buffer_total_queued_size"])
require.Equal(t, expectedOutput[2].PluginID, acc.Metrics[2].Tags["plugin_id"])
require.Equal(t, expectedOutput[2].PluginType, acc.Metrics[2].Tags["plugin_type"])
require.Equal(t, expectedOutput[2].PluginCategory, acc.Metrics[2].Tags["plugin_category"])
require.Equal(t, *expectedOutput[2].RetryCount, acc.Metrics[2].Fields["retry_count"])
require.Equal(t, *expectedOutput[2].BufferQueueLength, acc.Metrics[2].Fields["buffer_queue_length"])
require.Equal(t, *expectedOutput[2].BufferTotalQueuedSize, acc.Metrics[2].Fields["buffer_total_queued_size"])
require.Equal(t, *expectedOutput[2].EmitRecords, acc.Metrics[2].Fields["emit_records"])
require.Equal(t, *expectedOutput[2].EmitSize, acc.Metrics[2].Fields["emit_size"])
require.Equal(t, *expectedOutput[2].EmitCount, acc.Metrics[2].Fields["emit_count"])
require.Equal(t, *expectedOutput[2].RollbackCount, acc.Metrics[2].Fields["rollback_count"])
require.Equal(t, *expectedOutput[2].SlowFlushCount, acc.Metrics[2].Fields["slow_flush_count"])
require.Equal(t, *expectedOutput[2].WriteCount, acc.Metrics[2].Fields["write_count"])
require.Equal(t, *expectedOutput[2].FlushTimeCount, acc.Metrics[2].Fields["flush_time_count"])
require.Equal(t, *expectedOutput[2].BufferStageLength, acc.Metrics[2].Fields["buffer_stage_length"])
require.Equal(t, *expectedOutput[2].BufferStageByteSize, acc.Metrics[2].Fields["buffer_stage_byte_size"])
require.Equal(t, *expectedOutput[2].BufferQueueByteSize, acc.Metrics[2].Fields["buffer_queue_byte_size"])
require.Equal(t, *expectedOutput[2].AvailBufferSpaceRatios, acc.Metrics[2].Fields["buffer_available_buffer_space_ratios"])
require.Equal(t, expectedOutput[3].PluginID, acc.Metrics[3].Tags["plugin_id"])
require.Equal(t, expectedOutput[3].PluginType, acc.Metrics[3].Tags["plugin_type"])
require.Equal(t, expectedOutput[3].PluginCategory, acc.Metrics[3].Tags["plugin_category"])
require.Equal(t, *expectedOutput[3].RetryCount, acc.Metrics[3].Fields["retry_count"])
require.Equal(t, *expectedOutput[3].BufferQueueLength, acc.Metrics[3].Fields["buffer_queue_length"])
require.Equal(t, *expectedOutput[3].BufferTotalQueuedSize, acc.Metrics[3].Fields["buffer_total_queued_size"])
require.Equal(t, *expectedOutput[3].EmitRecords, acc.Metrics[3].Fields["emit_records"])
require.Equal(t, *expectedOutput[3].RollbackCount, acc.Metrics[3].Fields["rollback_count"])
require.Equal(t, *expectedOutput[3].SlowFlushCount, acc.Metrics[3].Fields["slow_flush_count"])
require.Equal(t, *expectedOutput[3].AvailBufferSpaceRatios, acc.Metrics[3].Fields["buffer_available_buffer_space_ratios"])
}
| {
"content_hash": "f3d5389e2b16dc4db5f0f890a70c6031",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 142,
"avg_line_length": 36.5,
"alnum_prop": 0.6252283105022831,
"repo_name": "Brightspace/telegraf",
"id": "9cd67ecdc3a6ff7ff8d14f3647dbdcfc8cd8ebd6",
"size": "8760",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "plugins/inputs/fluentd/fluentd_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "9352068"
},
{
"name": "Makefile",
"bytes": "14981"
},
{
"name": "PowerShell",
"bytes": "1385"
},
{
"name": "Ragel",
"bytes": "10377"
},
{
"name": "Ruby",
"bytes": "1981"
},
{
"name": "Shell",
"bytes": "32178"
}
],
"symlink_target": ""
} |
require_relative 'spec_helper'
module Barometer
describe WeatherBug, vcr: {
cassette_name: 'WeatherBug'
} do
it 'auto-registers this weather service as :weather_bug' do
expect( Barometer::WeatherService.source(:weather_bug) ).to eq Barometer::WeatherBug
end
describe '.call' do
let(:query) { build_query }
context 'when no keys are provided' do
it 'raises an error' do
expect {
WeatherBug.call(query)
}.to raise_error(Barometer::WeatherService::KeyRequired)
end
end
context 'when keys are provided' do
let(:config) do
{
keys: {
client_id: WEATHERBUG_CLIENT_ID,
client_secret: WEATHERBUG_CLIENT_SECRET
}
}
end
let(:converted_query) do
ConvertedQuery.new('39.1,77.1', :coordinates, :metric)
end
subject { WeatherBug.call(query, config) }
before do
allow(query).to receive(:convert!).with(:coordinates).
and_return(converted_query)
end
it 'converts the query to accepted formats' do
WeatherBug.call(query, config)
expect(query).to have_received(:convert!).with(:coordinates).at_least(:once)
end
it 'includes the expected data' do
result = WeatherBug.call(query, config)
expect(result.query).to eq '39.1,77.1'
expect(result.format).to eq :coordinates
expect(result).to be_metric
expect(result).to have_data(:current, :observed_at).as_format(:time)
expect(result).to have_data(:current, :humidity).as_format(:float)
expect(result).to have_data(:current, :icon).as_format(:number)
expect(result).to have_data(:current, :temperature).as_format(:temperature)
expect(result).to have_data(:current, :dew_point).as_format(:temperature)
expect(result).to have_data(:current, :wind).as_format(:vector)
expect( subject.forecast.size ).to be_within(1).of(19)
day_forcast = subject.forecast.find{ |p| !p.high.nil? }
expect(day_forcast).to have_data(:high).as_format(:temperature)
expect(day_forcast).to have_data(:starts_at).as_format(:time)
expect(day_forcast).to have_data(:ends_at).as_format(:time)
expect(day_forcast).to have_data(:condition).as_format(:string)
expect(day_forcast).to have_data(:icon).as_format(:number)
expect(day_forcast).to have_data(:pop).as_format(:float)
night_forcast = subject.forecast.find{ |p| !p.low.nil? }
expect(night_forcast).to have_data(:low).as_format(:temperature)
expect(night_forcast).to have_data(:starts_at).as_format(:time)
expect(night_forcast).to have_data(:ends_at).as_format(:time)
expect(night_forcast).to have_data(:condition).as_format(:string)
expect(night_forcast).to have_data(:icon).as_format(:number)
expect(night_forcast).to have_data(:pop).as_format(:float)
end
end
end
end
end
| {
"content_hash": "0a01c17ed126a3bb85ab86c79d65b797",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 90,
"avg_line_length": 36.56470588235294,
"alnum_prop": 0.6106821106821106,
"repo_name": "attack/barometer-weather_bug",
"id": "b81f7d9ca0d42181ba1e596fe744dc9cac7938d8",
"size": "3108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/weather_bug_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "17010"
}
],
"symlink_target": ""
} |
INT32 CS_INIT(CS_T *cs)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE_NP);
return pthread_mutex_init(cs,&attr);
}
INT32 CS_ENTER(CS_T *cs)
{
return pthread_mutex_lock(cs);
}
INT32 CS_LEAVE(CS_T *cs)
{
return pthread_mutex_unlock(cs);
}
TID_T THREAD_CREATE(void *(*func)(void*),void* param)
{
TID_T tid;
INT32 ret;
pthread_attr_t attr;
pthread_attr_init(&attr);
sigset_t newmask,oldmask;
sigemptyset(&newmask);
sigaddset(&newmask,SIGPIPE);
sigprocmask(SIG_SETMASK,&newmask,&oldmask);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
ret = pthread_create(&tid,&attr,func,param);
sigprocmask(SIG_SETMASK,&oldmask,&newmask);
if(ret == 0)
return tid;
else return (TID_T)-1;
}
| {
"content_hash": "211d8f14b93bc13fbfcde9033a6e79b0",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 64,
"avg_line_length": 18.68888888888889,
"alnum_prop": 0.6587395957193817,
"repo_name": "hykych/socks5",
"id": "9355dd5d6aa80d7cdfc79d009a4e20cba99e62cd",
"size": "865",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/src/libthread/libthread.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3860"
},
{
"name": "C++",
"bytes": "15932"
},
{
"name": "Makefile",
"bytes": "940"
}
],
"symlink_target": ""
} |
'use strict';
const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;
/**
* Get the certificate from the provisioning service.
*
* @param {string} certificateName Name of the certificate to retrieve.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName Name of the provisioning service the
* certificate is associated with.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _get(certificateName, resourceGroupName, provisioningServiceName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
let ifMatch = (options && options.ifMatch !== undefined) ? options.ifMatch : undefined;
// Validate
try {
if (certificateName === null || certificateName === undefined || typeof certificateName.valueOf() !== 'string') {
throw new Error('certificateName cannot be null or undefined and it must be of type string.');
}
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}';
requestUrl = requestUrl.replace('{certificateName}', encodeURIComponent(certificateName));
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
let queryParameters = [];
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['CertificateResponse']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/**
* @summary Upload the certificate to the provisioning service.
*
* Add new certificate or update an existing certificate.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName The name of the certificate create or
* update.
*
* @param {object} certificateDescription The certificate body.
*
* @param {string} [certificateDescription.certificate] Base-64 representation
* of the X509 leaf certificate .cer file or just .pem file content.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate. This is required
* to update an existing certificate, and ignored while creating a brand new
* certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _createOrUpdate(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
let ifMatch = (options && options.ifMatch !== undefined) ? options.ifMatch : undefined;
// Validate
try {
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (certificateName === null || certificateName === undefined || typeof certificateName.valueOf() !== 'string') {
throw new Error('certificateName cannot be null or undefined and it must be of type string.');
}
if (certificateName !== null && certificateName !== undefined) {
if (certificateName.length > 256)
{
throw new Error('"certificateName" should satisfy the constraint - "MaxLength": 256');
}
}
if (certificateDescription === null || certificateDescription === undefined) {
throw new Error('certificateDescription cannot be null or undefined.');
}
if (ifMatch !== null && ifMatch !== undefined && typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
requestUrl = requestUrl.replace('{certificateName}', encodeURIComponent(certificateName));
let queryParameters = [];
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'PUT';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
// Serialize Request
let requestContent = null;
let requestModel = null;
try {
if (certificateDescription !== null && certificateDescription !== undefined) {
let requestModelMapper = new client.models['CertificateBodyDescription']().mapper();
requestModel = client.serialize(requestModelMapper, certificateDescription, 'certificateDescription');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
`payload - ${JSON.stringify(certificateDescription, null, 2)}.`);
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['CertificateResponse']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/**
* @summary Delete the Provisioning Service Certificate.
*
* Deletes the specified certificate assosciated with the Provisioning Service
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} ifMatch ETag of the certificate
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName This is a mandatory field, and is the
* logical name of the certificate that the provisioning service will access
* by.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] This is optional, and it is the
* Common Name of the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data within the
* certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if certificate
* has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] A description that mentions the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Time the certificate is created.
*
* @param {date} [options.certificatelastUpdated] Time the certificate is last
* updated.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains a private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _deleteMethod(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
let certificatename = (options && options.certificatename !== undefined) ? options.certificatename : undefined;
let certificaterawBytes = (options && options.certificaterawBytes !== undefined) ? options.certificaterawBytes : undefined;
let certificateisVerified = (options && options.certificateisVerified !== undefined) ? options.certificateisVerified : undefined;
let certificatepurpose = (options && options.certificatepurpose !== undefined) ? options.certificatepurpose : undefined;
let certificatecreated = (options && options.certificatecreated !== undefined) ? options.certificatecreated : undefined;
let certificatelastUpdated = (options && options.certificatelastUpdated !== undefined) ? options.certificatelastUpdated : undefined;
let certificatehasPrivateKey = (options && options.certificatehasPrivateKey !== undefined) ? options.certificatehasPrivateKey : undefined;
let certificatenonce = (options && options.certificatenonce !== undefined) ? options.certificatenonce : undefined;
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (ifMatch === null || ifMatch === undefined || typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (certificateName === null || certificateName === undefined || typeof certificateName.valueOf() !== 'string') {
throw new Error('certificateName cannot be null or undefined and it must be of type string.');
}
if (certificatename !== null && certificatename !== undefined && typeof certificatename.valueOf() !== 'string') {
throw new Error('certificatename must be of type string.');
}
if (certificaterawBytes && !Buffer.isBuffer(certificaterawBytes)) {
throw new Error('certificaterawBytes must be of type buffer.');
}
if (certificateisVerified !== null && certificateisVerified !== undefined && typeof certificateisVerified !== 'boolean') {
throw new Error('certificateisVerified must be of type boolean.');
}
if (certificatepurpose !== null && certificatepurpose !== undefined && typeof certificatepurpose.valueOf() !== 'string') {
throw new Error('certificatepurpose must be of type string.');
}
if (certificatecreated && !(certificatecreated instanceof Date ||
(typeof certificatecreated.valueOf() === 'string' && !isNaN(Date.parse(certificatecreated))))) {
throw new Error('certificatecreated must be of type date.');
}
if (certificatelastUpdated && !(certificatelastUpdated instanceof Date ||
(typeof certificatelastUpdated.valueOf() === 'string' && !isNaN(Date.parse(certificatelastUpdated))))) {
throw new Error('certificatelastUpdated must be of type date.');
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined && typeof certificatehasPrivateKey !== 'boolean') {
throw new Error('certificatehasPrivateKey must be of type boolean.');
}
if (certificatenonce !== null && certificatenonce !== undefined && typeof certificatenonce.valueOf() !== 'string') {
throw new Error('certificatenonce must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
requestUrl = requestUrl.replace('{certificateName}', encodeURIComponent(certificateName));
let queryParameters = [];
if (certificatename !== null && certificatename !== undefined) {
queryParameters.push('certificate.name=' + encodeURIComponent(certificatename));
}
if (certificaterawBytes !== null && certificaterawBytes !== undefined) {
queryParameters.push('certificate.rawBytes=' + encodeURIComponent(client.serializeObject(certificaterawBytes)));
}
if (certificateisVerified !== null && certificateisVerified !== undefined) {
queryParameters.push('certificate.isVerified=' + encodeURIComponent(certificateisVerified.toString()));
}
if (certificatepurpose !== null && certificatepurpose !== undefined) {
queryParameters.push('certificate.purpose=' + encodeURIComponent(certificatepurpose));
}
if (certificatecreated !== null && certificatecreated !== undefined) {
queryParameters.push('certificate.created=' + encodeURIComponent(client.serializeObject(certificatecreated)));
}
if (certificatelastUpdated !== null && certificatelastUpdated !== undefined) {
queryParameters.push('certificate.lastUpdated=' + encodeURIComponent(client.serializeObject(certificatelastUpdated)));
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined) {
queryParameters.push('certificate.hasPrivateKey=' + encodeURIComponent(certificatehasPrivateKey.toString()));
}
if (certificatenonce !== null && certificatenonce !== undefined) {
queryParameters.push('certificate.nonce=' + encodeURIComponent(certificatenonce));
}
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'DELETE';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200 && statusCode !== 204) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
return callback(null, result, httpRequest, response);
});
}
/**
* Get all the certificates tied to the provisioning service.
*
* @param {string} resourceGroupName Name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service to
* retrieve certificates for.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateListDescription} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _list(resourceGroupName, provisioningServiceName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
// Validate
try {
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates';
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
let queryParameters = [];
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'GET';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['CertificateListDescription']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/**
* Generate verification code for Proof of Possession.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate. This is required to update
* an existing certificate, and ignored while creating a brand new certificate.
*
* @param {string} resourceGroupName name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Description mentioning the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link VerificationCodeResponse} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _generateVerificationCode(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
let certificatename = (options && options.certificatename !== undefined) ? options.certificatename : undefined;
let certificaterawBytes = (options && options.certificaterawBytes !== undefined) ? options.certificaterawBytes : undefined;
let certificateisVerified = (options && options.certificateisVerified !== undefined) ? options.certificateisVerified : undefined;
let certificatepurpose = (options && options.certificatepurpose !== undefined) ? options.certificatepurpose : undefined;
let certificatecreated = (options && options.certificatecreated !== undefined) ? options.certificatecreated : undefined;
let certificatelastUpdated = (options && options.certificatelastUpdated !== undefined) ? options.certificatelastUpdated : undefined;
let certificatehasPrivateKey = (options && options.certificatehasPrivateKey !== undefined) ? options.certificatehasPrivateKey : undefined;
let certificatenonce = (options && options.certificatenonce !== undefined) ? options.certificatenonce : undefined;
// Validate
try {
if (certificateName === null || certificateName === undefined || typeof certificateName.valueOf() !== 'string') {
throw new Error('certificateName cannot be null or undefined and it must be of type string.');
}
if (ifMatch === null || ifMatch === undefined || typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch cannot be null or undefined and it must be of type string.');
}
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (certificatename !== null && certificatename !== undefined && typeof certificatename.valueOf() !== 'string') {
throw new Error('certificatename must be of type string.');
}
if (certificaterawBytes && !Buffer.isBuffer(certificaterawBytes)) {
throw new Error('certificaterawBytes must be of type buffer.');
}
if (certificateisVerified !== null && certificateisVerified !== undefined && typeof certificateisVerified !== 'boolean') {
throw new Error('certificateisVerified must be of type boolean.');
}
if (certificatepurpose !== null && certificatepurpose !== undefined && typeof certificatepurpose.valueOf() !== 'string') {
throw new Error('certificatepurpose must be of type string.');
}
if (certificatecreated && !(certificatecreated instanceof Date ||
(typeof certificatecreated.valueOf() === 'string' && !isNaN(Date.parse(certificatecreated))))) {
throw new Error('certificatecreated must be of type date.');
}
if (certificatelastUpdated && !(certificatelastUpdated instanceof Date ||
(typeof certificatelastUpdated.valueOf() === 'string' && !isNaN(Date.parse(certificatelastUpdated))))) {
throw new Error('certificatelastUpdated must be of type date.');
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined && typeof certificatehasPrivateKey !== 'boolean') {
throw new Error('certificatehasPrivateKey must be of type boolean.');
}
if (certificatenonce !== null && certificatenonce !== undefined && typeof certificatenonce.valueOf() !== 'string') {
throw new Error('certificatenonce must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}/generateVerificationCode';
requestUrl = requestUrl.replace('{certificateName}', encodeURIComponent(certificateName));
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
let queryParameters = [];
if (certificatename !== null && certificatename !== undefined) {
queryParameters.push('certificate.name=' + encodeURIComponent(certificatename));
}
if (certificaterawBytes !== null && certificaterawBytes !== undefined) {
queryParameters.push('certificate.rawBytes=' + encodeURIComponent(client.serializeObject(certificaterawBytes)));
}
if (certificateisVerified !== null && certificateisVerified !== undefined) {
queryParameters.push('certificate.isVerified=' + encodeURIComponent(certificateisVerified.toString()));
}
if (certificatepurpose !== null && certificatepurpose !== undefined) {
queryParameters.push('certificate.purpose=' + encodeURIComponent(certificatepurpose));
}
if (certificatecreated !== null && certificatecreated !== undefined) {
queryParameters.push('certificate.created=' + encodeURIComponent(client.serializeObject(certificatecreated)));
}
if (certificatelastUpdated !== null && certificatelastUpdated !== undefined) {
queryParameters.push('certificate.lastUpdated=' + encodeURIComponent(client.serializeObject(certificatelastUpdated)));
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined) {
queryParameters.push('certificate.hasPrivateKey=' + encodeURIComponent(certificatehasPrivateKey.toString()));
}
if (certificatenonce !== null && certificatenonce !== undefined) {
queryParameters.push('certificate.nonce=' + encodeURIComponent(certificatenonce));
}
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
httpRequest.body = null;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['VerificationCodeResponse']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/**
* @summary Verify certificate's private key possession.
*
* Verifies the certificate's private key possession by providing the leaf cert
* issued by the verifying pre uploaded certificate.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate.
*
* @param {object} request The name of the certificate
*
* @param {string} [request.certificate] base-64 representation of X509
* certificate .cer file or just .pem file content.
*
* @param {string} resourceGroupName Resource group name.
*
* @param {string} provisioningServiceName Provisioning service name.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Describe the purpose of the
* certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} callback - The callback.
*
* @returns {function} callback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
function _verifyCertificate(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options, callback) {
/* jshint validthis: true */
let client = this.client;
if(!callback && typeof options === 'function') {
callback = options;
options = null;
}
if (!callback) {
throw new Error('callback cannot be null.');
}
let certificatename = (options && options.certificatename !== undefined) ? options.certificatename : undefined;
let certificaterawBytes = (options && options.certificaterawBytes !== undefined) ? options.certificaterawBytes : undefined;
let certificateisVerified = (options && options.certificateisVerified !== undefined) ? options.certificateisVerified : undefined;
let certificatepurpose = (options && options.certificatepurpose !== undefined) ? options.certificatepurpose : undefined;
let certificatecreated = (options && options.certificatecreated !== undefined) ? options.certificatecreated : undefined;
let certificatelastUpdated = (options && options.certificatelastUpdated !== undefined) ? options.certificatelastUpdated : undefined;
let certificatehasPrivateKey = (options && options.certificatehasPrivateKey !== undefined) ? options.certificatehasPrivateKey : undefined;
let certificatenonce = (options && options.certificatenonce !== undefined) ? options.certificatenonce : undefined;
// Validate
try {
if (certificateName === null || certificateName === undefined || typeof certificateName.valueOf() !== 'string') {
throw new Error('certificateName cannot be null or undefined and it must be of type string.');
}
if (ifMatch === null || ifMatch === undefined || typeof ifMatch.valueOf() !== 'string') {
throw new Error('ifMatch cannot be null or undefined and it must be of type string.');
}
if (request === null || request === undefined) {
throw new Error('request cannot be null or undefined.');
}
if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
}
if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
}
if (provisioningServiceName === null || provisioningServiceName === undefined || typeof provisioningServiceName.valueOf() !== 'string') {
throw new Error('provisioningServiceName cannot be null or undefined and it must be of type string.');
}
if (certificatename !== null && certificatename !== undefined && typeof certificatename.valueOf() !== 'string') {
throw new Error('certificatename must be of type string.');
}
if (certificaterawBytes && !Buffer.isBuffer(certificaterawBytes)) {
throw new Error('certificaterawBytes must be of type buffer.');
}
if (certificateisVerified !== null && certificateisVerified !== undefined && typeof certificateisVerified !== 'boolean') {
throw new Error('certificateisVerified must be of type boolean.');
}
if (certificatepurpose !== null && certificatepurpose !== undefined && typeof certificatepurpose.valueOf() !== 'string') {
throw new Error('certificatepurpose must be of type string.');
}
if (certificatecreated && !(certificatecreated instanceof Date ||
(typeof certificatecreated.valueOf() === 'string' && !isNaN(Date.parse(certificatecreated))))) {
throw new Error('certificatecreated must be of type date.');
}
if (certificatelastUpdated && !(certificatelastUpdated instanceof Date ||
(typeof certificatelastUpdated.valueOf() === 'string' && !isNaN(Date.parse(certificatelastUpdated))))) {
throw new Error('certificatelastUpdated must be of type date.');
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined && typeof certificatehasPrivateKey !== 'boolean') {
throw new Error('certificatehasPrivateKey must be of type boolean.');
}
if (certificatenonce !== null && certificatenonce !== undefined && typeof certificatenonce.valueOf() !== 'string') {
throw new Error('certificatenonce must be of type string.');
}
if (this.client.apiVersion === null || this.client.apiVersion === undefined || typeof this.client.apiVersion.valueOf() !== 'string') {
throw new Error('this.client.apiVersion cannot be null or undefined and it must be of type string.');
}
if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
throw new Error('this.client.acceptLanguage must be of type string.');
}
} catch (error) {
return callback(error);
}
// Construct URL
let baseUrl = this.client.baseUri;
let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Devices/provisioningServices/{provisioningServiceName}/certificates/{certificateName}/verify';
requestUrl = requestUrl.replace('{certificateName}', encodeURIComponent(certificateName));
requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
requestUrl = requestUrl.replace('{provisioningServiceName}', encodeURIComponent(provisioningServiceName));
let queryParameters = [];
if (certificatename !== null && certificatename !== undefined) {
queryParameters.push('certificate.name=' + encodeURIComponent(certificatename));
}
if (certificaterawBytes !== null && certificaterawBytes !== undefined) {
queryParameters.push('certificate.rawBytes=' + encodeURIComponent(client.serializeObject(certificaterawBytes)));
}
if (certificateisVerified !== null && certificateisVerified !== undefined) {
queryParameters.push('certificate.isVerified=' + encodeURIComponent(certificateisVerified.toString()));
}
if (certificatepurpose !== null && certificatepurpose !== undefined) {
queryParameters.push('certificate.purpose=' + encodeURIComponent(certificatepurpose));
}
if (certificatecreated !== null && certificatecreated !== undefined) {
queryParameters.push('certificate.created=' + encodeURIComponent(client.serializeObject(certificatecreated)));
}
if (certificatelastUpdated !== null && certificatelastUpdated !== undefined) {
queryParameters.push('certificate.lastUpdated=' + encodeURIComponent(client.serializeObject(certificatelastUpdated)));
}
if (certificatehasPrivateKey !== null && certificatehasPrivateKey !== undefined) {
queryParameters.push('certificate.hasPrivateKey=' + encodeURIComponent(certificatehasPrivateKey.toString()));
}
if (certificatenonce !== null && certificatenonce !== undefined) {
queryParameters.push('certificate.nonce=' + encodeURIComponent(certificatenonce));
}
queryParameters.push('api-version=' + encodeURIComponent(this.client.apiVersion));
if (queryParameters.length > 0) {
requestUrl += '?' + queryParameters.join('&');
}
// Create HTTP transport objects
let httpRequest = new WebResource();
httpRequest.method = 'POST';
httpRequest.url = requestUrl;
httpRequest.headers = {};
// Set Headers
httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
if (this.client.generateClientRequestId) {
httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
}
if (ifMatch !== undefined && ifMatch !== null) {
httpRequest.headers['If-Match'] = ifMatch;
}
if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
httpRequest.headers['accept-language'] = this.client.acceptLanguage;
}
if(options) {
for(let headerName in options['customHeaders']) {
if (options['customHeaders'].hasOwnProperty(headerName)) {
httpRequest.headers[headerName] = options['customHeaders'][headerName];
}
}
}
// Serialize Request
let requestContent = null;
let requestModel = null;
try {
if (request !== null && request !== undefined) {
let requestModelMapper = new client.models['VerificationCodeRequest']().mapper();
requestModel = client.serialize(requestModelMapper, request, 'request');
requestContent = JSON.stringify(requestModel);
}
} catch (error) {
let serializationError = new Error(`Error "${error.message}" occurred in serializing the ` +
`payload - ${JSON.stringify(request, null, 2)}.`);
return callback(serializationError);
}
httpRequest.body = requestContent;
// Send Request
return client.pipeline(httpRequest, (err, response, responseBody) => {
if (err) {
return callback(err);
}
let statusCode = response.statusCode;
if (statusCode !== 200) {
let error = new Error(responseBody);
error.statusCode = response.statusCode;
error.request = msRest.stripRequest(httpRequest);
error.response = msRest.stripResponse(response);
if (responseBody === '') responseBody = null;
let parsedErrorResponse;
try {
parsedErrorResponse = JSON.parse(responseBody);
if (parsedErrorResponse) {
let internalError = null;
if (parsedErrorResponse.error) internalError = parsedErrorResponse.error;
error.code = internalError ? internalError.code : parsedErrorResponse.code;
error.message = internalError ? internalError.message : parsedErrorResponse.message;
}
if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
let resultMapper = new client.models['ErrorDetails']().mapper();
error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
}
} catch (defaultError) {
error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
`- "${responseBody}" for the default response.`;
return callback(error);
}
return callback(error);
}
// Create Result
let result = null;
if (responseBody === '') responseBody = null;
// Deserialize Response
if (statusCode === 200) {
let parsedResponse = null;
try {
parsedResponse = JSON.parse(responseBody);
result = JSON.parse(responseBody);
if (parsedResponse !== null && parsedResponse !== undefined) {
let resultMapper = new client.models['CertificateResponse']().mapper();
result = client.deserialize(resultMapper, parsedResponse, 'result');
}
} catch (error) {
let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
deserializationError.request = msRest.stripRequest(httpRequest);
deserializationError.response = msRest.stripResponse(response);
return callback(deserializationError);
}
}
return callback(null, result, httpRequest, response);
});
}
/** Class representing a DpsCertificate. */
class DpsCertificate {
/**
* Create a DpsCertificate.
* @param {IotDpsClient} client Reference to the service client.
*/
constructor(client) {
this.client = client;
this._get = _get;
this._createOrUpdate = _createOrUpdate;
this._deleteMethod = _deleteMethod;
this._list = _list;
this._generateVerificationCode = _generateVerificationCode;
this._verifyCertificate = _verifyCertificate;
}
/**
* Get the certificate from the provisioning service.
*
* @param {string} certificateName Name of the certificate to retrieve.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName Name of the provisioning service the
* certificate is associated with.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
getWithHttpOperationResponse(certificateName, resourceGroupName, provisioningServiceName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._get(certificateName, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Get the certificate from the provisioning service.
*
* @param {string} certificateName Name of the certificate to retrieve.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName Name of the provisioning service the
* certificate is associated with.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CertificateResponse} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
get(certificateName, resourceGroupName, provisioningServiceName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._get(certificateName, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._get(certificateName, resourceGroupName, provisioningServiceName, options, optionalCallback);
}
}
/**
* @summary Upload the certificate to the provisioning service.
*
* Add new certificate or update an existing certificate.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName The name of the certificate create or
* update.
*
* @param {object} certificateDescription The certificate body.
*
* @param {string} [certificateDescription.certificate] Base-64 representation
* of the X509 leaf certificate .cer file or just .pem file content.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate. This is required
* to update an existing certificate, and ignored while creating a brand new
* certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
createOrUpdateWithHttpOperationResponse(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._createOrUpdate(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Upload the certificate to the provisioning service.
*
* Add new certificate or update an existing certificate.
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName The name of the certificate create or
* update.
*
* @param {object} certificateDescription The certificate body.
*
* @param {string} [certificateDescription.certificate] Base-64 representation
* of the X509 leaf certificate .cer file or just .pem file content.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.ifMatch] ETag of the certificate. This is required
* to update an existing certificate, and ignored while creating a brand new
* certificate.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CertificateResponse} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
createOrUpdate(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._createOrUpdate(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._createOrUpdate(resourceGroupName, provisioningServiceName, certificateName, certificateDescription, options, optionalCallback);
}
}
/**
* @summary Delete the Provisioning Service Certificate.
*
* Deletes the specified certificate assosciated with the Provisioning Service
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} ifMatch ETag of the certificate
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName This is a mandatory field, and is the
* logical name of the certificate that the provisioning service will access
* by.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] This is optional, and it is the
* Common Name of the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data within the
* certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if certificate
* has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] A description that mentions the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Time the certificate is created.
*
* @param {date} [options.certificatelastUpdated] Time the certificate is last
* updated.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains a private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<null>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
deleteMethodWithHttpOperationResponse(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._deleteMethod(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Delete the Provisioning Service Certificate.
*
* Deletes the specified certificate assosciated with the Provisioning Service
*
* @param {string} resourceGroupName Resource group identifier.
*
* @param {string} ifMatch ETag of the certificate
*
* @param {string} provisioningServiceName The name of the provisioning
* service.
*
* @param {string} certificateName This is a mandatory field, and is the
* logical name of the certificate that the provisioning service will access
* by.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] This is optional, and it is the
* Common Name of the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data within the
* certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if certificate
* has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] A description that mentions the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Time the certificate is created.
*
* @param {date} [options.certificatelastUpdated] Time the certificate is last
* updated.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains a private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {null} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {null} [result] - The deserialized result object if an error did not occur.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
deleteMethod(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._deleteMethod(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._deleteMethod(resourceGroupName, ifMatch, provisioningServiceName, certificateName, options, optionalCallback);
}
}
/**
* Get all the certificates tied to the provisioning service.
*
* @param {string} resourceGroupName Name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service to
* retrieve certificates for.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CertificateListDescription>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
listWithHttpOperationResponse(resourceGroupName, provisioningServiceName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._list(resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Get all the certificates tied to the provisioning service.
*
* @param {string} resourceGroupName Name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service to
* retrieve certificates for.
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CertificateListDescription} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateListDescription} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
list(resourceGroupName, provisioningServiceName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._list(resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._list(resourceGroupName, provisioningServiceName, options, optionalCallback);
}
}
/**
* Generate verification code for Proof of Possession.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate. This is required to update
* an existing certificate, and ignored while creating a brand new certificate.
*
* @param {string} resourceGroupName name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Description mentioning the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<VerificationCodeResponse>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
generateVerificationCodeWithHttpOperationResponse(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._generateVerificationCode(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* Generate verification code for Proof of Possession.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate. This is required to update
* an existing certificate, and ignored while creating a brand new certificate.
*
* @param {string} resourceGroupName name of resource group.
*
* @param {string} provisioningServiceName Name of provisioning service.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Description mentioning the
* purpose of the certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {VerificationCodeResponse} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link VerificationCodeResponse} for more
* information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
generateVerificationCode(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._generateVerificationCode(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._generateVerificationCode(certificateName, ifMatch, resourceGroupName, provisioningServiceName, options, optionalCallback);
}
}
/**
* @summary Verify certificate's private key possession.
*
* Verifies the certificate's private key possession by providing the leaf cert
* issued by the verifying pre uploaded certificate.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate.
*
* @param {object} request The name of the certificate
*
* @param {string} [request.certificate] base-64 representation of X509
* certificate .cer file or just .pem file content.
*
* @param {string} resourceGroupName Resource group name.
*
* @param {string} provisioningServiceName Provisioning service name.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Describe the purpose of the
* certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<CertificateResponse>} - The deserialized result object.
*
* @reject {Error} - The error object.
*/
verifyCertificateWithHttpOperationResponse(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options) {
let client = this.client;
let self = this;
return new Promise((resolve, reject) => {
self._verifyCertificate(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
httpOperationResponse.body = result;
if (err) { reject(err); }
else { resolve(httpOperationResponse); }
return;
});
});
}
/**
* @summary Verify certificate's private key possession.
*
* Verifies the certificate's private key possession by providing the leaf cert
* issued by the verifying pre uploaded certificate.
*
* @param {string} certificateName The mandatory logical name of the
* certificate, that the provisioning service uses to access.
*
* @param {string} ifMatch ETag of the certificate.
*
* @param {object} request The name of the certificate
*
* @param {string} [request.certificate] base-64 representation of X509
* certificate .cer file or just .pem file content.
*
* @param {string} resourceGroupName Resource group name.
*
* @param {string} provisioningServiceName Provisioning service name.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.certificatename] Common Name for the certificate.
*
* @param {buffer} [options.certificaterawBytes] Raw data of certificate.
*
* @param {boolean} [options.certificateisVerified] Indicates if the
* certificate has been verified by owner of the private key.
*
* @param {string} [options.certificatepurpose] Describe the purpose of the
* certificate. Possible values include: 'clientAuthentication',
* 'serverAuthentication'
*
* @param {date} [options.certificatecreated] Certificate creation time.
*
* @param {date} [options.certificatelastUpdated] Certificate last updated
* time.
*
* @param {boolean} [options.certificatehasPrivateKey] Indicates if the
* certificate contains private key.
*
* @param {string} [options.certificatenonce] Random number generated to
* indicate Proof of Possession.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @param {function} [optionalCallback] - The optional callback.
*
* @returns {function|Promise} If a callback was passed as the last parameter
* then it returns the callback else returns a Promise.
*
* {Promise} A promise is returned
*
* @resolve {CertificateResponse} - The deserialized result object.
*
* @reject {Error} - The error object.
*
* {function} optionalCallback(err, result, request, response)
*
* {Error} err - The Error object if an error occurred, null otherwise.
*
* {object} [result] - The deserialized result object if an error did not occur.
* See {@link CertificateResponse} for more information.
*
* {object} [request] - The HTTP Request object if an error did not occur.
*
* {stream} [response] - The HTTP Response stream if an error did not occur.
*/
verifyCertificate(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options, optionalCallback) {
let client = this.client;
let self = this;
if (!optionalCallback && typeof options === 'function') {
optionalCallback = options;
options = null;
}
if (!optionalCallback) {
return new Promise((resolve, reject) => {
self._verifyCertificate(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options, (err, result, request, response) => {
if (err) { reject(err); }
else { resolve(result); }
return;
});
});
} else {
return self._verifyCertificate(certificateName, ifMatch, request, resourceGroupName, provisioningServiceName, options, optionalCallback);
}
}
}
module.exports = DpsCertificate;
| {
"content_hash": "7d9defb127283468086e8336271116d7",
"timestamp": "",
"source": "github",
"line_count": 2021,
"max_line_length": 265,
"avg_line_length": 45.13508164275111,
"alnum_prop": 0.682069328422022,
"repo_name": "xingwu1/azure-sdk-for-node",
"id": "d939454b0030bec5a20c131cd8d2ec4f50fae657",
"size": "91535",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/services/deviceprovisioningservicesManagement/lib/operations/dpsCertificate.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "661"
},
{
"name": "JavaScript",
"bytes": "122792600"
},
{
"name": "Shell",
"bytes": "437"
},
{
"name": "TypeScript",
"bytes": "2558"
}
],
"symlink_target": ""
} |
//
// UserCenterViewController.m
// XXRouter
//
// Created by Shawn on 2017/5/9.
// Copyright © 2017年 Shawn. All rights reserved.
//
#import "UserCenterViewController.h"
#import "TestRouter.h"
@interface UserCenterViewController ()
@end
@implementation UserCenterViewController
+ (void)load
{
XXRouterItem * homeItem = [[XXRouterItem alloc]initWithClassName:NSStringFromClass(self) nibName:@"UserCenterViewController" key:@"my"];
homeItem.customHandleCompletion = ^(XXRouter *router,XXRouterItem *item, NSDictionary *param) {
UITabBarController * tbc = (UITabBarController *)[[[[UIApplication sharedApplication]windows]firstObject]rootViewController];
NSArray * vcs = tbc.viewControllers;
UINavigationController * nai = [vcs lastObject];
if ([[nai.viewControllers firstObject] isKindOfClass:self]) {
[nai popViewControllerAnimated:NO];
tbc.selectedViewController = nai;
}
return [nai.viewControllers lastObject];
// return nil;
};
[[TestRouter shareRouter]reigsterRouterItem:homeItem];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (IBAction)msgCenter:(id)sender {
[[TestRouter shareRouter] routerWithKey:@"home" param:@{@"user":@"value"}];
}
- (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": "a29b8617e0f53e779f8f465020514df3",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 140,
"avg_line_length": 31.310344827586206,
"alnum_prop": 0.7098017621145375,
"repo_name": "ShawnCow/XXRouter",
"id": "0c0a2b8eb94c0b1596cfb04b1fb3935adad82d45",
"size": "1819",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XXRouterDemo/XXRouter/UserCenterViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "38699"
},
{
"name": "Ruby",
"bytes": "511"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_13) on Sun Jan 24 12:52:51 EST 2010 -->
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
Uses of Interface edu.uci.ics.jung.visualization.transform.MutableTransformer (jung2 2.0.1 API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="Uses of Interface edu.uci.ics.jung.visualization.transform.MutableTransformer (jung2 2.0.1 API)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?edu/uci/ics/jung/visualization/transform//class-useMutableTransformer.html" target="_top"><B>FRAMES</B></A>
<A HREF="MutableTransformer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>edu.uci.ics.jung.visualization.transform.MutableTransformer</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#edu.uci.ics.jung.visualization"><B>edu.uci.ics.jung.visualization</B></A></TD>
<TD>Frameworks and mechanisms for visualizing JUNG graphs using Swing/AWT. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#edu.uci.ics.jung.visualization.transform"><B>edu.uci.ics.jung.visualization.transform</B></A></TD>
<TD>Visualization mechanisms related to transformations, including lens effects. </TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#edu.uci.ics.jung.visualization.transform.shape"><B>edu.uci.ics.jung.visualization.transform.shape</B></A></TD>
<TD>Visualization mechanisms related to transformation of graph element shapes. </TD>
</TR>
</TABLE>
<P>
<A NAME="edu.uci.ics.jung.visualization"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/package-summary.html">edu.uci.ics.jung.visualization</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/package-summary.html">edu.uci.ics.jung.visualization</A> declared as <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#layoutTransformer">layoutTransformer</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#viewTransformer">viewTransformer</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/package-summary.html">edu.uci.ics.jung.visualization</A> that return <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#getLayoutTransformer()">getLayoutTransformer</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#getTransformer(edu.uci.ics.jung.visualization.Layer)">getTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/Layer.html" title="enum in edu.uci.ics.jung.visualization">Layer</A> layer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>MultiLayerTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/MultiLayerTransformer.html#getTransformer(edu.uci.ics.jung.visualization.Layer)">getTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/Layer.html" title="enum in edu.uci.ics.jung.visualization">Layer</A> layer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#getViewTransformer()">getViewTransformer</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/package-summary.html">edu.uci.ics.jung.visualization</A> with parameters of type <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#setLayoutTransformer(edu.uci.ics.jung.visualization.transform.MutableTransformer)">setLayoutTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> transformer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#setTransformer(edu.uci.ics.jung.visualization.Layer, edu.uci.ics.jung.visualization.transform.MutableTransformer)">setTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/Layer.html" title="enum in edu.uci.ics.jung.visualization">Layer</A> layer,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> transformer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MultiLayerTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/MultiLayerTransformer.html#setTransformer(edu.uci.ics.jung.visualization.Layer, edu.uci.ics.jung.visualization.transform.MutableTransformer)">setTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/Layer.html" title="enum in edu.uci.ics.jung.visualization">Layer</A> layer,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> transformer)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected void</CODE></FONT></TD>
<TD><CODE><B>BasicTransformer.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/BasicTransformer.html#setViewTransformer(edu.uci.ics.jung.visualization.transform.MutableTransformer)">setViewTransformer</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> transformer)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="edu.uci.ics.jung.visualization.transform"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A> that implement <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/HyperbolicTransformer.html" title="class in edu.uci.ics.jung.visualization.transform">HyperbolicTransformer</A></B></CODE>
<BR>
HyperbolicTransformer wraps a MutableAffineTransformer and modifies
the transform and inverseTransform methods so that they create a
fisheye projection of the graph points, with points near the
center spread out and points near the edges collapsed onto the
circumference of an ellipse.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/LensTransformer.html" title="class in edu.uci.ics.jung.visualization.transform">LensTransformer</A></B></CODE>
<BR>
LensTransformer wraps a MutableAffineTransformer and modifies
the transform and inverseTransform methods so that they create a
projection of the graph points within an elliptical lens.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MagnifyTransformer.html" title="class in edu.uci.ics.jung.visualization.transform">MagnifyTransformer</A></B></CODE>
<BR>
MagnifyTransformer wraps a MutableAffineTransformer and modifies
the transform and inverseTransform methods so that they create an
enlarging projection of the graph points.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableAffineTransformer.html" title="class in edu.uci.ics.jung.visualization.transform">MutableAffineTransformer</A></B></CODE>
<BR>
Provides methods to mutate the AffineTransform used by AffineTransformer
base class to map points from one coordinate system to
another.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformerDecorator.html" title="class in edu.uci.ics.jung.visualization.transform">MutableTransformerDecorator</A></B></CODE>
<BR>
a complete decorator that wraps a MutableTransformer.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A> declared as <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>MutableTransformerDecorator.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformerDecorator.html#delegate">delegate</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A> that return <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></CODE></FONT></TD>
<TD><CODE><B>MutableTransformerDecorator.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformerDecorator.html#getDelegate()">getDelegate</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A> with parameters of type <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B>MutableTransformerDecorator.</B><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformerDecorator.html#setDelegate(edu.uci.ics.jung.visualization.transform.MutableTransformer)">setDelegate</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/package-summary.html">edu.uci.ics.jung.visualization.transform</A> with parameters of type <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/HyperbolicTransformer.html#HyperbolicTransformer(java.awt.Component, edu.uci.ics.jung.visualization.transform.MutableTransformer)">HyperbolicTransformer</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html" title="class or interface in java.awt">Component</A> component,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
create an instance with a possibly shared transform</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/LensTransformer.html#LensTransformer(java.awt.Component, edu.uci.ics.jung.visualization.transform.MutableTransformer)">LensTransformer</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html" title="class or interface in java.awt">Component</A> component,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
create an instance with a possibly shared transform</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MagnifyTransformer.html#MagnifyTransformer(java.awt.Component, edu.uci.ics.jung.visualization.transform.MutableTransformer)">MagnifyTransformer</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html" title="class or interface in java.awt">Component</A> component,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
create an instance with a possibly shared transform</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformerDecorator.html#MutableTransformerDecorator(edu.uci.ics.jung.visualization.transform.MutableTransformer)">MutableTransformerDecorator</A></B>(<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<P>
<A NAME="edu.uci.ics.jung.visualization.transform.shape"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/package-summary.html">edu.uci.ics.jung.visualization.transform.shape</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Classes in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/package-summary.html">edu.uci.ics.jung.visualization.transform.shape</A> that implement <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/HyperbolicShapeTransformer.html" title="class in edu.uci.ics.jung.visualization.transform.shape">HyperbolicShapeTransformer</A></B></CODE>
<BR>
HyperbolicShapeTransformer extends HyperbolicTransformer and
adds implementations for methods in ShapeFlatnessTransformer.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> class</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/MagnifyShapeTransformer.html" title="class in edu.uci.ics.jung.visualization.transform.shape">MagnifyShapeTransformer</A></B></CODE>
<BR>
MagnifyShapeTransformer extends MagnifyTransformer and
adds implementations for methods in ShapeTransformer.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/package-summary.html">edu.uci.ics.jung.visualization.transform.shape</A> with parameters of type <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/HyperbolicShapeTransformer.html#HyperbolicShapeTransformer(java.awt.Component, edu.uci.ics.jung.visualization.transform.MutableTransformer)">HyperbolicShapeTransformer</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html" title="class or interface in java.awt">Component</A> component,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
Create an instance, setting values from the passed component
and registering to listen for size changes on the component,
with a possibly shared transform <code>delegate</code>.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/shape/MagnifyShapeTransformer.html#MagnifyShapeTransformer(java.awt.Component, edu.uci.ics.jung.visualization.transform.MutableTransformer)">MagnifyShapeTransformer</A></B>(<A HREF="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Component.html" title="class or interface in java.awt">Component</A> component,
<A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform">MutableTransformer</A> delegate)</CODE>
<BR>
Create an instance, setting values from the passed component
and registering to listen for size changes on the component,
with a possibly shared transform <code>delegate</code>.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../edu/uci/ics/jung/visualization/transform/MutableTransformer.html" title="interface in edu.uci.ics.jung.visualization.transform"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?edu/uci/ics/jung/visualization/transform//class-useMutableTransformer.html" target="_top"><B>FRAMES</B></A>
<A HREF="MutableTransformer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2010 null. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "c845c70da76fc1346a9446a8530af474",
"timestamp": "",
"source": "github",
"line_count": 486,
"max_line_length": 448,
"avg_line_length": 66.13786008230453,
"alnum_prop": 0.6831347416233705,
"repo_name": "tobyclemson/msci-project",
"id": "bc3809aa4972fe743fa1c8c31b385fa7b9db82d2",
"size": "32143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/jung-2.0.1/doc/edu/uci/ics/jung/visualization/transform/class-use/MutableTransformer.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "89867"
},
{
"name": "Ruby",
"bytes": "137019"
}
],
"symlink_target": ""
} |
package me.thuanle;
import java.io.File;
import java.io.IOException;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.GestureList;
import com.leapmotion.leap.KeyTapGesture;
import com.leapmotion.leap.Listener;
import com.leapmotion.leap.Pointable;
import com.leapmotion.leap.PointableList;
import com.leapmotion.leap.ScreenTapGesture;
import com.leapmotion.leap.SwipeGesture;
import me.thuanle.connector.connector.ASTConnector;
import me.thuanle.connector.connector.ASTProtocol;
import me.thuanle.connector.connector.ASTRequest;
import me.thuanle.connector.connector.ASTResponse;
import me.thuanle.wrapper.LMKeyTapGestureWrapper;
import me.thuanle.wrapper.LMPointableWrapper;
import me.thuanle.wrapper.LMScreenTapGestureWrapper;
import me.thuanle.wrapper.LMSwipeGestureWrapper;
class LMClient {
public static void main(String[] args) {
ASTConnector.getDefaultConnector();
// Create a sample listener and controller
SampleListener listener = new SampleListener();
Controller controller = new Controller();
// Have the sample listener receive events from the controller
controller.addListener(listener);
// Keep this process running until Enter is pressed
System.out.println("Press Enter to quit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
// Remove the sample listener when done
controller.removeListener(listener);
}
}
class SampleListener extends Listener {
public void onConnect(Controller controller) {
System.out.println("Connected");
controller.enableGesture(Gesture.Type.TYPE_SWIPE);
//controller.enableGesture(Gesture.Type.TYPE_CIRCLE);
controller.enableGesture(Gesture.Type.TYPE_SCREEN_TAP);
controller.enableGesture(Gesture.Type.TYPE_KEY_TAP);
}
public void onDisconnect(Controller controller) {
//Note: not dispatched when running in a debugger.
}
public void onExit(Controller controller) {
System.out.println("Exited");
}
public void onFrame(Controller controller) {
// Get the most recent frame and report some basic information
final Frame frame = controller.frame();
if (frame.hands().count() + frame.tools().count() + frame.gestures().count() > 0) {
System.out.println("Frame id: " + frame.id()
+ ", timestamp: " + frame.timestamp()
+ ", hands: " + frame.hands().count()
+ ", fingers: " + frame.fingers().count()
+ ", tools: " + frame.tools().count()
+ ", gestures " + frame.gestures().count());
//System.out.println("Receive:" + post(frame).toJson());
GestureList gestures = frame.gestures();
for (int i = 0; i < gestures.count(); i++) {
Gesture gesture = gestures.get(i);
switch (gesture.type()) {
case TYPE_SWIPE:
SwipeGesture swipe = new SwipeGesture(gesture);
System.out.println("Swipe id: " + swipe.id()
+ ", " + swipe.state()
+ ", position: " + swipe.position()
+ ", direction: " + swipe.direction()
+ ", speed: " + swipe.speed());
post(swipe);
break;
case TYPE_SCREEN_TAP:
ScreenTapGesture screenTap = new ScreenTapGesture(gesture);
System.out.println("Screen Tap id: " + screenTap.id()
+ ", " + screenTap.state()
+ ", position: " + screenTap.position()
+ ", direction: " + screenTap.direction());
post(screenTap);
break;
case TYPE_KEY_TAP:
KeyTapGesture keyTap = new KeyTapGesture(gesture);
System.out.println("Key Tap id: " + keyTap.id()
+ ", " + keyTap.state()
+ ", position: " + keyTap.position()
+ ", direction: " + keyTap.direction());
post(keyTap);
break;
default:
System.out.println("Unknown gesture type.");
break;
}
}
PointableList pointables = frame.pointables();
for (int i = 0; i < pointables.count(); i++) {
Pointable pointable = pointables.get(i);
post(pointable);
}
System.out.println();
}
}
private ASTResponse post(Pointable pointable) {
if (pointable.isValid()) {
LMPointableWrapper pointableWrapper = new LMPointableWrapper(pointable);
ASTRequest message = new ASTRequest(ASTProtocol.Type.Leap.Gesture.TYPE_POINTABLE);
message.to = ASTConnector.DEFAULT_TO_ROLE;
message.data = pointableWrapper;
return ASTConnector.getDefaultConnector().post(message);
} else {
return ASTResponse.getDummyResponse();
}
}
public void onInit(Controller controller) {
System.out.println("Initialized");
}
public ASTResponse post(SwipeGesture gesture) {
if (gesture.isValid()) {
LMSwipeGestureWrapper gestureWrapper = new LMSwipeGestureWrapper(gesture);
ASTRequest message = new ASTRequest(ASTProtocol.Type.Leap.Gesture.TYPE_SWIPE);
message.to = ASTConnector.DEFAULT_TO_ROLE;
message.data = gestureWrapper;
return ASTConnector.getDefaultConnector().post(message);
} else {
return ASTResponse.getDummyResponse();
}
}
public ASTResponse post(ScreenTapGesture gesture) {
if (gesture.isValid()) {
LMScreenTapGestureWrapper gestureWrapper = new LMScreenTapGestureWrapper(gesture);
ASTRequest message = new ASTRequest(ASTProtocol.Type.Leap.Gesture.TYPE_SCREEN_TAP);
message.to = ASTConnector.DEFAULT_TO_ROLE;
message.data = gestureWrapper;
return ASTConnector.getDefaultConnector().post(message);
} else {
return ASTResponse.getDummyResponse();
}
}
public ASTResponse post(KeyTapGesture gesture) {
if (gesture.isValid()) {
LMKeyTapGestureWrapper gestureWrapper = new LMKeyTapGestureWrapper(gesture);
ASTRequest message = new ASTRequest(ASTProtocol.Type.Leap.Gesture.TYPE_KEY_TAP);
message.to = ASTConnector.DEFAULT_TO_ROLE;
message.data = gestureWrapper;
return ASTConnector.getDefaultConnector().post(message);
} else {
return ASTResponse.getDummyResponse();
}
}
}
| {
"content_hash": "bf3b548f66d011ddae9f4385679df706",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 95,
"avg_line_length": 38.03191489361702,
"alnum_prop": 0.5794405594405594,
"repo_name": "glass-earth/glass-earth",
"id": "f891c963ed929be95cc1f3d18767be9e46b84868",
"size": "7150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LeapMotion/src/main/java/me/thuanle/LMClient.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3624"
},
{
"name": "C#",
"bytes": "233230"
},
{
"name": "CSS",
"bytes": "74637"
},
{
"name": "Go",
"bytes": "39957"
},
{
"name": "Java",
"bytes": "120169"
},
{
"name": "JavaScript",
"bytes": "144478"
}
],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
use yii\db\ActiveRecord;
use \yii\web\IdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
/**
* @inheritdoc 建立模型表
*/
public static function tableName()
{
return '{{%user}}';
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
//自动登陆时会调用
$temp = parent::find()->where(['id'=>$id])->one();
return isset($temp)?new static($temp):null;
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['accessToken' => $token]);
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* @username
*/
public function getUsername()
{
return $this->username;
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->pwd === $password;
}
}
| {
"content_hash": "2ed247c4274d6ae8a4970cb7532498d8",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 74,
"avg_line_length": 18.238095238095237,
"alnum_prop": 0.5321148825065274,
"repo_name": "zxx1988328/ytwo",
"id": "2bf111f08c169dbf505ddd8884d34ee929f0aba7",
"size": "1941",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "models/User.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "524"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "74976"
},
{
"name": "HTML",
"bytes": "9754"
},
{
"name": "JavaScript",
"bytes": "176494"
},
{
"name": "PHP",
"bytes": "95848"
}
],
"symlink_target": ""
} |
.class public interface abstract Lcom/android/settings/widget/GearPreference$OnGearClickListener;
.super Ljava/lang/Object;
.source "GearPreference.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/settings/widget/GearPreference;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x609
name = "OnGearClickListener"
.end annotation
# virtual methods
.method public abstract onGearClick(Lcom/android/settings/widget/GearPreference;)V
.end method
| {
"content_hash": "c7c3f3631f6e3a5c645603ab34103cf5",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 97,
"avg_line_length": 28.210526315789473,
"alnum_prop": 0.8097014925373134,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "6b87541894728fdbbfa4da15a0264dff995d7972",
"size": "536",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "SecSettings/smali/com/android/settings/widget/GearPreference$OnGearClickListener.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
import "reflect-metadata";
import {expect} from "chai";
import {Post} from "./entity/Post";
import {Connection} from "../../../../../src/connection/Connection";
import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../../../utils/test-utils";
describe("database schema > column length > sqlite", () => {
let connections: Connection[];
before(async () => {
connections = await createTestingConnections({
entities: [Post],
enabledDrivers: ["sqlite", "better-sqlite3"],
});
});
beforeEach(() => reloadTestingDatabases(connections));
after(() => closeTestingConnections(connections));
it("all types should create with correct size", () => Promise.all(connections.map(async connection => {
const queryRunner = connection.createQueryRunner();
const table = await queryRunner.getTable("post");
await queryRunner.release();
expect(table!.findColumnByName("character")!.length).to.be.equal("50");
expect(table!.findColumnByName("varchar")!.length).to.be.equal("50");
expect(table!.findColumnByName("nchar")!.length).to.be.equal("50");
expect(table!.findColumnByName("nvarchar")!.length).to.be.equal("50");
expect(table!.findColumnByName("varying_character")!.length).to.be.equal("50");
expect(table!.findColumnByName("native_character")!.length).to.be.equal("50");
})));
it("all types should update their size", () => Promise.all(connections.map(async connection => {
let metadata = connection.getMetadata(Post);
metadata.findColumnWithPropertyName("character")!.length = "100";
metadata.findColumnWithPropertyName("varchar")!.length = "100";
metadata.findColumnWithPropertyName("nchar")!.length = "100";
metadata.findColumnWithPropertyName("nvarchar")!.length = "100";
metadata.findColumnWithPropertyName("varying_character")!.length = "100";
metadata.findColumnWithPropertyName("native_character")!.length = "100";
await connection.synchronize(false);
const queryRunner = connection.createQueryRunner();
const table = await queryRunner.getTable("post");
await queryRunner.release();
expect(table!.findColumnByName("character")!.length).to.be.equal("100");
expect(table!.findColumnByName("varchar")!.length).to.be.equal("100");
expect(table!.findColumnByName("nchar")!.length).to.be.equal("100");
expect(table!.findColumnByName("nvarchar")!.length).to.be.equal("100");
expect(table!.findColumnByName("varying_character")!.length).to.be.equal("100");
expect(table!.findColumnByName("native_character")!.length).to.be.equal("100");
await connection.synchronize(false);
})));
});
| {
"content_hash": "d65254c7ea16b8c5ddf249c06cefdafc",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 119,
"avg_line_length": 46.31147540983606,
"alnum_prop": 0.6608849557522124,
"repo_name": "gintsgints/typeorm",
"id": "64a9d7f8fe57ed74c5ae8e4cb27c336357decc2c",
"size": "2825",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/functional/database-schema/column-length/sqlite/column-length-sqlite..ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "13752"
},
{
"name": "TypeScript",
"bytes": "5135498"
}
],
"symlink_target": ""
} |
import styles from './index.css';
export default React => ({
label,
icon,
}) => (
<button className={styles.dark}>
<div>{icon}</div>
<div>{label}</div>
</button>
);
| {
"content_hash": "2acc64ed2e3207af03292e2aca06e688",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 33,
"avg_line_length": 17.3,
"alnum_prop": 0.5953757225433526,
"repo_name": "VinSpee/react-redux-postcss-boilerplate",
"id": "7d7b2f68e1ce59605d315144fbf6893890977038",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web_modules/button/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1096"
},
{
"name": "HTML",
"bytes": "253"
},
{
"name": "JavaScript",
"bytes": "27552"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/enilsen16/Eefgilm)
[](http://badge.fury.io/rb/eefgilm)
[](https://waffle.io/enilsen16/eefgilm)
#Eefgilm: A gem for cleaning up your Gemfile
#Description:
Eefgilm automatically modifies a ruby gemfile to make them a little easier to read, it does this by alphabetizing the gems, removing all comments, and removing all whitespace including leading and trailing.
These Gemfile best practices are all loosely based on a [blog post](http://mcdowall.info/posts/gemfile-best-practices-and-discourse/) written by John McDowall.
###These best practices are:
- Consistent use of Ruby hash syntax. Use either the old hashrocket or the new Ruby 1.9 syntax, but not both.
- Consistent use of a single quoted delimiter. Use either apostrophes or quotation marks, but not both.
- No commented Gem references. If it’s commented out, it shouldn’t be there.
- Comments relating to a Gem are on the same line as the gem statement, not above.
- Group gems that are sourced from Git repos at the top. Chances are they are referencing pre-versions that will become general release and you can change the reference to be part of the General project group later.
- Group gems that are sourced from a project path after Git repo sourced Gems. These are probably gems that you might make public and thus reference in the general project gem group later.
- Group all of the General project gems together (consider using the :default group).
- Group all of the Production project gems together after the General gems.
- Group all of the Asset gems after the Production group.
- Group all of the Test related gems after the Asset gems.
- Group all of the Development related gems after the Test gems.
- Within all Gem groups, sort the references by Alphabetical order.
- When adding new gems, maintain the alphabetical ordering within the groups.
## Installation
The simplest way to install Eefgilm is to run this command:
gem install eefgilm
Alternatively you can include it in a gem file with:
gem 'eefgilm'
and then run
bundle install
---
## Usage
Once you have installed eefgilm on your system or in a project directory its quite simple to use. In the directory who's gemfile you would like to modify run:
eefgilm
Currently it will not ask you for any confirmation before making modifications, nor will it create a backup so please be careful when using eefgilm. It may be a good idea to backup your gemfile beforehand hand this can be done with:
cp Gemfile Gemfilebackup
---
## Demo
A gif showing a gemfile before and after running Eefgilm.

---
## Contributing
We welcome contributions! If you want to help out you have many options:
1. Fork it ( https://github.com/enilsen16/eefgilm/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
---
##Issues
If you find a bug or have a suggestion, please create a new issue and we will look into it. Thank You.
[Create a new issue](https://github.com/enilsen16/Eefgilm/issues/new)
---
##Thanks
The following people have helped with development or project design in one form or another:<br>
[Steve Buckley](https://github.com/buckleys78)<br>
[Brook Riggio](https://github.com/brookr)<br>
[Cheri](https://github.com/cherimarie)<br>
[David](https://github.com/dbalatero)<br>
---
##License
And now for the fun part...
The MIT License (MIT)
Copyright (c) <2014> <Marco Lindsay & Erik Nilsen>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
| {
"content_hash": "8a017c77d6494f2e7cab592268fab507",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 232,
"avg_line_length": 43.828828828828826,
"alnum_prop": 0.7710174717368962,
"repo_name": "enilsen16/Eefgilm",
"id": "b0fd878bb930b3ff068aa7d9d4d7693fd5c9d6c2",
"size": "4869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6811"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_152-release) on Fri Dec 21 14:31:46 CST 2018 -->
<title>G-Index</title>
<meta name="date" content="2018-12-21">
<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="G-Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../com/basecamp/turbolinks/package-summary.html">Package</a></li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-2.html">Prev Letter</a></li>
<li><a href="index-4.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-3.html" target="_top">Frames</a></li>
<li><a href="index-3.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">G</a> <a href="index-4.html">H</a> <a href="index-5.html">O</a> <a href="index-6.html">P</a> <a href="index-7.html">R</a> <a href="index-8.html">S</a> <a href="index-9.html">T</a> <a href="index-10.html">V</a> <a name="I:G">
<!-- -->
</a>
<h2 class="title">G</h2>
<dl>
<dt><span class="memberNameLink"><a href="../com/basecamp/turbolinks/TurbolinksSession.html#getActivity--">getActivity()</a></span> - Method in class com.basecamp.turbolinks.<a href="../com/basecamp/turbolinks/TurbolinksSession.html" title="class in com.basecamp.turbolinks">TurbolinksSession</a></dt>
<dd>
<div class="block">Returns the activity attached to the Turbolinks call.</div>
</dd>
<dt><span class="memberNameLink"><a href="../com/basecamp/turbolinks/TurbolinksSession.html#getDefault-android.content.Context-">getDefault(Context)</a></span> - Static method in class com.basecamp.turbolinks.<a href="../com/basecamp/turbolinks/TurbolinksSession.html" title="class in com.basecamp.turbolinks">TurbolinksSession</a></dt>
<dd>
<div class="block">Convenience method that returns a default TurbolinksSession.</div>
</dd>
<dt><span class="memberNameLink"><a href="../com/basecamp/turbolinks/TurbolinksSession.html#getNew-android.content.Context-">getNew(Context)</a></span> - Static method in class com.basecamp.turbolinks.<a href="../com/basecamp/turbolinks/TurbolinksSession.html" title="class in com.basecamp.turbolinks">TurbolinksSession</a></dt>
<dd>
<div class="block">Creates a brand new TurbolinksSession that the calling application will be responsible for
managing.</div>
</dd>
<dt><span class="memberNameLink"><a href="../com/basecamp/turbolinks/TurbolinksSession.html#getWebView--">getWebView()</a></span> - Method in class com.basecamp.turbolinks.<a href="../com/basecamp/turbolinks/TurbolinksSession.html" title="class in com.basecamp.turbolinks">TurbolinksSession</a></dt>
<dd>
<div class="block">Returns the internal WebView used by Turbolinks.</div>
</dd>
</dl>
<a href="index-1.html">A</a> <a href="index-2.html">C</a> <a href="index-3.html">G</a> <a href="index-4.html">H</a> <a href="index-5.html">O</a> <a href="index-6.html">P</a> <a href="index-7.html">R</a> <a href="index-8.html">S</a> <a href="index-9.html">T</a> <a href="index-10.html">V</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../com/basecamp/turbolinks/package-summary.html">Package</a></li>
<li>Class</li>
<li><a href="../overview-tree.html">Tree</a></li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="index-2.html">Prev Letter</a></li>
<li><a href="index-4.html">Next Letter</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?index-files/index-3.html" target="_top">Frames</a></li>
<li><a href="index-3.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "573511b2d66e5813b0080498e4a57ee4",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 385,
"avg_line_length": 42.99285714285714,
"alnum_prop": 0.6579165974414355,
"repo_name": "turbolinks/turbolinks-android",
"id": "3a705d25931fc344c6921a4b27032b347ed6f7b2",
"size": "6019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/index-files/index-3.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1169"
},
{
"name": "Java",
"bytes": "73389"
},
{
"name": "JavaScript",
"bytes": "3888"
},
{
"name": "Prolog",
"bytes": "457"
},
{
"name": "Ruby",
"bytes": "1200"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "133c4ffb012b00463a866813ce548f52",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "48691066e138a41135c3f7ca882f329b1d0fdd45",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Lycopodiophyta/Lycopodiopsida/Lycopodiales/Lycopodiaceae/Huperzia/Urostachys chamaepeuce/Urostachys chamaepeuce maximus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package run
import (
"fmt"
"os"
"runtime"
"runtime/pprof"
log "github.com/Sirupsen/logrus"
pp "github.com/megamsys/libgo/cmd"
"github.com/megamsys/megdcui/subd/httpd"
"github.com/megamsys/megdcui/meta"
)
// Server represents a container for the metadata and storage data and services.
// It is built using a config and it manages the startup and shutdown of all
// services in the proper order.
type Server struct {
version string // Build version
err chan error
closing chan struct{}
Services []Service
// Profiling
CPUProfile string
MemProfile string
}
// NewServer returns a new instance of Server built from a config.
func NewServer(c *Config, version string) (*Server, error) {
s := &Server{
version: version,
err: make(chan error),
closing: make(chan struct{}),
}
s.appendHTTPDService(c.Meta, c.HTTPD)
return s, nil
}
func (s *Server) appendHTTPDService(c *meta.Config,h *httpd.Config) {
e := *h
if !e.Enabled {
log.Warn("skip httpd service.")
return
}
srv := httpd.NewService(c,h)
s.Services = append(s.Services, srv)
}
// Err returns an error channel that multiplexes all out of band errors received from all services.
func (s *Server) Err() <-chan error { return s.err }
// Open opens the meta and data store and all services.
func (s *Server) Open() error {
if err := func() error {
//Start profiling, if set.
startProfile(s.CPUProfile, s.MemProfile)
//go s.monitorErrorChan(s.?.Err())
for _, service := range s.Services {
if err := service.Open(); err != nil {
return fmt.Errorf("open service: %s", err)
}
}
log.Debug(pp.Colorfy("ō͡≡o˞̶ engine up", "green", "", "bold"))
return nil
}(); err != nil {
s.Close()
return err
}
return nil
}
// Close shuts down the meta and data stores and all services.
func (s *Server) Close() error {
stopProfile()
for _, service := range s.Services {
service.Close()
}
if s.closing != nil {
close(s.closing)
}
/*if s.eventHander !=nil {
s.CloseEventChannel
}*/
return nil
}
// monitorErrorChan reads an error channel and resends it through the server.
func (s *Server) monitorErrorChan(ch <-chan error) {
for {
select {
case err, ok := <-ch:
if !ok {
return
}
s.err <- err
case <-s.closing:
return
}
}
}
// Service represents a service attached to the server.
type Service interface {
Open() error
Close() error
}
// prof stores the file locations of active profiles.
var prof struct {
cpu *os.File
mem *os.File
}
// StartProfile initializes the cpu and memory profile, if specified.
func startProfile(cpuprofile, memprofile string) {
if cpuprofile != "" {
f, err := os.Create(cpuprofile)
if err != nil {
log.Errorf("cpuprofile: %v", err)
}
log.Infof("writing CPU profile to: %s", cpuprofile)
prof.cpu = f
pprof.StartCPUProfile(prof.cpu)
}
if memprofile != "" {
f, err := os.Create(memprofile)
if err != nil {
log.Errorf("memprofile: %v", err)
}
log.Infof("writing mem profile to: %s", memprofile)
prof.mem = f
runtime.MemProfileRate = 4096
}
}
// StopProfile closes the cpu and memory profiles if they are running.
func stopProfile() {
if prof.cpu != nil {
pprof.StopCPUProfile()
prof.cpu.Close()
log.Infof("CPU profile stopped")
}
if prof.mem != nil {
pprof.Lookup("heap").WriteTo(prof.mem, 0)
prof.mem.Close()
log.Infof("mem profile stopped")
}
}
| {
"content_hash": "cd8b8c15b35f391c5ee5b810a1647cdb",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 99,
"avg_line_length": 21.30817610062893,
"alnum_prop": 0.6688311688311688,
"repo_name": "vijaykanthm28/megdcui",
"id": "b0dfd4f577778479dbc7be72143c301ebb69dfe7",
"size": "3394",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "cmd/megdcui/run/server.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "377734"
},
{
"name": "Go",
"bytes": "94127"
},
{
"name": "HTML",
"bytes": "212025"
},
{
"name": "JavaScript",
"bytes": "7131294"
},
{
"name": "Makefile",
"bytes": "2553"
},
{
"name": "Ruby",
"bytes": "286"
}
],
"symlink_target": ""
} |
from gi.repository import Gst
Gst.init(None)
from numpy import fromstring
import subprocess
import traceback
from threading import Timer
from TurtleArt.taconstants import XO1, XO4
import logging
log = logging.getLogger('turtleart-activity')
log.setLevel(logging.ERROR)
# Initial device settings
RATE = 48000
MIC_BOOST = True
DC_MODE_ENABLE = False
CAPTURE_GAIN = 50
BIAS = True
# Setting on quit
QUIT_MIC_BOOST = False
QUIT_DC_MODE_ENABLE = False
QUIT_CAPTURE_GAIN = 100
QUIT_BIAS = True
SENSOR_AC_NO_BIAS = 'external'
SENSOR_AC_BIAS = 'sound'
SENSOR_DC_NO_BIAS = 'voltage'
SENSOR_DC_BIAS = 'resistance'
class AudioGrab():
""" The interface between measure and the audio device """
def __init__(self, callable1, parent,
mode=None, bias=None, gain=None, boost=None):
""" Initialize the class: callable1 is a data buffer;
activity is the parent class """
self.callable1 = callable1
self.parent = parent
self.rate = RATE
if self.parent.hw in [XO1, XO4]:
self.channels = 1
else:
self.channels = None
if self.channels is None:
self.channels = 2
self.we_are_logging = False
self._log_this_sample = False
self._logging_timer = None
self._logging_counter = 0
self._image_counter = 0
self._logging_interval = 0
self._channels_logged = []
self._busy = False
self._dont_queue_the_buffer = False
# self._display_counter = DISPLAY_DUTY_CYCLE
# self.activity.wave.set_channels(self.channels)
for i in range(self.channels):
self._channels_logged.append(False)
# Set mixer to known state
self.set_dc_mode(DC_MODE_ENABLE)
self.set_bias(BIAS)
self.set_capture_gain(CAPTURE_GAIN)
self.set_mic_boost(MIC_BOOST)
self._set_sensor_type(mode, bias, gain, boost)
self.master = self.get_master()
self.dc_mode = self.get_dc_mode()
self.bias = self.get_bias()
self.capture_gain = self.get_capture_gain()
self.mic_boost = self.get_mic_boost()
# Set up gstreamer pipeline
self._pad_count = 0
self.pads = []
self.queue = []
self.fakesink = []
self.pipeline = Gst.Pipeline.new('pipeline')
self.alsasrc = Gst.ElementFactory.make('alsasrc', 'alsa-source')
self.pipeline.add(self.alsasrc)
self.caps1 = Gst.ElementFactory.make('capsfilter', 'caps1')
self.pipeline.add(self.caps1)
caps_str = 'audio/x-raw,rate=(int)%d,channels=(int)%d,depth=(int)16'\
% (RATE, self.channels)
self.caps1.set_property('caps', Gst.caps_from_string(caps_str))
if self.channels == 1:
self.fakesink.append(Gst.ElementFactory.make('fakesink', 'fsink'))
self.pipeline.add(self.fakesink[0])
self.fakesink[0].connect('handoff', self.on_buffer, 0)
self.fakesink[0].set_property('signal-handoffs', True)
self.alsasrc.link(self.caps1)
self.caps1.link(self.fakesink[0])
else:
if not hasattr(self, 'splitter'):
self.splitter = Gst.ElementFactory.make('deinterleave')
self.pipeline.add(self.splitter)
self.splitter.set_properties('keep-positions=true', 'name=d')
self.splitter.connect('pad-added', self._splitter_pad_added)
self.alsasrc.link(self.caps1)
self.caps1.link(self.splitter)
for i in range(self.channels):
self.queue.append(Gst.ElementFactory.make('queue'))
self.pipeline.add(self.queue[i])
self.fakesink.append(Gst.ElementFactory.make('fakesink'))
self.pipeline.add(self.fakesink[i])
self.fakesink[i].connect('handoff', self.on_buffer, i)
self.fakesink[i].set_property('signal-handoffs', True)
def _unlink_sink_queues(self):
''' Build the sink pipelines '''
# If there were existing pipelines, unlink them
for i in range(self._pad_count):
log.debug('unlinking old elements')
try:
self.splitter.unlink(self.queue[i])
self.queue[i].unlink(self.fakesink[i])
except BaseException:
traceback.print_exc()
# Build the new pipelines
self._pad_count = 0
self.pads = []
log.debug('building new pipelines')
def _splitter_pad_added(self, element, pad):
''' Seems to be the case that ring is right channel 0,
tip is left channel 1'''
self.pads.append(pad)
if self._pad_count < self.channels:
pad.link(self.queue[self._pad_count].get_static_pad('sink'))
self.queue[self._pad_count].get_static_pad('src').link(
self.fakesink[self._pad_count].get_static_pad('sink'))
self._pad_count += 1
else:
log.debug('ignoring channels > %d' % self.channels)
def set_handoff_signal(self, handoff_state):
'''Sets whether the handoff signal would generate an interrupt
or not'''
for i in range(len(self.fakesink)):
self.fakesink[i].set_property('signal-handoffs', handoff_state)
def _new_buffer(self, buf, channel):
''' Use a new buffer '''
if not self._dont_queue_the_buffer:
self.callable1(buf, channel=channel)
def on_buffer(self, element, data_buffer, pad, channel):
'''The function that is called whenever new data is available
This is the signal handler for the handoff signal'''
temp_buffer = fromstring(data_buffer.extract_dup(
0, data_buffer.get_size()), 'int16')
if not self._dont_queue_the_buffer:
self._new_buffer(temp_buffer, channel=channel)
return False
def set_freeze_the_display(self, freeze=False):
''' Useful when just the display is needed to be frozen, but
logging should continue '''
self._dont_queue_the_buffer = not freeze
def get_freeze_the_display(self):
'''Returns state of queueing the buffer'''
return not self._dont_queue_the_buffer
def start_sound_device(self):
'''Start or Restart grabbing data from the audio capture'''
Gst.Event.new_flush_start()
self.pipeline.set_state(Gst.State.PLAYING)
def stop_sound_device(self):
'''Stop grabbing data from capture device'''
Gst.Event.new_flush_stop(False)
self.pipeline.set_state(Gst.State.NULL)
def set_logging_params(self, start_stop=False, interval=0):
''' Configures for logging of data: starts or stops a session;
and sets the logging interval. '''
self.we_are_logging = start_stop
self._logging_interval = interval
if not start_stop:
if self._logging_timer:
self._logging_timer.cancel()
self._logging_timer = None
self._log_this_sample = False
self._logging_counter = 0
elif interval != 0:
self._make_timer()
self._busy = False
def _sample_now(self):
''' Log the current sample now. This method is called from the
_logging_timer object when the interval expires. '''
self._log_this_sample = True
self._make_timer()
def _make_timer(self):
''' Create the next timer that will trigger data logging. '''
self._logging_timer = Timer(self._logging_interval, self._sample_now)
self._logging_timer.start()
def set_sampling_rate(self, sr):
''' Sets the sampling rate of the logging device. Sampling
rate must be given as an integer for example 16000 for setting
16Khz sampling rate The sampling rate would be set in the
device to the nearest available. '''
self.pause_grabbing()
caps_str = 'audio/x-raw-int,rate=%d,channels=%d,depth=16' % (
sr, self.channels)
self.caps1.set_property('caps', Gst.caps_from_string(caps_str))
self.resume_grabbing()
def set_callable1(self, callable1):
'''Sets the callable to the drawing function for giving the
data at the end of idle-add'''
self.callable1 = callable1
def get_sampling_rate(self):
''' Gets the sampling rate of the capture device '''
return int(self.caps1.get_property('caps')[0]['rate'])
def start_grabbing(self):
'''Called right at the start of the Activity'''
self.start_sound_device()
self.set_handoff_signal(True)
def pause_grabbing(self):
'''When Activity goes into background'''
if self.we_are_logging:
log.debug('We are logging... will not pause grabbing.')
else:
log.debug('Pause grabbing.')
self.save_state()
self.stop_sound_device()
return
def resume_grabbing(self):
'''When Activity becomes active after going to background'''
if self.we_are_logging:
log.debug('We are logging... already grabbing.')
else:
log.debug('Restore grabbing.')
self.restore_state()
self.start_sound_device()
self.set_handoff_signal(True)
return
def stop_grabbing(self):
'''Not used ???'''
self.stop_sound_device()
self.set_handoff_signal(False)
def save_state(self):
'''Saves the state of all audio controls'''
self.master = self.get_master()
self.bias = self.get_bias()
self.dc_mode = self.get_dc_mode()
self.capture_gain = self.get_capture_gain()
self.mic_boost = self.get_mic_boost()
def restore_state(self):
'''Put back all audio control settings from the saved state'''
self.set_master(self.master)
self.set_bias(self.bias)
self.stop_grabbing()
if self.channels > 1:
self._unlink_sink_queues()
self.set_dc_mode(self.dc_mode)
self.start_grabbing()
self.set_capture_gain(self.capture_gain)
self.set_mic_boost(self.mic_boost)
def amixer_set(self, control, state):
''' Direct call to amixer for old systems. '''
if state:
check_output(
['amixer', 'set', "%s" % (control), 'unmute'],
'Problem with amixer set "%s" unmute' % (control))
else:
check_output(
['amixer', 'set', "%s" % (control), 'mute'],
'Problem with amixer set "%s" mute' % (control))
def mute_master(self):
'''Mutes the Master Control'''
self.amixer_set('Master', False)
def unmute_master(self):
'''Unmutes the Master Control'''
self.amixer_set('Master', True)
def set_master(self, master_val):
'''Sets the Master gain slider settings
master_val must be given as an integer between 0 and 100 indicating the
percentage of the slider to be set'''
check_output(
['amixer', 'set', 'Master', "%d%s" % (master_val, '%')],
'Problem with amixer set Master')
def get_master(self):
'''Gets the MIC gain slider settings. The value returned is an
integer between 0 and 100 and is an indicative of the
percentage 0 to 100%'''
output = check_output(['amixer', 'get', 'Master'],
'amixer: Could not get Master volume')
if output is None:
return 100
else:
pos = output.find('Front Left:')
if pos == -1:
pos = output.find('Mono:')
output = output[pos:]
output = output[output.find('[') + 1:]
output = output[:output.find('%]')]
return int(output)
def set_bias(self, bias_state=False):
'''Enables / disables bias voltage.'''
if self.parent.hw == XO1:
self.amixer_set('MIC Bias Enable', bias_state)
else:
self.amixer_set('V_REFOUT Enable', bias_state)
def get_bias(self):
'''Check whether bias voltage is enabled.'''
if self.parent.hw == XO1:
control = 'MIC Bias Enable'
else:
control = 'V_REFOUT Enable'
output = check_output(['amixer', 'get', control],
'amixer: Could not get mic bias voltage')
if output is None:
return False
else:
output = output[output.find('Mono:'):]
output = output[output.find('[') + 1:]
output = output[:output.find(']')]
if output == 'on':
return True
return False
def set_dc_mode(self, dc_mode=False):
'''Sets the DC Mode Enable control
pass False to mute and True to unmute'''
self.amixer_set('DC Mode Enable', dc_mode)
def get_dc_mode(self):
'''Returns the setting of DC Mode Enable control
i.e. True: Unmuted and False: Muted'''
output = check_output(['amixer', 'get', "DC Mode Enable"],
'amixer: Could not get DC Mode')
if output is None:
return False
else:
output = output[output.find('Mono:'):]
output = output[output.find('[') + 1:]
output = output[:output.find(']')]
if output == 'on':
return True
return False
def set_mic_boost(self, mic_boost=False):
'''Set Mic Boost.
for analog mic boost: True = +20dB, False = 0dB
for mic1 boost: True = 8, False = 0'''
self.amixer_set('Mic Boost (+20dB)', mic_boost)
def get_mic_boost(self):
'''Return Mic Boost setting.
for analog mic boost: True = +20dB, False = 0dB
for mic1 boost: True = 8, False = 0'''
output = check_output(['amixer', 'get', "Mic Boost (+20dB)"],
'amixer: Could not get mic boost')
if output is None:
return False
else:
output = output[output.find('Mono:'):]
output = output[output.find('[') + 1:]
output = output[:output.find(']')]
if output == 'on':
return True
return False
def set_capture_gain(self, capture_val):
'''Sets the Capture gain slider settings capture_val must be
given as an integer between 0 and 100 indicating the
percentage of the slider to be set'''
check_output(
['amixer', 'set', 'Capture', "%d%s" % (capture_val, '%')],
'Problem with amixer set Capture')
def get_capture_gain(self):
'''Gets the Capture gain slider settings. The value returned
is an integer between 0 and 100 and is an indicative of the
percentage 0 to 100%'''
output = check_output(['amixer', 'get', 'Capture'],
'amixer: Could not get Capture level')
if output is None:
return 100
else:
pos = output.find('Front Left:')
if pos == -1:
pos = output.find('Mono:')
output = output[pos:]
output = output[output.find('[') + 1:]
output = output[:output.find('%]')]
return int(output)
def set_mic_gain(self, mic_val):
'''Sets the MIC gain slider settings mic_val must be given as
an integer between 0 and 100 indicating the percentage of the
slider to be set'''
check_output(
['amixer', 'set', 'Mic', "%d%s" % (mic_val, '%')],
'Problem with amixer set Mic')
def get_mic_gain(self):
'''Gets the MIC gain slider settings. The value returned is an
integer between 0 and 100 and is an indicative of the
percentage 0 to 100%'''
output = check_output(['amixer', 'get', 'Mic'],
'amixer: Could not get mic gain level')
if output is None:
return 100
else:
output = output[output.find('Mono:'):]
output = output[output.find('[') + 1:]
output = output[:output.find('%]')]
return int(output)
def _set_sensor_type(self, mode=None, bias=None, gain=None, boost=None):
'''Helper to modify (some) of the sensor settings.'''
if mode is not None:
self.set_dc_mode(mode)
if bias is not None:
self.set_bias(bias)
if gain is not None:
self.set_capture_gain(gain)
if boost is not None:
self.set_mic_boost(boost)
self.save_state()
def _on_activity_quit(self):
'''When Activity quits'''
self.set_mic_boost(QUIT_MIC_BOOST)
self.set_dc_mode(QUIT_DC_MODE_ENABLE)
self.set_capture_gain(QUIT_CAPTURE_GAIN)
self.set_bias(QUIT_BIAS)
self.stop_sound_device()
def on_activity_quit(self):
AudioGrab._on_activity_quit(self)
check_output(
['amixer', 'set', 'Analog Mic Boost', "62%"],
'restore Analog Mic Boost')
def check_output(command, warning):
''' Workaround for old systems without subprocess.check_output'''
if hasattr(subprocess, 'check_output'):
try:
output = subprocess.check_output(command)
except subprocess.CalledProcessError:
log.warning(warning)
return None
else:
import subprocess
cmd = ''
for c in command:
cmd += c
cmd += ' '
(status, output) = subprocess.getstatusoutput(cmd)
if status != 0:
log.warning(warning)
return None
return output
| {
"content_hash": "3f61f0b3e8f8ff32957e96b46133b97f",
"timestamp": "",
"source": "github",
"line_count": 493,
"max_line_length": 79,
"avg_line_length": 36.21906693711968,
"alnum_prop": 0.568660394265233,
"repo_name": "walterbender/turtleart",
"id": "15660d98d92049edf4db0033677394a02b64ef01",
"size": "18627",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "plugins/audio_sensors/audiograb.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "134"
},
{
"name": "Python",
"bytes": "1740337"
}
],
"symlink_target": ""
} |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ClientDetailsComponent } from './client-details.component';
describe('ClientDetailsComponent', () => {
let component: ClientDetailsComponent;
let fixture: ComponentFixture<ClientDetailsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ ClientDetailsComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ClientDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
| {
"content_hash": "f6eb448481ac3b81deb388a3511bb3f0",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 73,
"avg_line_length": 27.28,
"alnum_prop": 0.6935483870967742,
"repo_name": "jibanez74/BusinessPanel",
"id": "9ebce45b64b1aa06e9f3a2f1cbcaa4293af07e63",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/components/client-details/client-details.component.spec.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "95"
},
{
"name": "HTML",
"bytes": "23260"
},
{
"name": "JavaScript",
"bytes": "1645"
},
{
"name": "TypeScript",
"bytes": "31647"
}
],
"symlink_target": ""
} |
#ifndef __D3D11RENDERWINDOW_H__
#define __D3D11RENDERWINDOW_H__
#include "OgreD3D11Prerequisites.h"
#include "OgreRenderWindow.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT
#pragma warning( disable : 4451 ) // http://social.msdn.microsoft.com/Forums/en-US/winappswithnativecode/thread/314b5826-0a66-4307-abfe-87b8052c3c07/
# include <agile.h>
# if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PC_APP)
# include <windows.ui.xaml.media.dxinterop.h>
# endif
#endif
namespace Ogre
{
class D3D11RenderWindowBase
: public RenderWindow
{
public:
D3D11RenderWindowBase(D3D11Device& device, IDXGIFactoryN* pDXGIFactory);
~D3D11RenderWindowBase();
virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams);
virtual void destroy(void);
void reposition(int left, int top) {}
void resize(unsigned int width, unsigned int height) {}
bool isClosed() const { return mClosed; }
bool isHidden() const { return mHidden; }
void getCustomAttribute( const String& name, void* pData );
/** Overridden - see RenderTarget.
*/
virtual void copyContentsToMemory(const PixelBox &dst, FrameBuffer buffer);
bool requiresTextureFlipping() const { return false; }
protected:
void _createSizeDependedD3DResources(); // assumes mpBackBuffer is already initialized
void _destroySizeDependedD3DResources();
IDXGIDeviceN* _queryDxgiDevice(); // release after use
// just check if the multisampling requested is supported by the device
bool _checkMultiSampleQuality(UINT SampleCount, UINT *outQuality, DXGI_FORMAT format);
void _updateViewportsDimensions();
protected:
D3D11Device & mDevice; // D3D11 driver
IDXGIFactoryN* mpDXGIFactory;
bool mIsExternal; // window not created by Ogre
bool mSizing;
bool mClosed;
bool mHidden;
// -------------------------------------------------------
// DirectX-specific
// -------------------------------------------------------
DXGI_SAMPLE_DESC mFSAAType;
UINT mDisplayFrequency;
bool mVSync;
unsigned int mVSyncInterval;
// Window size depended resources - must be released before swapchain resize and recreated later
ID3D11Texture2D* mpBackBuffer;
ID3D11RenderTargetView* mRenderTargetView;
ID3D11DepthStencilView* mDepthStencilView;
};
class D3D11RenderWindowSwapChainBased
: public D3D11RenderWindowBase
{
public:
D3D11RenderWindowSwapChainBased(D3D11Device& device, IDXGIFactoryN* pDXGIFactory);
~D3D11RenderWindowSwapChainBased() { destroy(); }
virtual void destroy(void);
/// Get the presentation parameters used with this window
DXGI_SWAP_CHAIN_DESC_N* getPresentationParameters(void) { return &mSwapChainDesc; }
void swapBuffers( );
protected:
void _createSizeDependedD3DResources(); // obtains mpBackBuffer from mpSwapChain
void _createSwapChain();
virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice) = 0;
void _resizeSwapChainBuffers(unsigned width, unsigned height);
protected:
// Pointer to swap chain
IDXGISwapChainN * mpSwapChain;
DXGI_SWAP_CHAIN_DESC_N mSwapChainDesc;
};
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
class D3D11RenderWindowHwnd
: public D3D11RenderWindowSwapChainBased
{
public:
D3D11RenderWindowHwnd(D3D11Device& device, IDXGIFactoryN* pDXGIFactory);
~D3D11RenderWindowHwnd() { destroy(); }
virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams);
virtual void destroy(void);
bool isVisible() const;
void setHidden(bool hidden);
void reposition(int left, int top);
void resize(unsigned int width, unsigned int height);
void setFullscreen(bool fullScreen, unsigned int width, unsigned int height);
// Method for dealing with resize / move & 3d library
void windowMovedOrResized();
HWND getWindowHandle() const { return mHWnd; }
void getCustomAttribute( const String& name, void* pData );
protected:
/// Are we in the middle of switching between fullscreen and windowed
bool _getSwitchingFullscreen() const { return mSwitchingFullscreen; }
/// Indicate that fullscreen / windowed switching has finished
void _finishSwitchingFullscreen();
virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice);
void setActive(bool state);
protected:
HWND mHWnd; // Win32 window handle
bool mSwitchingFullscreen; // Are we switching from fullscreen to windowed or vice versa
};
#endif
#if OGRE_PLATFORM == OGRE_PLATFORM_WINRT
class D3D11RenderWindowCoreWindow
: public D3D11RenderWindowSwapChainBased
{
public:
D3D11RenderWindowCoreWindow(D3D11Device& device, IDXGIFactoryN* pDXGIFactory);
~D3D11RenderWindowCoreWindow() { destroy(); }
virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams);
virtual void destroy(void);
Windows::UI::Core::CoreWindow^ getCoreWindow() const { return mCoreWindow.Get(); }
bool isVisible() const;
// Method for dealing with resize / move & 3d library
void windowMovedOrResized();
protected:
virtual HRESULT _createSwapChainImpl(IDXGIDeviceN* pDXGIDevice);
protected:
Platform::Agile<Windows::UI::Core::CoreWindow> mCoreWindow;
};
#if (OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && (OGRE_WINRT_TARGET_TYPE == DESKTOP_APP)
class D3D11RenderWindowImageSource
: public D3D11RenderWindowBase
{
public:
D3D11RenderWindowImageSource(D3D11Device& device, IDXGIFactoryN* pDXGIFactory);
~D3D11RenderWindowImageSource() { destroy(); }
virtual void create(const String& name, unsigned width, unsigned height, bool fullScreen, const NameValuePairList *miscParams);
virtual void destroy(void);
virtual void resize(unsigned int width, unsigned int height);
virtual void update(bool swapBuffers = true);
virtual void swapBuffers();
virtual bool isVisible() const { return mImageSourceNative != NULL; }
Windows::UI::Xaml::Media::ImageBrush^ getImageBrush() const { return mBrush; }
virtual void getCustomAttribute( const String& name, void* pData ); // "ImageBrush" -> Windows::UI::Xaml::Media::ImageBrush^
protected:
void _createSizeDependedD3DResources(); // creates mpBackBuffer
protected:
Windows::UI::Xaml::Media::ImageBrush^ mBrush; // size independed
Windows::UI::Xaml::Media::Imaging::SurfaceImageSource^ mImageSource; // size depended, can be NULL
ISurfaceImageSourceNative* mImageSourceNative; // size depended, can be NULL
};
#endif // (OGRE_PLATFORM == OGRE_PLATFORM_WINRT) && (OGRE_WINRT_TARGET_TYPE == DESKTOP_APP)
#endif
}
#endif
| {
"content_hash": "727ec93d3a2728b0c0da3824c637a291",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 149,
"avg_line_length": 33.90355329949239,
"alnum_prop": 0.7355891600539003,
"repo_name": "albmarvil/The-Eternal-Sorrow",
"id": "2f16a7026acc63d3b716a0a2236be34a127929d5",
"size": "8038",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "dependencies/Ogre/RenderSystems/Direct3D11/include/OgreD3D11RenderWindow.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "16484"
},
{
"name": "C++",
"bytes": "1770913"
},
{
"name": "FLUX",
"bytes": "10330"
},
{
"name": "GLSL",
"bytes": "10431"
},
{
"name": "HTML",
"bytes": "10181"
},
{
"name": "Lua",
"bytes": "600542"
}
],
"symlink_target": ""
} |
import java.io.FileReader;
import java.util.ArrayList;
import org.json.simple.*;
import org.json.simple.parser.JSONParser;
public class coreServiceFramework extends DoLogging {
static String tmpDir = "/tmp/";
public String callService(String service, String method, ArrayList<functionParam> params){
JSONObject reply = null;
try {
JSONParser parser = new JSONParser();
JSONObject reqJson = (JSONObject)parser.parse(new FileReader(tmpDir+"request.json"));
String currSvc = (String)reqJson.get("svcName");
String currFunc = (String)reqJson.get("funcName");
String serviceReplyMq = (String)reqJson.get("serviceReplyMq");
reqJson.put("svcName", service);
reqJson.put("funcName", method);
if(reqJson.containsKey("serverId"))
reqJson.remove("serverId");
if(reqJson.containsKey("processId"))
reqJson.remove("processId");
JSONArray paramArr = new JSONArray();
for(int i=0; i<params.size(); i++){
functionParam p = params.get(i);
JSONObject param = new JSONObject();
String paramNum = "param" + ((Integer)(i+1)).toString();
param.put("name", paramNum);
param.put("type", p.type);
param.put("value", p.value.toString());
paramArr.add(param);
}
reqJson.put("params", paramArr);
String stack = (String)reqJson.get("stack");
stack = stack + "|" + currSvc + ":" + currFunc;
reqJson.put("stack", stack);
//System.out.println(reqJson.toJSONString());
this.connectToBroker();
this.send("svcQueue"+service, reqJson, serviceReplyMq);
reply = this.listenAndFilter();
}
catch(Exception e){
doLogging(e.getMessage(), "Error-CSVCFW");
}
return reply.get("response").toString();
}
public functionParam encodeFunctionParams(String obj){
functionParam out = new functionParam();
out.type = obj.getClass().getSimpleName();
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(char obj){
functionParam out = new functionParam();
out.type = "char";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(int obj){
functionParam out = new functionParam();
out.type = "int";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(boolean obj){
functionParam out = new functionParam();
out.type = "boolean";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(byte obj){
functionParam out = new functionParam();
out.type = "byte";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(short obj){
functionParam out = new functionParam();
out.type = "short";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(long obj){
functionParam out = new functionParam();
out.type = "long";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(float obj){
functionParam out = new functionParam();
out.type = "float";
out.value = obj;
return out;
}
public functionParam encodeFunctionParams(double obj){
functionParam out = new functionParam();
out.type = "double";
out.value = obj;
return out;
}
public void doLogging(String logStr, String severity){
try {
JSONParser parser = new JSONParser();
JSONObject reqJson = (JSONObject)parser.parse(new FileReader(tmpDir+"request.json"));
//System.out.println(reqJson);
doLogging(reqJson, "service", reqJson.get("serverId").toString(),
reqJson.get("processId").toString(), (String)reqJson.get("funcName"), logStr, severity);
}
catch(Exception e){
e.printStackTrace();
}
}
/*public static void main(String[] args) {
coreServiceFramework obj = new coreServiceFramework();
ArrayList<functionParam> list = new ArrayList<functionParam>();
list.add(encodeFunctionParams("newVal"));
list.add(encodeFunctionParams(123));
System.out.println(obj.callService("Dummy", "func1", list));
//obj.doLogging("Hello sexy khurana", "DUDE");
}*/
}
| {
"content_hash": "ce083b931627b11e94cb8df123a0067e",
"timestamp": "",
"source": "github",
"line_count": 132,
"max_line_length": 99,
"avg_line_length": 31.265151515151516,
"alnum_prop": 0.6648897504240369,
"repo_name": "hemantverma1/ServerlessPlatform",
"id": "32d498c40ddda2e2e2891cff9c11179d7ff041a7",
"size": "4127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ServerlessServices/src/coreServiceFramework.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "11608"
},
{
"name": "Java",
"bytes": "189991"
}
],
"symlink_target": ""
} |
require 'mdtex/version'
require 'mdtex/util'
require 'capture_std'
module Mdtex
end
Dir[File.join(File.dirname(__FILE__), 'mdtex/tasks', '**/*.rake')].each { |rake| load rake }
| {
"content_hash": "440c43dc5a4a0667e0ba7f789d333615",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 92,
"avg_line_length": 22.375,
"alnum_prop": 0.6815642458100558,
"repo_name": "izumin5210/mdTeX",
"id": "149c888acc7d13f22054fdf39814491f674cbf44",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/mdtex.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6171"
}
],
"symlink_target": ""
} |
package com.shejiaomao.weibo.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.cattong.entity.StatusCatalog;
import com.shejiaomao.weibo.BaseActivity;
import com.shejiaomao.maobo.R;
import com.shejiaomao.weibo.SheJiaoMaoApplication;
import com.shejiaomao.weibo.common.theme.ThemeUtil;
import com.shejiaomao.weibo.service.adapter.HotStatusesListAdapter;
import com.shejiaomao.weibo.service.listener.GoBackClickListener;
import com.shejiaomao.weibo.service.listener.GoHomeClickListener;
import com.shejiaomao.weibo.service.listener.MicroBlogContextMenuListener;
import com.shejiaomao.weibo.service.listener.MicroBlogItemClickListener;
import com.shejiaomao.weibo.service.listener.StatusRecyclerListener;
import com.shejiaomao.weibo.service.listener.StatusScrollListener;
import com.shejiaomao.weibo.service.task.HotStatusesTask;
public class HotStatusesActivity extends BaseActivity {
private SheJiaoMaoApplication sheJiaoMao;
private HotStatusesListAdapter adapter;
private ListView lvMicroBlog;
private View listFooter;
private int type;
private StatusRecyclerListener recyclerListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystatuses);
sheJiaoMao = (SheJiaoMaoApplication)getApplication();
initComponents();
bindEvent();
executeTask();
}
private void initComponents() {
LinearLayout llHeaderBase = (LinearLayout)findViewById(R.id.llHeaderBase);
lvMicroBlog = (ListView)this.findViewById(R.id.lvMicroBlog);
ThemeUtil.setSecondaryHeader(llHeaderBase);
ThemeUtil.setContentBackground(lvMicroBlog);
ThemeUtil.setListViewStyle(lvMicroBlog);
Intent intent = this.getIntent();
type = intent.getIntExtra("STATUS_CATALOG", StatusCatalog.Hot_Retweet.getCatalogNo());
TextView tvTitle = (TextView)this.findViewById(R.id.tvTitle);
int titleId = R.string.title_hot_retweets;
if (type == StatusCatalog.Hot_Comment.getCatalogNo()) {
titleId = R.string.title_hot_comments;
}
tvTitle.setText(titleId);
adapter = new HotStatusesListAdapter(this, sheJiaoMao.getCurrentAccount());
showMoreFooter();
lvMicroBlog.setAdapter(adapter);
lvMicroBlog.setFastScrollEnabled(sheJiaoMao.isSliderEnabled());
lvMicroBlog.setOnScrollListener(new StatusScrollListener());
setBack2Top(lvMicroBlog);
recyclerListener = new StatusRecyclerListener();
lvMicroBlog.setRecyclerListener(recyclerListener);
}
private void bindEvent() {
Button btnBack = (Button)this.findViewById(R.id.btnBack);
btnBack.setOnClickListener(new GoBackClickListener());
Button btnOperate = (Button) this.findViewById(R.id.btnOperate);
btnOperate.setVisibility(View.VISIBLE);
btnOperate.setText(R.string.btn_home);
btnOperate.setOnClickListener(new GoHomeClickListener());
ListView lvMicroBlog = (ListView)this.findViewById(R.id.lvMicroBlog);
lvMicroBlog.setOnItemClickListener(new MicroBlogItemClickListener(this));
MicroBlogContextMenuListener contextMenuListener =
new MicroBlogContextMenuListener(lvMicroBlog);
lvMicroBlog.setOnCreateContextMenuListener(contextMenuListener);
}
private void executeTask() {
new HotStatusesTask(this, adapter, type).execute();
}
public void showLoadingFooter() {
if (listFooter != null) {
lvMicroBlog.removeFooterView(listFooter);
}
listFooter = getLayoutInflater().inflate(R.layout.list_item_loading, null);
ThemeUtil.setListViewLoading(listFooter);
lvMicroBlog.addFooterView(listFooter);
}
public void showMoreFooter() {
if (listFooter != null) {
lvMicroBlog.removeFooterView(listFooter);
}
listFooter = getLayoutInflater().inflate(R.layout.list_item_more, null);
ThemeUtil.setListViewMore(listFooter);
listFooter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
executeTask();
}
});
lvMicroBlog.addFooterView(listFooter);
}
public void showNoMoreFooter() {
if (listFooter != null) {
lvMicroBlog.removeFooterView(listFooter);
}
listFooter = getLayoutInflater().inflate(R.layout.list_item_more, null);
ThemeUtil.setListViewMore(listFooter);
TextView tvFooter = (TextView) listFooter.findViewById(R.id.tvFooter);
tvFooter.setText(R.string.label_no_more);
lvMicroBlog.addFooterView(listFooter);
}
@Override
protected void onDestroy() {
super.onDestroy();
adapter.clear();
}
}
| {
"content_hash": "3069eeb278c436c1cd1df75053a4a12b",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 88,
"avg_line_length": 32.74285714285714,
"alnum_prop": 0.7866492146596858,
"repo_name": "Terry-L/YiBo",
"id": "d93a08d2e65223b853cb32e85ec6911539ba1ec2",
"size": "4584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "YiBo/src/com/shejiaomao/weibo/activity/HotStatusesActivity.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2675703"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4e436bc67021b0355563c39aff2a2790",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "8dbf0d21411662b272f858df10092dcd1259c236",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Nephrodium/Nephrodium scolopendrioides/Nephrodium scolopendrioides littorale/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import os, sys; sys.path.insert(0, os.path.join("..",".."))
from nodebox.graphics import *
from nodebox.graphics.physics import Particle, Force, System
# This example demonstrates the Animation object,
# which can be used to store and replay a sequence of image frames.
# This is useful for caching pre-rendered effects, like a spell or an explosion.
# This is just the explosion system from the previous example in a more condensed form.
s = System(gravity=(0, 1.0))
for i in range(80):
s.append(Particle(x=200, y=250, mass=random(5.0,10.0), radius=5, life=30))
s.force(strength=4.5, threshold=70)
# Instead of drawing the system directly to the canvas,
# we render each step offscreen as an image,
# and then gather the images in an animation loop.
explosion = Animation(duration=0.75, loop=False)
for i in range(30):
s.update(limit=20)
img = render(s.draw, 400, 400)
explosion.append(img)
# This can take several seconds:
# - calculating forces in the system is costly (if possible, load Psyco to speed them up),
# - rendering each image takes time (specifically, initialising a new empty image).
# If possible, reduce the image frames in size (smaller images = faster rendering).
# When the user clicks on the canvas, the explosion animation is played.
# We keep a list of explosions currently playing:
explosions = []
def on_mouse_press(canvas, mouse):
# When the mouse is clicked, start a new explosion at the mouse position.
explosions.append((mouse.x, mouse.y, explosion.copy()))
def draw(canvas):
canvas.clear()
global explosions
for x, y, e in explosions:
push()
translate(x-200, y-250) # Draw from the origin of the explosion.
e.update() # Move to the next frame in the animation.
image(e.frame) # Draw the current frame.
pop()
# Remove explosions that are done playing.
explosions = [(x, y, e) for x, y, e in explosions if not e.done]
canvas.size = 700, 700
canvas.on_mouse_press = on_mouse_press # Register mouse event handler.
canvas.run(draw)
| {
"content_hash": "6543f4bf81d02105d99c093e3a2dfa6c",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 90,
"avg_line_length": 38,
"alnum_prop": 0.6976076555023923,
"repo_name": "nodebox/nodebox-opengl",
"id": "bc82ccc442c4e8e26dd6a4696aed26b85678bc1f",
"size": "2166",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/08-physics/04-animation.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "988527"
},
{
"name": "C++",
"bytes": "11733"
},
{
"name": "Makefile",
"bytes": "5647"
},
{
"name": "OpenEdge ABL",
"bytes": "1056553"
},
{
"name": "Prolog",
"bytes": "48202"
},
{
"name": "Python",
"bytes": "680546"
},
{
"name": "TeX",
"bytes": "68101"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
J. Jap. Bot. 47(9): 257 (1972)
#### Original name
Usnea nipparensis f. reagens Asahina
### Remarks
null | {
"content_hash": "2778cbbf011b3198c8fa2c9b55d36f82",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 36,
"avg_line_length": 12.846153846153847,
"alnum_prop": 0.6826347305389222,
"repo_name": "mdoering/backbone",
"id": "d3006d5b1e8091b9d926e13bd84ffa196dfc1f3b",
"size": "224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Usnea/Usnea nipparensis/Usnea nipparensis reagens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) WSO2 Inc. (http://www.wso2.org) 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.
-->
<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.jaggeryjs.modules</groupId>
<artifactId>jaggery-modules</artifactId>
<version>1.5.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>markdown-parent</artifactId>
<version>1.5.1-SNAPSHOT</version>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<name>markdown Module</name>
<description>markdown Module</description>
<modules>
<module>feature</module>
</modules>
</project>
| {
"content_hash": "3ea52172ff927f8a657ca258890e7819",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 201,
"avg_line_length": 37.945945945945944,
"alnum_prop": 0.6944444444444444,
"repo_name": "ayshsandu/jaggery-extensions",
"id": "54ae8d3d436fadf5c0887b388708108d983d4f7f",
"size": "1404",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "markdown/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "60194"
},
{
"name": "HTML",
"bytes": "6544"
},
{
"name": "Java",
"bytes": "165108"
},
{
"name": "JavaScript",
"bytes": "871450"
},
{
"name": "XSLT",
"bytes": "197173"
}
],
"symlink_target": ""
} |
package Google::Ads::AdWords::v201406::ManagedCustomerLink;
use strict;
use warnings;
__PACKAGE__->_set_element_form_qualified(1);
sub get_xmlns { 'https://adwords.google.com/api/adwords/mcm/v201406' };
our $XML_ATTRIBUTE_CLASS;
undef $XML_ATTRIBUTE_CLASS;
sub __get_attr_class {
return $XML_ATTRIBUTE_CLASS;
}
use Class::Std::Fast::Storable constructor => 'none';
use base qw(Google::Ads::SOAP::Typelib::ComplexType);
{ # BLOCK to scope variables
my %managerCustomerId_of :ATTR(:get<managerCustomerId>);
my %clientCustomerId_of :ATTR(:get<clientCustomerId>);
my %linkStatus_of :ATTR(:get<linkStatus>);
my %pendingDescriptiveName_of :ATTR(:get<pendingDescriptiveName>);
__PACKAGE__->_factory(
[ qw( managerCustomerId
clientCustomerId
linkStatus
pendingDescriptiveName
) ],
{
'managerCustomerId' => \%managerCustomerId_of,
'clientCustomerId' => \%clientCustomerId_of,
'linkStatus' => \%linkStatus_of,
'pendingDescriptiveName' => \%pendingDescriptiveName_of,
},
{
'managerCustomerId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
'clientCustomerId' => 'SOAP::WSDL::XSD::Typelib::Builtin::long',
'linkStatus' => 'Google::Ads::AdWords::v201406::LinkStatus',
'pendingDescriptiveName' => 'SOAP::WSDL::XSD::Typelib::Builtin::string',
},
{
'managerCustomerId' => 'managerCustomerId',
'clientCustomerId' => 'clientCustomerId',
'linkStatus' => 'linkStatus',
'pendingDescriptiveName' => 'pendingDescriptiveName',
}
);
} # end BLOCK
1;
=pod
=head1 NAME
Google::Ads::AdWords::v201406::ManagedCustomerLink
=head1 DESCRIPTION
Perl data type class for the XML Schema defined complexType
ManagedCustomerLink from the namespace https://adwords.google.com/api/adwords/mcm/v201406.
Represents an AdWords manager-client link.
=head2 PROPERTIES
The following properties may be accessed using get_PROPERTY / set_PROPERTY
methods:
=over
=item * managerCustomerId
=item * clientCustomerId
=item * linkStatus
=item * pendingDescriptiveName
=back
=head1 METHODS
=head2 new
Constructor. The following data structure may be passed to new():
=head1 AUTHOR
Generated by SOAP::WSDL
=cut
| {
"content_hash": "3114c1cffc440cad3779516611fb900f",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 90,
"avg_line_length": 18.647540983606557,
"alnum_prop": 0.6857142857142857,
"repo_name": "gitpan/Google-Ads-AdWords-Client",
"id": "3e8f62671445fc7010de13d1a1de6e7c385e3c16",
"size": "2275",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/Google/Ads/AdWords/v201406/ManagedCustomerLink.pm",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "18425492"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="camipro_plugin_title">Camipro</string>
<color name="camipro_plus">#459900</color>
<color name="camipro_minus">#E30000</color>
<string name="camipro_current_balance">Solde actuel</string>
<string name="camipro_ebanking_1month_title">Total du dernier mois</string>
<string name="camipro_ebanking_3months_title">Total des 3 derniers mois</string>
<string name="camipro_ebanking_average_title">Moyenne mensuelle</string>
<string name="camipro_balance_section_title">Solde Camipro</string>
<string name="camipro_transactions_section_title">Dernière mise à jour %s</string>
<string name="camipro_ebanking_section_title">Chargement par e-banking</string>
<string name="camipro_statistics_section_title">Statistiques</string>
<string name="camipro_no_recent_transactions">Pas de transactions récentes</string>
<string name="camipro_ebanking_infos_text">Afin de charger votre carte CAMIPRO, veuillez reporter les indications de paiement ci-dessous (no de compte, no de référence, etc.) dans l\'interface e-banking fourni par votre établissement financier.\nLe type de paiement à effectuer est un paiement par BVR orange.</string>
<string name="camipro_ebanking_paid_to_title">Versement pour</string>
<string name="camipro_ebanking_account_number_title">Numéro de compte</string>
<string name="camipro_ebanking_ref_number_title">Numéro de référence</string>
<string name="camipro_ebanking_infos_remark">Le délai de traitement du chargement de votre carte CAMIPRO est de 2 à 3 jours ouvrables.\nLe montant maximal est de CHF 300.-</string>
<string name="camipro_string_recharge">Charger la carte</string>
<string name="camipro_string_logout">Déconnexion</string>
<string name="camipro_error_camipro_down">PocketCampus a essayé de se connecter aux serveurs Camipro, mais ils semblent hors-ligne.</string>
<string name="camipro_menu_send_by_email">Envoyer par email</string>
</resources>
| {
"content_hash": "d789350705e959ea09ec45ec7565c836",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 322,
"avg_line_length": 59.97142857142857,
"alnum_prop": 0.7265364459266317,
"repo_name": "ValentinMinder/pocketcampus",
"id": "93dd706ea10965526d8f711b7adbf38f5bd44929",
"size": "2114",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugin/camipro/android/src/main/res/values-fr/camipro_strings.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "876"
},
{
"name": "C",
"bytes": "24548"
},
{
"name": "C#",
"bytes": "934103"
},
{
"name": "CSS",
"bytes": "33788"
},
{
"name": "HTML",
"bytes": "393132"
},
{
"name": "Java",
"bytes": "1971771"
},
{
"name": "JavaScript",
"bytes": "120550"
},
{
"name": "Objective-C",
"bytes": "3611367"
},
{
"name": "PHP",
"bytes": "363528"
},
{
"name": "Python",
"bytes": "52585"
},
{
"name": "Ruby",
"bytes": "6419"
},
{
"name": "Shell",
"bytes": "11498"
},
{
"name": "Thrift",
"bytes": "37896"
}
],
"symlink_target": ""
} |
var _ = require('underscore');
var async = require('async');
var glob = require('glob');
var path = require('path');
var DEFAULTS = {
base: '.',
extensions: ['js']
};
var ADD_NAME = /(define\s*\(\s*)([^\s'"])/;
var CHANGE_NAME = /(define\s*\(\s*['"]).*?(['"])/;
var DEFINE =
/define\s*\(\s*(?:['"](.*?)['"]\s*,\s*)?(?:\[\s*([\s\S]*?)\s*\])?(?!\s*\))/;
var DEFINED_IDS = ['require', 'exports', 'module'];
var getExt = function (filePath) {
return path.extname(filePath).slice(1);
};
var getName = function (pathName, options) {
var ext = getExt(pathName);
pathName = pathName.slice(0, -ext.length - 1);
return path.relative(options.base, pathName);
};
var getRequiredIds = function (define) {
return define[2] ?
_.difference(
_.invoke(define[2].split(/\s*,\s*/), 'slice', 1, -1),
DEFINED_IDS
) : [];
};
var getDependencies = function (ids, options, cb) {
async.parallel({
requires: function (cb) {
async.map(ids, function (id, cb) {
var pattern = path.join(options.base, id) + '*';
async.waterfall([
_.partial(glob, pattern, {nodir: true}),
function (filePaths) {
var match = _.find(filePaths, function (filePath) {
return _.include(options.extensions, getExt(filePath)) &&
getName(filePath, options) === id;
});
if (!match) return cb(new Error("Cannot find module '" + id + "'"));
cb(null, path.relative('.', match));
}
], cb);
}, cb);
}
}, cb);
};
module.exports = function (file, options, cb) {
var source = file.buffer.toString();
var define = DEFINE.exec(source);
// If this file lacks a `define` statement, there's nothing to do.
if (!define) return cb(null, {});
// If the source has a named module in it, rename it to what the user
// expects it to be. This generally only happens with authors release
// packages that don't follow the best practice of defining themselves
// anonymously. If that's not the case, simply add the name to the `define`.
options = _.extend({}, DEFAULTS, options);
var name = getName(file.path, options);
source =
define[1] ?
source.replace(CHANGE_NAME, '$1' + name + '$2') :
source.replace(ADD_NAME, "$1'" + name + "', $2");
async.waterfall([
_.partial(getDependencies, getRequiredIds(define), options),
function (hashes, cb) {
var selfIndex = _.indexOf(file.requires, file.path);
cb(null, {
buffer: new Buffer(source),
requires: file.requires.slice(0, selfIndex)
.concat(hashes.requires)
.concat(file.requires.slice(selfIndex))
});
}
], cb);
};
| {
"content_hash": "fa813ab1095fdcfe5d7e8d0985eb48d6",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 80,
"avg_line_length": 31.611764705882354,
"alnum_prop": 0.5790844808336435,
"repo_name": "caseywebdev/cogs-transformer-concat-amd",
"id": "4720c32a69b4b7fcb1c274e25b5ac207fde6360f",
"size": "2687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "39"
},
{
"name": "JavaScript",
"bytes": "3828"
}
],
"symlink_target": ""
} |
package com.arckenver.nations.cmdexecutor.nationadmin;
import java.util.stream.Collectors;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import com.arckenver.nations.ConfigHandler;
import com.arckenver.nations.DataHandler;
import com.arckenver.nations.LanguageHandler;
import com.arckenver.nations.Utils;
import com.arckenver.nations.cmdelement.NationNameElement;
import com.arckenver.nations.object.Nation;
public class NationadminFlagExecutor implements CommandExecutor
{
public static void create(CommandSpec.Builder cmd) {
cmd.child(CommandSpec.builder()
.description(Text.of(""))
.permission("nations.command.nationadmin.flag")
.arguments(
GenericArguments.optional(new NationNameElement(Text.of("nation"))),
GenericArguments.optional(GenericArguments.choices(Text.of("flag"), ConfigHandler.getNode("nations", "flags")
.getChildrenMap()
.keySet()
.stream()
.map(key -> key.toString())
.collect(Collectors.toMap(flag -> flag, flag -> flag)))),
GenericArguments.optional(GenericArguments.bool(Text.of("bool"))))
.executor(new NationadminFlagExecutor())
.build(), "flag");
}
public CommandResult execute(CommandSource src, CommandContext ctx) throws CommandException
{
if (!ctx.<String>getOne("nation").isPresent() || !ctx.<String>getOne("flag").isPresent())
{
src.sendMessage(Text.of(TextColors.YELLOW, "/na flag <nation> <flag> [true|false]"));
return CommandResult.success();
}
String nationName = ctx.<String>getOne("nation").get();
Nation nation = DataHandler.getNation(nationName);
if (nation == null)
{
src.sendMessage(Text.of(TextColors.RED, LanguageHandler.ERROR_BADNATIONNAME));
return CommandResult.success();
}
String flag = ctx.<String>getOne("flag").get();
boolean bool = (ctx.<Boolean>getOne("bool").isPresent()) ? ctx.<Boolean>getOne("bool").get() : !nation.getFlag(flag);
nation.setFlag(flag, bool);
DataHandler.saveNation(nation.getUUID());
src.sendMessage(Utils.formatNationDescription(nation, Utils.CLICKER_ADMIN));
return CommandResult.success();
}
}
| {
"content_hash": "74e4e06379ccdbe044955afe67c40e57",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 119,
"avg_line_length": 41,
"alnum_prop": 0.7533438237608182,
"repo_name": "Arckenver/Nations",
"id": "a378cb92e7139a46dc6a0cfd83be6f3f26b9bdc8",
"size": "2542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/arckenver/nations/cmdexecutor/nationadmin/NationadminFlagExecutor.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "394928"
}
],
"symlink_target": ""
} |
package io.vertx.test.codegen.testjsonmapper.ambiguousoverload;
import io.vertx.codegen.annotations.VertxGen;
import java.time.ZonedDateTime;
/**
* @author <a href="mailto:julien@julienviet.com">Julien Viet</a>
*/
@VertxGen
public interface APIInterfaceWithZonedDateTime {
static ZonedDateTime deserialize(String s) {
throw new UnsupportedOperationException();
}
void doSomething(ZonedDateTime dateTime);
void doSomething(String dateTime);
}
| {
"content_hash": "3a3b90f7e388f25c0d176acbd1c2a453",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 65,
"avg_line_length": 22.047619047619047,
"alnum_prop": 0.7775377969762419,
"repo_name": "eclipse-vertx/vertx-codegen",
"id": "089c98567adc376134728e5383fbd85eec9a0e02",
"size": "463",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/test/java/io/vertx/test/codegen/testjsonmapper/ambiguousoverload/APIInterfaceWithZonedDateTime.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1507566"
}
],
"symlink_target": ""
} |
'use strict';
/*global $, msp*/
msp.Controller.prototype.datasetValueWidget = function (args) {
var self = this,
attr = {
container: self.selector,
id: args.id,
pretext: args.pretext || '',
},
attr2,
widget = null;
if (!args.elem_pre) {
args.elem_pre = '';
}
if (!args.dataset) {
args.elem.html('');
} else if (args.dataset.data_type === msp.enum.BOOLEAN) {
$(self.selector + ' #descr').html(args.dataset.descr);
args.elem.html(args.elem_pre);
} else {
$(self.selector + ' #descr').html(args.dataset.descr);
attr.newValue = args.newValue;
if (args.dataset.semantics) {
attr.type = 'select';
attr.list = args.dataset.semantics;
} else if (args.dataset.data_type === msp.enum.INTEGER) {
attr.type = 'spinner';
} else if (args.dataset.data_type === msp.enum.REAL) {
attr.type = 'slider';
attr.slider_value_id = args.id + '-value';
}
if (args.rule) {
if (args.dataset.semantics) {
attr.selected = args.dataset.semantics[args.rule.value];
} else {
attr2 = args.rule.getMinMax();
attr.min = attr2.min;
attr.max = attr2.max;
attr.value = args.rule.value;
}
} else {
if (args.dataset.semantics) {
attr.selected = undefined;
} else {
attr.min = args.dataset.min_value;
attr.max = args.dataset.max_value;
attr.value = args.dataset.min_value;
}
}
widget = new msp.Widget(attr);
args.elem.html(args.elem_pre + msp.e('p', {}, widget.html()));
widget.prepare();
}
return widget;
};
msp.Controller.prototype.editBooleanRule = function (args) {
var self = this,
owner = self.model.layer.owner === self.model.config.config.user,
value,
html = '',
make_op = function (dataset) {
return dataset ? new msp.Widget({
container: self.selector,
id: 'rule-op',
type: 'select',
list: self.klasses.op,
includeItem: function (item) {
if (dataset.data_type === msp.enum.BOOLEAN) {
return item.name === '==' || item.name === 'NOT';
}
return true;
},
nameForItem: function (item) {
if (dataset.data_type === msp.enum.BOOLEAN) {
if (item.name === '==') {
return 'IS';
}
return 'IS NOT';
}
return item.name;
},
selected: args.rule ? args.rule.op : null,
pretext: 'Define the operator:<br/>'
}) : new msp.Widget({
container: self.selector,
pretext: 'No datasets available.',
id: 'rule-op',
type: 'paragraph'
});
},
op = args.rule ? make_op(args.rule.dataset) : null,
threshold,
pretext = 'Define the threshold:<br/>',
regex;
value = new msp.Widget({
container: self.selector,
id: 'rule-defs',
type: 'paragraph',
});
if (args.rule) {
html += args.rule.getCriteria().name;
regex = new RegExp('==');
html = html
.replace(/^- If/, 'Do not allocate if')
.replace(regex, 'equals:');
if (!owner) {
html += msp.e('p', {}, 'Et ole tämän tason omistaja. Muutokset ovat tilapäisiä.');
}
html += msp.e('p', {}, 'Rule is based on ' + args.dataset.name);
} else {
html += msp.e('p', {}, args.dataset.html());
}
html += msp.e('p', {id: 'descr'}, '');
html += value.html();
self.editor.html(html);
if (args.rule) {
threshold = self.datasetValueWidget({
id: 'thrs',
dataset: args.dataset,
rule: args.rule,
elem: value,
elem_pre: msp.e('p', {}, op.html()),
pretext: pretext
});
} else {
args.dataset.changed((function changed() {
var dataset2 = args.dataset.getSelected();
op = make_op(dataset2);
threshold = self.datasetValueWidget({
id: 'thrs',
dataset: dataset2,
elem: value,
elem_pre: msp.e('p', {}, op.html()),
pretext: pretext
});
return changed;
}()));
}
return function () {
var retval = {},
dataset = args.rule ? args.dataset : args.dataset.getSelected();
if (!args.rule) {
retval.dataset = dataset ? dataset.id : undefined;
}
retval.op = op.getSelected();
if (retval.op) {
retval.op = retval.op.id;
}
if (dataset.data_type === msp.enum.BOOLEAN) {
retval.value = 1; // the semantics of binary datasets are 0: false, 1: true
} else {
retval.value = threshold ? threshold.getValue() : 0;
if (dataset.semantics) {
retval.value = parseInt(retval.value, 10);
}
}
return retval;
};
};
msp.Controller.prototype.editBoxcarRule = function (args) {
// boxcar rule converts data value into range [0..weight] or [weight..0] if weight is negative
// the rule consists of four values (x0, x1, x2, x3) and a boolean form parameter in addition to weight
// the data value is first mapped to a value (y) between 0 and 1
// if data value (x) is <= x0, y = 0, (1 if form is false)
// if data value (x) is between x0 and x1, y increases linearly from 0 to 1, (1 to 0 if form is false)
// if data value (x) is between x1 and x2, y = 1, (0 if form is false)
// if data value (x) is between x2 and x3, y decreases linearly from 1 to 0, (0 to 1 if form is false)
// if data value (x) is >= x3, y = 0, (1 if form is false)
// final rule value is then y*weight
var self = this,
html = '',
form = new msp.Widget({
container: self.selector,
id: 'form',
type: 'select',
list: {1: 'Normal _/¯\\_', 2: 'Inverted ¯\\_/¯'},
selected: args.rule ? args.rule.boxcar_type : 'Normal _/¯\\_',
}),
x0 = new msp.Widget({
container: self.selector,
id: 'x0p',
type: 'paragraph'
}),
x1 = new msp.Widget({
container: self.selector,
id: 'x1p',
type: 'paragraph'
}),
x2 = new msp.Widget({
container: self.selector,
id: 'x2p',
type: 'paragraph'
}),
x3 = new msp.Widget({
container: self.selector,
id: 'x3p',
type: 'paragraph'
}),
weight = new msp.Widget({
container: self.selector,
id: 'weight',
type: 'text',
value: args.rule ? args.rule.weight : 1,
pretext: 'Weight: '
}),
x0Widget,
x1Widget,
x2Widget,
x3Widget,
x0v,
x1v,
x2v,
x3v,
newValue;
if (args.rule) {
html += msp.e('p', {}, 'Rule is based on ' + args.dataset.name);
} else {
html += msp.e('p', {}, args.dataset.html());
}
html += msp.e('p', {id: 'descr'}, '');
html += form.html();
html += x0.html();
html += x1.html();
html += x2.html();
html += x3.html();
html += weight.html();
self.editor.html(html);
newValue = function (value) {
x0v = x0Widget.getFloatValue();
x1v = x1Widget.getFloatValue();
x2v = x2Widget.getFloatValue();
x3v = x3Widget.getFloatValue();
if (this.id === 'x0') {
if (x1v < value) {
x1Widget.setValue(value);
}
if (x2v < value) {
x2Widget.setValue(value);
}
if (x3v < value) {
x3Widget.setValue(value);
}
} else if (this.id === 'x1') {
if (x0v > value) {
x0Widget.setValue(value);
}
if (x2v < value) {
x2Widget.setValue(value);
}
if (x3v < value) {
x3Widget.setValue(value);
}
} else if (this.id === 'x2') {
if (x0v > value) {
x0Widget.setValue(value);
}
if (x1v > value) {
x1Widget.setValue(value);
}
if (x3v < value) {
x3Widget.setValue(value);
}
} else if (this.id === 'x3') {
if (x0v > value) {
x0Widget.setValue(value);
}
if (x1v > value) {
x1Widget.setValue(value);
}
if (x2v > value) {
x2Widget.setValue(value);
}
}
};
if (args.rule) {
x0Widget = self.datasetValueWidget({id: 'x0', dataset: args.dataset, rule: args.rule, elem: x0, newValue: newValue});
x1Widget = self.datasetValueWidget({id: 'x1', dataset: args.dataset, rule: args.rule, elem: x1, newValue: newValue});
x2Widget = self.datasetValueWidget({id: 'x2', dataset: args.dataset, rule: args.rule, elem: x2, newValue: newValue});
x3Widget = self.datasetValueWidget({id: 'x3', dataset: args.dataset, rule: args.rule, elem: x3, newValue: newValue});
x0Widget.setValue(args.rule.boxcar_x0);
x1Widget.setValue(args.rule.boxcar_x1);
x2Widget.setValue(args.rule.boxcar_x2);
x3Widget.setValue(args.rule.boxcar_x3);
} else {
args.dataset.changed((function changed() {
var set = args.dataset.getSelected();
x0Widget = self.datasetValueWidget({id: 'x0', dataset: set, rule: args.rule, elem: x0, newValue: newValue});
x1Widget = self.datasetValueWidget({id: 'x1', dataset: set, rule: args.rule, elem: x1, newValue: newValue});
x2Widget = self.datasetValueWidget({id: 'x2', dataset: set, rule: args.rule, elem: x2, newValue: newValue});
x3Widget = self.datasetValueWidget({id: 'x3', dataset: set, rule: args.rule, elem: x3, newValue: newValue});
return changed;
}()));
}
return function () {
var retval = {
boxcar_type: {value:form.getValue(), selected: form.getSelected()},
boxcar_x0: x0Widget.getFloatValue(),
boxcar_x1: x1Widget.getFloatValue(),
boxcar_x2: x2Widget.getFloatValue(),
boxcar_x3: x3Widget.getFloatValue(),
weight: weight.getValue()
};
if (!args.rule) {
retval.dataset = args.dataset.getSelected().id;
}
return retval;
};
};
msp.Controller.prototype.editBayesianRule = function (args) {
// rule is a node in a Bayesian network
// for now we assume it is a (hard) evidence node, i.e.,
// the dataset must be integer, and its value range the same as the node's
var self = this,
dataset_list = [],
network = null,
nodes = [],
node,
offset,
html = '',
dataset_info = function (dataset) {
var states = '',
j = 0;
if (!dataset) {
return {
descr: msp.e('font', {color: 'red'}, 'No suitable datasets available.'),
states: ''
};
}
if (dataset.semantics) {
$.each(dataset.semantics, function (i, value) {
if (j > 0) {
states += ', ';
}
states += i + ': ' + value;
j += 1;
});
}
return {
descr: dataset.descr,
states: 'States: ' + dataset.min_value + '..' + dataset.max_value + msp.e('p', {}, states)
};
};
if (!args.rule) {
$.each(self.model.datasets.layers, function (i, dataset) {
if (dataset.data_type === msp.enum.INTEGER) {
dataset_list.push(dataset);
}
});
args.dataset = new msp.Widget({
container: self.selector,
id: 'rule-dataset',
type: 'select',
list: dataset_list,
selected: dataset_list[0],
pretext: 'Base the rule on dataset: '
});
}
network = self.networks.find(function (network) {
return network.name === self.model.layer.network.name;
});
$.each(network.nodes, function (i, node) {
var used = node.name === self.model.layer.output_node.name;
if (args.rule && node.name === args.rule.node) {
// current
nodes.push(node);
return true;
}
if (!used) {
$.each(self.model.layer.rules, function (i, rule) {
if (node.name === rule.node) {
// already used
used = true;
return false;
}
});
}
if (!used) {
nodes.push(node);
}
});
node = new msp.Widget({
container: self.selector,
id: 'rule-node',
type: 'select',
list: nodes,
selected: args.rule ? args.rule.node : nodes[0],
pretext: 'Link the dataset to node: '
});
offset = new msp.Widget({
container: self.selector,
id: 'rule-offset',
type: 'spinner',
value: args.rule ? args.rule.state_offset : 0,
min: -10,
max: 10,
pretext: 'Offset (to match states): '
});
if (args.rule) {
html += msp.e('p', {}, 'Rule is based on ' + args.dataset.name);
} else {
html += msp.e('p', {}, args.dataset.html());
}
html += msp.e('p', {id: 'dataset-states'}, '') +
msp.e('p', {id: 'descr'}, '') +
msp.e('p', {}, offset.html()) +
node.html() +
msp.e('p', {id: 'node-states'}, '');
self.editor.html(html);
offset.prepare();
if (args.rule) {
html = dataset_info(args.dataset);
$(self.selector + ' #descr').html(html.descr);
$(self.selector + ' #dataset-states').html(html.states);
} else {
args.dataset.changed((function changed() {
html = dataset_info(args.dataset.getSelected());
$(self.selector + ' #descr').html(html.descr);
$(self.selector + ' #dataset-states').html(html.states);
return changed;
}()));
}
node.changed((function changed() {
var n = node.getSelected(),
states = '',
desc = '';
if (n) {
$.each(n.states, function (i, state) {
if (i > 0) {
states += ', ';
}
states += i + ': ' + state;
});
if (n.attributes) {
desc = n.attributes.HR_Desc;
}
}
$(self.selector + ' #node-states').html('Description: ' + desc + '<br/>' + 'States: ' + states);
return changed;
}()));
return function () {
var retval = {};
if (!args.rule) {
retval.dataset = args.dataset.getSelected().id;
}
retval.state_offset = offset.getValue();
retval.node = node.getSelected().name;
return retval;
};
};
| {
"content_hash": "8b5ba985c72ebc758139ec156a1c6f41",
"timestamp": "",
"source": "github",
"line_count": 474,
"max_line_length": 125,
"avg_line_length": 33.5,
"alnum_prop": 0.47219598211474273,
"repo_name": "ajolma/SmartSeaMSPTool",
"id": "b918e222ca752a22b94824be255065643fbe8568",
"size": "17186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/js/rule_editor.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7025"
},
{
"name": "HTML",
"bytes": "9339"
},
{
"name": "JavaScript",
"bytes": "182622"
},
{
"name": "Makefile",
"bytes": "998"
},
{
"name": "Perl",
"bytes": "247787"
},
{
"name": "Perl 6",
"bytes": "62097"
},
{
"name": "Python",
"bytes": "8070"
}
],
"symlink_target": ""
} |
using System;
using System.Net;
using System.Web;
using System.Web.Routing;
using SuperScript.ExternalFile.Storage;
namespace SuperScript.ExternalFile.Handlers
{
/// <summary>
/// Causes a request to be made to the <see cref="IStore"/> implementation to remove the store.
/// </summary>
public class Remove : IHttpHandler
{
// the implementation of IStore to be used for processing the call
private readonly IStore _storeProvider;
public RequestContext RequestContext { get; set; }
/// <summary>
/// <para>Default constructor for <see cref="Remove"/>.</para>
/// </summary>
public Remove()
{
// verify that we've been given an implementation of IStore to use
_storeProvider = Configuration.Settings.Instance.StoreProvider;
if (_storeProvider == null)
{
throw new NotSpecifiedException("No implementation of SuperScript.ExternalFile.Storage.IStore has been specified.");
}
}
public Remove(RequestContext requestContext) : this()
{
RequestContext = requestContext;
}
/// <summary>
/// The main entry point for incoming requests.
/// </summary>
public void ProcessRequest(HttpContext context)
{
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Cache.SetNoStore();
context.Response.Cache.SetExpires(DateTime.MinValue);
_storeProvider.Remove();
context.Response.StatusCode = (int) HttpStatusCode.OK;
}
public bool IsReusable
{
get { return false; }
}
}
} | {
"content_hash": "e7d05d8384e833d46a32b18f8a92773b",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 132,
"avg_line_length": 26.508196721311474,
"alnum_prop": 0.6573902288188003,
"repo_name": "Supertext/SuperScript.ExternalFile",
"id": "c53ef744ca55b9ebee29095afc7b59d3c933aa89",
"size": "1619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Handlers/Remove.ashx.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "761"
},
{
"name": "C#",
"bytes": "113209"
}
],
"symlink_target": ""
} |
let _isActive = false;
export const LOG_LEVELS = {
ERROR: 1,
WARNING: 2,
NORMAL: 4
};
export const configureLogger = (options) => {
options = options || {};
_isActive = options.isActive;
};
export const log = (message, logLevel) => {
if (!_isActive) { return; }
logLevel = logLevel || LOG_LEVELS.NORMAL;
switch(logLevel) {
case LOG_LEVELS.ERROR:
return console.error ? console.error(message) : console.log(message);
case LOG_LEVELS.WARNING:
return console.warn ? console.warn(message) : console.log(message);
case LOG_LEVELS.NORMAL:
default:
return console.log(message);
}
};
| {
"content_hash": "73974c03c4a8f33d5047783b32b40f91",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 81,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.5994152046783626,
"repo_name": "flashrecruit/belay",
"id": "9514d3672814100122c8abbf6f24727697141756",
"size": "684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/utils/log.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "247435"
},
{
"name": "HTML",
"bytes": "555803"
},
{
"name": "JavaScript",
"bytes": "60456"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
namespace MvcMovie.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Name = table.Column<string>(nullable: true),
NormalizedName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityRole", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false),
ConcurrencyStamp = table.Column<string>(nullable: true),
Email = table.Column<string>(nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
LockoutEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
NormalizedEmail = table.Column<string>(nullable: true),
NormalizedUserName = table.Column<string>(nullable: true),
PasswordHash = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
SecurityStamp = table.Column<string>(nullable: true),
TwoFactorEnabled = table.Column<bool>(nullable: false),
UserName = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ApplicationUser", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
RoleId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityRoleClaim<string>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserClaim<string>", x => x.Id);
table.ForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(nullable: false),
ProviderKey = table.Column<string>(nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserLogin<string>", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id");
table.ForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id");
});
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable("AspNetRoleClaims");
migrationBuilder.DropTable("AspNetUserClaims");
migrationBuilder.DropTable("AspNetUserLogins");
migrationBuilder.DropTable("AspNetUserRoles");
migrationBuilder.DropTable("AspNetRoles");
migrationBuilder.DropTable("AspNetUsers");
}
}
}
| {
"content_hash": "ea4c560b16a484b0a64822604576b0e9",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 122,
"avg_line_length": 47.18421052631579,
"alnum_prop": 0.5055772448410485,
"repo_name": "NemoChenTW/MvcMovie",
"id": "438ced4713fa5e66078ec4e6b79a15365600af37",
"size": "7174",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/MvcMovie/Migrations/00000000000000_CreateIdentitySchema.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "128425"
},
{
"name": "CSS",
"bytes": "584"
},
{
"name": "HTML",
"bytes": "6818"
},
{
"name": "JavaScript",
"bytes": "1616"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal;
namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp
{
internal static class FSharpGlyphTags
{
public static ImmutableArray<string> GetTags(FSharpGlyph glyph)
{
return GlyphTags.GetTags(FSharpGlyphHelpers.ConvertTo(glyph));
}
}
}
| {
"content_hash": "450a3906f26a6bec1c05bf96392d0f1a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 74,
"avg_line_length": 34.294117647058826,
"alnum_prop": 0.7444253859348199,
"repo_name": "davkean/roslyn",
"id": "8a0cac5050b58b071df4e5b122ff3bf7933dd791",
"size": "585",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/Tools/ExternalAccess/FSharp/FSharpGlyphTags.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "134997671"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "233223"
},
{
"name": "Shell",
"bytes": "92956"
},
{
"name": "Visual Basic .NET",
"bytes": "71479723"
}
],
"symlink_target": ""
} |
Some webworkers for a rewards system
| {
"content_hash": "53bdd8e8e5e9320e6de6a6fd20d69e83",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 36,
"avg_line_length": 37,
"alnum_prop": 0.8378378378378378,
"repo_name": "Sun-Wukong/sc_workers",
"id": "947d82cc9adf1b834242fa233c88728b99d06ba5",
"size": "50",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2542"
},
{
"name": "JavaScript",
"bytes": "20833"
}
],
"symlink_target": ""
} |
import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
class HomePage extends PolymerElement {
static get template() {
return html`
<div class="card">
<h1>Home</h1>
<p>This is a sample Polymer One Page Application generated automatically with the Polymer CLI.</p>
</div>
`;
}
}
window.customElements.define('home-page', HomePage);
| {
"content_hash": "2377cf76ff74f95434e42935953df403",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 106,
"avg_line_length": 24.75,
"alnum_prop": 0.6641414141414141,
"repo_name": "google/security-crawl-maze",
"id": "b8525b29f616d87ce4d05c7d41a02706b46c08c2",
"size": "928",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test-cases/javascript/frameworks/polymer/src/home-page.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2641"
},
{
"name": "HTML",
"bytes": "41609"
},
{
"name": "JavaScript",
"bytes": "11789"
},
{
"name": "Python",
"bytes": "16494"
},
{
"name": "TypeScript",
"bytes": "5623"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'apache::mod::reqtimeout', :type => :class do
let :pre_condition do
'class { "apache":
default_mods => false,
}'
end
context "on a Debian OS" do
let :facts do
{
:osfamily => 'Debian',
:operatingsystemrelease => '6',
:concat_basedir => '/dne',
:operatingsystem => 'Debian',
:id => 'root',
:kernel => 'Linux',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
:lsbdistcodename => 'squeeze',
:is_pe => false,
}
end
context "passing no parameters" do
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-40,minrate=500\nRequestReadTimeout body=10,minrate=500$/) }
end
context "passing timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']" do
let :params do
{:timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600\nRequestReadTimeout body=60,minrate=600$/) }
end
context "passing timeouts => 'header=20-60,minrate=600'" do
let :params do
{:timeouts => 'header=20-60,minrate=600'}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600$/) }
end
end
context "on a RedHat OS" do
let :facts do
{
:osfamily => 'RedHat',
:operatingsystemrelease => '6',
:concat_basedir => '/dne',
:operatingsystem => 'Redhat',
:id => 'root',
:kernel => 'Linux',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
:is_pe => false,
}
end
context "passing no parameters" do
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-40,minrate=500\nRequestReadTimeout body=10,minrate=500$/) }
end
context "passing timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']" do
let :params do
{:timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600\nRequestReadTimeout body=60,minrate=600$/) }
end
context "passing timeouts => 'header=20-60,minrate=600'" do
let :params do
{:timeouts => 'header=20-60,minrate=600'}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600$/) }
end
end
context "on a FreeBSD OS" do
let :facts do
{
:osfamily => 'FreeBSD',
:operatingsystemrelease => '9',
:concat_basedir => '/dne',
:operatingsystem => 'FreeBSD',
:id => 'root',
:kernel => 'FreeBSD',
:path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
:is_pe => false,
}
end
context "passing no parameters" do
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-40,minrate=500\nRequestReadTimeout body=10,minrate=500$/) }
end
context "passing timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']" do
let :params do
{:timeouts => ['header=20-60,minrate=600', 'body=60,minrate=600']}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600\nRequestReadTimeout body=60,minrate=600$/) }
end
context "passing timeouts => 'header=20-60,minrate=600'" do
let :params do
{:timeouts => 'header=20-60,minrate=600'}
end
it { is_expected.to contain_class("apache::params") }
it { is_expected.to contain_apache__mod('reqtimeout') }
it { is_expected.to contain_file('reqtimeout.conf').with_content(/^RequestReadTimeout header=20-60,minrate=600$/) }
end
end
end
| {
"content_hash": "cf68b961d1ce38b2f14023d78ce28c4e",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 161,
"avg_line_length": 46.12173913043478,
"alnum_prop": 0.5859728506787331,
"repo_name": "carvefx/puphpet-testing",
"id": "97aa7db453d990a9829af3d8525aa9d335c9ec16",
"size": "5304",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "puphpet/puppet/modules/apache/spec/classes/mod/reqtimeout_spec.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Erlang",
"bytes": "82414"
},
{
"name": "HTML",
"bytes": "206416"
},
{
"name": "JavaScript",
"bytes": "105"
},
{
"name": "Makefile",
"bytes": "24757"
},
{
"name": "PHP",
"bytes": "68"
},
{
"name": "Pascal",
"bytes": "5391"
},
{
"name": "Perl",
"bytes": "37269"
},
{
"name": "Prolog",
"bytes": "225"
},
{
"name": "Puppet",
"bytes": "1088362"
},
{
"name": "Python",
"bytes": "180"
},
{
"name": "QMake",
"bytes": "3267"
},
{
"name": "R",
"bytes": "526"
},
{
"name": "Ruby",
"bytes": "1918969"
},
{
"name": "Shell",
"bytes": "136059"
},
{
"name": "VimL",
"bytes": "10301"
}
],
"symlink_target": ""
} |
package loon.utils;
import loon.LSystem;
import loon.geom.PointF;
import loon.geom.RectF;
public class URecognizerAnalyze {
protected int _tx, _ty;
protected int state;
protected int _key = -1;
protected boolean gesture = true;
protected TArray<PointF> points = new TArray<PointF>(256);
protected URecognizerResult result = new URecognizerResult(LSystem.UNKNOWN, 0, -1);
protected boolean active = false;
protected int gestureSet;
protected URecognizer recognizer;
public URecognizerAnalyze() {
this(URecognizer.GESTURES_DEFAULT);
}
public URecognizerAnalyze(int gesture) {
this.gestureSet = gesture;
this.recognizer = new URecognizer(gesture);
}
public TArray<PointF> getPoints() {
return points;
}
public void addPoint(float x, float y) {
if (!active) {
return;
}
points.add(new PointF(x, y));
}
public void addPoints(TArray<PointF> points) {
if (!active) {
return;
}
points.addAll(points);
}
public URecognizerResult recognize() {
if (!active) {
return null;
}
if (points.size() == 0) {
return null;
}
return (result = recognizer.getRecognize(points));
}
public RectF getBoundingBox() {
return recognizer.boundingBox;
}
public int[] getBounds() {
return recognizer.bounds;
}
public PointF getPosition() {
return recognizer.centroid;
}
public String getName() {
return result.getName();
}
public float getScore() {
return result.getScore();
}
public int getIndex() {
return result.getIndex();
}
public void setActive(boolean state) {
active = state;
}
public boolean getActive() {
return active;
}
public void pressed() {
clear();
}
public void released() {
recognize();
}
public void dragged(int x, int y) {
addPoint(x, y);
}
public void clear() {
points.clear();
result._name = "";
result._score = 0;
result._index = -1;
}
}
| {
"content_hash": "ff06dd2d85cc923551de2413b7df64ea",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 84,
"avg_line_length": 16.18103448275862,
"alnum_prop": 0.6771443793287161,
"repo_name": "cping/LGame",
"id": "71e0c86613f32f55bfe56ef4015b1254ec48087a",
"size": "2584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/Loon-Neo/src/loon/utils/URecognizerAnalyze.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1472"
},
{
"name": "C",
"bytes": "3901"
},
{
"name": "C#",
"bytes": "3682953"
},
{
"name": "C++",
"bytes": "24221"
},
{
"name": "CSS",
"bytes": "115312"
},
{
"name": "HTML",
"bytes": "1782"
},
{
"name": "Java",
"bytes": "26857190"
},
{
"name": "JavaScript",
"bytes": "177232"
},
{
"name": "Shell",
"bytes": "236"
}
],
"symlink_target": ""
} |
package gov.hhs.fha.nhinc.docsubmission.adapter.deferred.response;
import javax.annotation.Resource;
import javax.xml.ws.BindingType;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.soap.Addressing;
/**
*
* @author JHOPPESC
*/
@BindingType(value = javax.xml.ws.soap.SOAPBinding.SOAP12HTTP_BINDING)
@Addressing(enabled = true)
public class AdapterXDRResponseSecured implements gov.hhs.fha.nhinc.adapterxdrresponsesecured.AdapterXDRResponseSecuredPortType {
@Resource
private WebServiceContext context;
public gov.hhs.healthit.nhin.XDRAcknowledgementType provideAndRegisterDocumentSetBResponse(
oasis.names.tc.ebxml_regrep.xsd.rs._3.RegistryResponseType body) {
return new AdapterXDRResponseImpl().provideAndRegisterDocumentSetBResponse(body, context);
}
}
| {
"content_hash": "fe5024d49995f34ead3c58fd7b722103",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 129,
"avg_line_length": 35.17391304347826,
"alnum_prop": 0.7948084054388134,
"repo_name": "beiyuxinke/CONNECT",
"id": "df5f6b1d29e50542ca320b1e27248f991c6d1ff9",
"size": "2484",
"binary": false,
"copies": "2",
"ref": "refs/heads/CONNECT_integration",
"path": "Product/Production/Adapters/DocumentSubmission_a0/src/main/java/gov/hhs/fha/nhinc/docsubmission/adapter/deferred/response/AdapterXDRResponseSecured.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "73091"
},
{
"name": "HTML",
"bytes": "178809"
},
{
"name": "Java",
"bytes": "14358905"
},
{
"name": "JavaScript",
"bytes": "6991"
},
{
"name": "PLSQL",
"bytes": "67148"
},
{
"name": "Python",
"bytes": "773"
},
{
"name": "SQLPL",
"bytes": "1363363"
},
{
"name": "Shell",
"bytes": "7384"
},
{
"name": "XSLT",
"bytes": "108247"
}
],
"symlink_target": ""
} |
package com.bagri.server.hazelcast.impl;
import static com.bagri.core.Constants.pn_client_dataFactory;
import static com.bagri.core.Constants.pn_schema_address;
import static com.bagri.core.Constants.pn_schema_name;
import static com.bagri.core.Constants.pn_schema_password;
import static com.bagri.core.Constants.pn_schema_user;
import static com.bagri.support.util.PropUtils.enrichBDBProperties;
import static com.bagri.server.hazelcast.util.HazelcastUtils.getHazelcastClientByName;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import com.bagri.client.hazelcast.impl.SchemaRepositoryImpl;
import com.bagri.core.api.SchemaRepository;
import com.bagri.core.system.Module;
import com.bagri.core.system.Schema;
import com.bagri.core.xquery.api.XQProcessor;
import com.bagri.rest.RepositoryProvider;
import com.bagri.server.hazelcast.management.ModuleManagement;
import com.bagri.server.hazelcast.management.ModuleManager;
import com.bagri.server.hazelcast.management.SchemaManagement;
import com.bagri.xqj.BagriXQDataFactory;
import com.bagri.xquery.saxon.XQProcessorClient;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.Member;
public class RepositoryProviderImpl implements RepositoryProvider {
private ModuleManagement moduleService;
private SchemaManagement schemaService;
private Map<String, SchemaRepository> repos = new ConcurrentHashMap<>();
public SchemaManagement getSchemaManagement() {
return schemaService;
}
public void setModuleManagement(ModuleManagement moduleService) {
this.moduleService = moduleService;
}
public void setSchemaManagement(SchemaManagement schemaService) {
this.schemaService = schemaService;
}
@Override
public Module getModule(String name) {
return ((ModuleManager) moduleService.getEntityManager(name)).getModule();
}
@Override
public Collection<String> getSchemaNames() {
return Arrays.asList(schemaService.getSchemaNames());
}
@Override
public Schema getSchema(String name) {
return schemaService.getSchema(name);
}
@Override
public Collection<Schema> getSchemas() {
return schemaService.getEntities();
}
@Override
public SchemaRepository getRepository(String clientId) {
if (clientId == null) {
if (repos.size() > 0) {
return repos.values().iterator().next();
}
return null;
}
return repos.get(clientId);
}
@Override
public SchemaRepository connect(String schemaName, String userName, String password) {
String address = "";
HazelcastInstance hzInstance = getHazelcastClientByName(schemaName);
if (hzInstance != null) {
int cnt = 0;
for (Member m: hzInstance.getCluster().getMembers()) {
if (cnt > 0) {
address += ",";
}
address += m.getSocketAddress().getHostString() + ":" + m.getSocketAddress().getPort();
cnt++;
}
} else {
return null;
}
Properties props = new Properties();
props.setProperty(pn_schema_address, address);
props.setProperty(pn_schema_name, schemaName);
props.setProperty(pn_schema_user, userName);
props.setProperty(pn_schema_password, password);
enrichBDBProperties(System.getProperties(), props, "bdb.client.", false);
XQProcessor proc = new XQProcessorClient();
BagriXQDataFactory xqFactory = new BagriXQDataFactory();
xqFactory.setProcessor(proc);
props.put(pn_client_dataFactory, xqFactory);
SchemaRepository xRepo = new SchemaRepositoryImpl(props);
repos.put(xRepo.getClientId(), xRepo);
return xRepo;
}
@Override
public void disconnect(String clientId) {
SchemaRepository xRepo = repos.remove(clientId);
if (xRepo != null) {
xRepo.close();
}
}
}
| {
"content_hash": "3294388bd22da9b9205c320ad4d5d123",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 92,
"avg_line_length": 31.811475409836067,
"alnum_prop": 0.7335738211801082,
"repo_name": "dsukhoroslov/bagri",
"id": "ffa7740823da840e1afcb9f3975867569fb96c3b",
"size": "3881",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bagri-server/bagri-server-hazelcast/src/main/java/com/bagri/server/hazelcast/impl/RepositoryProviderImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "49711"
},
{
"name": "C#",
"bytes": "9713"
},
{
"name": "Dockerfile",
"bytes": "675"
},
{
"name": "GAP",
"bytes": "81"
},
{
"name": "HTML",
"bytes": "1505"
},
{
"name": "Java",
"bytes": "5235980"
},
{
"name": "Shell",
"bytes": "30349"
},
{
"name": "XQuery",
"bytes": "34449"
}
],
"symlink_target": ""
} |
1. [Overview](#overview)
2. [Module Description - What the module does and why it is useful](#module-description)
3. [Setup - The basics of getting started with php](#setup)
* [What php affects](#what-php-affects)
* [Setup requirements](#setup-requirements)
* [Beginning with php](#beginning-with-php)
4. [Usage - Configuration options and additional functionality](#usage)
5. [Reference - An under-the-hood peek at what the module is doing and how](#reference)
5. [Limitations - OS compatibility, etc.](#limitations)
6. [Development - Guide for contributing to the module](#development)
## Overview
This PHP module installs, configures and manages the PHP-FPM service and the
PHP command-line.
WARNING: The module is in alpha state
## Module Description
This PHP module installs, configures and manages the PHP-FPM service.
In future releases it will also provide
* installation and configuration for the PHP command-line tools
* an integrate of the Facebook HipHop virtual machine as alternative to PHP-FPM
## Setup
### What php affects
* A list of files, packages, services, or operations that the module will alter,
impact, or execute on the system it's installed on.
* This is a great place to stick any warnings.
* Can be in list or paragraph form.
### Setup Requirements **OPTIONAL**
If your module requires anything extra before setting up (pluginsync enabled,
etc.), mention it here.
### Beginning with php
The very basic steps needed for a user to get the module up and running.
If your most recent release breaks compatibility or requires particular steps
for upgrading, you may wish to include an additional section here: Upgrading
(For an example, see http://forge.puppetlabs.com/puppetlabs/firewall).
## Usage
Put the classes, types, and resources for customizing, configuring, and doing
the fancy stuff with your module here.
## Reference
###Classes
####Public classes
* `php::fpm`: Installs and configures PHP-FPM Service.
####Private classes
* `php::fpm::install`: Installs the PHP-FPM packages.
* `php::fpm::config`: Configures global configuration and central directories.
* `php::fpm::instance_default`: Generates a default PHP-FPM instance using php::fpm_instance.
* `php::fpm::service`: Deletes default Manages the PHP-FPM service.
###Defined Types
####php::fpm_instance
###Parameters
####php::fpm
#####`config_file`
The path of the central PHP-FPM configuration file.
#####`include_dir`
The path of the PHP-FPM include_dir. The include_dir is the place for storing the FPM instance
pool configuration files.
#####`purge_conf_dir`
Wether the include_dir should be purged. Valid values are 'true', 'false'. Defaults to 'true'.
When set to 'true', only FPM instance pool configurations files managed by Puppet are stored.
#####`log_dir`
The path of the central and pool instance logs.
#####`var_dir`
The path of var dir, the base_dir for session dirs and more.
#####`session_dir`
The path of the session base_dir. By default, every fpm pool instance gets an own
directory inside session_dir with permissions restricted to the user/group of the instance.
#####`override_options`
The hash of override options to pass into the global PHP-FPM configuration file.
The hash is merged together with defaults from params.pp into a final options hash.
~~~
$override_options = {
'item' => 'thing',
}
~~~
#####`package_manage`
Whether to manage the PHP-FPM package. Defaults to true.
#####`package_ensure`
Whether the package exists or should be a specific version.
Valid values are 'present', 'absent', or 'x.y.z'. Defaults to 'present'.
#####`package_name`
The name of the PHP-FPM package to install. Defaults are OS dependent, defined in params.pp.
#####`config_manage`
Whether to manage the PHP-FPM global configuration. Defaults to true.
#####`service_manage`
Whether to manage the PHP-FPM service. Defaults to true.
#####`service_name`
The name of the PHP-FPM service. Defaults are OS dependent, defined in params.pp.
#####`service_enable`
Whether the PHP-FPM service should be enabled. Valid values are 'true', 'false'. Defaults to 'true'.
####php::fpm_instance
#####`ensure`
#####`user`
#####`group`
#####`override_options`
## Limitations
This module has been tested on:
* CentOS 7
## Development
The rules for contributing ot this module are as close to the Puppet Labs module
contribution guide as possible.
Check out the complete [module contribution guide](https://docs.puppetlabs.com/forge/contributing.html).
## Release Notes/Contributors/Etc **Optional**
If you aren't using changelog, put your release notes here (though you should
consider using changelog). You may also add any additional sections you feel are
necessary or important to include here. Please use the `## ` header.
### Authors
This module is heavy inspired by the style of puppetlabs-mysql. The following contributors have contributed to this module:
| {
"content_hash": "9de33dccfeb65bc93971775bc7574421",
"timestamp": "",
"source": "github",
"line_count": 174,
"max_line_length": 123,
"avg_line_length": 28.39080459770115,
"alnum_prop": 0.738663967611336,
"repo_name": "wiredobjects/puppet-php",
"id": "e8b2ec83f5e96f8d4bb15e17beefc0ce9259d223",
"size": "4971",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "741"
},
{
"name": "Puppet",
"bytes": "9530"
},
{
"name": "Ruby",
"bytes": "7342"
}
],
"symlink_target": ""
} |
define('app', ['angular', 'angular-ui-router', 'angular-cookie', 'cookies', 'angular-translate', 'loading-bar', 'socket'], function(angular) {
var app = angular.module('app', [
'ui.router',
'chieffancypants.loadingBar',
'ivpusic.cookie',
'pascalprecht.translate',
'ngCookies',
'btford.socket-io',
]);
app.config(function($stateProvider, $urlRouterProvider, $locationProvider, $translateProvider) {
$locationProvider.html5Mode(true);
$urlRouterProvider.otherwise("/");
/*
* Use language from static .json files from /lang/ directory
*/
$translateProvider.useStaticFilesLoader({
prefix: '/lang/',
suffix: '.json'
});
/*
* Select lang, by default it engish
*/
var lang = window.navigator.userLanguage || window.navigator.language || "en";
$translateProvider.preferredLanguage(lang);
/*
* Use cookie as storage for translate
*/
$translateProvider.useCookieStorage();
/*
* Register templates
*/
$stateProvider
.state('cmn', {
abstract: true,
templateUrl: '/app/templates/cmn.html'
})
.state('cmn.panel', {
views: {
'top-panel': {
templateUrl: '/app/modules/misc/views/topPanel.html'
},
'': {
template: '<ui-view/>'
},
'footer': {
templateUrl: '/app/views/footer.html'
}
}
})
});
/*
* Config as angular constant
* TODO: remake with Grunt
*/
app.constant('config', {
apiUrl: '//api.mootkit.lc',
host: 'mootkit.lc'
});
app.run(['$rootScope', 'cfpLoadingBar', 'auth',
function ($rootScope, cfpLoadingBar, auth) {
/*
* Use events for page loading bar
*/
$rootScope.$on('$stateChangeStart', function() {
cfpLoadingBar.start();
});
$rootScope.$on('$stateChangeSuccess', function() {
cfpLoadingBar.complete();
});
/*
* Init auth mechanism, like loading cookies and verify tokens etc
*/
auth.init();
}]);
return app;
}); | {
"content_hash": "bcf724c72abeff665adb364626216d12",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 142,
"avg_line_length": 29.529411764705884,
"alnum_prop": 0.47649402390438245,
"repo_name": "cv21/mootkit",
"id": "32324e77e533a178d2fef877a8503aeb7a486382",
"size": "2510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/app/app.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "119383"
},
{
"name": "HTML",
"bytes": "26007"
},
{
"name": "JavaScript",
"bytes": "32472"
},
{
"name": "Shell",
"bytes": "198"
}
],
"symlink_target": ""
} |
package com.bramblellc.myapplication.services;
public class ActionConstants {
public static final String REGISTER_ACTION = "com.bramblellc.myapplication.services.REGISTER";
public static final String LOGIN_ACTION = "com.bramblellc.myapplication.services.LOGIN";
public static final String ANALYZE_ACTION = "com.bramblellc.myapplication.services.ANALYZE";
public static final String SENSOR_ACTION = "com.bramblellc.myapplication.sensor.SENSOR";
}
| {
"content_hash": "d4e45ac5e128270c65c86e2a04b83503",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 98,
"avg_line_length": 46.5,
"alnum_prop": 0.7935483870967742,
"repo_name": "BrambleLLC/H4H_2015",
"id": "4c7d96ad9c9c2e4cca9648737557f0731e22c8fc",
"size": "465",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Android/MyApplication/app/src/main/java/com/bramblellc/myapplication/services/ActionConstants.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3290"
},
{
"name": "HTML",
"bytes": "8361"
},
{
"name": "Java",
"bytes": "91603"
},
{
"name": "JavaScript",
"bytes": "1770"
},
{
"name": "Python",
"bytes": "8413"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="tab_def_normal_color">#aaff4400</color>
<color name="tab_def_selected_color">#ffff2200</color>
<color name="tab_def_indicator_color">#ffff2200</color>
<color name="tab_def_pager_primary_color">#2f2459</color>
<color name="nav_def_line_divider_color">@android:color/transparent</color>
</resources> | {
"content_hash": "deba162425ea133e3dab16b7096d0572",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 79,
"avg_line_length": 42.44444444444444,
"alnum_prop": 0.6963350785340314,
"repo_name": "SilentWolf1993/TabPager",
"id": "baca4eeb9cbce284051048df86c4742f423c5208",
"size": "382",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tabnav/src/main/res/values/colors.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "95865"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<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/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.apache.felix</groupId>
<artifactId>org.apache.felix.ipojo.runtime.composite-it</artifactId>
<version>1.12.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>ipojo-composite-runtime-test</artifactId>
<name>${project.artifactId}</name>
</project> | {
"content_hash": "55211013615f9c375d78aecb2986d314",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 204,
"avg_line_length": 40.75,
"alnum_prop": 0.7075664621676891,
"repo_name": "apache/felix-dev",
"id": "3ca125fe7b1054783211a0169e7363fd5657798c",
"size": "1467",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ipojo/runtime/composite-it/ipojo-composite-runtime-test/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "53237"
},
{
"name": "Groovy",
"bytes": "9231"
},
{
"name": "HTML",
"bytes": "372812"
},
{
"name": "Java",
"bytes": "28836360"
},
{
"name": "JavaScript",
"bytes": "248796"
},
{
"name": "Scala",
"bytes": "40378"
},
{
"name": "Shell",
"bytes": "12628"
},
{
"name": "XSLT",
"bytes": "151258"
}
],
"symlink_target": ""
} |
if (typeof dojo != "undefined")
{
dojo.provide("org.cometd.TimeStampExtension");
}
/**
* The timestamp extension adds the optional timestamp field to all outgoing messages.
*/
org.cometd.TimeStampExtension = function()
{
this.outgoing = function(message)
{
message.timestamp = new Date().toUTCString();
return message;
};
};
| {
"content_hash": "2ccdd3d4a26fbb41d41f7af55c27b37f",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 86,
"avg_line_length": 20.11111111111111,
"alnum_prop": 0.6602209944751382,
"repo_name": "iSynthetica/yii-poland",
"id": "474aa6aeef59a6962c87803b801ed5973bfbf809",
"size": "980",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "frontend/web/js/libs/org/cometd/TimeStampExtension.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "338"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "415489"
},
{
"name": "JavaScript",
"bytes": "661738"
},
{
"name": "PHP",
"bytes": "419483"
},
{
"name": "TypeScript",
"bytes": "3098"
}
],
"symlink_target": ""
} |
#ifndef PROFILE_H_
#define PROFILE_H_
#include "State.h"
#include "EmissionTable.h"
#define PROFILE_FILENAME_LENGTH 256
typedef struct Profile {
char name[STATE_NAME_LENGTH];
char filename[PROFILE_FILENAME_LENGTH];
uint16_t length;
struct EmissionTable* emission_tables;
} Profile;
struct Profile* Profile__create(char name[STATE_NAME_LENGTH]);
void Profile__destroy();
bool Profile__read(struct Profile* self, char filename[]);
struct EmissionTable* Profile__add_emission(struct Profile* self);
LOGODD_T Profile__by_literals(struct Profile* self, Literal query[]);
bool Profile__str(struct Profile* self, char* buffer);
#endif // PROFILE_H_
| {
"content_hash": "0f6a094202f27c00f64375b22cc5dcef",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 69,
"avg_line_length": 26.64,
"alnum_prop": 0.7402402402402403,
"repo_name": "hillerlab/CESAR2.0",
"id": "81271452ff9bf22945d9c1fd787821dc0d745392",
"size": "743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Profile.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AngelScript",
"bytes": "435508"
},
{
"name": "C",
"bytes": "14809587"
},
{
"name": "C++",
"bytes": "126875"
},
{
"name": "Gnuplot",
"bytes": "36237"
},
{
"name": "HTML",
"bytes": "11954"
},
{
"name": "M4",
"bytes": "7552"
},
{
"name": "Makefile",
"bytes": "111622"
},
{
"name": "Objective-C",
"bytes": "1799"
},
{
"name": "PLSQL",
"bytes": "8971"
},
{
"name": "Perl",
"bytes": "145168"
},
{
"name": "PostScript",
"bytes": "2595"
},
{
"name": "Python",
"bytes": "1617"
},
{
"name": "Roff",
"bytes": "20366"
},
{
"name": "Shell",
"bytes": "34590"
},
{
"name": "TSQL",
"bytes": "150939"
}
],
"symlink_target": ""
} |
package org.eclipse.ceylon.javax.tools;
import org.eclipse.ceylon.javax.lang.model.element.Modifier;
import org.eclipse.ceylon.javax.lang.model.element.NestingKind;
import org.eclipse.ceylon.javax.tools.ForwardingFileObject;
import org.eclipse.ceylon.javax.tools.JavaFileObject;
import org.eclipse.ceylon.javax.tools.JavaFileObject.Kind;
/**
* Forwards calls to a given file object. Subclasses of this class
* might override some of these methods and might also provide
* additional fields and methods.
*
* @param <F> the kind of file object forwarded to by this object
* @author Peter von der Ahé
* @since 1.6
*/
public class ForwardingJavaFileObject<F extends JavaFileObject>
extends ForwardingFileObject<F>
implements JavaFileObject
{
/**
* Creates a new instance of ForwardingJavaFileObject.
* @param fileObject delegate to this file object
*/
protected ForwardingJavaFileObject(F fileObject) {
super(fileObject);
}
public Kind getKind() {
return fileObject.getKind();
}
public boolean isNameCompatible(String simpleName, Kind kind) {
return fileObject.isNameCompatible(simpleName, kind);
}
public NestingKind getNestingKind() { return fileObject.getNestingKind(); }
public Modifier getAccessLevel() { return fileObject.getAccessLevel(); }
}
| {
"content_hash": "70f6b11e2fcc93a6fc30f984f2655a97",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 79,
"avg_line_length": 30.133333333333333,
"alnum_prop": 0.7404129793510325,
"repo_name": "ceylon/ceylon",
"id": "8a5a36f1d676e8781b70cc6f4dc9ed08b7eea91c",
"size": "2568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "compiler-java/langtools/src/share/classes/org/eclipse/ceylon/javax/tools/ForwardingJavaFileObject.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3806"
},
{
"name": "CSS",
"bytes": "19001"
},
{
"name": "Ceylon",
"bytes": "6230332"
},
{
"name": "GAP",
"bytes": "178688"
},
{
"name": "Groovy",
"bytes": "28376"
},
{
"name": "HTML",
"bytes": "4562"
},
{
"name": "Java",
"bytes": "24954709"
},
{
"name": "JavaScript",
"bytes": "499145"
},
{
"name": "Makefile",
"bytes": "19934"
},
{
"name": "Perl",
"bytes": "2756"
},
{
"name": "Roff",
"bytes": "47559"
},
{
"name": "Shell",
"bytes": "212436"
},
{
"name": "XSLT",
"bytes": "1992114"
}
],
"symlink_target": ""
} |
<?php
/**
* Created by PhpStorm.
* User: karlvaniseghem
* Date: 19/10/15
* Time: 17:15
*/
namespace Bakgat\Notos\Tests\Domain\Model\Identity;
use Bakgat\Notos\Domain\Model\Identity\DomainName;
use Bakgat\Notos\Domain\Model\Identity\DomainNameIsUnique;
use Bakgat\Notos\Domain\Model\Identity\DomainNameSpecification;
use Mockery\MockInterface;
use Mockery as m;
use Orchestra\Testbench\TestCase;
class DomainNameIsUniqueTest extends TestCase
{
/** @var MockInterface $orgRepo */
private $orgRepo;
/** @var DomainNameSpecification $spec */
private $spec;
public function setUp()
{
parent::setUp();
$this->orgRepo = m::mock('Bakgat\Notos\Domain\Model\Identity\OrganizationRepository');
$this->spec = new DomainNameIsUnique($this->orgRepo);
}
/**
* @test
* @group domainname
*/
public function should_return_true_if_unique()
{
$this->orgRepo->shouldReceive('organizationOfDomain')->andReturnNull();
$this->assertTrue($this->spec->isSatisfiedBy(new DomainName('klimtoren.be')));
}
/**
* @test
* @group domainname
*/
public function should_return_false_if_not_unique()
{
$this->orgRepo->shouldReceive('organizationOfDomain')->andReturn(['id' => 1]);
$this->assertFalse($this->spec->isSatisfiedBy(new DomainName('not_unique.be')));
}
} | {
"content_hash": "e3b6c0fdccf3212d633cca146614b025",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 94,
"avg_line_length": 26.673076923076923,
"alnum_prop": 0.665465032444124,
"repo_name": "bakgat/notos",
"id": "7db41de6c1f853102394933f7d8c562e993f9823",
"size": "1387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Domain/Model/Identity/DomainNameIsUniqueTest.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "654298"
}
],
"symlink_target": ""
} |
<p>(<a href="/">Home</a>)</p>
$body$
<a href="https://github.com/housejeffries-pages/$pageId$/blob/master/page.md"><img style="position: absolute; top: 0; right: 0; border: 0;" src="/forkme_right_green_007200.png" alt="Fork me on GitHub"></a>
| {
"content_hash": "a1118929daae2179a87db89b50f1c19d",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 207,
"avg_line_length": 49.4,
"alnum_prop": 0.6558704453441295,
"repo_name": "seagreen/housejeffries",
"id": "c4258f1c306fe2a44b9ee997966ce5c5819b3bd5",
"size": "247",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/page-nav.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "801"
},
{
"name": "HTML",
"bytes": "1606"
},
{
"name": "Haskell",
"bytes": "19434"
},
{
"name": "Nix",
"bytes": "296"
}
],
"symlink_target": ""
} |
class CEOSAIStrategicAIOrder_DeclareWar : public CEOSAIStrategicAIOrder
{
public:
CEOSAIStrategicAIOrder_DeclareWar( CEOSAIStrategicAI* pStrategicAI ) : CEOSAIStrategicAIOrder( pStrategicAI ){ m_iTargetPlayer = 0; }
void SetTarget( int iTargetPlayer ){ m_iTargetPlayer = iTargetPlayer; }
virtual void Execute( long iCurrentTurn ); // Send the declaration
private:
int m_iTargetPlayer;
};
| {
"content_hash": "5b62bd7599d572292f22669a045bb8be",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 135,
"avg_line_length": 36.54545454545455,
"alnum_prop": 0.7786069651741293,
"repo_name": "BritClousing/EOSAI",
"id": "434bf69c8899592b8e96235dc45f1d3926ed9841",
"size": "453",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "EOSAI/EOSAIStrategicAIOrder_DeclareWar.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "10143"
},
{
"name": "C",
"bytes": "4798"
},
{
"name": "C++",
"bytes": "4233524"
},
{
"name": "CSS",
"bytes": "3350"
},
{
"name": "HTML",
"bytes": "98025"
},
{
"name": "Objective-C",
"bytes": "11281"
},
{
"name": "QML",
"bytes": "58768"
},
{
"name": "QMake",
"bytes": "859"
}
],
"symlink_target": ""
} |
package banana
import (
"sort"
)
// Letter represents a tile character.
type Letter rune
const (
// noLetter is used in the absense of a valid letter to return.
noLetter = Letter(rune(0))
)
// String turns the letter into a string.
func (l Letter) String() string {
return string(l)
}
// Tiles represents a set of tiles.
type Tiles struct {
freq map[Letter]int
count int
}
// Clone returns a deep copy of the set of tiles.
func (t *Tiles) Clone() *Tiles {
freq := make(map[Letter]int)
for l, idx := range t.freq {
freq[l] = idx
}
return &Tiles{
freq: freq,
count: t.count,
}
}
// NewTiles returns an initialized and empty tile set.
func NewTiles() *Tiles {
return &Tiles{
freq: make(map[Letter]int),
}
}
// tilesFromDistribution initializes a tile set according to a given
// distribution and scale factor.
func tilesFromDistribution(d Distribution) *Tiles {
var (
freq = make(map[Letter]int)
count = 0
)
for n, letters := range d {
for _, letter := range letters {
// Map the new index back to the letter.
freq[letter] = n
// Update our total count.
count += n
}
}
return &Tiles{freq: freq, count: count}
}
// Freq returns the frequency of a given letter.
func (t *Tiles) Freq(l Letter) int {
return t.freq[l]
}
// Add adds tiles from one tile set to another, without modifying the tile set
// to add.
func (t *Tiles) Add(o *Tiles) {
for l, freq := range o.freq {
t.add(l, freq)
}
}
// Inc adds one to the count of the given letter.
func (t *Tiles) Inc(l Letter) {
t.add(l, 1)
}
// Dec removes one from the count of the given letter. This is allowed to be
// negative and is actually a key part of diffing tile sets.
func (t *Tiles) Dec(l Letter) {
t.add(l, -1)
}
func (t *Tiles) add(l Letter, delta int) {
t.count += delta
t.freq[l] += delta
}
func (t *Tiles) letters() []Letter {
ls := make([]Letter, t.count)
i := 0
for letter, freq := range t.freq {
for j := 0; j < freq; j++ {
ls[i] = letter
i++
}
}
sort.Slice(ls, func(i, j int) bool { return ls[i] < ls[j] })
return ls
}
func (t *Tiles) AsList() []string {
ls := make([]string, t.count)
i := 0
for letter, freq := range t.freq {
str := letter.String()
for j := 0; j < freq; j++ {
ls[i] = str
i++
}
}
sort.Strings(ls)
return ls
}
func (t *Tiles) Update(l Letter, freq int) {
of := t.freq[l]
t.freq[l] = freq
t.count += freq - of
}
func (t *Tiles) Count() int {
return t.count
}
func (t *Tiles) forEach(f func(l Letter, freq int) bool) {
type letterFreq struct {
l Letter
f int
}
lfs := make([]letterFreq, len(t.freq))
for l, freq := range t.freq {
lfs = append(lfs, letterFreq{l: l, f: freq})
}
sort.Slice(lfs, func(i, j int) bool { return lfs[i].l < lfs[j].l })
for _, lf := range lfs {
if f(lf.l, lf.f) {
break
}
}
}
| {
"content_hash": "0dc575e14e1d97dc700640272068a737",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 78,
"avg_line_length": 18.78,
"alnum_prop": 0.6240681576144835,
"repo_name": "bcspragu/Bananagrama",
"id": "19d727d67cbe2c020277efe399a7241dcd78161d",
"size": "2817",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "banana/tiles.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1083"
},
{
"name": "Go",
"bytes": "93582"
},
{
"name": "HTML",
"bytes": "1098"
},
{
"name": "JavaScript",
"bytes": "234532"
},
{
"name": "Shell",
"bytes": "1374"
},
{
"name": "TypeScript",
"bytes": "2326"
},
{
"name": "Vue",
"bytes": "74271"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<!--
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<opicmsppdfgenerator>
<general>
<enable_frontend>1</enable_frontend>
</general>
</opicmsppdfgenerator>
</default>
</config> | {
"content_hash": "2aecb8061d5570f8b36108f8ac13b86f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 142,
"avg_line_length": 28.615384615384617,
"alnum_prop": 0.6129032258064516,
"repo_name": "letunhatkong/tradebanner",
"id": "3095fda968e804d2f6ccf6baf7cf6e6a741fbf42",
"size": "1063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/Eadesigndev/Opicmsppdfgenerator/etc/config.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "158924"
},
{
"name": "HTML",
"bytes": "956313"
},
{
"name": "JavaScript",
"bytes": "221669"
},
{
"name": "PHP",
"bytes": "2473541"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.