text stringlengths 2 1.04M | meta dict |
|---|---|
package com.amazonaws.services.medialive.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.medialive.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* MediaPackageOutputSettings JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class MediaPackageOutputSettingsJsonUnmarshaller implements Unmarshaller<MediaPackageOutputSettings, JsonUnmarshallerContext> {
public MediaPackageOutputSettings unmarshall(JsonUnmarshallerContext context) throws Exception {
MediaPackageOutputSettings mediaPackageOutputSettings = new MediaPackageOutputSettings();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return mediaPackageOutputSettings;
}
private static MediaPackageOutputSettingsJsonUnmarshaller instance;
public static MediaPackageOutputSettingsJsonUnmarshaller getInstance() {
if (instance == null)
instance = new MediaPackageOutputSettingsJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "10943f6b803011821626f7c999f8ec80",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 136,
"avg_line_length": 34.6271186440678,
"alnum_prop": 0.6769456681350955,
"repo_name": "aws/aws-sdk-java",
"id": "d7ca7b554fd28329c75aa59a1935e5b5847ff908",
"size": "2623",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/transform/MediaPackageOutputSettingsJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
struct core_map;
int core_map_get_int(struct core_map *self, void *key);
#endif
| {
"content_hash": "9817739964fcf0589b30dbd62ed63f80",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 55,
"avg_line_length": 16.4,
"alnum_prop": 0.7073170731707317,
"repo_name": "sebhtml/biosal",
"id": "51931d55cea19b7de52f1c9a4191def7c23bbe49",
"size": "137",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "core/helpers/map_helper.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "2144610"
},
{
"name": "C++",
"bytes": "505"
},
{
"name": "Makefile",
"bytes": "40448"
},
{
"name": "Objective-C",
"bytes": "119"
},
{
"name": "Python",
"bytes": "7639"
},
{
"name": "R",
"bytes": "4105"
},
{
"name": "Ruby",
"bytes": "4126"
},
{
"name": "Shell",
"bytes": "67651"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="center" />
<module name="config" />
<module name="consumer" />
<module name="facade" />
<module name="gateway" />
<module name="monitor" />
<module name="provider" />
<module name="sso" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="center" target="1.8" />
<module name="cloud" target="1.8" />
<module name="config" target="1.8" />
<module name="consumer" target="1.8" />
<module name="facade" target="1.8" />
<module name="gateway" target="1.8" />
<module name="monitor" target="1.8" />
<module name="parent" target="1.8" />
<module name="provider" target="1.8" />
<module name="service" target="1.8" />
<module name="sso" target="1.8" />
<module name="ssotest" target="1.8" />
</bytecodeTargetLevel>
</component>
</project> | {
"content_hash": "3ab0b2fa08051e0e706422648b73c50a",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 85,
"avg_line_length": 40.25714285714286,
"alnum_prop": 0.603264726756565,
"repo_name": "JerryNiu/cloud",
"id": "adb1c589d3d0cfd6a3854772a295fc0ead905bbb",
"size": "1409",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/compiler.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1218"
},
{
"name": "Java",
"bytes": "41378"
}
],
"symlink_target": ""
} |
package com.appleframework.cache.redis;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service("testService")
public class TestService {
@Cacheable(value = "testd", key = "#name")
public String getCache(String name) {
System.out.println("-----service in------" + System.currentTimeMillis());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
return "hello " + name;
}
}
| {
"content_hash": "a455d425153c5d9833a59db7c46c919d",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 75,
"avg_line_length": 26.444444444444443,
"alnum_prop": 0.6848739495798319,
"repo_name": "xushaomin/apple-cache",
"id": "9065f7fe8bb5bb4ad6ae11f7eab8af4e93fe1bcd",
"size": "476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "apple-cache-jedis/src/test/java/com/appleframework/cache/redis/TestService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
from freebase.schema import dump_base, dump_type, restore
try:
import jsonlib2 as json
except ImportError:
try:
import simplejson as json
except ImportError:
import json
import sys
def cmd_dump_base(fb, baseid):
"""dump a base to stdout
%prog dump_base baseid
Dump a base by outputting a json representation
of the types and properties involved.
"""
print >> sys.stdout, json.dumps(dump_base(fb.mss, baseid), indent=2)
def cmd_dump_type(fb, typeid, follow_types=True):
"""dump a type to stdout
%prog dump_type typeid [follow_types=True]
Dump a type by outputting a json representation
of the type and properties involved.
"""
print >> sys.stdout, json.dumps(dump_type(fb.mss, typeid, follow_types), indent=2)
def cmd_restore(fb, newlocation, graphfile):
"""restore a graph object to the graph
%prog restore newlocation graphfile
Restore a graph object to the newlocation
"""
fh = open(graphfile, "r")
graph = json.loads(fh.read())
fh.close()
return restore(fb.mss, graph, newlocation, ignore_types=None)
| {
"content_hash": "aae42d0cfe8a960979ed00c33d405594",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 86,
"avg_line_length": 27.341463414634145,
"alnum_prop": 0.6815343443354148,
"repo_name": "yuvadm/freebase-python",
"id": "b5a30da071d0166dcf4a25957be6270741376589",
"size": "1121",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "freebase/fcl/schema.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "JavaScript",
"bytes": "90677"
},
{
"name": "Python",
"bytes": "413743"
}
],
"symlink_target": ""
} |
import * as React from 'react';
import { graphql, compose } from 'react-apollo';
import withMutationState from 'apollo-mutation-state';
import { Form, Field } from 'react-final-form';
import withFlashMessage from 'components/flash/withFlashMessage';
import RenderField from 'components/form/RenderField';
import SubmitField from 'components/form/SubmitField';
import CHANGE_USER_PASSWORD from 'graphql/users/changeUserPasswordMutation.graphql';
// typings
import { ApolloQueryResult } from 'apollo-client/core/types';
import {
FlashMessageVariables,
ChangePasswordMutation,
ChangePasswordMutationVariables,
MutationState,
MutationStateProps,
User
} from 'types';
interface IProps {
redirect: (path: string, message: FlashMessageVariables) => void;
handleSubmit: (event: any) => void;
changePassword: ({ }: ChangePasswordMutationVariables) => Promise<ApolloQueryResult<ChangePasswordMutation>>;
mutation: MutationState;
}
class ChangeUserPassword extends React.Component<IProps, {}> {
private changePasswordForm: any;
constructor(props: IProps) {
super(props);
this.submitForm = this.submitForm.bind(this);
}
private async submitForm(values: any) {
const { data: { changePassword: { errors } } } = await this.props.changePassword(values);
if (!errors) {
this.props.redirect('/', { notice: 'User password was successfully updated' });
} else {
this.changePasswordForm.form.change('current_password', '');
this.changePasswordForm.form.change('password', '');
this.changePasswordForm.form.change('password_confirmation', '');
return errors;
}
}
public render() {
const { mutation: { loading } } = this.props;
return (
<div className="change-user-password">
<div className="columns">
<div className="column is-offset-one-quarter is-half">
<h1 className="title is-3">Changer votre mot de passe</h1>
<Form
onSubmit={this.submitForm}
ref={(input: any) => {
this.changePasswordForm = input;
}}
render={({ handleSubmit, pristine }: any) => (
<form onSubmit={handleSubmit}>
<Field name="current_password" label="Current password" type="password" component={RenderField} />
<Field name="password" label="New password" type="password" component={RenderField} />
<Field
name="password_confirmation"
label="Confirm your password"
type="password"
component={RenderField}
/>
<SubmitField loading={loading} disabled={pristine} value="Update" />
</form>
)}
/>
</div>
</div>
</div>
);
}
}
const withChangeUserPassword = graphql<ChangePasswordMutation, ChangePasswordMutationVariables & MutationStateProps>(
CHANGE_USER_PASSWORD,
{
props: ({ mutate, ownProps: { wrapMutate } }) => ({
changePassword(user: User) {
return wrapMutate(mutate!({ variables: { ...user } }));
}
})
}
);
export default compose(
withMutationState({ wrapper: true, propagateError: true }),
withChangeUserPassword,
withFlashMessage
)(ChangeUserPassword);
| {
"content_hash": "215cb48acc68d63ee15f251573a64370",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 117,
"avg_line_length": 33.63636363636363,
"alnum_prop": 0.6360360360360361,
"repo_name": "MatthieuSegret/graphql-rails-blog",
"id": "de11156e2d62b987b56ce6ed859c1ec9251b0a76",
"size": "3330",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/src/containers/users/ChangeUserPassword.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1590"
},
{
"name": "HTML",
"bytes": "453"
},
{
"name": "JavaScript",
"bytes": "1028"
},
{
"name": "Ruby",
"bytes": "45613"
},
{
"name": "TypeScript",
"bytes": "65759"
}
],
"symlink_target": ""
} |
module Egauge
class << self
def configuration
@configuration ||= Configuration.new
end
def configure
yield configuration
end
end
class Configuration
attr_accessor :url
end
end
| {
"content_hash": "530ed23f19eef02a59712ec76fae02ae",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 42,
"avg_line_length": 13.6875,
"alnum_prop": 0.6575342465753424,
"repo_name": "9minutesnooze/egauge-gem",
"id": "6cd770151486f5878a32e78e4ed25b1fb1db900e",
"size": "219",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "lib/egauge/configuration.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11134"
}
],
"symlink_target": ""
} |
namespace k4aviewer
{
class K4APollingThread
{
public:
K4APollingThread(std::function<bool(bool)> &&pollFn) : m_pollFn(std::move(pollFn))
{
m_thread = std::thread(&K4APollingThread::Run, this);
}
void Stop()
{
StopAsync();
if (m_thread.joinable())
{
m_thread.join();
}
}
void StopAsync()
{
m_shouldExit = true;
}
bool IsRunning() const
{
return m_isRunning;
}
~K4APollingThread()
{
Stop();
}
private:
static void Run(K4APollingThread *instance)
{
instance->m_isRunning = true;
CleanupGuard runGuard([instance]() { instance->m_isRunning = false; });
bool firstRun = true;
while (!instance->m_shouldExit)
{
if (!instance->m_pollFn(firstRun))
{
instance->m_shouldExit = true;
}
firstRun = false;
}
}
std::thread m_thread;
volatile bool m_shouldExit = false;
volatile bool m_isRunning = false;
std::function<bool(bool)> m_pollFn;
};
} // namespace k4aviewer
#endif
| {
"content_hash": "05423be519c109691b651d3265119b91",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 86,
"avg_line_length": 19.1,
"alnum_prop": 0.5322862129144852,
"repo_name": "microsoft/Azure-Kinect-Sensor-SDK",
"id": "9a43713008edd215e5ebe0d8a114f7b0b284b4a5",
"size": "1433",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tools/k4aviewer/k4apollingthread.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "900992"
},
{
"name": "C#",
"bytes": "429378"
},
{
"name": "C++",
"bytes": "1662296"
},
{
"name": "CMake",
"bytes": "205182"
},
{
"name": "CSS",
"bytes": "2388"
},
{
"name": "Dockerfile",
"bytes": "399"
},
{
"name": "HTML",
"bytes": "3954"
},
{
"name": "PowerShell",
"bytes": "9249"
},
{
"name": "Python",
"bytes": "349473"
},
{
"name": "Shell",
"bytes": "4599"
}
],
"symlink_target": ""
} |
.class Landroid/support/v4/view/cp;
.super Landroid/support/v4/view/co;
# direct methods
.method constructor <init>()V
.locals 0
invoke-direct {p0}, Landroid/support/v4/view/co;-><init>()V
return-void
.end method
# virtual methods
.method public G(Landroid/view/View;)Z
.locals 1
invoke-static {p1}, Landroid/support/v4/view/db;->a(Landroid/view/View;)Z
move-result v0
return v0
.end method
.method public I(Landroid/view/View;)Z
.locals 1
invoke-static {p1}, Landroid/support/v4/view/db;->b(Landroid/view/View;)Z
move-result v0
return v0
.end method
.method public c(Landroid/view/View;I)V
.locals 0
invoke-static {p1, p2}, Landroid/support/v4/view/cz;->a(Landroid/view/View;I)V
return-void
.end method
.method public e(Landroid/view/View;I)V
.locals 0
invoke-static {p1, p2}, Landroid/support/v4/view/db;->a(Landroid/view/View;I)V
return-void
.end method
| {
"content_hash": "492c7c53fbb18b83ae09ce11e6f9667c",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 82,
"avg_line_length": 18.88,
"alnum_prop": 0.6832627118644068,
"repo_name": "Pittvandewitt/v4a_material_reformatted_src",
"id": "9427206387e3c134c4be25205380ceb295ad7417",
"size": "944",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "smali/android/support/v4/view/cp.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Shell",
"bytes": "807"
},
{
"name": "Smali",
"bytes": "10020608"
}
],
"symlink_target": ""
} |
package org.apache.hadoop.mapreduce.server.tasktracker.userlogs;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.TaskLogsTruncater;
import org.apache.hadoop.mapred.TaskTracker;
import org.apache.hadoop.mapred.UserLogCleaner;
/**
* This manages user logs on the {@link TaskTracker}.
*/
public class UserLogManager {
private static final Log LOG = LogFactory.getLog(UserLogManager.class);
private BlockingQueue<UserLogEvent> userLogEvents =
new LinkedBlockingQueue<UserLogEvent>();
private TaskLogsTruncater taskLogsTruncater;
private UserLogCleaner userLogCleaner;
private Thread monitorLogEvents = new Thread() {
@Override
public void run() {
while (true) {
try {
monitor();
} catch (Exception e) {
LOG.warn("Exception while monitoring user log events", e);
}
}
}
};
/**
* Create the user log manager to manage user logs on {@link TaskTracker}.
*
* It should be explicitly started using {@link #start()} to start functioning
*
* @param conf
* The {@link Configuration}
*
* @throws IOException
*/
public UserLogManager(Configuration conf) throws IOException {
taskLogsTruncater = new TaskLogsTruncater(conf);
userLogCleaner = new UserLogCleaner(this, conf);
monitorLogEvents.setDaemon(true);
}
/**
* Starts managing the logs
*/
public void start() {
userLogCleaner.start();
monitorLogEvents.start();
}
protected void monitor() throws Exception {
UserLogEvent event = userLogEvents.take();
processEvent(event);
}
protected void processEvent(UserLogEvent event) throws IOException {
if (event instanceof JvmFinishedEvent) {
doJvmFinishedAction((JvmFinishedEvent) event);
} else if (event instanceof JobCompletedEvent) {
doJobCompletedAction((JobCompletedEvent) event);
} else if (event instanceof JobStartedEvent) {
doJobStartedAction((JobStartedEvent) event);
} else if (event instanceof DeleteJobEvent) {
doDeleteJobAction((DeleteJobEvent) event);
} else {
LOG.warn("Unknown event " + event.getEventType() + " passed.");
}
}
/**
* Called during TaskTracker restart/re-init.
*
* @param conf
* TT's conf
* @throws IOException
*/
public void clearOldUserLogs(Configuration conf)
throws IOException {
userLogCleaner.clearOldUserLogs(conf);
}
private void doJvmFinishedAction(JvmFinishedEvent event) {
taskLogsTruncater.truncateLogs(event.getJvmInfo());
}
private void doJobStartedAction(JobStartedEvent event) {
userLogCleaner.unmarkJobFromLogDeletion(event.getJobID());
}
private void doJobCompletedAction(JobCompletedEvent event) {
userLogCleaner.markJobLogsForDeletion(event.getJobCompletionTime(), event
.getRetainHours(), event.getJobID());
}
private void doDeleteJobAction(DeleteJobEvent event) throws IOException {
userLogCleaner.deleteJobLogs(event.getJobID());
}
/**
* Add the {@link UserLogEvent} for processing.
*
* @param event
*/
public void addLogEvent(UserLogEvent event) {
userLogEvents.add(event);
}
/**
* Get {@link UserLogCleaner}.
*
* This method is called only from unit tests.
*
* @return {@link UserLogCleaner}
*/
public UserLogCleaner getUserLogCleaner() {
return userLogCleaner;
}
}
| {
"content_hash": "c91a29eece72ff8dfa44a153bc1803b1",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 80,
"avg_line_length": 28.100775193798448,
"alnum_prop": 0.7020689655172414,
"repo_name": "coderplay/hadoop-common",
"id": "724469a560780907004acbe086155f2d7b8bc568",
"size": "4431",
"binary": false,
"copies": "5",
"ref": "refs/heads/yahoo-hadoop-0.20.104",
"path": "src/mapred/org/apache/hadoop/mapreduce/server/tasktracker/userlogs/UserLogManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "368322"
},
{
"name": "C++",
"bytes": "353837"
},
{
"name": "Java",
"bytes": "12648952"
},
{
"name": "JavaScript",
"bytes": "21457"
},
{
"name": "Objective-C",
"bytes": "112020"
},
{
"name": "PHP",
"bytes": "152555"
},
{
"name": "Perl",
"bytes": "149888"
},
{
"name": "Python",
"bytes": "613479"
},
{
"name": "Ruby",
"bytes": "28485"
},
{
"name": "Shell",
"bytes": "1080312"
},
{
"name": "Smalltalk",
"bytes": "56562"
}
],
"symlink_target": ""
} |
package com.asakusafw.yaess.bootstrap;
/**
* Represents an extended argument.
* @since 0.8.0
*/
public class ExtendedArgument {
/**
* The parameter prefix of extended arguments.
*/
public static final String PREFIX = "-X-"; //$NON-NLS-1$
private final String name;
private final String value;
/**
* Creates a new instance.
* @param name the argument name
* @param value the argument value
*/
public ExtendedArgument(String name, String value) {
this.name = name;
this.value = value;
}
/**
* Returns the name.
* The name does not include the common {@link #PREFIX prefix}.
* @return the name
*/
public String getName() {
return name;
}
/**
* Returns the value.
* @return the value
*/
public String getValue() {
return value;
}
@Override
public String toString() {
return String.format("%s%s:%s", PREFIX, name, value); //$NON-NLS-1$
}
}
| {
"content_hash": "495b1c3f6c6aa8d171d321c930f96e75",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 75,
"avg_line_length": 20.32,
"alnum_prop": 0.5767716535433071,
"repo_name": "asakusafw/asakusafw",
"id": "e3af61c3ff30fdd0179e97794d39b348781a27fd",
"size": "1628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yaess-project/asakusa-yaess-bootstrap/src/main/java/com/asakusafw/yaess/bootstrap/ExtendedArgument.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "31"
},
{
"name": "CSS",
"bytes": "650"
},
{
"name": "Groovy",
"bytes": "277016"
},
{
"name": "Java",
"bytes": "12812573"
},
{
"name": "Lex",
"bytes": "12506"
},
{
"name": "Shell",
"bytes": "10149"
}
],
"symlink_target": ""
} |
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['*.js', 'client/app/**/*.js', 'server/**/*.js', 'database/**/*.js', '*.json', 'spec/**/*.js'],
options: {
ignores: [
]
}
},
uglify: {
target: {
files: {
// These need to be uglified in specific order, app files last.
'client/allmincode.js': [
'bower_components/adjective-adjective-animal/dist/adjective-adjective-animal.min.js',
'bower_components/angular/angular.min.js',
'bower_components/angular-ui-router/release/angular-ui-router.min.js',
'bower_components/angular-animate/angular-animate.min.js',
'bower_components/angular-bootstrap/ui-bootstrap-tpls.min.js',
'client/lib/nochunkbufferfixpeer.min.js',
'bower_components/localforage/dist/localforage.min.js',
'bower_components/jquery/dist/jquery.min.js',
'bower_components/angular-ui-notification/dist/angular-ui-notification.min.js',
'bower_components/bootstrap/dist/js/bootstrap.min.js',
'client/app/**/*.js'
]
}
}
},
cssmin: {
target: {
files: {
'client/assets/styles.min.css': [
'bower_components/angular-ui-notification/dist/angular-ui-notification.min.css',
'bower_components/font-awesome/css/font-awesome.min.css',
'bower_components/bootstrap/dist/css/bootstrap.min.css',
'client/assets/styles.css'
]
}
}
},
watch: {
files: ['client/app/**/*.js'],
tasks: ['jshint']
}
});
//Automatic desktop notifications for Grunt errors and warnings
grunt.loadNpmTasks('grunt-notify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-concat');
/*************************************************************
Run `$ grunt jshint` before submitting PR
Or run `$ grunt` with no arguments to watch files
**************************************************************/
grunt.registerTask('default', ['watch']);
grunt.registerTask('minall', ['uglify', 'cssmin']);
};
| {
"content_hash": "b67568c5953347881206c87e0ce98b77",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 108,
"avg_line_length": 33.98550724637681,
"alnum_prop": 0.567590618336887,
"repo_name": "MAKE-SITY/MKSTream",
"id": "8a09b2dae1b131164e9670ba1ce9b707ed1912d4",
"size": "2345",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Gruntfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8070"
},
{
"name": "HTML",
"bytes": "12426"
},
{
"name": "JavaScript",
"bytes": "48103"
}
],
"symlink_target": ""
} |
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Nationality extends ORM
{
protected $_db = 'default';
protected $_table_name = 'Nationality';
protected $_primary_key = 'id';
protected $_table_columns = array(
'id' => array('data_type' => 'int', 'is_nullable' => false),
'grajdanstvo' => array('data_type' => 'string', 'is_nullable' => false),
);
public function rules()
{
return array(
'grajdanstvo' => array(
array('not_empty'),
//array('alpha', array(':value', true)), - иначе нельзя вводить пробел и тире
array('min_length', array(':value', 2)),
array('max_length', array(':value', 50)),
),
);
}
public function labels()
{
return array(
'grajdanstvo' => 'Гражданство',
);
}
public function filters()
{
return array(
true => array(
array('trim'),
array('Security::xss_clean', array(':value')),
)
);
}
} | {
"content_hash": "d06f5ebc13b16a75b4b028ea8c582a07",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 93,
"avg_line_length": 25.46511627906977,
"alnum_prop": 0.4958904109589041,
"repo_name": "Roquie/autoschool",
"id": "115629fe259837f7c6524338662e2f5e6d9a6091",
"size": "1135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "www/application/classes/Model/Nationality.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "377184"
},
{
"name": "CSS",
"bytes": "203212"
},
{
"name": "JavaScript",
"bytes": "1154515"
},
{
"name": "PHP",
"bytes": "1544657"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "15e443687c131903e2bc4d406732f95b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "7cab88c3fbfb22fca8f435b762eaff9cade19fdd",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Hordeum/Hordeum vulgare/ Syn. Hordeum vulgare revelatum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace IPC {
class Listener;
//------------------------------------------------------------------------------
// See
// http://www.chromium.org/developers/design-documents/inter-process-communication
// for overview of IPC in Chromium.
// Channels are implemented using named pipes on Windows, and
// socket pairs (or in some special cases unix domain sockets) on POSIX.
// On Windows we access pipes in various processes by name.
// On POSIX we pass file descriptors to child processes and assign names to them
// in a lookup table.
// In general on POSIX we do not use unix domain sockets due to security
// concerns and the fact that they can leave garbage around the file system
// (MacOS does not support abstract named unix domain sockets).
// You can use unix domain sockets if you like on POSIX by constructing the
// the channel with the mode set to one of the NAMED modes. NAMED modes are
// currently used by automation and service processes.
class IPC_EXPORT Channel : public Sender {
// Security tests need access to the pipe handle.
friend class ChannelTest;
public:
// Flags to test modes
enum ModeFlags {
MODE_NO_FLAG = 0x0,
MODE_SERVER_FLAG = 0x1,
MODE_CLIENT_FLAG = 0x2,
MODE_NAMED_FLAG = 0x4,
#if defined(OS_POSIX)
MODE_OPEN_ACCESS_FLAG = 0x8, // Don't restrict access based on client UID.
#endif
};
// Some Standard Modes
enum Mode {
MODE_NONE = MODE_NO_FLAG,
MODE_SERVER = MODE_SERVER_FLAG,
MODE_CLIENT = MODE_CLIENT_FLAG,
// Channels on Windows are named by default and accessible from other
// processes. On POSIX channels are anonymous by default and not accessible
// from other processes. Named channels work via named unix domain sockets.
// On Windows MODE_NAMED_SERVER is equivalent to MODE_SERVER and
// MODE_NAMED_CLIENT is equivalent to MODE_CLIENT.
MODE_NAMED_SERVER = MODE_SERVER_FLAG | MODE_NAMED_FLAG,
MODE_NAMED_CLIENT = MODE_CLIENT_FLAG | MODE_NAMED_FLAG,
#if defined(OS_POSIX)
// An "open" named server accepts connections from ANY client.
// The caller must then implement their own access-control based on the
// client process' user Id.
MODE_OPEN_NAMED_SERVER = MODE_OPEN_ACCESS_FLAG | MODE_SERVER_FLAG |
MODE_NAMED_FLAG
#endif
};
// The Hello message is internal to the Channel class. It is sent
// by the peer when the channel is connected. The message contains
// just the process id (pid). The message has a special routing_id
// (MSG_ROUTING_NONE) and type (HELLO_MESSAGE_TYPE).
enum {
HELLO_MESSAGE_TYPE = kuint16max // Maximum value of message type (uint16),
// to avoid conflicting with normal
// message types, which are enumeration
// constants starting from 0.
};
// The maximum message size in bytes. Attempting to receive a message of this
// size or bigger results in a channel error.
static const size_t kMaximumMessageSize = 128 * 1024 * 1024;
// Amount of data to read at once from the pipe.
static const size_t kReadBufferSize = 4 * 1024;
// Initialize a Channel.
//
// |channel_handle| identifies the communication Channel. For POSIX, if
// the file descriptor in the channel handle is != -1, the channel takes
// ownership of the file descriptor and will close it appropriately, otherwise
// it will create a new descriptor internally.
// |mode| specifies whether this Channel is to operate in server mode or
// client mode. In server mode, the Channel is responsible for setting up the
// IPC object, whereas in client mode, the Channel merely connects to the
// already established IPC object.
// |listener| receives a callback on the current thread for each newly
// received message.
//
Channel(const IPC::ChannelHandle &channel_handle, Mode mode,
Listener* listener);
virtual ~Channel();
// Connect the pipe. On the server side, this will initiate
// waiting for connections. On the client, it attempts to
// connect to a pre-existing pipe. Note, calling Connect()
// will not block the calling thread and may complete
// asynchronously.
bool Connect() WARN_UNUSED_RESULT;
// Close this Channel explicitly. May be called multiple times.
// On POSIX calling close on an IPC channel that listens for connections will
// cause it to close any accepted connections, and it will stop listening for
// new connections. If you just want to close the currently accepted
// connection and listen for new ones, use ResetToAcceptingConnectionState.
void Close();
// Get the process ID for the connected peer.
//
// Returns base::kNullProcessId if the peer is not connected yet. Watch out
// for race conditions. You can easily get a channel to another process, but
// if your process has not yet processed the "hello" message from the remote
// side, this will fail. You should either make sure calling this is either
// in response to a message from the remote side (which guarantees that it's
// been connected), or you wait for the "connected" notification on the
// listener.
base::ProcessId peer_pid() const;
// Send a message over the Channel to the listener on the other end.
//
// |message| must be allocated using operator new. This object will be
// deleted once the contents of the Message have been sent.
virtual bool Send(Message* message) OVERRIDE;
#if defined(OS_POSIX)
// On POSIX an IPC::Channel wraps a socketpair(), this method returns the
// FD # for the client end of the socket.
// This method may only be called on the server side of a channel.
// This method can be called on any thread.
int GetClientFileDescriptor() const;
// Same as GetClientFileDescriptor, but transfers the ownership of the
// file descriptor to the caller.
// This method can be called on any thread.
int TakeClientFileDescriptor();
// On POSIX an IPC::Channel can either wrap an established socket, or it
// can wrap a socket that is listening for connections. Currently an
// IPC::Channel that listens for connections can only accept one connection
// at a time.
// Returns true if the channel supports listening for connections.
bool AcceptsConnections() const;
// Returns true if the channel supports listening for connections and is
// currently connected.
bool HasAcceptedConnection() const;
// Returns true if the peer process' effective user id can be determined, in
// which case the supplied client_euid is updated with it.
bool GetClientEuid(uid_t* client_euid) const;
// Closes any currently connected socket, and returns to a listening state
// for more connections.
void ResetToAcceptingConnectionState();
#endif // defined(OS_POSIX) && !defined(OS_NACL)
// Returns true if a named server channel is initialized on the given channel
// ID. Even if true, the server may have already accepted a connection.
static bool IsNamedServerInitialized(const std::string& channel_id);
#if !defined(OS_NACL)
// Generates a channel ID that's non-predictable and unique.
static std::string GenerateUniqueRandomChannelID();
// Generates a channel ID that, if passed to the client as a shared secret,
// will validate that the client's authenticity. On platforms that do not
// require additional this is simply calls GenerateUniqueRandomChannelID().
// For portability the prefix should not include the \ character.
static std::string GenerateVerifiedChannelID(const std::string& prefix);
#endif
#if defined(OS_LINUX)
// Sandboxed processes live in a PID namespace, so when sending the IPC hello
// message from client to server we need to send the PID from the global
// PID namespace.
static void SetGlobalPid(int pid);
#endif
protected:
// Used in Chrome by the TestSink to provide a dummy channel implementation
// for testing. TestSink overrides the "interesting" functions in Channel so
// no actual implementation is needed. This will cause un-overridden calls to
// segfault. Do not use outside of test code!
Channel() : channel_impl_(0) { }
private:
// PIMPL to which all channel calls are delegated.
class ChannelImpl;
ChannelImpl *channel_impl_;
};
} // namespace IPC
#endif // IPC_IPC_CHANNEL_H_
| {
"content_hash": "5e3819881aad9b09bfb65ae7f6dd8984",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 82,
"avg_line_length": 42.61734693877551,
"alnum_prop": 0.7116006225308272,
"repo_name": "zcbenz/cefode-chromium",
"id": "29caec3419b177909349990da1cc8b61cd0f4934",
"size": "8806",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ipc/ipc_channel.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1174304"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "76026099"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "157904700"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "3225038"
},
{
"name": "JavaScript",
"bytes": "18180217"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "7139426"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "932901"
},
{
"name": "Python",
"bytes": "8654916"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3621"
},
{
"name": "Shell",
"bytes": "1533012"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
} |
from typing import Any, Dict, List, Optional
import numpy as np
from paralleldomain.decoding.common import DecoderSettings
from paralleldomain.decoding.directory.sensor_frame_decoder import DirectoryCameraSensorFrameDecoder
from paralleldomain.decoding.frame_decoder import FrameDecoder, TDateTime
from paralleldomain.decoding.sensor_frame_decoder import (
CameraSensorFrameDecoder,
LidarSensorFrameDecoder,
RadarSensorFrameDecoder,
)
from paralleldomain.model.class_mapping import ClassDetail
from paralleldomain.model.ego import EgoPose
from paralleldomain.model.sensor import CameraSensorFrame, LidarSensorFrame, RadarSensorFrame
from paralleldomain.model.type_aliases import FrameId, SceneName, SensorName
from paralleldomain.utilities.any_path import AnyPath
from paralleldomain.utilities.fsio import read_json
class DirectoryFrameDecoder(FrameDecoder[None]):
def __init__(
self,
dataset_name: str,
scene_name: SceneName,
dataset_path: AnyPath,
settings: DecoderSettings,
image_folder: str,
semantic_segmentation_folder: str,
metadata_folder: Optional[str],
camera_name: str,
class_map: List[ClassDetail],
):
super().__init__(dataset_name=dataset_name, scene_name=scene_name, settings=settings)
self.dataset_path = dataset_path
self.image_folder = image_folder
self.semantic_segmentation_folder = semantic_segmentation_folder
self.camera_name = camera_name
self._metadata_folder = metadata_folder
self._class_map = class_map
def _decode_ego_pose(self, frame_id: FrameId) -> EgoPose:
raise ValueError("Loading from directory does not support ego pose!")
def _decode_available_sensor_names(self, frame_id: FrameId) -> List[SensorName]:
return [self.camera_name]
def _decode_available_camera_names(self, frame_id: FrameId) -> List[SensorName]:
return [self.camera_name]
def _decode_available_lidar_names(self, frame_id: FrameId) -> List[SensorName]:
raise ValueError("Loading from directory does not support lidar data!")
def _decode_datetime(self, frame_id: FrameId) -> None:
return None
def _create_camera_sensor_frame_decoder(self) -> CameraSensorFrameDecoder[None]:
return DirectoryCameraSensorFrameDecoder(
dataset_name=self.dataset_name,
scene_name=self.scene_name,
dataset_path=self.dataset_path,
settings=self.settings,
image_folder=self.image_folder,
semantic_segmentation_folder=self.semantic_segmentation_folder,
metadata_folder=self._metadata_folder,
class_map=self._class_map,
)
def _decode_camera_sensor_frame(
self, decoder: CameraSensorFrameDecoder[None], frame_id: FrameId, sensor_name: SensorName
) -> CameraSensorFrame[None]:
return CameraSensorFrame[None](sensor_name=sensor_name, frame_id=frame_id, decoder=decoder)
def _create_lidar_sensor_frame_decoder(self) -> LidarSensorFrameDecoder[None]:
raise ValueError("Loading from directory does not support lidar data!")
def _decode_lidar_sensor_frame(
self, decoder: LidarSensorFrameDecoder[None], frame_id: FrameId, sensor_name: SensorName
) -> LidarSensorFrame[None]:
raise ValueError("Loading from directoy does not support lidar data!")
def _decode_available_radar_names(self, frame_id: FrameId) -> List[SensorName]:
raise ValueError("Loading from directory does not support radar data!")
def _create_radar_sensor_frame_decoder(self) -> RadarSensorFrameDecoder[TDateTime]:
raise ValueError("Loading from directory does not support radar data!")
def _decode_radar_sensor_frame(
self, decoder: RadarSensorFrameDecoder[TDateTime], frame_id: FrameId, sensor_name: SensorName
) -> RadarSensorFrame[TDateTime]:
raise ValueError("Loading from directory does not support radar data!")
def _decode_metadata(self, frame_id: FrameId) -> Dict[str, Any]:
if self._metadata_folder is None:
return dict()
metadata_path = self.dataset_path / self._metadata_folder / f"{AnyPath(frame_id).stem + '.json'}"
return read_json(metadata_path)
| {
"content_hash": "775dca633ab8a8940a5a3a450d3f199f",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 105,
"avg_line_length": 44.23711340206186,
"alnum_prop": 0.7093917501747844,
"repo_name": "parallel-domain/pd-sdk",
"id": "2b95c8c26e0083eed4b7c62887532f56e8416658",
"size": "4291",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "paralleldomain/decoding/directory/frame_decoder.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "1030434"
},
{
"name": "Shell",
"bytes": "1375"
}
],
"symlink_target": ""
} |
```
# From top directory of supplement
julia scripts/process_awsoutput.jl awsoutput/misocp3q/ results/misocp3q.csv
julia scripts/process_awsoutput.jl awsoutput/bonmin awsoutput/misocp3q awsoutput/misocpApr6 results/solvercomparison.csv
```
# Processing CSV output
```
# From top directory of supplement
julia scripts/process_csv.jl check results/misocp3q.csv
# if there are runs to exclude, list them in an "exclude" file
julia scripts/process_csv.jl statuscounts results/misocp3q.csv postprocessing/misocp3q_statuscounts.csv --exclude=postprocessing/misocp3q_exclude
julia scripts/process_csv.jl geomeans results/misocp3q.csv --exclude=postprocessing/misocp3q_exclude > postprocessing/misocp3q_geomeans
julia scripts/process_csv.jl check results/solvercomparison.csv
julia scripts/process_csv.jl statuscounts results/solvercomparison.csv postprocessing/solvercomparison_statuscounts.csv --exclude=postprocessing/solvercomparison_exclude --bestof="BONMIN BONMIN_BB BONMIN_OA BONMIN_OADIS" --bestof="PAJ_CPLEX_MOSEK_msd_bestof2 PAJ_CPLEX_MOSEK_msd PAJ_CPLEX_MOSEK_msdnostarts"
julia scripts/process_csv.jl geomeans results/solvercomparison.csv --exclude=postprocessing/solvercomparison_exclude > postprocessing/solvercomparison_geomeans
julia scripts/process_csv.jl geomeans results/solvercomparison.csv --exclude=postprocessing/solvercomparison_exclude --bestof="BONMIN BONMIN_BB BONMIN_OA BONMIN_OADIS" --bestof="PAJ_CPLEX_MOSEK_msd_bestof2 PAJ_CPLEX_MOSEK_msd PAJ_CPLEX_MOSEK_msdnostarts"
```
# Generating performance profiles
```
# output goes into jld file
julia scripts/process_csv.jl perfprofile results/misocp3q.csv postprocessing/subpscaling_perf.jld PAJ_CPLEX_MOSEK_dualonly PAJ_CPLEX_MOSEK_dualonlynoscale --exclude=postprocessing/misocp3q_exclude
julia postprocessing/subpscaling_perf.jl
julia scripts/process_csv.jl perfprofile results/misocp3q.csv postprocessing/subpsep_perf.jld PAJ_CPLEX_MOSEK_dualonly PAJ_CPLEX_MOSEK_primonlynorelax PAJ_CPLEX_MOSEK_msddualonly PAJ_CPLEX_MOSEK_msdprimonlynorelax --exclude=postprocessing/misocp3q_exclude
julia postprocessing/subpsep_perf.jl
julia scripts/process_csv.jl perfprofile results/solvercomparison.csv postprocessing/solvercomparison_perf.jld CPLEX_MISOCP PAJ_CPLEX_MOSEK_msd PAJ_CPLEX_MOSEK SCIP_MISOCP BONMIN PAJ_CBC_ECOS PAJ_GLPK_ECOS --exclude=postprocessing/solvercomparison_exclude --bestof="BONMIN BONMIN_BB BONMIN_OA BONMIN_OADIS" --bestof="PAJ_CPLEX_MOSEK_msd_bestof2 PAJ_CPLEX_MOSEK_msd PAJ_CPLEX_MOSEK_msdnostarts"
julia postprocessing/solvercomparison_perf.jl
```
| {
"content_hash": "ed9595cebeee922bd31232b7f562c7d5",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 394,
"avg_line_length": 60.80952380952381,
"alnum_prop": 0.831636648394675,
"repo_name": "mlubin/PajaritoSupplement",
"id": "807ccf9d4899ca860b26d98e0b98a2b50ed7fbf4",
"size": "2580",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Julia",
"bytes": "36522"
},
{
"name": "Python",
"bytes": "22581"
}
],
"symlink_target": ""
} |
"""
debug.py
"""
import re
import time
import sys
import types
import gc
import os
from cStringIO import StringIO
normalize_re = re.compile(r'\d+')
class ObjCallLogger(object):
"""Log every call"""
def __init__(self, obj):
self.obj = obj
self.log = []
def __getattr__(self, name):
attr = getattr(self.obj, name)
def _(*a, **kw):
call = format_call(name, *a, **kw)
ncall = normalize_re.sub('-', call)
t1 = time.time()
r = attr(*a, **kw)
cost = time.time() - t1
self.log.append((call, ncall, cost))
return r
return _
def format_call(funcname, *a, **kw):
arglist = [(repr(x)) for x in a]
arglist += ["%s=%r" % (k, v) for k, v in kw.iteritems()]
return "%s(%s)" % (funcname, ", ".join(arglist))
class CallLogger(object):
def __init__(self, funcpath):
self.orig_func = obj_from_string(funcpath)
if isinstance(self.orig_func, types.MethodType):
raise NotImplementedError("Do not support methods yet.")
self.funcpath = funcpath
self.log = []
self.__global_replace__ = False
global_replace(self.orig_func, self)
def __call__(self, *a, **kw):
call = format_call(self.funcpath, *a, **kw)
t1 = time.time()
try:
return self.orig_func(*a, **kw)
finally:
cost = time.time() - t1
self.log.append((call, cost))
def close(self):
global_replace(self, self.orig_func)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
self.close()
def obj_from_string(s):
# stolen from Mocker http://labix.org/mocker
import_stack = s.split(".")
attr_stack = []
while import_stack:
module_path = ".".join(import_stack)
try:
object = __import__(module_path, {}, {}, [""])
except ImportError:
attr_stack.insert(0, import_stack.pop())
if not import_stack:
raise
continue
else:
for attr in attr_stack:
object = getattr(object, attr)
break
return object
def global_replace(remove, install):
"""Replace object 'remove' with object 'install' on all dictionaries."""
# stolen from Mocker http://labix.org/mocker
for referrer in gc.get_referrers(remove):
if (type(referrer) is dict and
referrer.get("__global_replace__", True)):
for key, value in referrer.items():
if value is remove:
referrer[key] = install
def capture_output(func, *args, **kw):
# Not threadsafe!
out = StringIO()
old_stdout = sys.stdout
sys.stdout = out
try:
func(*args, **kw)
finally:
sys.stdout = old_stdout
return out.getvalue()
def is_process_alive(pid):
try:
os.kill(pid, 0)
except OSError, e:
if e.errno == 3: # process is dead
return False
elif e.errno == 1: # no permission
return True
else:
raise
else:
return True
| {
"content_hash": "d9f0fefef1e8cf67660fa06780a01bd5",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 76,
"avg_line_length": 26,
"alnum_prop": 0.532520325203252,
"repo_name": "douban/douban-utils",
"id": "2912d5aa3631053aeb7ab4677557224702cae8e2",
"size": "3238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "douban/utils/debug.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "62678"
}
],
"symlink_target": ""
} |
"""
this is the code to accompany the Lesson 3 (decision tree) mini-project
use an DT to identify emails from the Enron corpus by their authors
Sara has label 0
Chris has label 1
"""
import sys
import os
from time import time
#sys.path.append("../tools/")
os.chdir("C:/Vindico/Projects/Code/Python/Python/Course/Udacity/Intro to Machine Learning/ud120-projects-master/tools/")
from email_preprocess import preprocess
from sklearn import tree
from sklearn.metrics import accuracy_score
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
### your code goes here ###
#########################################################
clf = tree.DecisionTreeClassifier(min_samples_split=40)
t0 = time()
clf.fit(features_train, labels_train)
print "training time:", round(time()-t0, 3), "s"
t0 = time()
pred = clf.predict(features_test)
print "predicting time:", round(time()-t0, 3), "s"
acc = accuracy_score(pred, labels_test)
print acc
# What's the number of features in your data?
len(features_train[0]) | {
"content_hash": "61b6fecc330eea5a150858560a71aea3",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 120,
"avg_line_length": 28.622222222222224,
"alnum_prop": 0.6669254658385093,
"repo_name": "tuanvu216/udacity-course",
"id": "3faa9521c6de3f27aa27b699e3dafa11c5435b17",
"size": "1307",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "intro_to_machine_learning/lesson/lesson_3_decision_trees/dt_author_id.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3736"
},
{
"name": "HTML",
"bytes": "143388"
},
{
"name": "JavaScript",
"bytes": "169689"
},
{
"name": "Jupyter Notebook",
"bytes": "3237655"
},
{
"name": "Python",
"bytes": "400129"
},
{
"name": "Ruby",
"bytes": "448"
},
{
"name": "Shell",
"bytes": "538"
}
],
"symlink_target": ""
} |
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["children", "weight", "level", "Component"];
import { createScopedElement } from "../../../lib/jsxRuntime";
import { usePlatform } from "../../../hooks/usePlatform";
import { classNames } from "../../../lib/classNames";
import { getClassName } from "../../../helpers/getClassName";
import { ANDROID } from "../../../lib/platform";
import Headline from "../Headline/Headline";
var Title = function Title(_ref) {
var children = _ref.children,
_ref$weight = _ref.weight,
weight = _ref$weight === void 0 ? 'regular' : _ref$weight,
_ref$level = _ref.level,
level = _ref$level === void 0 ? '1' : _ref$level,
Component = _ref.Component,
restProps = _objectWithoutProperties(_ref, _excluded);
var platform = usePlatform();
if (!Component) {
Component = 'h' + level;
}
if (platform === ANDROID && level === '3') {
var headlineWeight = weight === 'regular' ? weight : 'medium';
return createScopedElement(Headline, _extends({
Component: Component
}, restProps, {
weight: headlineWeight
}), children);
}
return createScopedElement(Component, _extends({}, restProps, {
vkuiClass: classNames(getClassName('Title', platform), "Title--w-".concat(weight), "Title--l-".concat(level))
}), children);
};
export default Title;
//# sourceMappingURL=Title.js.map | {
"content_hash": "0cb48198201dd1228cb03601fc263de1",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 113,
"avg_line_length": 36.41463414634146,
"alnum_prop": 0.6483590087073008,
"repo_name": "cdnjs/cdnjs",
"id": "9a4e562fc1c70dc3ddb9e92ad3a70a07bc40efd9",
"size": "1493",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "ajax/libs/vkui/4.22.0/components/Typography/Title/Title.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'TeamResult.start_time'
db.add_column('scorebrd_teamresult', 'start_time',
self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2013, 1, 26, 0, 0)),
keep_default=False)
# Adding field 'TeamResult.end_time'
db.add_column('scorebrd_teamresult', 'end_time',
self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2013, 1, 26, 0, 0)),
keep_default=False)
def backwards(self, orm):
# Deleting field 'TeamResult.start_time'
db.delete_column('scorebrd_teamresult', 'start_time')
# Deleting field 'TeamResult.end_time'
db.delete_column('scorebrd_teamresult', 'end_time')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'scorebrd.competition': {
'Meta': {'object_name': 'Competition'},
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['scorebrd.Group']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'scorebrd.event': {
'Meta': {'object_name': 'Event'},
'competitions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['scorebrd.Competition']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'scorebrd.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'matches': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['scorebrd.Match']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'teams': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['scorebrd.Team']", 'symmetrical': 'False'})
},
'scorebrd.match': {
'Meta': {'object_name': 'Match'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'playing': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}),
'referee': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'scoreA': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'scoreB': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'teamA': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'homelanders'", 'to': "orm['scorebrd.Team']"}),
'teamB': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'foreigners'", 'to': "orm['scorebrd.Team']"})
},
'scorebrd.team': {
'Meta': {'object_name': 'Team'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'})
},
'scorebrd.teamresult': {
'Meta': {'object_name': 'TeamResult'},
'draws': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'end_time': ('django.db.models.fields.DateTimeField', [], {}),
'goal_diff': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'goal_shot': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scorebrd.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'loses': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'matches_played': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'points': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'start_time': ('django.db.models.fields.DateTimeField', [], {}),
'team': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['scorebrd.Team']"}),
'wins': ('django.db.models.fields.IntegerField', [], {'default': '0'})
}
}
complete_apps = ['scorebrd'] | {
"content_hash": "8d9a9f9f7375347bcdfcf2637d0d4fc1",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 182,
"avg_line_length": 65.51282051282051,
"alnum_prop": 0.549119373776908,
"repo_name": "xlcteam/scoreBoard",
"id": "baab0908a88db40d6443cecade497ac3e6e19375",
"size": "7689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scorebrd/migrations/0006_auto__add_field_teamresult_start_time__add_field_teamresult_end_time.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "32311"
},
{
"name": "Python",
"bytes": "99306"
}
],
"symlink_target": ""
} |
layout: leaf-node
title: "CPsquare"
title-url: "https://cpsquare.org/"
author: [ "" ]
groups: [ "pedagogical-styles" ]
categories: [ "communities-of-practice" ]
topics: [ "ongoing-projects" ]
summary: >
The idea of CPsquare is mutual motivating to learning new things, achieving determined goals in specific time frame and developing skills in certain areas. The idea came into being in the USA and is somewhat similar to discussion brainstorming, which aims at getting to know the opinions of the community members and drawing important conclusions for the future joint study. Each member shares his or her goals that they want to achieve in the nearest future as well as limitations and others control their progress and try to help by motivating and indicating appropriate ways. Moreover, the members of the community allow to divide tasks from the most important to the ones that can be quit. They help to notice, which activities do not bring the expected results and convince not to lose energy for them.
cite: >
pub-date: 2017-01-01
added_date: 2017-04-29
resource-type: external-page
--- | {
"content_hash": "c53cc110d7060e2eacb3f41dcb0cdbcb",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 809,
"avg_line_length": 73.33333333333333,
"alnum_prop": 0.7836363636363637,
"repo_name": "lvollherbst/edtech-test",
"id": "5bf137faf079efa867b01e88584bf88049bf95e4",
"size": "1104",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "_leaf_nodes/2017-01-01-cpsquare.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "75203"
},
{
"name": "HTML",
"bytes": "94436"
},
{
"name": "JavaScript",
"bytes": "60717"
},
{
"name": "Ruby",
"bytes": "4992"
}
],
"symlink_target": ""
} |
package io.github.thankpoint.security.api.crypt;
/**
* Extends {@link AbstractSecurityGetCryptorFactory} with ability to {@link #setCryptorFactory(SecurityCryptorFactory)
* set} the {@link SecurityCryptorFactory}.
*
* @param <C> the type of the {@link SecurityCryptorFactory}.
* @author thks
*/
public abstract interface AbstractSecuritySetCryptorFactory<C extends SecurityCryptorFactory>
extends AbstractSecurityGetCryptorFactory<C> {
/**
* @param factory the {@link SecurityCryptorFactory} to set.
*/
void setCryptorFactory(C factory);
}
| {
"content_hash": "666253619b4f4e7bca25433051c060e1",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 118,
"avg_line_length": 31.27777777777778,
"alnum_prop": 0.7619893428063943,
"repo_name": "thankpoint/thanks4java",
"id": "6fc5768ceb9e7d15ac281ec81afd921372854ba0",
"size": "563",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "security/src/main/java/io/github/thankpoint/security/api/crypt/AbstractSecuritySetCryptorFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "605121"
}
],
"symlink_target": ""
} |
package edu.purdue.safewalk.bitmaps;
import java.lang.Math;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.support.v4.util.LruCache;
import android.util.Log;
import android.widget.ImageView;
/**
* This class was created to help fix the crashes caused by bitmaps being loaded
* and overflowing the memory. It contains helper methods for dealing with
* bitmaps.
*
* @author David Tschida (dtschida)
* @date Sep 8, 2013 7:29:10 PM
*
*/
public final class BitmapHelper
{
private static String TAG = "BitmapHelper";
private static LruCache<String, Bitmap> mMemoryCache;
/**
* This method is used to create a sample size for a bitmap given the
* required size and the Options class for the bitmap.
*
* Run this method after first running
*
* <pre>
* <code>
* final BitmapFactory.Options foo = new BitmapFactory.Options();
* foo.inJustDecodeBounds = true;
* BitmapFactory.decodeResource(Resources, int, foo);
* </code>
* </pre>
*
* Then set the output to <code>foo.inSampleSize</code> and then decode the
* image.
*
* (If using the same BitmapFactory, remember to change
* <code>inJustDecodeBounds</code> back to false.)
*
* This method was taken from the Developer tutorial on the android website
* (licensed under Creative Commons) The original source can be found here:
* {@link http
* ://developer.android.com/training/displaying-bitmaps/load-bitmap.html}
*
* @param options
* A bitmap options class created with
* @param reqWidth
* The preferred width of the image.
* @param reqHeight
* The preferred height of the image.
* @return The sample size (to be used set to options.inSampleSize)
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
float reqWidth, float reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round(height
/ reqHeight);
final int widthRatio = Math.round(width / reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
Log.v(TAG, "inSampleSize = " + inSampleSize);
return inSampleSize;
}
/**
* Allows decoding of a bitmap with a specified height and width.
*
* Modified from the Android developer tutorial. Original source can be
* found at {@link http
* ://developer.android.com/training/displaying-bitmaps/load-bitmap.html}
*
* @param filename
* The filename of the file to be decoded.
* @param reqWidth
* The preferred width of the output bitmap.
* @param reqHeight
* The preferred height of the output bitmap.
* @return the decoded bitmap, or null
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
float reqWidth, float reqHeight)
{
Log.v(TAG, "Recieved " + filename + " with (w,h): (" + reqWidth + ", "
+ reqHeight + ").");
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap decodedBitmap = BitmapFactory.decodeFile(filename, options);
Log.v(TAG, "The Bitmap is " + decodedBitmap.toString());
return decodedBitmap;
}
public static void loadBitmapAsAsyncTask(String filepath,
ImageView imageView, float width, float height)
{
final Bitmap bitmap = getBitmapFromMemCache(filepath);
if(bitmap != null)
{
imageView.setImageBitmap(bitmap);
}
else if (cancelPotentialWork(filepath, imageView))
{
BitmapWorkerTask task = new BitmapWorkerTask(imageView, height,
width);
AsyncDrawable downloadedDrawable = new AsyncDrawable(task);
imageView.setImageDrawable(downloadedDrawable);
task.execute(filepath/* , cookie */);
}
}
private static boolean cancelPotentialWork(String filepath,
ImageView imageView)
{
BitmapWorkerTask bitmapLoaderTask = getBitmapWorkerTask(imageView);
if (bitmapLoaderTask != null)
{
String bitmapPath = bitmapLoaderTask.filename;
if ((bitmapPath == null) || (!bitmapPath.equals(filepath)))
{
bitmapLoaderTask.cancel(true);
} else
{
// The same URL is already being downloaded.
return false;
}
}
return true;
}
public static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView)
{
if (imageView != null)
{
Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable)
{
AsyncDrawable downloadedDrawable = (AsyncDrawable) drawable;
return downloadedDrawable.getBitmapWorkerTask();
}
}
return null;
}
public void initMemoryCache()
{
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 15;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return (bitmap.getRowBytes() * bitmap.getHeight()) / 1024;
}
};
}
public static void clearCache()
{
mMemoryCache.evictAll();
}
public static void addBitmapToMemoryCache(String key, Bitmap bitmap) {
assert(mMemoryCache != null);
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
public static Bitmap getBitmapFromMemCache(String key) {
assert(mMemoryCache != null);
return mMemoryCache.get(key);
}
}
| {
"content_hash": "46c5607fa7b13df0e172bd766d5c0c94",
"timestamp": "",
"source": "github",
"line_count": 210,
"max_line_length": 80,
"avg_line_length": 29.757142857142856,
"alnum_prop": 0.6989918386941911,
"repo_name": "Purdue-ACM-SIGAPP/SafeWalk",
"id": "be490b38dc1de8b17e23d48c190b26459f1b978f",
"size": "6249",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/SafeWalk/app/src/main/java/edu/purdue/safewalk/bitmaps/BitmapHelper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "2040"
},
{
"name": "CSS",
"bytes": "181888"
},
{
"name": "Java",
"bytes": "330704"
},
{
"name": "JavaScript",
"bytes": "572738"
},
{
"name": "Objective-C",
"bytes": "202977"
},
{
"name": "Python",
"bytes": "1243"
},
{
"name": "Shell",
"bytes": "338"
},
{
"name": "Swift",
"bytes": "3574"
}
],
"symlink_target": ""
} |
. $(dirname ${BASH_SOURCE})/../util.sh
desc "Create a service that fronts any version of this demo"
run "cat $(relative svc.yaml)"
run "kubectl --namespace=demos apply -f $(relative svc.yaml)"
desc "Deploy v1 of our app"
run "cat $(relative deployment.yaml)"
run "kubectl --namespace=demos apply -f $(relative deployment.yaml)"
# The output of describe is too wide, uncomment the following if needed.
# desc "Check it"
# run "kubectl --namespace=demos describe deployment deployment-demo"
tmux new -d -s my-session \
"sleep 10; $(dirname $BASH_SOURCE)/split1_control.sh" \; \
split-window -v -p 66 "$(dirname ${BASH_SOURCE})/split1_hit_svc.sh" \; \
split-window -v "$(dirname ${BASH_SOURCE})/split1_watch.sh v1" \; \
split-window -h -d "$(dirname ${BASH_SOURCE})/split1_watch.sh v2" \; \
select-pane -t 0 \; \
attach \;
| {
"content_hash": "1e9dad621edd76dd7699564d9a14119b",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 76,
"avg_line_length": 40.38095238095238,
"alnum_prop": 0.6733490566037735,
"repo_name": "jdavis7257/contrib",
"id": "af2055781102c81ec5403d75726016a1465feb0a",
"size": "1468",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "micro-demos/deployments/demo.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2918"
},
{
"name": "Go",
"bytes": "1106606"
},
{
"name": "HTML",
"bytes": "32616"
},
{
"name": "JavaScript",
"bytes": "28648"
},
{
"name": "Lua",
"bytes": "3089"
},
{
"name": "Makefile",
"bytes": "19187"
},
{
"name": "Nginx",
"bytes": "2890"
},
{
"name": "Python",
"bytes": "14245"
},
{
"name": "Ruby",
"bytes": "7689"
},
{
"name": "Shell",
"bytes": "86502"
}
],
"symlink_target": ""
} |
FactoryGirl.define do
factory :admin_user, class: Portfolio::AdminUser do
pass = Faker::Internet.password
email Faker::Internet.email
password pass
before(:validation) do |user|
user.password_confirmation = pass
end
end
end
| {
"content_hash": "faebd588100b31bc843ede8a6431b1f8",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 23.181818181818183,
"alnum_prop": 0.7019607843137254,
"repo_name": "messuti-edd/rails-portfolio",
"id": "7d5cb63f1f4a6a021eb2d3e237edb6624dbd722e",
"size": "255",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/factories/admin_user_factory.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4332"
},
{
"name": "HTML",
"bytes": "35868"
},
{
"name": "JavaScript",
"bytes": "2231"
},
{
"name": "Ruby",
"bytes": "92859"
},
{
"name": "Shell",
"bytes": "283"
}
],
"symlink_target": ""
} |
package net.cloudkit.enterprises.javassist;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
/**
* http://www.blogjava.net/bukebushuo/articles/229703.html
* http://jd.benow.ca/
*/
public class Test {
// 入口启动函数
public static void main(String[] args) throws Exception {
// 这个是得到反编译的池
ClassPool pool = ClassPool.getDefault();
// 新建一个class
// CtClass cc = pool.makeClass("Point");
// 设置目标类的解包后的路径,确保能够找到需要修改的类
// 取得需要反编译的jar文件,设定路径
pool.insertClassPath("F:/Downloads/jrebel.jar");
// 获得要需要反编译修改的类文件,完整包路径
// CtClass ctClass = pool.get("com.zeroturnaround.javarebel.dP");
CtClass ctClass = pool.get("com.zeroturnaround.javarebel.eG");
// 设置方法需要的参数
CtClass[] param = new CtClass[2];
// param[0] = pool.get("com.zeroturnaround.javarebel.Yz");
// param[1] = pool.get("com.zeroturnaround.licensing.UserLicense");
param[0] = pool.get("com.zeroturnaround.jrebel.bundled.org.bouncycastle.crypto.params.RSAKeyParameters");
param[1] = pool.get("com.zeroturnaround.licensing.UserLicense");
/*
// 取得需要修改的方法
CtMethod method = ctClass.getDeclaredMethod("validate");
// 插入修改项,我们让他直接返回(注意:根据方法的具体返回值返回,因为这个方法返回值是void,所以直接return;)
method.insertBefore("{if(true) return false;}");
*/
/*
for(CtMethod ctMethod1 : ctClass.getMethods()) {
System.out.println(ctMethod1.getName() + ctMethod1.getParameterTypes());
for (CtClass ctClass1 : ctMethod1.getParameterTypes()) {
System.out.println(ctClass1.getName());
}
}
*/
// 取得需要修改的方法
// CtMethod ctMethod = ctClass.getDeclaredMethod("a", param);
CtMethod ctMethod = ctClass.getDeclaredMethod("a", param);
// 插入代码块
// ctMethod.insertBefore("{if(true) return true;}");
// 设置新的代码
ctMethod.setBody("return true;");
/*
CtMethod fMethod = ctClass.getDeclaredMethod("f");
CtMethod gMethod = CtNewMethod.copy(fMethod, "g", ctClass, null);
ctClass.addMethod(gMethod);
*/
// ctClass.toClass();
// update the class file
// 写入保存
ctClass.writeFile("F:/Downloads/");
// ctClass.writeFile();
}
}
| {
"content_hash": "ea3ee3b2bad9a342fe5cde2d36aed15a",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 113,
"avg_line_length": 30.662337662337663,
"alnum_prop": 0.6094875052943668,
"repo_name": "icloudkit/net.cloudkit",
"id": "e97f9590fe7d54a9d634c0e62d84dd0c49521436",
"size": "3317",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "net.cloudkit.enterprises/src/test/java/net/cloudkit/enterprises/javassist/Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "44897"
},
{
"name": "FreeMarker",
"bytes": "46"
},
{
"name": "Groovy",
"bytes": "3199"
},
{
"name": "HTML",
"bytes": "209837"
},
{
"name": "Java",
"bytes": "1754930"
},
{
"name": "JavaScript",
"bytes": "40957"
},
{
"name": "Smarty",
"bytes": "65656"
}
],
"symlink_target": ""
} |
FROM ubuntu:18.04
ENV LANG=C.UTF-8 LC_ALL=C.UTF-8
ENV PATH /opt/conda/bin:$PATH
ARG TAG
RUN apt-get update && \
apt-get install -y autoconf gcc gfortran g++ make wget gsl-bin git libgsl-dev && apt-get clean all
RUN apt-get install -y curl grep sed dpkg
RUN TINI_VERSION=`curl https://github.com/krallin/tini/releases/latest | grep -o "/v.*\"" | sed 's:^..\(.*\).$:\1:'` && \
curl -L "https://github.com/krallin/tini/releases/download/v${TINI_VERSION}/tini_${TINI_VERSION}.deb" > tini.deb
RUN dpkg -i tini.deb
RUN rm tini.deb
RUN apt-get clean
RUN /usr/sbin/groupadd -g 1000 user && \
/usr/sbin/useradd -u 1000 -g 1000 -d /opt/redmapper redmapper && \
mkdir /opt/redmapper && chown redmapper.user /opt/redmapper && \
chown redmapper.user /opt
USER redmapper
RUN wget --quiet https://github.com/conda-forge/miniforge/releases/download/4.9.2-5/Miniforge3-Linux-x86_64.sh -O ~/miniforge.sh && \
/bin/bash ~/miniforge.sh -b -p /opt/conda && \
rm ~/miniforge.sh
RUN . /opt/conda/etc/profile.d/conda.sh && conda create --yes --name redmapper-env
RUN echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/.bashrc && \
echo "conda activate redmapper-env" >> ~/.bashrc
RUN echo ". /opt/conda/etc/profile.d/conda.sh" >> ~/startup.sh && \
echo "conda activate redmapper-env" >> ~/startup.sh
RUN . /opt/conda/etc/profile.d/conda.sh && conda activate redmapper-env && \
conda install --yes python=3.8 numpy scipy astropy matplotlib pyyaml fitsio esutil healpy healsparse && \
conda clean -af --yes
LABEL redmapper-tag="${TAG}"
RUN . /opt/conda/etc/profile.d/conda.sh && conda activate redmapper-env && cd ~/ && \
git clone https://github.com/erykoff/redmapper --branch=${TAG} && cd ~/redmapper && \
cd ~/redmapper && python setup.py install
ENTRYPOINT [ "/usr/bin/tini", "--" ]
CMD [ "/bin/bash", "-lc" ]
| {
"content_hash": "79e52f77743948a6daa8cacd806f85e4",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 133,
"avg_line_length": 43.53488372093023,
"alnum_prop": 0.6591880341880342,
"repo_name": "erykoff/redmapper",
"id": "349e41e9bd3fd32e53ceb4a67b8cfe0b062795f5",
"size": "1872",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "35922"
},
{
"name": "Dockerfile",
"bytes": "1872"
},
{
"name": "Python",
"bytes": "971787"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="actionbar">#FF333333</color>
<color name="divider">#FF222222</color>
<color name="drawer">#FF333333</color>
</resources> | {
"content_hash": "d1b02fb63f2afa6efafe5d8d84cacba8",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 45,
"avg_line_length": 32.666666666666664,
"alnum_prop": 0.6632653061224489,
"repo_name": "changjiashuai/md-slide-android",
"id": "f039dbd12d618cbd7842eef03a643778fc45eb18",
"size": "196",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/src/main/res/values/colors.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "50108"
},
{
"name": "Shell",
"bytes": "370"
}
],
"symlink_target": ""
} |
REM The MIT License (MIT)
REM Copyright (c) 2014 brunoais
REM Permission is hereby granted, free of charge, to any person obtaining a copy
REM of this software and associated documentation files (the "Software"), to deal
REM in the Software without restriction, including without limitation the rights
REM to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
REM copies of the Software, and to permit persons to whom the Software is
REM furnished to do so, subject to the following conditions:
REM
REM The above copyright notice and this permission notice shall be included in all
REM copies or substantial portions of the Software.
REM
REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
REM IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
REM FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
REM AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
REM LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
REM OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
REM SOFTWARE.
@echo off
setlocal enableextensions enabledelayedexpansion
REM Parameters management (all optional)
REM Set defaults
SET PcheckDir=.
REM Searching for files with single hard link (1) or multiple hard link (2, by default)
SET PcheckKind=1
IF %1 EQU 1 (
SET PcheckDir=.
SET PcheckKind=1
) ELSE (
IF "%1"=="" (
SET PcheckDir=.
)
IF "%2"=="" (
SET PcheckKind=2
)
)
REM Rights elevation
REM Adapted from http://superuser.com/a/757106/176343
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' NEQ '0' (
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs"
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~f0", "%PcheckDir% %PcheckKind%", "%CD%", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs"
pushd "%CD%"
CD /D "%~dp0"
REM adapted from http://stackoverflow.com/questions/17687358/batch-file-command-line-to-get-target-path-of-internet-shortcut-url-in-the
pushd %1
pushd %2
@echo off
REM For each file in directory
for %%F in (%PcheckDir%\*) do (
call :checkHardLink "%%~dpnxF" %PcheckKind%
)
popd
popd
pause
goto end
:checkHardLink inputfile
REM Get the hardlink list.
REM This works because fsutil lists a single hardlink per line in the output
set "cmd=fsutil hardlink list %1 | find /V /C """
for /f %%l in ('!cmd!') do set copies=%%l
IF %PcheckKind% EQU 1 (
REM Searching for files with single hard link
IF %copies% EQU 1 (
Echo %copies%: %1%
)
) ELSE (
REM Searching for files with multiple hard link
IF %copies% NEQ 1 (
Echo %copies%: %1%
)
)
:end
| {
"content_hash": "a8dd20a095a0f48da0f3be5ecbd21afc",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 135,
"avg_line_length": 28.281553398058254,
"alnum_prop": 0.7305183659457604,
"repo_name": "brunoais/cmd-dir-hardlinks",
"id": "cc7e02943055416e04e4984c999c64d4967be496",
"size": "2913",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "listHardLinks.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "2913"
}
],
"symlink_target": ""
} |
package com.joanzapata.android;
import android.content.Context;
import java.util.List;
/**
* Same as QuickAdapter, but adds an "itemChanged" boolean in the
* convert() method params, which allows you to know if you are
* adapting the new view to the same item or not, and therefore
* make a difference between dataset changed / dataset invalidated.
* <p/>
* Abstraction class of a BaseAdapter in which you only need
* to provide the convert() implementation.<br/>
* Using the provided BaseAdapterHelper, your code is minimalist.
* @param <T> The type of the items in the list.
*/
public abstract class EnhancedQuickAdapter<T> extends QuickAdapter<T> {
/**
* Create a QuickAdapter.
* @param context The context.
* @param layoutResId The layout resource id of each item.
*/
public EnhancedQuickAdapter(Context context, int layoutResId) {
super(context, layoutResId);
}
/**
* Same as QuickAdapter#QuickAdapter(Context,int) but with
* some initialization data.
* @param context The context.
* @param layoutResId The layout resource id of each item.
* @param data A new list is created out of this one to avoid mutable list
*/
public EnhancedQuickAdapter(Context context, int layoutResId, List<T> data) {
super(context, layoutResId, data);
}
@Override
protected final void convert(BaseAdapterHelper helper, T item) {
boolean itemChanged = helper.associatedObject == null || !helper.associatedObject.equals(item);
helper.associatedObject = item;
convert(helper, item, itemChanged);
}
/**
* @param helper The helper to use to adapt the view.
* @param item The item you should adapt the view to.
* @param itemChanged Whether or not the helper was bound to another object before.
*/
protected abstract void convert(BaseAdapterHelper helper, T item, boolean itemChanged);
}
| {
"content_hash": "dcc30612ac6564b3d8c45c18b9c58330",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 103,
"avg_line_length": 37.0188679245283,
"alnum_prop": 0.6901121304791029,
"repo_name": "skyacer/android-open-project-demo",
"id": "59984828cee82377ef73215cb3eb0ffe92bd4ac3",
"size": "1962",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "quick-adapter-demo/app/src/main/java/com/joanzapata/android/EnhancedQuickAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2630648"
},
{
"name": "R",
"bytes": "305"
}
],
"symlink_target": ""
} |
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const http = require('http');
const https = require('https');
const host = '*'.repeat(64);
const MAX_TRIES = 5;
const errCodes = ['ENOTFOUND', 'EAI_FAIL'];
function tryGet(mod, tries) {
// Bad host name should not throw an uncatchable exception.
// Ensure that there is time to attach an error listener.
const req = mod.get({ host: host, port: 42 }, common.mustNotCall());
req.on('error', common.mustCall(function(err) {
if (err.code === 'EAGAIN' && tries < MAX_TRIES) {
tryGet(mod, ++tries);
return;
}
assert(errCodes.includes(err.code), err);
}));
// http.get() called req1.end() for us
}
function tryRequest(mod, tries) {
const req = mod.request({
method: 'GET',
host: host,
port: 42
}, common.mustNotCall());
req.on('error', common.mustCall(function(err) {
if (err.code === 'EAGAIN' && tries < MAX_TRIES) {
tryRequest(mod, ++tries);
return;
}
assert(errCodes.includes(err.code), err);
}));
req.end();
}
function test(mod) {
tryGet(mod, 0);
tryRequest(mod, 0);
}
if (common.hasCrypto) {
test(https);
} else {
common.printSkipMessage('missing crypto');
}
test(http);
| {
"content_hash": "00ecc844311fec1d65dc1db4077e6f18",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 70,
"avg_line_length": 22.964912280701753,
"alnum_prop": 0.6249045072574484,
"repo_name": "enclose-io/compiler",
"id": "20e12f24fbf4f7ef5f8a913a721459cafce7414b",
"size": "2443",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "lts/test/parallel/test-http-dns-error.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "11474"
},
{
"name": "Shell",
"bytes": "131"
}
],
"symlink_target": ""
} |
(function (window, $, undefined) {
'use strict';
var PluginFinderModel = function PluginFinderrModel() {
var self = this;
self.cachedAvailablePlugins = [];
self.availablePlugins = ko.observableArray();
self.query = ko.observable('');
self.isLoading = ko.observable(false);
self.isInstalling = ko.observable(false);
self.install = ko.observable('');
self.uninstall = ko.observable('');
self.requestedPluginDetail = ko.observable('');
self.query.subscribe(function(value) {
// remove all the current beers, which removes them from the view
self.availablePlugins.removeAll();
for(var x in self.cachedAvailablePlugins) {
if(self.cachedAvailablePlugins[x].name().toLowerCase().indexOf(value.toLowerCase()) >= 0) {
self.availablePlugins.push(self.cachedAvailablePlugins[x]);
}
}
}
);
self.installPlugin = function (plugin) {
self.install(plugin);
};
self.uninstallPlugin = function (plugin) {
self.uninstall(plugin);
};
self.launchPluginDetail = function (plugin) {
self.requestedPluginDetail(plugin);
};
};
//
// Custom Binding
//
ko.bindingHandlers.loadingWhen = {
init: function (element) {
var
$element = $(element),
currentPosition = $element.css("position"),
$loader = $("<div>").addClass("loader").hide();
//add the loader
$element.append($loader);
//make sure that we can absolutely position the loader against the original element
if (currentPosition == "auto" || currentPosition == "static")
$element.css("position", "relative");
//center the loader
$loader.css({
position: "absolute",
top: "50%",
left: "50%",
"margin-left": -($loader.width() / 2) + "px",
"margin-top": -($loader.height() / 2) + "px"
});
},
update: function (element, valueAccessor) {
var isLoading = ko.utils.unwrapObservable(valueAccessor()),
$element = $(element),
$childrenToHide = $element.children(":not(div.loader)"),
$loader = $element.find("div.loader");
if (isLoading) {
$childrenToHide.css("visibility", "hidden").attr("disabled", "disabled");
$loader.show();
}
else {
$loader.fadeOut("fast");
$childrenToHide.css("visibility", "visible").removeAttr("disabled").show();
}
}
};
var Plugin = function Plugin(rawPlugin, configManager) {
var self = this;
self.rawPlugin = rawPlugin;
self.config = {};
self.isEnabled = ko.observable(true);
self.name = ko.computed(function () {
return self.rawPlugin.name.replace('openrov-plugin-','');
});
self.url = ko.computed(function () {
return self.rawPlugin.url;
});
self.homepage = ko.observable('');
self.description = ko.observable('');
self.raiting = ko.observable('');
self.installed = ko.computed(function () {
return self.rawPlugin.InstalledOnROV === true ? true : false;
});
//Get data from server
/*configManager.get(self.name(), function (pluginConfig) {
if (pluginConfig != undefined && pluginConfig.isEnabled != undefined) {
self.config = pluginConfig;
self.isEnabled(pluginConfig.isEnabled.toBool());
}
});*/
//Update data to server when changed
self.isEnabled.subscribe(function (newIsEnabled) {
if (newIsEnabled == true) {
self.rawPlugin.enable();
} else {
self.rawPlugin.disable();
}
self.config.isEnabled = newIsEnabled.toString();
configManager.set(self.name(), self.config);
});
var giturl = self.rawPlugin.url.replace('.git','').replace('git://github.com/','https://api.github.com/repos/')
$.getJSON( giturl, function( data ) {
self.description(data.description);
self.raiting(data.stargazers_count);
self.homepage(data.homepage != null ? data.homepage : data.html_url);
});
};
var PluginFinder = function PluginFinder(cockpit) {
console.log('Loading Plugin Finder plugin.');
this.cockpit = cockpit;
this.model = new PluginFinderModel();
var self = this;
var configManager = new PluginFinderConfig();
$('#plugin-settings').append('<div id="plugin-finder-settings"></div>');
//this technique forces relative path to the js file instead of the excution directory
var jsFileLocation = urlOfJsFile('plugin-finder.js');
$('#plugin-finder-settings').load(jsFileLocation + '../settings.html', function () {
//Get plugins from somewhere and bind them somewhere
ko.applyBindings(self.model, document.getElementById('pluginFinder-settings'));
$('#collapsePluginFinder').on('show', function (e) {
if (self.model.cachedAvailablePlugins.length==0){
self.model.isLoading(true);
self.cockpit.socket.emit('plugin-finder.search','');
}
});
});
this.model.install.subscribe(function(plugin){
self.model.isInstalling(true);
self.cockpit.socket.emit('plugin-finder.install',plugin.rawPlugin.name);
});
this.model.uninstall.subscribe(function(plugin){
self.model.isInstalling(true);
self.cockpit.socket.emit('plugin-finder.uninstall',plugin.rawPlugin.name);
});
this.model.requestedPluginDetail.subscribe(function(plugin){
window.open("http://bower.io/search/?q="+plugin.name(),"bowerInfo");
});
self.cockpit.socket.on('pluginfindersearchresults', function(results){
console.log('evaluating plugin for pluginmanager');
results.forEach(function (plugin) {
var plg = new Plugin(plugin, configManager);
self.model.availablePlugins.push(plg);
self.model.cachedAvailablePlugins.push(plg);
});
self.model.isLoading(false);
});
self.cockpit.socket.on('pluginfinderinstallresults', function(result){
console.log(result);
self.model.isInstalling(false);
});
self.cockpit.socket.on('pluginfinderuninstallresults', function(result){
console.log(result);
self.model.isInstalling(false);
});
self.cockpit.socket.on('pluginfinderinstallstatus', function(status){
console.log(status);
});
self.cockpit.socket.on('pluginfinderrestartRequired', function(){
alert('Plugin Installed, you will need to refresh the browser to load the plugin. ');
});
};
window.Cockpit.plugins.push(PluginFinder);
}(window, jQuery));
| {
"content_hash": "3886231872f55d1060537dcfbabbd5dd",
"timestamp": "",
"source": "github",
"line_count": 197,
"max_line_length": 115,
"avg_line_length": 33.91370558375635,
"alnum_prop": 0.6189193234545727,
"repo_name": "binary42/openrov-software",
"id": "bc834169eb346cd0ef90c2f4d564f0e25c27f292",
"size": "6681",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/system-plugins/plugin-finder/public/js/plugin-finder.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/subliminal.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/subliminal.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/subliminal"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/subliminal"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
| {
"content_hash": "02fdb2fe1741f011baced429467d9fc7",
"timestamp": "",
"source": "github",
"line_count": 173,
"max_line_length": 343,
"avg_line_length": 38.64739884393064,
"alnum_prop": 0.7072988333831888,
"repo_name": "nvbn/subliminal",
"id": "94286f1670ca9db91219e64309ded24d58fc8b93",
"size": "6778",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "docs/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "141379"
}
],
"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_301) on Thu Feb 10 11:17:18 GMT 2022 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Package com.github.rvesse.airline.help.sections.common (Airline - Library 2.8.4 API)</title>
<meta name="date" content="2022-02-10">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package com.github.rvesse.airline.help.sections.common (Airline - Library 2.8.4 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/github/rvesse/airline/help/sections/common/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package com.github.rvesse.airline.help.sections.common" class="title">Uses of Package<br>com.github.rvesse.airline.help.sections.common</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/github/rvesse/airline/help/sections/common/package-summary.html">com.github.rvesse.airline.help.sections.common</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.github.rvesse.airline.help.sections.common">com.github.rvesse.airline.help.sections.common</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.github.rvesse.airline.help.sections.common">
<!-- -->
</a>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../../com/github/rvesse/airline/help/sections/common/package-summary.html">com.github.rvesse.airline.help.sections.common</a> used by <a href="../../../../../../../com/github/rvesse/airline/help/sections/common/package-summary.html">com.github.rvesse.airline.help.sections.common</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../../com/github/rvesse/airline/help/sections/common/class-use/BasicHint.html#com.github.rvesse.airline.help.sections.common">BasicHint</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../../com/github/rvesse/airline/help/sections/common/class-use/BasicSection.html#com.github.rvesse.airline.help.sections.common">BasicSection</a> </td>
</tr>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../../com/github/rvesse/airline/help/sections/common/class-use/ProseSection.html#com.github.rvesse.airline.help.sections.common">ProseSection</a> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/github/rvesse/airline/help/sections/common/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2012–2022. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "c5b7b3344c3ab896a04c6c8630afadc3",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 384,
"avg_line_length": 39.90909090909091,
"alnum_prop": 0.6312832194381169,
"repo_name": "rvesse/airline",
"id": "9b4173a6e91ca5876df8dfd2ea4b037545073ca3",
"size": "6585",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "docs/javadoc/2.8.4/airline/com/github/rvesse/airline/help/sections/common/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "91"
},
{
"name": "Java",
"bytes": "2176058"
},
{
"name": "Shell",
"bytes": "4550"
}
],
"symlink_target": ""
} |
<?php
namespace DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstance;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRatio;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface;
/**
* A homogeneous material with a definite composition.
*
* Class FHIRSubstanceIngredient
* @package \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstance
*/
class FHIRSubstanceIngredient extends FHIRBackboneElement
{
// name of FHIR type this class describes
const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_SUBSTANCE_DOT_INGREDIENT;
const FIELD_QUANTITY = 'quantity';
const FIELD_SUBSTANCE_CODEABLE_CONCEPT = 'substanceCodeableConcept';
const FIELD_SUBSTANCE_REFERENCE = 'substanceReference';
/** @var string */
private $_xmlns = 'http://hl7.org/fhir';
/**
* A relationship of two Quantity values - expressed as a numerator and a
* denominator.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* The amount of the ingredient in the substance - a concentration ratio.
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRatio
*/
protected $quantity = null;
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
*/
protected $substanceCodeableConcept = null;
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
*/
protected $substanceReference = null;
/**
* Validation map for fields in type Substance.Ingredient
* @var array
*/
private static $_validationRules = [ ];
/**
* FHIRSubstanceIngredient Constructor
* @param null|array $data
*/
public function __construct($data = null)
{
if (null === $data || [] === $data) {
return;
}
if (!is_array($data)) {
throw new \InvalidArgumentException(sprintf(
'FHIRSubstanceIngredient::_construct - $data expected to be null or array, %s seen',
gettype($data)
));
}
parent::__construct($data);
if (isset($data[self::FIELD_QUANTITY])) {
if ($data[self::FIELD_QUANTITY] instanceof FHIRRatio) {
$this->setQuantity($data[self::FIELD_QUANTITY]);
} else {
$this->setQuantity(new FHIRRatio($data[self::FIELD_QUANTITY]));
}
}
if (isset($data[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT])) {
if ($data[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT] instanceof FHIRCodeableConcept) {
$this->setSubstanceCodeableConcept($data[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT]);
} else {
$this->setSubstanceCodeableConcept(new FHIRCodeableConcept($data[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT]));
}
}
if (isset($data[self::FIELD_SUBSTANCE_REFERENCE])) {
if ($data[self::FIELD_SUBSTANCE_REFERENCE] instanceof FHIRReference) {
$this->setSubstanceReference($data[self::FIELD_SUBSTANCE_REFERENCE]);
} else {
$this->setSubstanceReference(new FHIRReference($data[self::FIELD_SUBSTANCE_REFERENCE]));
}
}
}
/**
* @return string
*/
public function _getFHIRTypeName()
{
return self::FHIR_TYPE_NAME;
}
/**
* @return string
*/
public function _getFHIRXMLElementDefinition()
{
$xmlns = $this->_getFHIRXMLNamespace();
if (null !== $xmlns) {
$xmlns = " xmlns=\"{$xmlns}\"";
}
return "<SubstanceIngredient{$xmlns}></SubstanceIngredient>";
}
/**
* A relationship of two Quantity values - expressed as a numerator and a
* denominator.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* The amount of the ingredient in the substance - a concentration ratio.
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRatio
*/
public function getQuantity()
{
return $this->quantity;
}
/**
* A relationship of two Quantity values - expressed as a numerator and a
* denominator.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* The amount of the ingredient in the substance - a concentration ratio.
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRRatio $quantity
* @return static
*/
public function setQuantity(FHIRRatio $quantity = null)
{
$this->quantity = $quantity;
return $this;
}
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
*/
public function getSubstanceCodeableConcept()
{
return $this->substanceCodeableConcept;
}
/**
* A concept that may be defined by a formal reference to a terminology or ontology
* or may be provided by text.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $substanceCodeableConcept
* @return static
*/
public function setSubstanceCodeableConcept(FHIRCodeableConcept $substanceCodeableConcept = null)
{
$this->substanceCodeableConcept = $substanceCodeableConcept;
return $this;
}
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference
*/
public function getSubstanceReference()
{
return $this->substanceReference;
}
/**
* A reference from one resource to another.
* If the element is present, it must have a value for at least one of the defined
* elements, an \@id referenced from the Narrative, or extensions
*
* Another substance that is a component of this substance. (choose any one of
* substance*, but only one)
*
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRReference $substanceReference
* @return static
*/
public function setSubstanceReference(FHIRReference $substanceReference = null)
{
$this->substanceReference = $substanceReference;
return $this;
}
/**
* Returns the validation rules that this type's fields must comply with to be considered "valid"
* The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
*
* @return array
*/
public function _getValidationRules()
{
return self::$_validationRules;
}
/**
* Validates that this type conforms to the specifications set forth for it by FHIR. An empty array must be seen as
* passing.
*
* @return array
*/
public function _getValidationErrors()
{
$errs = parent::_getValidationErrors();
$validationRules = $this->_getValidationRules();
if (null !== ($v = $this->getQuantity())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_QUANTITY] = $fieldErrs;
}
}
if (null !== ($v = $this->getSubstanceCodeableConcept())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT] = $fieldErrs;
}
}
if (null !== ($v = $this->getSubstanceReference())) {
if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
$errs[self::FIELD_SUBSTANCE_REFERENCE] = $fieldErrs;
}
}
if (isset($validationRules[self::FIELD_QUANTITY])) {
$v = $this->getQuantity();
foreach($validationRules[self::FIELD_QUANTITY] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_DOT_INGREDIENT, self::FIELD_QUANTITY, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_QUANTITY])) {
$errs[self::FIELD_QUANTITY] = [];
}
$errs[self::FIELD_QUANTITY][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT])) {
$v = $this->getSubstanceCodeableConcept();
foreach($validationRules[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_DOT_INGREDIENT, self::FIELD_SUBSTANCE_CODEABLE_CONCEPT, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT])) {
$errs[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT] = [];
}
$errs[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_SUBSTANCE_REFERENCE])) {
$v = $this->getSubstanceReference();
foreach($validationRules[self::FIELD_SUBSTANCE_REFERENCE] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUBSTANCE_DOT_INGREDIENT, self::FIELD_SUBSTANCE_REFERENCE, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_SUBSTANCE_REFERENCE])) {
$errs[self::FIELD_SUBSTANCE_REFERENCE] = [];
}
$errs[self::FIELD_SUBSTANCE_REFERENCE][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
$v = $this->getModifierExtension();
foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
$errs[self::FIELD_MODIFIER_EXTENSION] = [];
}
$errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_EXTENSION])) {
$v = $this->getExtension();
foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_EXTENSION])) {
$errs[self::FIELD_EXTENSION] = [];
}
$errs[self::FIELD_EXTENSION][$rule] = $err;
}
}
}
if (isset($validationRules[self::FIELD_ID])) {
$v = $this->getId();
foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
$err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
if (null !== $err) {
if (!isset($errs[self::FIELD_ID])) {
$errs[self::FIELD_ID] = [];
}
$errs[self::FIELD_ID][$rule] = $err;
}
}
}
return $errs;
}
/**
* @param \SimpleXMLElement|string|null $sxe
* @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstance\FHIRSubstanceIngredient $type
* @param null|int $libxmlOpts
* @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstance\FHIRSubstanceIngredient
*/
public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
return null;
}
if (is_string($sxe)) {
libxml_use_internal_errors(true);
$sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
if ($sxe === false) {
throw new \DomainException(sprintf('FHIRSubstanceIngredient::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
}
libxml_use_internal_errors(false);
}
if (!($sxe instanceof \SimpleXMLElement)) {
throw new \InvalidArgumentException(sprintf('FHIRSubstanceIngredient::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
}
if (null === $type) {
$type = new FHIRSubstanceIngredient;
} elseif (!is_object($type) || !($type instanceof FHIRSubstanceIngredient)) {
throw new \RuntimeException(sprintf(
'FHIRSubstanceIngredient::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIRSubstance\FHIRSubstanceIngredient or null, %s seen.',
is_object($type) ? get_class($type) : gettype($type)
));
}
FHIRBackboneElement::xmlUnserialize($sxe, $type);
$xmlNamespaces = $sxe->getDocNamespaces(false, false);
if ([] !== $xmlNamespaces) {
$ns = reset($xmlNamespaces);
if (false !== $ns && '' !== $ns) {
$type->_xmlns = $ns;
}
}
$attributes = $sxe->attributes();
$children = $sxe->children();
if (isset($children->quantity)) {
$type->setQuantity(FHIRRatio::xmlUnserialize($children->quantity));
}
if (isset($children->substanceCodeableConcept)) {
$type->setSubstanceCodeableConcept(FHIRCodeableConcept::xmlUnserialize($children->substanceCodeableConcept));
}
if (isset($children->substanceReference)) {
$type->setSubstanceReference(FHIRReference::xmlUnserialize($children->substanceReference));
}
return $type;
}
/**
* @param null|\SimpleXMLElement $sxe
* @param null|int $libxmlOpts
* @return \SimpleXMLElement
*/
public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
{
if (null === $sxe) {
$sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
}
parent::xmlSerialize($sxe);
if (null !== ($v = $this->getQuantity())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_QUANTITY, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getSubstanceCodeableConcept())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_SUBSTANCE_CODEABLE_CONCEPT, null, $v->_getFHIRXMLNamespace()));
}
if (null !== ($v = $this->getSubstanceReference())) {
$v->xmlSerialize($sxe->addChild(self::FIELD_SUBSTANCE_REFERENCE, null, $v->_getFHIRXMLNamespace()));
}
return $sxe;
}
/**
* @return array
*/
public function jsonSerialize()
{
$a = parent::jsonSerialize();
if (null !== ($v = $this->getQuantity())) {
$a[self::FIELD_QUANTITY] = $v;
}
if (null !== ($v = $this->getSubstanceCodeableConcept())) {
$a[self::FIELD_SUBSTANCE_CODEABLE_CONCEPT] = $v;
}
if (null !== ($v = $this->getSubstanceReference())) {
$a[self::FIELD_SUBSTANCE_REFERENCE] = $v;
}
if ([] !== ($vs = $this->_getFHIRComments())) {
$a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
}
return $a;
}
/**
* @return string
*/
public function __toString()
{
return self::FHIR_TYPE_NAME;
}
} | {
"content_hash": "8ced60e51b1db7e62c9747835bbfddac",
"timestamp": "",
"source": "github",
"line_count": 446,
"max_line_length": 243,
"avg_line_length": 40.62331838565022,
"alnum_prop": 0.5949332155867093,
"repo_name": "dcarbone/php-fhir-generated",
"id": "843bba41f8b9e576f0e8bf915c2b1478d447a0ca",
"size": "21007",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DCarbone/PHPFHIRGenerated/R4/FHIRElement/FHIRBackboneElement/FHIRSubstance/FHIRSubstanceIngredient.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "113066525"
}
],
"symlink_target": ""
} |
@implementation URAlertview
- (id)initWithFrame:(CGRect)frame
title:(NSString*)title
buttonColor:(UIColor*)color
onTap:(OKButtonClick)block
{
self = [super initWithFrame:frame];
if (self)
{
self.onTap = block;
CGSize screenSize = [UIScreen mainScreen].bounds.size;
UIView *blurView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenSize.width, screenSize.height)];
blurView.backgroundColor = [UIColor colorWithWhite:0 alpha:.6];
blurView.alpha = 0;
UIView *menuView = [[UIView alloc] init];
menuView.x = 0;
menuView.y = 0;
menuView.width = (screenSize.width * 0.5) * 0.75;
menuView.height = 100;
menuView.layer.cornerRadius = 10;
menuView.layer.masksToBounds = YES;
menuView.backgroundColor=[UIColor whiteColor];
[blurView addSubview:menuView];
UILabel *notificationLabel = [[UILabel alloc] initWithFrame:CGRectZero];
notificationLabel.x = 20;
notificationLabel.y = 30;
notificationLabel.width = menuView.width - 40;
notificationLabel.backgroundColor = [UIColor clearColor];
notificationLabel.textColor = [UIColor blackColor];
notificationLabel.font = [UIFont systemFontOfSize:17];
notificationLabel.numberOfLines = 0;
notificationLabel.lineBreakMode = NSLineBreakByWordWrapping;
notificationLabel.text = title;
[notificationLabel sizeToFit];
notificationLabel.centerX = menuView.width * 0.5;
[menuView addSubview:notificationLabel];
UIButton *okButton = [UIButton new];
okButton.x = 0;
okButton.y = notificationLabel.bottom + 30;
okButton.width = menuView.width;
okButton.height = 70;
[okButton setTitle:@"OK" forState:UIControlStateNormal];
[okButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
okButton.backgroundColor = color;
[okButton addTarget:self action:@selector(okButtonPress:) forControlEvents:UIControlEventTouchUpInside];
[menuView addSubview:okButton];
menuView.height = okButton.bottom;
menuView.centerX = screenSize.width * 0.5;
menuView.centerY = screenSize.height * 0.5 - 50;
AppDelegate *appdelegate = [UIApplication sharedApplication].delegate;
[[appdelegate window] addSubview:blurView];
[UIView animateWithDuration:0.2 animations:^{
blurView.alpha = 1;
}];
}
return self;
}
- (void)okButtonPress:(id)sender
{
if (self.onTap) {
self.onTap(self);
}
}
@end
| {
"content_hash": "47eeb7c796ba3de0188f1265f80876fe",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 112,
"avg_line_length": 35.80263157894737,
"alnum_prop": 0.6361631753031973,
"repo_name": "macL0vin/URAlertview",
"id": "a5272c420194068feb841cc238017b62fd9f746c",
"size": "2882",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "URAlertview.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "3322"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:color="@color/primary_text_disabled_material_light"/>
<item android:color="@color/primary_text_default_material_light"/>
</selector>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/mnc-sdk-release/frameworks/support/v7/appcompat/res/color/abc_primary_text_material_light.xml --><!-- From: file:/Users/northfoxz/Documents/TIL/reactnative/whatsthis/node_modules/react-native-camera/android/build/intermediates/exploded-aar/com.android.support/appcompat-v7/23.0.1/res/color/abc_primary_text_material_light.xml --> | {
"content_hash": "33386be0fb102df0f5ab48c07de7cc15",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 453,
"avg_line_length": 65.85714285714286,
"alnum_prop": 0.749819233550253,
"repo_name": "NorthFoxz/react-native-camera-android",
"id": "b319ffca136f6d1d60d3713eb87c46fe622d0968",
"size": "1383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/build/intermediates/res/debug/color/abc_primary_text_material_light.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1454007"
},
{
"name": "JavaScript",
"bytes": "2373"
}
],
"symlink_target": ""
} |
class Profile;
namespace content {
class DownloadItem;
class DownloadManager;
}
namespace drive {
class DriveEntryProto;
class DriveFileSystemInterface;
class FileWriteHelper;
// Observes downloads to temporary local drive folder. Schedules these
// downloads for upload to drive service.
class DriveDownloadHandler : public AllDownloadItemNotifier::Observer {
public:
DriveDownloadHandler(FileWriteHelper* file_write_helper,
DriveFileSystemInterface* file_system);
virtual ~DriveDownloadHandler();
// Utility method to get DriveDownloadHandler with profile.
static DriveDownloadHandler* GetForProfile(Profile* profile);
// Become an observer of DownloadManager.
void Initialize(content::DownloadManager* download_manager,
const base::FilePath& drive_tmp_download_path);
// Callback used to return results from SubstituteDriveDownloadPath.
// TODO(hashimoto): Report error with a DriveFileError. crbug.com/171345
typedef base::Callback<void(const base::FilePath&)>
SubstituteDriveDownloadPathCallback;
void SubstituteDriveDownloadPath(
const base::FilePath& drive_path,
content::DownloadItem* download,
const SubstituteDriveDownloadPathCallback& callback);
// Sets drive path, for example, '/special/drive/MyFolder/MyFile',
// to external data in |download|. Also sets display name and
// makes |download| a temporary.
void SetDownloadParams(const base::FilePath& drive_path,
content::DownloadItem* download);
// Gets the target drive path from external data in |download|.
base::FilePath GetTargetPath(const content::DownloadItem* download);
// Checks if there is a Drive upload associated with |download|
bool IsDriveDownload(const content::DownloadItem* download);
// Checks a file corresponding to the download item exists in Drive.
void CheckForFileExistence(
const content::DownloadItem* download,
const content::CheckForFileExistenceCallback& callback);
private:
// AllDownloadItemNotifier::Observer overrides:
virtual void OnDownloadCreated(content::DownloadManager* manager,
content::DownloadItem* download) OVERRIDE;
virtual void OnDownloadUpdated(content::DownloadManager* manager,
content::DownloadItem* download) OVERRIDE;
// Removes the download.
void RemoveDownload(int id);
// Callback for DriveFileSystem::GetEntryInfoByPath().
// Used to implement SubstituteDriveDownloadPath().
void OnEntryFound(const base::FilePath& drive_dir_path,
const SubstituteDriveDownloadPathCallback& callback,
DriveFileError error,
scoped_ptr<DriveEntryProto> entry_proto);
// Callback for DriveFileSystem::CreateDirectory().
// Used to implement SubstituteDriveDownloadPath().
void OnCreateDirectory(const SubstituteDriveDownloadPathCallback& callback,
DriveFileError error);
// Starts the upload of a downloaded/downloading file.
void UploadDownloadItem(content::DownloadItem* download);
FileWriteHelper* file_write_helper_;
// The file system owned by DriveSystemService.
DriveFileSystemInterface* file_system_;
// Observe the DownloadManager for new downloads.
scoped_ptr<AllDownloadItemNotifier> notifier_;
// Temporary download location directory.
base::FilePath drive_tmp_download_path_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DriveDownloadHandler> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(DriveDownloadHandler);
};
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_DRIVE_DOWNLOAD_HANDLER_H_
| {
"content_hash": "a39e1c0281e3909f8004cf0807613bda",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 77,
"avg_line_length": 38.39393939393939,
"alnum_prop": 0.73770060510392,
"repo_name": "timopulkkinen/BubbleFish",
"id": "c80d8e0aaee8e8c2493207fcf2a5d84b15d47b00",
"size": "4356",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "chrome/browser/chromeos/drive/drive_download_handler.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1174304"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75801820"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "161884021"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "3531849"
},
{
"name": "JavaScript",
"bytes": "18556005"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "7254742"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "933011"
},
{
"name": "Python",
"bytes": "8808682"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3621"
},
{
"name": "Shell",
"bytes": "1537764"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Forms;
namespace ColoredAppBars
{
public class App : Application
{
public App()
{
// The root page of your application
MainPage = new NavigationPage(new Page1());
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| {
"content_hash": "9bca150d07f5e0adf6bef2a1cbb43aaf",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 55,
"avg_line_length": 19.757575757575758,
"alnum_prop": 0.5521472392638037,
"repo_name": "messier16/xamarin-plugins",
"id": "882e81c8f133b18faf77fe58992bb0d5a029bc63",
"size": "654",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "M16.ColorAppBars/Test/ColoredAppBars/ColoredAppBars/App.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "271931"
}
],
"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_25) on Sat Jun 11 21:57:14 CEST 2016 -->
<title>Overview</title>
<meta name="date" content="2016-06-11">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Overview";
}
}
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 class="navBarCell1Rev">Overview</li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-summary.html" target="_top">Frames</a></li>
<li><a href="overview-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">ITalentDocumentation</h1>
</div>
<div class="contentContainer">
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Packages table, listing packages, and an explanation">
<caption><span>Packages</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="be/italent/package-summary.html">be.italent</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="be/italent/model/package-summary.html">be.italent.model</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="be/italent/model/buider/package-summary.html">be.italent.model.buider</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="be/italent/repository/package-summary.html">be.italent.repository</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="be/italent/security/package-summary.html">be.italent.security</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="be/italent/service/package-summary.html">be.italent.service</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="be/italent/web/controller/package-summary.html">be.italent.web.controller</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="be/italent/web/resource/package-summary.html">be.italent.web.resource</a></td>
<td class="colLast"> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="be/italent/web/resource/assembler/package-summary.html">be.italent.web.resource.assembler</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</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 class="navBarCell1Rev">Overview</li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-files/index-1.html">Index</a></li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?overview-summary.html" target="_top">Frames</a></li>
<li><a href="overview-summary.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": "4244d66a0224ed411be38233fb323cf7",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 137,
"avg_line_length": 31.429411764705883,
"alnum_prop": 0.6505708403518623,
"repo_name": "niekvandael/iTalent",
"id": "2a5def8601c4323a9019575f0356faa0366b4881",
"size": "5343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "italent/doc/overview-summary.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "210"
},
{
"name": "CSS",
"bytes": "79618"
},
{
"name": "HTML",
"bytes": "2092479"
},
{
"name": "Java",
"bytes": "145036"
},
{
"name": "JavaScript",
"bytes": "74574"
},
{
"name": "Shell",
"bytes": "269"
}
],
"symlink_target": ""
} |
<?php
use dektrium\user\models\Token;
use dektrium\user\models\User;
use tests\codeception\_pages\LoginPage;
use tests\codeception\_pages\SettingsPage;
use yii\helpers\Html;
$I = new FunctionalTester($scenario);
$I->wantTo('ensure that account settings page work');
$page = LoginPage::openBy($I);
$user = $I->getFixture('user')->getModel('user');
$page->login($user->username, 'qwerty');
$page = SettingsPage::openBy($I);
$I->amGoingTo('check that current password is required and must be valid');
$page->update($user->email, $user->username, 'wrong');
$I->see('Current password is not valid');
$I->amGoingTo('check that email is changing properly');
$page->update('new_user@example.com', $user->username, 'qwerty');
$I->seeRecord(User::className(), ['email' => $user->email, 'unconfirmed_email' => 'new_user@example.com']);
$I->see('A confirmation message has been sent to your new email address');
$user = $I->grabRecord(User::className(), ['id' => $user->id]);
$token = $I->grabRecord(Token::className(), ['user_id' => $user->id, 'type' => Token::TYPE_CONFIRM_NEW_EMAIL]);
$I->seeInEmail(Html::encode($token->getUrl()));
$I->seeInEmailRecipients($user->unconfirmed_email);
Yii::$app->user->logout();
$I->amGoingTo('log in using new email address before clicking the confirmation link');
$page = LoginPage::openBy($I);
$page->login('new_user@example.com', 'qwerty');
$I->see('Invalid login or password');
$I->amGoingTo('log in using new email address after clicking the confirmation link');
$user->attemptEmailChange($token->code);
$page->login('new_user@example.com', 'qwerty');
$I->see('Logout');
$I->seeRecord(User::className(), [
'id' => 1,
'email' => 'new_user@example.com',
'unconfirmed_email' => null
]);
$I->amGoingTo('reset email changing process');
$page = SettingsPage::openBy($I);
$page->update('user@example.com', $user->username, 'qwerty');
$I->see('A confirmation message has been sent to your new email address');
$I->seeRecord(User::className(), [
'id' => 1,
'email' => 'new_user@example.com',
'unconfirmed_email' => 'user@example.com'
]);
$page->update('new_user@example.com', $user->username, 'qwerty');
$I->see('Your account details have been updated');
$I->seeRecord(User::className(), [
'id' => 1,
'email' => 'new_user@example.com',
'unconfirmed_email' => null
]);
$I->amGoingTo('change username and password');
$page->update('new_user@example.com', 'nickname', 'qwerty', '123654');
$I->see('Your account details have been updated');
$I->seeRecord(User::className(), [
'username' => 'nickname',
'email' => 'new_user@example.com'
]);
Yii::$app->user->logout();
$I->amGoingTo('login with new credentials');
$page = LoginPage::openBy($I);
$page->login('nickname', '123654');
$I->see('Logout');
| {
"content_hash": "6d1dac977bac0abbce5cfc3b1df1af4f",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 111,
"avg_line_length": 36.578947368421055,
"alnum_prop": 0.6690647482014388,
"repo_name": "zogodo/weibin",
"id": "90743405a9b8da797ad6d5f99d2207333626eafe",
"size": "2780",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "vendor/dektrium/yii2-user/tests/codeception/functional/SettingsCept.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "PHP",
"bytes": "143149"
},
{
"name": "PLpgSQL",
"bytes": "18700"
},
{
"name": "Scala",
"bytes": "2237063"
},
{
"name": "TeX",
"bytes": "23588"
}
],
"symlink_target": ""
} |
namespace FineGameDesign.Utils
{
public sealed class TimerTextDeck
{
public string[] resourcePaths = {
"fast2.txt",
"fast1.txt",
"fast.txt",
"slow.txt"
};
public Timer timer;
private TextDeck[] decks;
public string Selected { get; private set; }
public void Setup()
{
decks = new TextDeck[resourcePaths.Length];
for (int index = 0, end = resourcePaths.Length; index < end; ++index)
{
TextDeck deck = new TextDeck();
deck.resourcePath = resourcePaths[index];
deck.Setup();
decks[index] = deck;
}
Selected = "";
}
public string Select()
{
int index = timer.StateIndex;
TextDeck deck = decks[index];
Selected = deck.RemoveAt(timer.NormalInState);
return Selected;
}
}
}
| {
"content_hash": "2bdfb1021d397890c2380225f2a64532",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 81,
"avg_line_length": 27.47222222222222,
"alnum_prop": 0.487360970677452,
"repo_name": "ethankennerly/word-sizzle",
"id": "c303ccd284bd83b815852575c30d8e711c698319",
"size": "989",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/TimerTextDeck.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "202321"
},
{
"name": "HLSL",
"bytes": "14896"
},
{
"name": "HTML",
"bytes": "9831"
},
{
"name": "ShaderLab",
"bytes": "66246"
}
],
"symlink_target": ""
} |
#include <vector>
#include "json.hpp"
#include "ThingTypes.hpp"
#include "HelperFunctions.hpp"
#include "RedditError.hpp"
namespace redd {
// Operators
bool operator ==(const Link& lhs, const Link& rhs) {
return lhs.author == rhs.author && lhs.id == rhs.id && lhs.name == rhs.name &&
lhs.subreddit_id == rhs.subreddit_id && lhs.title == rhs.title && rhs.url == lhs.url &&
lhs.created_utc == rhs.created_utc && lhs.score == rhs.score;
}
bool operator !=(const Link& lhs, const Link& rhs) {
return !(lhs == rhs);
}
bool operator ==(const Comment& lhs, const Comment& rhs) {
return lhs.children.size() == rhs.children.size() && lhs.author == rhs.author && lhs.id == rhs.id &&
lhs.link_id == rhs.link_id && lhs.parent_id == rhs.parent_id &&
lhs.subreddit_id == rhs.subreddit_id && lhs.created_utc == rhs.created_utc;
}
bool operator !=(const Comment& lhs, const Comment& rhs) {
return !(lhs == rhs);
}
bool operator ==(const T3Listing& lhs, const T3Listing& rhs) {
return lhs.after == rhs.after && lhs.before == rhs.before
&& lhs.links == rhs.links && lhs.modhash == rhs.modhash;
}
bool operator !=(const T3Listing& lhs, const T3Listing& rhs) {
return !(lhs == rhs);
}
bool operator ==(const PostCommentPair& lhs, const PostCommentPair& rhs) {
return lhs.link == rhs.link && lhs.comments == rhs.comments;
}
bool operator !=(const PostCommentPair& lhs, const PostCommentPair& rhs) {
return !(lhs == rhs);
}
//****************
namespace detail {
//****************
void ThingParser::parseT3Object(T3Listing& dest, const nlohmann::json& json) {
using detail::setIfNotNull;
if (json.find("data") != json.end()) {
setIfNotNull(dest.after, json["data"], "after", "");
setIfNotNull(dest.before, json["data"], "before", "");
setIfNotNull(dest.modhash, json["data"], "modhash", "");
if (json["data"].find("children") != json["data"].end()) {
for (auto it = json["data"]["children"].begin(); it != json["data"]["children"].end(); it++) {
dest.links.push_back(parseLinkT3((*it)["data"]));
}
}
}
dest.links.shrink_to_fit();
}
Comment ThingParser::parseCommentT1(const nlohmann::json& json_obj) {
Comment comment;
using detail::setIfNotNull;
setIfNotNull(comment.author, json_obj, "author", "");
setIfNotNull(comment.banned_by, json_obj, "banned_by", "");
setIfNotNull(comment.body, json_obj, "body", "");
setIfNotNull(comment.id, json_obj, "id", "");
setIfNotNull(comment.link_id, json_obj, "link_id", "");
setIfNotNull(comment.name, json_obj, "name", "");
setIfNotNull(comment.parent_id, json_obj, "parent_id", "");
setIfNotNull(comment.subreddit, json_obj, "subreddit", "");
setIfNotNull(comment.subreddit_id, json_obj, "subreddit_id", "");
setIfNotNull(comment.subreddit_name_prefixed, json_obj, "subreddit_name_prefixed", "");
setIfNotNull(comment.subreddit_type, json_obj, "subreddit_type", "");
setIfNotNull(comment.banned_at_utc, json_obj, "banned_at_utc", static_cast<long long>(-1));
setIfNotNull(comment.created, json_obj, "created", static_cast<long long>(-1));
setIfNotNull(comment.created_utc, json_obj, "created_utc", static_cast<long long>(-1));
setIfNotNull(comment.edited, json_obj, "edited", static_cast<long long>(-1));
auto iter = json_obj.find("edited");
if (iter != json_obj.end()) {
if (iter->is_number() && !iter->is_null()) {
setIfNotNull(comment.edited, json_obj, "edited", static_cast<long long>(-1));
}
}
setIfNotNull(comment.downs, json_obj, "downs", -1);
setIfNotNull(comment.gilded, json_obj, "gilded", -1);
setIfNotNull(comment.likes, json_obj, "likes", -1);
setIfNotNull(comment.num_reports, json_obj, "num_reports", -1);
setIfNotNull(comment.score, json_obj, "score", -1);
setIfNotNull(comment.ups, json_obj, "ups", -1);
setIfNotNull(comment.archived, json_obj, "archived", false);
setIfNotNull(comment.can_gild, json_obj, "can_gild", false);
setIfNotNull(comment.can_mod_post, json_obj, "can_mod_post", false);
setIfNotNull(comment.collapsed, json_obj, "collapsed", false);
setIfNotNull(comment.is_sumbitter, json_obj, "is_sumbitter", false);
setIfNotNull(comment.saved, json_obj, "saved", false);
setIfNotNull(comment.stickied, json_obj, "stickied", false);
if (json_obj.find("replies")!= json_obj.end()) {
if (json_obj["replies"].find("data") != json_obj["replies"].end()) {
auto child_array = json_obj["replies"]["data"].find("children");
if (child_array != json_obj["replies"]["data"].end()) {
for (auto& child : *child_array) {
comment.children.push_back(parseCommentT1(child["data"]));
}
}
}
}
return comment;
}
Link ThingParser::parseLinkT3(const nlohmann::json& json_obj) {
Link link;
using detail::setIfNotNull;
setIfNotNull(link.author, json_obj, "author", "");
setIfNotNull(link.banned_by, json_obj, "banned_by", "");
setIfNotNull(link.domain, json_obj, "domain", "");
setIfNotNull(link.id, json_obj, "id", "");
setIfNotNull(link.link_flair_text, json_obj, "link_flair_text", "");
setIfNotNull(link.name, json_obj, "name", "");
setIfNotNull(link.permalink, json_obj, "permalink", "");
setIfNotNull(link.selftext, json_obj, "selftext", "");
setIfNotNull(link.selftext_html, json_obj, "selftext_html", "");
setIfNotNull(link.subreddit, json_obj, "subreddit", "");
setIfNotNull(link.subreddit_id, json_obj, "subreddit_id", "");
setIfNotNull(link.subreddit_name_prefixed, json_obj, "subreddit_name_prefixed", "");
setIfNotNull(link.subreddit_type, json_obj, "subreddit_type", "");
setIfNotNull(link.thumbnail, json_obj, "thumbnail", "");
setIfNotNull(link.title, json_obj, "title", "");
setIfNotNull(link.url, json_obj, "url", "");
setIfNotNull(link.whitelist_status, json_obj, "whitelist_status", "");
setIfNotNull(link.approved_at_utc, json_obj, "approved_at_utc", static_cast<long long>(-1));
setIfNotNull(link.banned_at_utc, json_obj, "banned_at_utc", static_cast<long long>(-1));
setIfNotNull(link.created_utc, json_obj, "created_utc", static_cast<long long>(-1));
/* In the api, if it hasn't been edited it returns the value 'false' and not null for the key 'edited'
* We must first check if the type is a number to set it to the variable.
*/
auto iter = json_obj.find("edited");
if (iter != json_obj.end()) {
if (iter->is_number() && !iter->is_null()) {
setIfNotNull(link.edited, json_obj, "edited", static_cast<long long>(-1));
}
}
setIfNotNull(link.downs, json_obj, "downs", -1);
setIfNotNull(link.gilded, json_obj, "gilded", -1);
setIfNotNull(link.likes, json_obj, "likes", -1);
setIfNotNull(link.num_comments, json_obj, "num_comments", -1);
setIfNotNull(link.num_crossposts, json_obj, "num_crossposts", -1);
setIfNotNull(link.report_reasons, json_obj, "report_reasons", -1);
setIfNotNull(link.score, json_obj, "score", -1);
setIfNotNull(link.ups, json_obj, "ups", -1);
setIfNotNull(link.view_count, json_obj, "view_count", -1);
setIfNotNull(link.archived, json_obj, "archived", false);
setIfNotNull(link.can_gild, json_obj, "can_gild", false);
setIfNotNull(link.can_mod_post, json_obj, "can_mod_post", false);
setIfNotNull(link.clicked, json_obj, "clicked", false);
setIfNotNull(link.hidden, json_obj, "hidden", false);
setIfNotNull(link.hide_score, json_obj, "hide_score", false);
setIfNotNull(link.is_crosspostable, json_obj, "is_crosspostable", false);
setIfNotNull(link.is_self, json_obj, "is_self", false);
setIfNotNull(link.is_video, json_obj, "is_video", false);
setIfNotNull(link.locked, json_obj, "locked", false);
setIfNotNull(link.over_18, json_obj, "over_18", false);
setIfNotNull(link.spoiler, json_obj, "spoiler", false);
setIfNotNull(link.stickied, json_obj, "stickied", false);
setIfNotNull(link.visted, json_obj, "visted", false);
return link;
}
void ThingParser::parsePairObject(PostCommentPair& dest, const nlohmann::json& t3, const nlohmann::json& t1) {
if (t3.find("data") != t3.end()) {
if (t3["data"]["children"].size() != 1) {// there is always only one t3 object.
throw RedditError("An error has occured parsing, no T3 object found.");
}
else {
dest.link = parseLinkT3(t3["data"]["children"][0]["data"]);
}
}
if (t1.find("data") != t1.end()) {
for (auto& t1_obj : t1["data"]["children"]) {
dest.comments.push_back(parseCommentT1(t1_obj["data"]));
}
}
dest.comments.shrink_to_fit();
}
}//! detail namespace
}//! redd namespace
| {
"content_hash": "e0ff06077ee253ef323ae1d7401598e7",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 110,
"avg_line_length": 40.98623853211009,
"alnum_prop": 0.6295467263570229,
"repo_name": "Grandduchy/Reddit-plus-plus",
"id": "9c1ac6c9fa480e294896399751039f483606cd33",
"size": "8935",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ThingTypes.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "84611"
},
{
"name": "CMake",
"bytes": "330"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Entwicklungshilfe Spenden ohne Spendengeld zu verschwenden</title>
<meta name="description" content="Ein viel zu großer Teil von Spenden für die Entwicklungshilfe versickert in der Verwaltung der jeweiligen Organisationen. Wenn ich Geld spende, möchte ich im folgenden Jahr keinen UNICEF-Katalog bekommen oder unnötig Mitarbeiter in einer Zentrale bezahlen. Ich möchte, dass mein Geld direkt zu den Entwicklungsprojekten gelangt. Außerdem wäre es schön, wenn ich anstelle von Geld eigene Zeit investieren könnte, um dem Projekt zu helfen. 2009 habe ich eine perfekte Lösung gefunden.
Wenn ich mich richtig erinnere, dann versickert bei großen Hilfsorganisationen oftmals bis zu 40% in der Verwaltung und im Marketing, um neue Spendengelder zu aquirieren. Das Korruptionsthema ignoriere ich jetzt einfach mal. Egal, ob die Zahl stimmt oder nicht: Fakt ist, dass Spendengelder nicht direkt in ein Projekt fließen, sondern Geld abgezweigt wird. Natürlich hat das alles auch einen Sinn. Ich möchte aber, dass mein Geld oder meine Hilfe komplett ankommt, ohne Streuverluste. Und das gelingt mir seit 2009 so…
Ein (Aus)Flug nach Brasilien
2009 hatte ich das große Glück, dass Projekt Mandacaru in dem kleinen Städtchen Pedro II kennenzulernen. Mandacaru ist ein Bildungszentrum von Brasilianern für Brasilianer. Die einzige Deutsche, die bei Mandacaru seit Anbeginn dabei ist, ist Maria Platen. 2009 scheuchte Sie uns in zehn Tagen durch die zahlreichen Projekte, die Mandacaru betreibt. Mit ihrer deutschen Gründlichkeit, die dem Projekt über die Jahre sehr geholfen hat, trieb Sie auch uns von einem Ort zum anderen. Wir mussten alles sehen. Wir waren beeindruckt.
Die zehn Tage in Pedro II waren anstrengend. Neben außergewöhnlicher Gastfreundschaft, der bekannten brasilianischen Lebensfreude, haben uns einige Dinge aber auch schockiert und andere zum Nachdenken gebracht. Vor allem jedoch hat uns die aufopfernden Arbeit beeindruckt. Mandacaru betreibt einen Kindergarten, um Familien zu stärken. Mandacaru führt die Ökoschule Thomas a Kempis für moderne und nachhaltige Landwirtschaft in der Halbtrockenzone. Und als drittes großes Projekt gilt der Zisternenbau in den Außenbereichen. Dort, wo es kein fließendes Wasser gibt. Dort, wo einfache Bauern leben und oft sandigen oder trockenen Boden beackern.
Sämtliche der in den zehn Tagen erlebten Eindrücke hinterließen einen tiefgehenden Abdruck. Unter anderem auch den, dass Spenden helfen. Vor allem dann, wenn die Menschen vor Ort selbst entscheiden können, wofür das Geld eingesetzt werden soll. Schließlich wissen sie, was dringend gebraucht wird. Sei es für einen neuen Reifen am Jeep, um überhaupt die Projekte zu besuchen und zu betreuen oder sei es das Honorar für die Lehrer der Ökoschule.
Was ich dazu tue – eine Website für Mandacaru
Fast jedes Jahr besuchen Mitarbeiter von Mandacaru Deutschland. Denn in Deutschland gibt es den Missionshilfe Pedro II, Brasilien e.V., der Mandacaru unterstützt. Bei Ihren Besuchen reisen meist zwei BrasilianerInnen quer durch Deutschland und erklären und zeigen was Mandacaru macht, wie Spenden investiert werden und welche Hilfe die Projekte noch gebrauchen können.
Geld habe ich bis jetzt nicht wirklich nennenswert gespendet. Ich investiere Zeit und helfe mit den Werkzeugen, die ich am Besten bediene: Computer und Internet.
Bei einem dieser Besuche, 2011, habe ich dann gemeinsam mit Neto und Valmir die Website für Mandacaru aufgebaut. Nach zwei Nachmittagen stand die Website und wird seitdem selbstständig betreut. Sie basiert auf WordPress.com und die einzige Sonderfunktion, die ich jedes Jahr dazukaufe ist die eigene Domain cf-mandacaru.org. Dank WordPress.com fällt so gut wie keine Arbeit an. Und, was das großartigste ist: Die Website wird rege genutzt.
Oft und gerne zeige ich in Workshops die Website und demonstriere, wie rege Mitarbeiter – in vorderster Front Neto Santos – Beiträge schreiben und die eigene Arbeit dokumentieren. Mehr als die Meisten meiner Studenten der letzten Jahre, haben die Brasilianer den Sinn eines Blogs verstanden und genutzt.
Eine Website für den Verein
Für den Verein Missionshilfe Pedro II, Brasilien e.V. habe ich dann endlich letztes Jahr eine ordentliche Website gebaut. Die statische Website baue ich mit Jekyll und stelle die Inhalte online. Die Website verfolgt drei Ziele:
Vorstellung des Vereins
Abruf des Pedro Ponte Magazins
Sammeln von Spenden
Gestern habe ich die Website aktualisiert, das neue Pedro Ponte Magazin online gestellt, ein wunderbares Video von Mandacaru auf YouTube hochgeladen und das Theme optimiert.
Die Tage verschicke ich dann noch den Newsletter, der leider noch nicht wirklich viele Interessenten gefunden hat. Wenn Du gerne ein Projekt unterstützen möchtest, dann halte Dich mit dem Newsletter auf dem Laufenden. Wir verschicken Ihn ein- oder maximal zweimal im Jahr.
Und jetzt bist Du dran…
Mach die Welt ein wenig schöner und teile. Am Einfachsten geht das mit einer Spende und die Spenden an den Verein – ich bin kein Mitglied – gehen direkt nach Brasilien, denn alle Vereinsmitglieder arbeiten ehrenamtlich. Und weil die Schwester meiner Freundin Vorsitzende ist, verbürge ich mich dafür.
Helfen, Freuen &amp; Spenden ›für">
<link rel="canonical" href="https://mo.phlow.de/pedro-segundo/">
<!-- Google Search Console/Webmaster Tools Verification -->
<!-- Facebook Open Graph -->
<meta property="og:title" content="Entwicklungshilfe Spenden ohne Spendengeld zu verschwenden">
<meta property="og:description" content="Ein viel zu großer Teil von Spenden für die Entwicklungshilfe versickert in der Verwaltung der jeweiligen Organisationen. Wenn ich Geld spende, möchte ich im folgenden Jahr keinen UNICEF-Katalog bekommen oder unnötig Mitarbeiter in einer Zentrale bezahlen. Ich möchte, dass mein Geld direkt zu den...">
<meta property="og:url" content="https://mo.phlow.de/pedro-segundo/">
<meta property="og:locale" content="de_DE">
<meta property="og:type" content="website">
<meta property="og:site_name" content="Sign 'O' The Times">
<meta property="og:image" content="https://mo.phlow.de/images/pedro-segundo.jpg">
<!-- JSONLD Structured Data -->
<script type="application/ld+json">
{ "@context": "http://schema.org",
"@type": "BlogPosting",
"headline": "Spenden ohne Spendengeld zu verschwenden",
"alternativeHeadline": "Entwicklungshilfe",
"image": "https://mo.phlow.de/images/pedro-segundo.jpg",
"editor": "{"name"=>"Moritz »mo.« Sauer", "url"=>"http://moritz.sauer.io/"}",
"genre": "webdesign",
"keywords": "",
"wordcount": "805",
"publisher": "",
"url": "https://mo.phlow.de",
"datePublished": "2015-11-26 00:00:00 +0100",
"dateCreated": "2015-11-26 00:00:00 +0100",
"dateModified": "2015-11-26 00:00:00 +0100",
"author": {
"@type": "Organization",
"name": "{"name"=>"Moritz »mo.« Sauer", "url"=>"http://moritz.sauer.io/"}"
},
"description": "Ein viel zu großer Teil von Spenden für die Entwicklungshilfe versickert in der Verwaltung der jeweiligen Organisationen. Wenn ich Geld spende, möchte ich im folgenden Jahr keinen UNICEF-Katalog bekommen oder unnötig Mitarbeiter in einer Zentrale bezahlen. Ich möchte, dass mein Geld direkt zu den Entwicklungsprojekten gelangt. Außerdem wäre es schön, wenn ich anstelle von Geld eigene Zeit investieren könnte, um dem Projekt zu helfen. 2009 habe ich eine perfekte Lösung gefunden.
Wenn ich mich richtig erinnere, dann versickert bei großen Hilfsorganisationen oftmals bis zu 40% in der Verwaltung und im Marketing, um neue Spendengelder zu aquirieren. Das Korruptionsthema ignoriere ich jetzt einfach mal. Egal, ob die Zahl stimmt oder nicht: Fakt ist, dass Spendengelder nicht direkt in ein Projekt fließen, sondern Geld abgezweigt wird. Natürlich hat das alles auch einen Sinn. Ich möchte aber, dass mein Geld oder meine Hilfe komplett ankommt, ohne Streuverluste. Und das gelingt mir seit 2009 so…
Ein (Aus)Flug nach Brasilien
2009 hatte ich das große Glück, dass Projekt Mandacaru in dem kleinen Städtchen Pedro II kennenzulernen. Mandacaru ist ein Bildungszentrum von Brasilianern für Brasilianer. Die einzige Deutsche, die bei Mandacaru seit Anbeginn dabei ist, ist Maria Platen. 2009 scheuchte Sie uns in zehn Tagen durch die zahlreichen Projekte, die Mandacaru betreibt. Mit ihrer deutschen Gründlichkeit, die dem Projekt über die Jahre sehr geholfen hat, trieb Sie auch uns von einem Ort zum anderen. Wir mussten alles sehen. Wir waren beeindruckt.
Die zehn Tage in Pedro II waren anstrengend. Neben außergewöhnlicher Gastfreundschaft, der bekannten brasilianischen Lebensfreude, haben uns einige Dinge aber auch schockiert und andere zum Nachdenken gebracht. Vor allem jedoch hat uns die aufopfernden Arbeit beeindruckt. Mandacaru betreibt einen Kindergarten, um Familien zu stärken. Mandacaru führt die Ökoschule Thomas a Kempis für moderne und nachhaltige Landwirtschaft in der Halbtrockenzone. Und als drittes großes Projekt gilt der Zisternenbau in den Außenbereichen. Dort, wo es kein fließendes Wasser gibt. Dort, wo einfache Bauern leben und oft sandigen oder trockenen Boden beackern.
Sämtliche der in den zehn Tagen erlebten Eindrücke hinterließen einen tiefgehenden Abdruck. Unter anderem auch den, dass Spenden helfen. Vor allem dann, wenn die Menschen vor Ort selbst entscheiden können, wofür das Geld eingesetzt werden soll. Schließlich wissen sie, was dringend gebraucht wird. Sei es für einen neuen Reifen am Jeep, um überhaupt die Projekte zu besuchen und zu betreuen oder sei es das Honorar für die Lehrer der Ökoschule.
Was ich dazu tue – eine Website für Mandacaru
Fast jedes Jahr besuchen Mitarbeiter von Mandacaru Deutschland. Denn in Deutschland gibt es den Missionshilfe Pedro II, Brasilien e.V., der Mandacaru unterstützt. Bei Ihren Besuchen reisen meist zwei BrasilianerInnen quer durch Deutschland und erklären und zeigen was Mandacaru macht, wie Spenden investiert werden und welche Hilfe die Projekte noch gebrauchen können.
Geld habe ich bis jetzt nicht wirklich nennenswert gespendet. Ich investiere Zeit und helfe mit den Werkzeugen, die ich am Besten bediene: Computer und Internet.
Bei einem dieser Besuche, 2011, habe ich dann gemeinsam mit Neto und Valmir die Website für Mandacaru aufgebaut. Nach zwei Nachmittagen stand die Website und wird seitdem selbstständig betreut. Sie basiert auf WordPress.com und die einzige Sonderfunktion, die ich jedes Jahr dazukaufe ist die eigene Domain cf-mandacaru.org. Dank WordPress.com fällt so gut wie keine Arbeit an. Und, was das großartigste ist: Die Website wird rege genutzt.
Oft und gerne zeige ich in Workshops die Website und demonstriere, wie rege Mitarbeiter – in vorderster Front Neto Santos – Beiträge schreiben und die eigene Arbeit dokumentieren. Mehr als die Meisten meiner Studenten der letzten Jahre, haben die Brasilianer den Sinn eines Blogs verstanden und genutzt.
Eine Website für den Verein
Für den Verein Missionshilfe Pedro II, Brasilien e.V. habe ich dann endlich letztes Jahr eine ordentliche Website gebaut. Die statische Website baue ich mit Jekyll und stelle die Inhalte online. Die Website verfolgt drei Ziele:
Vorstellung des Vereins
Abruf des Pedro Ponte Magazins
Sammeln von Spenden
Gestern habe ich die Website aktualisiert, das neue Pedro Ponte Magazin online gestellt, ein wunderbares Video von Mandacaru auf YouTube hochgeladen und das Theme optimiert.
Die Tage verschicke ich dann noch den Newsletter, der leider noch nicht wirklich viele Interessenten gefunden hat. Wenn Du gerne ein Projekt unterstützen möchtest, dann halte Dich mit dem Newsletter auf dem Laufenden. Wir verschicken Ihn ein- oder maximal zweimal im Jahr.
Und jetzt bist Du dran…
Mach die Welt ein wenig schöner und teile. Am Einfachsten geht das mit einer Spende und die Spenden an den Verein – ich bin kein Mitglied – gehen direkt nach Brasilien, denn alle Vereinsmitglieder arbeiten ehrenamtlich. Und weil die Schwester meiner Freundin Vorsitzende ist, verbürge ich mich dafür.
Helfen, Freuen &amp; Spenden ›für"
}
</script>
<!-- Favicon -->
<link rel="icon" sizes="32x32" href="https://mo.phlow.de/assets/img/favicon-32x32.png" />
<link rel="icon" sizes="192x192" href="https://mo.phlow.de/assets/img/touch-icon-192x192.png" />
<link rel="apple-touch-icon-precomposed" sizes="180x180" href="https://mo.phlow.de/assets/img/apple-touch-icon-180x180-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="https://mo.phlow.de/assets/img/apple-touch-icon-152x152-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="https://mo.phlow.de/assets/img/apple-touch-icon-144x144-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="https://mo.phlow.de/assets/img/apple-touch-icon-120x120-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="https://mo.phlow.de/assets/img/apple-touch-icon-114x114-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="https://mo.phlow.de/assets/img/apple-touch-icon-76x76-precomposed.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="https://mo.phlow.de/assets/img/apple-touch-icon-72x72-precomposed.png" />
<link rel="apple-touch-icon-precomposed" href="https://mo.phlow.de/assets/img/apple-touch-icon-precomposed.png" />
<meta name="msapplication-TileImage" content="https://mo.phlow.de/assets/img/msapplication_tileimage.png" />
<meta name="msapplication-TileColor" content="#fabb00" />
<link rel="alternate" type="application/rss+xml" title="RSS Sign 'O' The Times" href="https://mo.phlow.de/feed.xml">
<link type="text/plain" rel="author" href="https://mo.phlow.de/humans.txt">
<link rel="stylesheet" href="https://mo.phlow.de/assets/css/styles.css">
</head>
<body id="post">
<header>
<div id="masthead" role="banner">
<div id="logo">
<a id="logo" href="/" title="Sign 'O' The Times">Sign 'O' The Times</a>
</div>
<div id="slogan">
Digitale Kultur / Digitales Leben
</div>
</div>
<nav id="navigation">
<a href="https://mo.phlow.de/artikel/">ARTIKEL</a>
/
<a href="https://mo.phlow.de/suche/">SUCHE</a>
/
<a href="https://mo.phlow.de/info/">ÜBER</a>
</nav>
</header>
<article>
<header>
<figure>
<img src="https://mo.phlow.de/images/pedro-segundo.jpg" width="970" alt="Spenden ohne Spendengeld zu verschwenden" itemprop="image">
</figure>
<p>Entwicklungshilfe</p>
<h1 itemprop="name headline">Spenden ohne Spendengeld zu verschwenden</h1>
</header>
<div itemprop="articleBody">
<p>Ein viel zu großer Teil von Spenden für die Entwicklungshilfe versickert in der Verwaltung der jeweiligen Organisationen. Wenn ich Geld spende, möchte ich im folgenden Jahr keinen UNICEF-Katalog bekommen oder unnötig Mitarbeiter in einer Zentrale bezahlen. Ich möchte, dass mein Geld direkt zu den Entwicklungsprojekten gelangt. Außerdem wäre es schön, wenn ich anstelle von Geld eigene Zeit investieren könnte, um dem Projekt zu helfen. 2009 habe ich eine perfekte Lösung gefunden.</p>
<p>Wenn ich mich richtig erinnere, dann versickert bei großen Hilfsorganisationen oftmals bis zu 40% in der Verwaltung und im Marketing, um neue Spendengelder zu aquirieren. Das Korruptionsthema ignoriere ich jetzt einfach mal. Egal, ob die Zahl stimmt oder nicht: Fakt ist, dass Spendengelder nicht direkt in ein Projekt fließen, sondern Geld abgezweigt wird. Natürlich hat das alles auch einen Sinn. Ich möchte aber, dass mein Geld oder meine Hilfe komplett ankommt, ohne Streuverluste. Und das gelingt mir seit 2009 so…</p>
<h2 id="ein-ausflug-nach-brasilien">Ein (Aus)Flug nach Brasilien</h2>
<p>2009 hatte ich das große Glück, dass <a href="http://cf-mandacaru.org/">Projekt Mandacaru</a> in dem kleinen <a href="https://www.google.de/maps/place/Pedro+II,+PI,+Brasilien/@-8.5422356,-48.0220115,5.56z/data=!4m2!3m1!1s0x07939aa9009b7f09:0xe6169cb9f64d3a98">Städtchen Pedro II</a> kennenzulernen. Mandacaru ist ein Bildungszentrum von Brasilianern für Brasilianer. Die einzige Deutsche, die bei Mandacaru seit Anbeginn dabei ist, ist Maria Platen. 2009 scheuchte Sie uns in zehn Tagen durch die zahlreichen Projekte, die Mandacaru betreibt. Mit ihrer deutschen Gründlichkeit, die dem Projekt über die Jahre sehr geholfen hat, trieb Sie auch uns von einem Ort zum anderen. Wir mussten alles sehen. Wir waren beeindruckt.</p>
<div class="flex-video"><iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d10938915.395734513!2d-48.02201148190218!3d-8.542235639692086!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x07939aa9009b7f09%3A0xe6169cb9f64d3a98!2sPedro+II%2C+PI%2C+Brasilien!5e0!3m2!1sde!2sde!4v1448539387298" width="600" height="450" frameborder="0" style="border:0" allowfullscreen=""></iframe></div>
<p>Die zehn Tage in Pedro II waren anstrengend. Neben außergewöhnlicher Gastfreundschaft, der bekannten brasilianischen Lebensfreude, haben uns einige Dinge aber auch schockiert und andere zum Nachdenken gebracht. Vor allem jedoch hat uns die aufopfernden Arbeit beeindruckt. Mandacaru betreibt einen Kindergarten, um Familien zu stärken. Mandacaru führt die Ökoschule Thomas a Kempis für moderne und nachhaltige Landwirtschaft in der Halbtrockenzone. Und als drittes großes Projekt gilt der Zisternenbau in den Außenbereichen. Dort, wo es kein fließendes Wasser gibt. Dort, wo einfache Bauern leben und oft sandigen oder trockenen Boden beackern.</p>
<div class="flex-video"><iframe width="560" height="315" src="https://www.youtube.com/embed/yUMQEyLkgCE" frameborder="0" allowfullscreen=""></iframe></div>
<p>Sämtliche der in den zehn Tagen erlebten Eindrücke hinterließen einen tiefgehenden Abdruck. Unter anderem auch den, dass Spenden helfen. Vor allem dann, wenn die Menschen vor Ort selbst entscheiden können, wofür das Geld eingesetzt werden soll. Schließlich wissen sie, was dringend gebraucht wird. Sei es für einen neuen Reifen am Jeep, um überhaupt die Projekte zu besuchen und zu betreuen oder sei es das Honorar für die Lehrer der Ökoschule.</p>
<h2 id="was-ich-dazu-tue--eine-website-für-mandacaru">Was ich dazu tue – eine Website für Mandacaru</h2>
<p>Fast jedes Jahr besuchen Mitarbeiter von Mandacaru Deutschland. Denn in Deutschland gibt es den <a href="http://pedro-segundo.de/ueber-missionshilfe-pedro-ii/">Missionshilfe Pedro II, Brasilien e.V.</a>, der Mandacaru unterstützt. Bei Ihren Besuchen reisen meist zwei BrasilianerInnen quer durch Deutschland und erklären und zeigen was Mandacaru macht, wie Spenden investiert werden und welche Hilfe die Projekte noch gebrauchen können.</p>
<blockquote>
<p>Geld habe ich bis jetzt nicht wirklich nennenswert gespendet. Ich investiere Zeit und helfe mit den Werkzeugen, die ich am Besten bediene: Computer und Internet.</p>
</blockquote>
<p>Bei einem dieser Besuche, 2011, habe ich dann gemeinsam mit Neto und Valmir die Website für Mandacaru aufgebaut. Nach zwei Nachmittagen stand die Website und wird seitdem selbstständig betreut. Sie basiert auf WordPress.com und die einzige <em>Sonderfunktion</em>, die ich jedes Jahr dazukaufe ist die eigene Domain cf-mandacaru.org. Dank WordPress.com fällt so gut wie keine Arbeit an. <strong>Und</strong>, was das großartigste ist: Die Website wird rege genutzt.</p>
<p>Oft und gerne zeige ich in Workshops die Website und demonstriere, wie rege Mitarbeiter – in vorderster Front Neto Santos – Beiträge schreiben und die eigene Arbeit dokumentieren. Mehr als die Meisten meiner Studenten der letzten Jahre, haben die Brasilianer den Sinn eines Blogs verstanden und genutzt.</p>
<h2 id="eine-website-für-den-verein">Eine Website für den Verein</h2>
<p>Für den Verein <em>Missionshilfe Pedro II, Brasilien e.V.</em> habe ich dann endlich letztes Jahr eine <a href="http://pedro-segundo.de/">ordentliche Website</a> gebaut. Die statische Website baue ich mit <a href="http://magazin.phlow.de/jekyll/">Jekyll</a> und stelle die Inhalte online. Die Website verfolgt drei Ziele:</p>
<ol>
<li><a href="http://pedro-segundo.de/ueber-missionshilfe-pedro-ii/">Vorstellung des Vereins</a></li>
<li><a href="http://pedro-segundo.de/ponte-magazin/">Abruf des Pedro Ponte Magazins</a></li>
<li><a href="http://pedro-segundo.de/spenden/">Sammeln von Spenden</a></li>
</ol>
<p>Gestern habe ich die Website aktualisiert, das neue <a href="http://pedro-segundo.de/ponte-magazin/">Pedro Ponte Magazin</a> online gestellt, ein wunderbares <a href="https://www.youtube.com/watch?v=yUMQEyLkgCE">Video von Mandacaru</a> auf YouTube hochgeladen und das Theme optimiert.</p>
<p>Die Tage verschicke ich dann noch den <a href="#">Newsletter</a>, der leider noch nicht wirklich viele Interessenten gefunden hat. Wenn Du gerne ein Projekt unterstützen möchtest, dann halte Dich mit dem Newsletter auf dem Laufenden. Wir verschicken Ihn ein- oder maximal zweimal im Jahr.</p>
<h2 id="und-jetzt-bist-du-dran">Und jetzt bist Du dran…</h2>
<p>Mach die Welt ein wenig schöner und teile. Am Einfachsten geht das mit einer Spende und die Spenden an den Verein – ich bin kein Mitglied – gehen direkt nach Brasilien, denn alle Vereinsmitglieder arbeiten ehrenamtlich. Und weil die Schwester meiner Freundin Vorsitzende ist, verbürge ich mich dafür.</p>
<p><a class="button radius" href="http://pedro-segundo.de/spenden/">Helfen, Freuen & Spenden ›für</a></p>
</div>
<footer>
<p class="post-meta">
<small>
– <time datetime="2015-11-26T00:00:00+01:00" itemprop="datePublished">26. Nov 2015</time>
/
<span itemprop="author" itemscope itemtype="http://schema.org/Person"><span itemprop="name"><a href="http://moritz.sauer.io/" title="">Moritz »mo.« Sauer</a></span></span>
</small>
</p>
</footer>
<footer>
<style>
#wufoo-w1qf4jie03oron5 {
display: none;
width: 100%;
padding: 1em;
background-color: #fff;
}
</style>
<button class="tem2" onclick="myFunction()">Was meinst Du? Kommentar schreiben!</button>
<script>
function myFunction() {
var x = document.getElementById("wufoo-w1qf4jie03oron5");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
<div id="wufoo-w1qf4jie03oron5">
<a href="https://phlowmedia.wufoo.eu/forms/w1qf4jie03oron5">Was meinst Du? Kommentar schreiben!</a>.
<script type="text/javascript">var w1qf4jie03oron5;(function(d, t) { var s = d.createElement(t), options = { 'userName':'phlowmedia', 'formHash':'w1qf4jie03oron5', 'autoResize':true, 'height':'687', 'async':true, 'host':'wufoo.eu', 'header':'show', 'defaultValues':'field5=Spenden+ohne+Spendengeld+zu+verschwenden', 'ssl':true}; s.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 'www.wufoo.eu/scripts/embed/form.js'; s.onload = s.onreadystatechange = function() { var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return; try { w1qf4jie03oron5 = new WufooForm();w1qf4jie03oron5.initialize(options);w1qf4jie03oron5.display(); } catch (e) {}}; var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr); })(document, 'script');</script>
</div>
</footer>
</article>
<footer id="footer-content">
<div id="footer">
<small><a href="https://phlow.de/impressum/" target="_blank">Impressum & Datenschutz</a></small> /
<small><a href="https://mo.phlow.de/kontakt/">Kontakt</a></small> /
<small><a href="https://mo.phlow.de/feed.xml">RSS</a></small> /
<small><a class="button" href="#masthead">↑</a></small>
</div><!-- /#footer -->
<div id="subfooter">
</div><!-- /#subfooter -->
</footer>
</body>
</html>
| {
"content_hash": "b44e47d7a9532cfa88dc095ab1e16af7",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 807,
"avg_line_length": 59.72345679012346,
"alnum_prop": 0.7606664461716554,
"repo_name": "Phlow/mo-phlow-de",
"id": "e3ac2741c125e91393828283b532473ca2cdbb74",
"size": "24420",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pedro-segundo/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1172752"
},
{
"name": "JavaScript",
"bytes": "1958"
},
{
"name": "Shell",
"bytes": "1161"
}
],
"symlink_target": ""
} |
/* iCheck plugin Flat skin, blue
----------------------------------- */
.icheckbox_flat-blue,
.iradio_flat-blue {
display: inline-block;
*display: inline;
vertical-align: middle;
margin: 0;
padding: 0;
width: 20px;
height: 20px;
background: url(blue.png) no-repeat;
border: none;
cursor: pointer;
}
.icheckbox_flat-blue {
background-position: 0 0;
}
.icheckbox_flat-blue.checked {
background-position: -22px 0;
}
.icheckbox_flat-blue.disabled {
background-position: -44px 0;
cursor: default;
}
.icheckbox_flat-blue.checked.disabled {
background-position: -66px 0;
}
.iradio_flat-blue {
background-position: -88px 0;
}
.iradio_flat-blue.checked {
background-position: -110px 0;
}
.iradio_flat-blue.disabled {
background-position: -132px 0;
cursor: default;
}
.iradio_flat-blue.checked.disabled {
background-position: -154px 0;
}
| {
"content_hash": "a64012d184d2af4ee1e860d9284991d1",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 43,
"avg_line_length": 22.522727272727273,
"alnum_prop": 0.5893037336024218,
"repo_name": "XuDeveloper/javaBank",
"id": "9cadfca248f0c767db4213757088c461ee3cc3b4",
"size": "991",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebContent/Public/vendors/iCheck/css/flat/blue.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "181528"
},
{
"name": "Java",
"bytes": "169912"
},
{
"name": "JavaScript",
"bytes": "61547"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<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.sonatype.oss</groupId>
<artifactId>oss-parent</artifactId>
<version>7</version>
</parent>
<groupId>net.fortytwo.rdfagents</groupId>
<artifactId>rdfagents-all</artifactId>
<version>1.3</version>
<packaging>pom</packaging>
<name>RDFAgents</name>
<description>Real-time messaging for the Semantic Web</description>
<url>https://github.com/joshsh/rdfagents</url>
<issueManagement>
<url>https://github.com/joshsh/rdfagents/issues</url>
<system>GitHub Issues</system>
</issueManagement>
<licenses>
<license>
<name>The MIT License</name>
<url>http://www.opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<url>git@github.com:joshsh/rdfagents.git</url>
<connection>scm:git:git@github.com:joshsh/rdfagents.git</connection>
<developerConnection>scm:git:git@github.com:joshsh/rdfagents.git</developerConnection>
</scm>
<developers>
<developer>
<name>Joshua Shinavier</name>
<email>josh@fortytwo.net</email>
<id>joshsh</id>
</developer>
</developers>
<properties>
<junit.version>4.12</junit.version>
<ripple.version>1.4</ripple.version>
<sesame.version>4.1.2</sesame.version>
<sesametools.version>1.10</sesametools.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<modules>
<module>rdfagents-core</module>
<module>rdfagents-csparql</module>
<module>rdfagents-demos</module>
<module>rdfagents-jade</module>
</modules>
<build>
<directory>${basedir}/target</directory>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- TODO: restore me after the move to RDF4J
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<version>1.3.1</version>
<executions>
<execution>
<id>enforce-dependency-convergence</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<DependencyConvergence />
</rules>
</configuration>
</execution>
</executions>
</plugin>
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-source</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<id>attach-javadoc</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
<execution>
<id>aggregate</id>
<goals>
<goal>aggregate</goal>
</goals>
<phase>site</phase>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.4</version>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>fortytwo</id>
<name>fortytwo.net Maven repository</name>
<url>http://fortytwo.net/maven2</url>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.fortytwo</groupId>
<artifactId>linked-data-sail</artifactId>
<version>${ripple.version}</version>
<exclusions>
<!-- temporary -->
<exclusion>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-rio-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.openrdf.sesame</groupId>
<artifactId>sesame-model</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.fortytwo.sesametools</groupId>
<artifactId>repository-sail</artifactId>
<version>${sesametools.version}</version>
<exclusions>
<!-- temporary -->
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.tilab.jade</groupId>
<artifactId>jade</artifactId>
<version>jjs-1</version>
<exclusions>
<!-- conflict with Sesame -->
<exclusion>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
</project>
| {
"content_hash": "346d9ef73f7c01d69acafb23eec0cf70",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 105,
"avg_line_length": 38.3411214953271,
"alnum_prop": 0.4521633150517977,
"repo_name": "joshsh/rdfagents",
"id": "2484a360c118ba74735b1d5a75d8a28c9f20d365",
"size": "8205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "194704"
}
],
"symlink_target": ""
} |
<?php
return [
'enter_code' => 'Masukkan kode yang ada digambar',
'incorrect_code' => 'Kode yang dimasukkan tidak valid.',
'update_code' => 'Perbarui',
];
| {
"content_hash": "ba35f417b557607a6403494a8f762bdf",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 60,
"avg_line_length": 25,
"alnum_prop": 0.5942857142857143,
"repo_name": "igoshev/laravel-captcha",
"id": "037bf1a0f970ea6a94def24f7c41dbc26416ca03",
"size": "175",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/resources/lang/vendor/bone/id/captcha.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "21319"
}
],
"symlink_target": ""
} |
from settings import *
import nltk
import sys
import textract
import re
import unicodedata
class Opinion:
def __init__(self, name):
self.name = name
self.total = 0
self.fore = 0
self.against = 0
self.no_opinions = 0
self.ratio_for = 0
self.ratio_against = 0
self.ratio_no_opinions = 0
def finalize(self):
if self.fore > self.total:
self.fore = self.total
if self.against > self.total:
self.against = self.total
if self.total < (self.fore + self.against):
self.total = self.fore + self.against
self.no_opinions = self.total - self.fore - self.against
if self.total != 0 and self.total != self.no_opinions:
self.ratio_for = self.fore / (self.total-self.no_opinions)
self.ratio_against = self.against / (self.total-self.no_opinions)
def parse_project(filename):
text = textract.process(project_directory + filename)
text = text.decode('utf-8')
text = text.strip().lower()
return text
def analyze_subject(candidate, subject):
words_subjects = subjects.get(subject, None)
if not words_subjects:
print("Subject " + subject + " does not exist")
exit()
if not candidate.get('opinions', None):
candidate['opinions'] = {}
candidate['opinions'][subject] = Opinion(subject.title())
sentences = candidate['sentences']
for sentence in sentences:
for token in sentence:
t = unicodedata.normalize('NFD', token).encode('ascii', 'ignore')
libre_echange = subjects[subject]
for word in words_subjects:
reg = re.compile(r".*" + word + ".*")
if re.search(reg, t.decode('utf-8')):
candidate['opinions'][subject].total += 1
for token in sentence:
#Suppression des accents
t2 = unicodedata.normalize('NFD', token).encode('ascii', 'ignore')
for a in againsts:
reg = re.compile(r".*" + a + ".*")
if re.search(reg, t2.decode('utf-8')):
candidate['opinions'][subject].against += 1
for f in fors:
reg = re.compile(r".*" + f + ".*")
if re.search(reg, t2.decode('utf-8')):
candidate['opinions'][subject].fore += 1
candidate['opinions'][subject].finalize()
def tokenize_project(candidate):
sentences = nltk.sent_tokenize(candidate['project'], 'french')
tokens = []
for sentence in sentences:
tokens.append(nltk.word_tokenize(sentence, 'french'))
return tokens
def print_results(candidate):
print('\n'+candidate['name'])
for opinion in candidate['opinions'].values():
print("\n"+opinion.name+" :")
print("Phrases concernées : " + str(opinion.total))
print("Avis pour : " + str(opinion.fore))
print("Avis contre : " + str(opinion.against))
print("Sans avis : " + str(opinion.no_opinions))
print("Indice pour : " + str(opinion.ratio_for))
print("Indice contre : " + str(opinion.ratio_against))
if(opinion.ratio_for>opinion.ratio_against):
print("Pour")
elif(opinion.ratio_against>opinion.ratio_for):
print("Contre")
else:
print("Neutre")
print('\n\n')
if __name__ == '__main__':
print("Analyse des programmes...\n\n")
for candidate in candidates:
candidate['project'] = parse_project(candidate.get('file'))
candidate['sentences'] = tokenize_project(candidate)
for subject in subjects:
analyze_subject(candidate, subject)
print_results(candidate)
subject = input("How about you choose a subject now : ")
subjects[subject] = []
key = input("key words for this subject(separated by ',') : ")
subjects[subject] = key.split(',')
for candidate in candidates:
analyze_subject(candidate, subject)
print_results(candidate)
| {
"content_hash": "2bc895d27ac2bbbb55415b81fa307d51",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 101,
"avg_line_length": 36.67768595041322,
"alnum_prop": 0.5297431275349257,
"repo_name": "zozoh94/PolReview",
"id": "d1628a32c8b27cd5bb9ecb8b89278be3e0f48bfc",
"size": "4477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pol_review.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8930"
},
{
"name": "TeX",
"bytes": "5767"
}
],
"symlink_target": ""
} |
<?php
namespace Unit\LiveTest\TestRun\Helper;
use LiveTest\TestRun\Properties;
use Base\Http\Response\Response;
use LiveTest\TestRun\Result\Result;
use LiveTest\Event\Dispatcher;
use LiveTest\Listener\Listener;
use phmLabs\Components\Annovent\Annotation\Event;
class InfoListener implements Listener
{
private $preRunCalled = false;
private $postRunCalled = false;
private $handleConnectionStatusCalled = false;
public function __construct($runId, Dispatcher $eventDispatcher)
{
}
/**
* @Event("LiveTest.Run.HandleConnectionStatus")
*/
public function handleConnectionStatus()
{
$this->handleConnectionStatusCalled = true;
}
public function isHandleConnectionStatusCalled()
{
return $this->handleConnectionStatusCalled;
}
} | {
"content_hash": "393c50438ff0c91c6eb9c583995faa76",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 66,
"avg_line_length": 22.61764705882353,
"alnum_prop": 0.7633289986996099,
"repo_name": "phmLabs/LiveTest2",
"id": "e9f3ce9c4af954ea9f6fde4cce050d66562660af",
"size": "769",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/Unit/LiveTest/TestRun/Helper/InfoListener.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2911"
},
{
"name": "PHP",
"bytes": "341136"
},
{
"name": "Smarty",
"bytes": "1642"
}
],
"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 (version 1.7.0_51) on Thu Feb 27 18:45:00 CET 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Package at.irian.ankor.fx.binding.cache (Ankor - Project 0.1 API)</title>
<meta name="date" content="2014-02-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package at.irian.ankor.fx.binding.cache (Ankor - Project 0.1 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/fx/binding/cache/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package at.irian.ankor.fx.binding.cache" class="title">Uses of Package<br>at.irian.ankor.fx.binding.cache</h1>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../at/irian/ankor/fx/binding/cache/package-summary.html">at.irian.ankor.fx.binding.cache</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#at.irian.ankor.fx.binding.cache">at.irian.ankor.fx.binding.cache</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="at.irian.ankor.fx.binding.cache">
<!-- -->
</a>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../at/irian/ankor/fx/binding/cache/package-summary.html">at.irian.ankor.fx.binding.cache</a> used by <a href="../../../../../../at/irian/ankor/fx/binding/cache/package-summary.html">at.irian.ankor.fx.binding.cache</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colOne"><a href="../../../../../../at/irian/ankor/fx/binding/cache/class-use/BindingCache.html#at.irian.ankor.fx.binding.cache">BindingCache</a> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><a href="../../../../../../at/irian/ankor/fx/binding/cache/class-use/BindingCache.CacheKey.html#at.irian.ankor.fx.binding.cache">BindingCache.CacheKey</a> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?at/irian/ankor/fx/binding/cache/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2014. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "03cd80ce3bb7f151086681b9430e8f48",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 318,
"avg_line_length": 37.5359477124183,
"alnum_prop": 0.6223228277903535,
"repo_name": "ankor-io/ankor-framework",
"id": "7bc8205bf2a36be55df82e4fe5f9436747b2eb79",
"size": "5743",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable",
"path": "website/ankorsite/static/javadoc/apidocs-0.1/at/irian/ankor/fx/binding/cache/package-use.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "526"
},
{
"name": "C",
"bytes": "12173"
},
{
"name": "C#",
"bytes": "157078"
},
{
"name": "CSS",
"bytes": "10636"
},
{
"name": "CoffeeScript",
"bytes": "48194"
},
{
"name": "HTML",
"bytes": "17806"
},
{
"name": "Java",
"bytes": "751745"
},
{
"name": "JavaScript",
"bytes": "290740"
},
{
"name": "Makefile",
"bytes": "811"
},
{
"name": "Objective-C",
"bytes": "114772"
},
{
"name": "PowerShell",
"bytes": "3261"
},
{
"name": "Python",
"bytes": "17835"
},
{
"name": "Shell",
"bytes": "36"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Mon May 07 18:52:24 PDT 2001 -->
<TITLE>
HTTPClient API: Class Cookie2
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT ID="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">
<A HREF="../HTTPClient/Cookie.html"><B>PREV CLASS</B></A>
<A HREF="../HTTPClient/CookieModule.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="Cookie2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
HTTPClient</FONT>
<BR>
Class Cookie2</H2>
<PRE>
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html">java.lang.Object</A>
|
+--<A HREF="../HTTPClient/Cookie.html">HTTPClient.Cookie</A>
|
+--<B>HTTPClient.Cookie2</B>
</PRE>
<HR>
<DL>
<DT>public class <B>Cookie2</B><DT>extends <A HREF="../HTTPClient/Cookie.html">Cookie</A></DL>
<P>
This class represents an http cookie as specified in the <A
HREF="http://www.ietf.org/rfc/rfc2965.txt">HTTP State Management Mechanism spec</A>
(also known as a version 1 cookie).
<P>
<DL>
<DT><B>Since: </B><DD>V0.3</DD>
<DT><B>Version: </B><DD>0.3-3 06/05/2001</DD>
<DT><B>Author: </B><DD>Ronald Tschalär</DD>
<DT><B>See Also: </B><DD><A HREF="../serialized-form.html#HTTPClient.Cookie2">Serialized Form</A></DL>
<HR>
<P>
<!-- ======== INNER CLASS SUMMARY ======== -->
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="field_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Field Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#comment">comment</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="../HTTPClient/URI.html">URI</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#comment_url">comment_url</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#discard">discard</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#domain_set">domain_set</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#path_set">path_set</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected int[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#port_list">port_list</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="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#port_list_str">port_list_str</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#port_set">port_set</A></B></CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#version">version</A></B></CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="fields_inherited_from_class_HTTPClient.Cookie"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Fields inherited from class HTTPClient.<A HREF="../HTTPClient/Cookie.html">Cookie</A></B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../HTTPClient/Cookie.html#domain">domain</A>,
<A HREF="../HTTPClient/Cookie.html#expires">expires</A>,
<A HREF="../HTTPClient/Cookie.html#name">name</A>,
<A HREF="../HTTPClient/Cookie.html#path">path</A>,
<A HREF="../HTTPClient/Cookie.html#secure">secure</A>,
<A HREF="../HTTPClient/Cookie.html#value">value</A></CODE></TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected </CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#Cookie2(HTTPClient.RoRequest)">Cookie2</A></B>(<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)</CODE>
<BR>
Use <code>parse()</code> to create cookies.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> </CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#Cookie2(java.lang.String, java.lang.String, java.lang.String, int[], java.lang.String, java.util.Date, boolean, boolean, java.lang.String, HTTPClient.URI)">Cookie2</A></B>(<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> name,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> value,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> domain,
int[] port_list,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> path,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/util/Date.html">Date</A> expires,
boolean discard,
boolean secure,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> comment,
<A HREF="../HTTPClient/URI.html">URI</A> comment_url)</CODE>
<BR>
Create a cookie.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Method Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#discard()">discard</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#getComment()">getComment</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../HTTPClient/URI.html">URI</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#getCommentURL()">getCommentURL</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#getPorts()">getPorts</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> int</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#getVersion()">getVersion</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected static <A HREF="../HTTPClient/Cookie.html">Cookie</A>[]</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#parse(java.lang.String, HTTPClient.RoRequest)">parse</A></B>(<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> set_cookie,
<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)</CODE>
<BR>
Parses the Set-Cookie2 header into an array of Cookies.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#sendWith(HTTPClient.RoRequest)">sendWith</A></B>(<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#toExternalForm()">toExternalForm</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../HTTPClient/Cookie2.html#toString()">toString</A></B>()</CODE>
<BR>
Create a string containing all the cookie fields.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_HTTPClient.Cookie"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class HTTPClient.<A HREF="../HTTPClient/Cookie.html">Cookie</A></B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="../HTTPClient/Cookie.html#equals(java.lang.Object)">equals</A>,
<A HREF="../HTTPClient/Cookie.html#expires()">expires</A>,
<A HREF="../HTTPClient/Cookie.html#getDomain()">getDomain</A>,
<A HREF="../HTTPClient/Cookie.html#getName()">getName</A>,
<A HREF="../HTTPClient/Cookie.html#getPath()">getPath</A>,
<A HREF="../HTTPClient/Cookie.html#getValue()">getValue</A>,
<A HREF="../HTTPClient/Cookie.html#hasExpired()">hasExpired</A>,
<A HREF="../HTTPClient/Cookie.html#hashCode()">hashCode</A>,
<A HREF="../HTTPClient/Cookie.html#isSecure()">isSecure</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TD><B>Methods inherited from class java.lang.<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html">Object</A></B></TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#clone()">clone</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#finalize()">finalize</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#getClass()">getClass</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#notify()">notify</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#notifyAll()">notifyAll</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#wait()">wait</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#wait(long)">wait</A>,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/Object.html#wait(long, int)">wait</A></CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<A NAME="field_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Field Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="version"><!-- --></A><H3>
version</H3>
<PRE>
protected int <B>version</B></PRE>
<DL>
</DL>
<HR>
<A NAME="discard"><!-- --></A><H3>
discard</H3>
<PRE>
protected boolean <B>discard</B></PRE>
<DL>
</DL>
<HR>
<A NAME="comment"><!-- --></A><H3>
comment</H3>
<PRE>
protected <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> <B>comment</B></PRE>
<DL>
</DL>
<HR>
<A NAME="comment_url"><!-- --></A><H3>
comment_url</H3>
<PRE>
protected <A HREF="../HTTPClient/URI.html">URI</A> <B>comment_url</B></PRE>
<DL>
</DL>
<HR>
<A NAME="port_list"><!-- --></A><H3>
port_list</H3>
<PRE>
protected int[] <B>port_list</B></PRE>
<DL>
</DL>
<HR>
<A NAME="port_list_str"><!-- --></A><H3>
port_list_str</H3>
<PRE>
protected <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> <B>port_list_str</B></PRE>
<DL>
</DL>
<HR>
<A NAME="path_set"><!-- --></A><H3>
path_set</H3>
<PRE>
protected boolean <B>path_set</B></PRE>
<DL>
</DL>
<HR>
<A NAME="port_set"><!-- --></A><H3>
port_set</H3>
<PRE>
protected boolean <B>port_set</B></PRE>
<DL>
</DL>
<HR>
<A NAME="domain_set"><!-- --></A><H3>
domain_set</H3>
<PRE>
protected boolean <B>domain_set</B></PRE>
<DL>
</DL>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="Cookie2(java.lang.String, java.lang.String, java.lang.String, int[], java.lang.String, java.util.Date, boolean, boolean, java.lang.String, HTTPClient.URI)"><!-- --></A><H3>
Cookie2</H3>
<PRE>
public <B>Cookie2</B>(<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> name,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> value,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> domain,
int[] port_list,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> path,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/util/Date.html">Date</A> expires,
boolean discard,
boolean secure,
<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> comment,
<A HREF="../HTTPClient/URI.html">URI</A> comment_url)</PRE>
<DL>
<DD>Create a cookie.<DD><DL>
<DT><B>Parameters:</B><DD><CODE>name</CODE> - the cookie name<DD><CODE>value</CODE> - the cookie value<DD><CODE>domain</CODE> - the host this cookie will be sent to<DD><CODE>port_list</CODE> - an array of allowed server ports for this cookie,
or null if the the cookie may be sent to any port<DD><CODE>path</CODE> - the path prefix for which this cookie will be sent<DD><CODE>epxires</CODE> - the Date this cookie expires, or null if never<DD><CODE>discard</CODE> - if true then the cookie will be discarded at the
end of the session regardless of expiry<DD><CODE>secure</CODE> - if true this cookie will only be over secure connections<DD><CODE>comment</CODE> - the comment associated with this cookie, or null if none<DD><CODE>comment_url</CODE> - the comment URL associated with this cookie, or null
if none<DT><B>Throws:</B><DD>NullPointerException - if <var>name</var>, <var>value</var>,
<var>domain</var>, or <var>path</var>
is null</DL>
</DD>
</DL>
<HR>
<A NAME="Cookie2(HTTPClient.RoRequest)"><!-- --></A><H3>
Cookie2</H3>
<PRE>
protected <B>Cookie2</B>(<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)</PRE>
<DL>
<DD>Use <code>parse()</code> to create cookies.<DD><DL>
<DT><B>See Also: </B><DD><A HREF="../HTTPClient/Cookie2.html#parse(java.lang.String, HTTPClient.RoRequest)"><CODE>parse(java.lang.String, HTTPClient.RoRequest)</CODE></A></DL>
</DD>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Method Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="parse(java.lang.String, HTTPClient.RoRequest)"><!-- --></A><H3>
parse</H3>
<PRE>
protected static <A HREF="../HTTPClient/Cookie.html">Cookie</A>[] <B>parse</B>(<A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> set_cookie,
<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)
throws <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/net/ProtocolException.html">ProtocolException</A></PRE>
<DL>
<DD>Parses the Set-Cookie2 header into an array of Cookies.<DD><DL>
<DT><B>Parameters:</B><DD><CODE>set_cookie</CODE> - the Set-Cookie2 header received from the server<DD><CODE>req</CODE> - the request used<DT><B>Returns:</B><DD>an array of Cookies as parsed from the Set-Cookie2 header<DT><B>Throws:</B><DD><A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/net/ProtocolException.html">ProtocolException</A> - if an error occurs during parsing</DL>
</DD>
</DL>
<HR>
<A NAME="getVersion()"><!-- --></A><H3>
getVersion</H3>
<PRE>
public int <B>getVersion</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Returns:</B><DD>the version as an int</DL>
</DD>
</DL>
<HR>
<A NAME="getComment()"><!-- --></A><H3>
getComment</H3>
<PRE>
public <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> <B>getComment</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Returns:</B><DD>the comment string, or null if none was set</DL>
</DD>
</DL>
<HR>
<A NAME="getCommentURL()"><!-- --></A><H3>
getCommentURL</H3>
<PRE>
public <A HREF="../HTTPClient/URI.html">URI</A> <B>getCommentURL</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Returns:</B><DD>the comment url</DL>
</DD>
</DL>
<HR>
<A NAME="getPorts()"><!-- --></A><H3>
getPorts</H3>
<PRE>
public int[] <B>getPorts</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Returns:</B><DD>the array of ports</DL>
</DD>
</DL>
<HR>
<A NAME="discard()"><!-- --></A><H3>
discard</H3>
<PRE>
public boolean <B>discard</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><A HREF="../HTTPClient/Cookie.html#discard()">discard</A> in class <A HREF="../HTTPClient/Cookie.html">Cookie</A></DL>
</DD>
<DD><DL>
<DT><B>Returns:</B><DD>true if the cookie should be discarded at the end of the
session; false otherwise</DL>
</DD>
</DL>
<HR>
<A NAME="sendWith(HTTPClient.RoRequest)"><!-- --></A><H3>
sendWith</H3>
<PRE>
protected boolean <B>sendWith</B>(<A HREF="../HTTPClient/RoRequest.html">RoRequest</A> req)</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><A HREF="../HTTPClient/Cookie.html#sendWith(HTTPClient.RoRequest)">sendWith</A> in class <A HREF="../HTTPClient/Cookie.html">Cookie</A></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>req</CODE> - the request to be sent<DT><B>Returns:</B><DD>true if this cookie should be sent with the request</DL>
</DD>
</DL>
<HR>
<A NAME="toExternalForm()"><!-- --></A><H3>
toExternalForm</H3>
<PRE>
protected <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> <B>toExternalForm</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><A HREF="../HTTPClient/Cookie.html#toExternalForm()">toExternalForm</A> in class <A HREF="../HTTPClient/Cookie.html">Cookie</A></DL>
</DD>
<DD><B>Tags copied from class: <A HREF="../HTTPClient/Cookie.html">Cookie</A></B></DD>
<DD><DL>
<DT><B>Returns:</B><DD>a string suitable for sending in a Cookie header.</DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public <A HREF="http://java.sun.com/products/jdk/1.2/docs/api/java/lang/String.html">String</A> <B>toString</B>()</PRE>
<DL>
<DD>Create a string containing all the cookie fields. The format is that
used in the Set-Cookie header.<DD><DL>
<DT><B>Overrides:</B><DD><A HREF="../HTTPClient/Cookie.html#toString()">toString</A> in class <A HREF="../HTTPClient/Cookie.html">Cookie</A></DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT ID="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">
<A HREF="../HTTPClient/Cookie.html"><B>PREV CLASS</B></A>
<A HREF="../HTTPClient/CookieModule.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="Cookie2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | <A HREF="#field_summary">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: <A HREF="#field_detail">FIELD</A> | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "5ce162a05e98dd16fd7edf1db24348b2",
"timestamp": "",
"source": "github",
"line_count": 629,
"max_line_length": 390,
"avg_line_length": 42.24483306836248,
"alnum_prop": 0.6386045461387927,
"repo_name": "unrelatedlabs/java-wemo-bridge",
"id": "50ee2506536121a5bdd32dd261409b8f0313c008",
"size": "26572",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "target/HTTPClient/doc/api/HTTPClient/Cookie2.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1559"
},
{
"name": "Groovy",
"bytes": "1157"
},
{
"name": "HTML",
"bytes": "1316028"
},
{
"name": "Java",
"bytes": "860256"
},
{
"name": "JavaScript",
"bytes": "3237"
},
{
"name": "Makefile",
"bytes": "3715"
},
{
"name": "Perl",
"bytes": "218"
},
{
"name": "Shell",
"bytes": "721"
}
],
"symlink_target": ""
} |
layout: model
title: Financial Indian News Sentiment Analysis (Small)
author: John Snow Labs
name: finclf_indian_news_sentiment
date: 2022-11-10
tags: [en, finance, licensed, classification, sentiment, indian]
task: Text Classification
language: en
edition: Finance NLP 1.0.0
spark_version: 3.0
supported: true
annotator: FinanceClassifierDLModel
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---
## Description
This is a `sm` version of Indian News Sentiment Analysis Text Classifier, which will retrieve if a text is either expression a Positive Emotion or a Negative one.
## Predicted Entities
`POSITIVE`, `NEGATIVE`
{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/finance/models/finclf_indian_news_sentiment_en_1.0.0_3.0_1668058786154.zip){:.button.button-orange.button-orange-trans.arr.button-icon}
## How to use
<div class="tabs-box" markdown="1">
{% include programmingLanguageSelectScalaPythonNLU.html %}
```python
document_assembler = nlp.DocumentAssembler() \
.setInputCol("text") \
.setOutputCol("document")
tokenizer = nlp.Tokenizer() \
.setInputCols(["document"]) \
.setOutputCol("token")
embeddings = nlp.BertEmbeddings.pretrained("bert_embeddings_sec_bert_base","en") \
.setInputCols(["document", "token"]) \
.setOutputCol("embeddings")
sembeddings = nlp.SentenceEmbeddings()\
.setInputCols(["document", "embeddings"]) \
.setOutputCol("sentence_embeddings") \
.setPoolingStrategy("AVERAGE")
classsifierdl = finance.ClassifierDLModel.pretrained("finclf_indian_news_sentiment", "en", "finance/models")\
.setInputCols(["sentence_embeddings"])\
.setOutputCol("label")
bert_clf_pipeline = Pipeline(stages=[document_assembler,
tokenizer,
embeddings,
sembeddings,
classsifierdl])
text = ["Eliminating shadow economy to have positive impact on GDP : Arun Jaitley"]
empty_df = spark.createDataFrame([[""]]).toDF("text")
model = bert_clf_pipeline.fit(empty_df)
res = model.transform(spark.createDataFrame([text]).toDF("text"))
```
</div>
## Results
```bash
+------------------------------------------------------------------------+----------+
|text |result |
+------------------------------------------------------------------------+----------+
|Eliminating shadow economy to have positive impact on GDP : Arun Jaitley|[POSITIVE]|
+------------------------------------------------------------------------+----------+
```
{:.model-param}
## Model Information
{:.table-model}
|---|---|
|Model Name:|finclf_indian_news_sentiment|
|Compatibility:|Finance NLP 1.0.0+|
|License:|Licensed|
|Edition:|Official|
|Input Labels:|[sentence_embeddings]|
|Output Labels:|[label]|
|Language:|en|
|Size:|23.6 MB|
## References
An in-house augmented version of [this dataset](https://www.kaggle.com/datasets/harshrkh/india-financial-news-headlines-sentiments)
## Benchmarking
```bash
precision recall f1-score support
NEGATIVE 0.75 0.78 0.76 21441
POSITIVE 0.73 0.69 0.71 18449
accuracy 0.74 39890
macro avg 0.74 0.74 0.74 39890
weighted avg 0.74 0.74 0.74 39890
```
| {
"content_hash": "4f12ce1e6f9224fdeb5c27be7bc98fa5",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 196,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.5941080196399345,
"repo_name": "JohnSnowLabs/spark-nlp",
"id": "820f404cc0906322ac9d514af7530671995f8a5a",
"size": "3670",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/_posts/gadde5300/2022-11-10-finclf_indian_news_sentiment_en.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "14452"
},
{
"name": "Java",
"bytes": "223289"
},
{
"name": "Makefile",
"bytes": "819"
},
{
"name": "Python",
"bytes": "1694517"
},
{
"name": "Scala",
"bytes": "4116435"
},
{
"name": "Shell",
"bytes": "5286"
}
],
"symlink_target": ""
} |
#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
#include <assert.h> // For assert.
#include <algorithm> // For std::max.
#include "webrtc/base/checks.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/system_wrappers/include/logging.h"
namespace webrtc {
namespace {
const int kDefaultSampleRateKhz = 48;
const int kDefaultPacketSizeMs = 20;
} // namespace
NackTracker::NackTracker(int nack_threshold_packets)
: nack_threshold_packets_(nack_threshold_packets),
sequence_num_last_received_rtp_(0),
timestamp_last_received_rtp_(0),
any_rtp_received_(false),
sequence_num_last_decoded_rtp_(0),
timestamp_last_decoded_rtp_(0),
any_rtp_decoded_(false),
sample_rate_khz_(kDefaultSampleRateKhz),
samples_per_packet_(sample_rate_khz_ * kDefaultPacketSizeMs),
max_nack_list_size_(kNackListSizeLimit) {}
NackTracker::~NackTracker() = default;
NackTracker* NackTracker::Create(int nack_threshold_packets) {
return new NackTracker(nack_threshold_packets);
}
void NackTracker::UpdateSampleRate(int sample_rate_hz) {
assert(sample_rate_hz > 0);
sample_rate_khz_ = sample_rate_hz / 1000;
}
void NackTracker::UpdateLastReceivedPacket(uint16_t sequence_number,
uint32_t timestamp) {
// Just record the value of sequence number and timestamp if this is the
// first packet.
if (!any_rtp_received_) {
sequence_num_last_received_rtp_ = sequence_number;
timestamp_last_received_rtp_ = timestamp;
any_rtp_received_ = true;
// If no packet is decoded, to have a reasonable estimate of time-to-play
// use the given values.
if (!any_rtp_decoded_) {
sequence_num_last_decoded_rtp_ = sequence_number;
timestamp_last_decoded_rtp_ = timestamp;
}
return;
}
if (sequence_number == sequence_num_last_received_rtp_)
return;
// Received RTP should not be in the list.
nack_list_.erase(sequence_number);
// If this is an old sequence number, no more action is required, return.
if (IsNewerSequenceNumber(sequence_num_last_received_rtp_, sequence_number))
return;
UpdateSamplesPerPacket(sequence_number, timestamp);
UpdateList(sequence_number);
sequence_num_last_received_rtp_ = sequence_number;
timestamp_last_received_rtp_ = timestamp;
LimitNackListSize();
}
void NackTracker::UpdateSamplesPerPacket(
uint16_t sequence_number_current_received_rtp,
uint32_t timestamp_current_received_rtp) {
uint32_t timestamp_increase =
timestamp_current_received_rtp - timestamp_last_received_rtp_;
uint16_t sequence_num_increase =
sequence_number_current_received_rtp - sequence_num_last_received_rtp_;
samples_per_packet_ = timestamp_increase / sequence_num_increase;
}
void NackTracker::UpdateList(uint16_t sequence_number_current_received_rtp) {
// Some of the packets which were considered late, now are considered missing.
ChangeFromLateToMissing(sequence_number_current_received_rtp);
if (IsNewerSequenceNumber(sequence_number_current_received_rtp,
sequence_num_last_received_rtp_ + 1))
AddToList(sequence_number_current_received_rtp);
}
void NackTracker::ChangeFromLateToMissing(
uint16_t sequence_number_current_received_rtp) {
NackList::const_iterator lower_bound =
nack_list_.lower_bound(static_cast<uint16_t>(
sequence_number_current_received_rtp - nack_threshold_packets_));
for (NackList::iterator it = nack_list_.begin(); it != lower_bound; ++it)
it->second.is_missing = true;
}
uint32_t NackTracker::EstimateTimestamp(uint16_t sequence_num) {
uint16_t sequence_num_diff = sequence_num - sequence_num_last_received_rtp_;
return sequence_num_diff * samples_per_packet_ + timestamp_last_received_rtp_;
}
void NackTracker::AddToList(uint16_t sequence_number_current_received_rtp) {
assert(!any_rtp_decoded_ ||
IsNewerSequenceNumber(sequence_number_current_received_rtp,
sequence_num_last_decoded_rtp_));
// Packets with sequence numbers older than |upper_bound_missing| are
// considered missing, and the rest are considered late.
uint16_t upper_bound_missing =
sequence_number_current_received_rtp - nack_threshold_packets_;
for (uint16_t n = sequence_num_last_received_rtp_ + 1;
IsNewerSequenceNumber(sequence_number_current_received_rtp, n); ++n) {
bool is_missing = IsNewerSequenceNumber(upper_bound_missing, n);
uint32_t timestamp = EstimateTimestamp(n);
NackElement nack_element(TimeToPlay(timestamp), timestamp, is_missing);
nack_list_.insert(nack_list_.end(), std::make_pair(n, nack_element));
}
}
void NackTracker::UpdateEstimatedPlayoutTimeBy10ms() {
while (!nack_list_.empty() &&
nack_list_.begin()->second.time_to_play_ms <= 10)
nack_list_.erase(nack_list_.begin());
for (NackList::iterator it = nack_list_.begin(); it != nack_list_.end(); ++it)
it->second.time_to_play_ms -= 10;
}
void NackTracker::UpdateLastDecodedPacket(uint16_t sequence_number,
uint32_t timestamp) {
if (IsNewerSequenceNumber(sequence_number, sequence_num_last_decoded_rtp_) ||
!any_rtp_decoded_) {
sequence_num_last_decoded_rtp_ = sequence_number;
timestamp_last_decoded_rtp_ = timestamp;
// Packets in the list with sequence numbers less than the
// sequence number of the decoded RTP should be removed from the lists.
// They will be discarded by the jitter buffer if they arrive.
nack_list_.erase(nack_list_.begin(),
nack_list_.upper_bound(sequence_num_last_decoded_rtp_));
// Update estimated time-to-play.
for (NackList::iterator it = nack_list_.begin(); it != nack_list_.end();
++it)
it->second.time_to_play_ms = TimeToPlay(it->second.estimated_timestamp);
} else {
assert(sequence_number == sequence_num_last_decoded_rtp_);
// Same sequence number as before. 10 ms is elapsed, update estimations for
// time-to-play.
UpdateEstimatedPlayoutTimeBy10ms();
// Update timestamp for better estimate of time-to-play, for packets which
// are added to NACK list later on.
timestamp_last_decoded_rtp_ += sample_rate_khz_ * 10;
}
any_rtp_decoded_ = true;
}
NackTracker::NackList NackTracker::GetNackList() const {
return nack_list_;
}
void NackTracker::Reset() {
nack_list_.clear();
sequence_num_last_received_rtp_ = 0;
timestamp_last_received_rtp_ = 0;
any_rtp_received_ = false;
sequence_num_last_decoded_rtp_ = 0;
timestamp_last_decoded_rtp_ = 0;
any_rtp_decoded_ = false;
sample_rate_khz_ = kDefaultSampleRateKhz;
samples_per_packet_ = sample_rate_khz_ * kDefaultPacketSizeMs;
}
void NackTracker::SetMaxNackListSize(size_t max_nack_list_size) {
RTC_CHECK_GT(max_nack_list_size, 0u);
// Ugly hack to get around the problem of passing static consts by reference.
const size_t kNackListSizeLimitLocal = NackTracker::kNackListSizeLimit;
RTC_CHECK_LE(max_nack_list_size, kNackListSizeLimitLocal);
max_nack_list_size_ = max_nack_list_size;
LimitNackListSize();
}
void NackTracker::LimitNackListSize() {
uint16_t limit = sequence_num_last_received_rtp_ -
static_cast<uint16_t>(max_nack_list_size_) - 1;
nack_list_.erase(nack_list_.begin(), nack_list_.upper_bound(limit));
}
int64_t NackTracker::TimeToPlay(uint32_t timestamp) const {
uint32_t timestamp_increase = timestamp - timestamp_last_decoded_rtp_;
return timestamp_increase / sample_rate_khz_;
}
// We don't erase elements with time-to-play shorter than round-trip-time.
std::vector<uint16_t> NackTracker::GetNackList(
int64_t round_trip_time_ms) const {
RTC_DCHECK_GE(round_trip_time_ms, 0);
std::vector<uint16_t> sequence_numbers;
for (NackList::const_iterator it = nack_list_.begin(); it != nack_list_.end();
++it) {
if (it->second.is_missing &&
it->second.time_to_play_ms > round_trip_time_ms)
sequence_numbers.push_back(it->first);
}
return sequence_numbers;
}
} // namespace webrtc
| {
"content_hash": "c0ffa8957703a1312b1f22d39469f2ee",
"timestamp": "",
"source": "github",
"line_count": 225,
"max_line_length": 80,
"avg_line_length": 36.035555555555554,
"alnum_prop": 0.6974592994573261,
"repo_name": "jchavanton/webrtc",
"id": "62cb2ec958af6b355bfb76325c101451988d5bfd",
"size": "8520",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "modules/audio_coding/neteq/nack_tracker.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "22469"
},
{
"name": "C",
"bytes": "3436867"
},
{
"name": "C++",
"bytes": "23454213"
},
{
"name": "Java",
"bytes": "538571"
},
{
"name": "Matlab",
"bytes": "42078"
},
{
"name": "Objective-C",
"bytes": "150376"
},
{
"name": "Objective-C++",
"bytes": "409009"
},
{
"name": "Protocol Buffer",
"bytes": "12040"
},
{
"name": "Python",
"bytes": "263107"
},
{
"name": "Ruby",
"bytes": "846"
},
{
"name": "Shell",
"bytes": "86389"
}
],
"symlink_target": ""
} |
var pad;
pad = require('./index');
module.exports = function(string, size, options) {
if (options == null) {
options = {};
}
if (typeof options === 'string') {
options = {
char: options
};
}
options.colors = true;
return pad(string, size, options);
};
| {
"content_hash": "533251333aad91c99c1444ec6c17110c",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 50,
"avg_line_length": 17.75,
"alnum_prop": 0.5669014084507042,
"repo_name": "adnanmuhammad/centosnodeoracle",
"id": "2a236a52422440dc71e09ea36af04081849f1663",
"size": "320",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "myapp/node_modules/pad/lib/colors.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "65580"
},
{
"name": "Shell",
"bytes": "113"
}
],
"symlink_target": ""
} |
package com.aspose.cloud.sdk.tasks.model;
import com.aspose.cloud.sdk.common.BaseResponse;
import com.google.gson.annotations.SerializedName;
/**
* Created by muhammadsohailismail on 5/18/15.
*/
public class AddAssignmentToProjectResponse extends BaseResponse {
@SerializedName("AssignmentItem")
public AssignmentItemModel assignmentItem;
@SerializedName("Message")
public String message;
}
| {
"content_hash": "4ece5b068804e134b3fb010d0c1de6de",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 66,
"avg_line_length": 29.357142857142858,
"alnum_prop": 0.7834549878345499,
"repo_name": "asposeforcloud/Aspose_Cloud_SDK_For_Android",
"id": "21959af9cff00e6b6adc6f1c38ea1873f436bc4d",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "asposecloudsdk/src/main/java/com/aspose/cloud/sdk/tasks/model/AddAssignmentToProjectResponse.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1039150"
}
],
"symlink_target": ""
} |
package org.apache.servicecomb.demo.discovery.server;
import org.apache.servicecomb.springboot.starter.provider.EnableServiceComb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableServiceComb
public class DiscoveryServer {
public static void main(String[] args) throws Exception {
SpringApplication.run(DiscoveryServer.class, args);
}
}
| {
"content_hash": "0b30e37381d8a014c09ccb871c565697",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 76,
"avg_line_length": 30,
"alnum_prop": 0.8311111111111111,
"repo_name": "acsukesh/java-chassis",
"id": "2792e995af26d3f6e4daa759c96cdb0e6c0bae7a",
"size": "1251",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "demo/demo-spring-boot-discovery/demo-spring-boot-discovery-server/src/main/java/org/apache/servicecomb/demo/discovery/server/DiscoveryServer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4087039"
},
{
"name": "Python",
"bytes": "2636"
},
{
"name": "Shell",
"bytes": "2835"
}
],
"symlink_target": ""
} |
<?php
/**
*
* @author Thomas Rabaix <thomas.rabaix@gmail.com>
*
* SVN : $Id$
**/
class swValidatorBlackListWords extends sfValidatorString
{
protected function configure($options = array(), $messages = array())
{
parent::configure($options, $messages);
$this->addOption('black_list_words', array());
$this->addOption('black_list_files', array());
$this->addMessage('black_listed_word', 'The field contains invalid word');
}
public function doClean($value)
{
$value = parent::doClean($value);
$black_listes_words = $this->getBlackListedWords();
$words = explode(' ', $value);
$words = array_unique($words);
$words = array_map(array($this, 'cleanWord'), $words);
$diff = array_intersect($words, $black_listes_words);
if(count($diff) > 0)
{
throw new sfValidatorError($this, 'black_listed_word', array('value' => $value));
}
return $value;
}
public function getBlackListedWords()
{
$words = $this->getOption('black_list_words');
foreach($this->getOption('black_list_files') as $file)
{
if(!is_readable($file))
{
throw new RuntimeException('The file is not present');
}
$words = array_merge($words, file($file));
}
// clean up words
$words = array_unique($words);
$words = array_map(array($this, 'cleanWord'), $words);
return $words;
}
public function cleanWord($word)
{
return strtolower(trim($word));
}
}
| {
"content_hash": "233b7aac5da39f8f786c40243062e7e8",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 87,
"avg_line_length": 21.442857142857143,
"alnum_prop": 0.603597601598934,
"repo_name": "rande/swFormExtraPlugin",
"id": "e856aee15711a1dd89529f0fc3d01bc6f8a06d36",
"size": "1750",
"binary": false,
"copies": "1",
"ref": "refs/heads/sf1.3",
"path": "lib/validators/swValidatorBlackListWords.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "140330"
},
{
"name": "PHP",
"bytes": "88476"
}
],
"symlink_target": ""
} |
using Parse.Core.Internal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Parse.Common.Internal;
namespace Parse {
/// <summary>
/// A common base class for ParseRelations.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class ParseRelationBase : IJsonConvertible {
#if UNITY
private static readonly bool isCompiledByIL2CPP = AppDomain.CurrentDomain.FriendlyName.Equals("IL2CPP Root Domain");
#else
private static readonly bool isCompiledByIL2CPP = false;
#endif
private ParseObject parent;
private string key;
private string targetClassName;
internal ParseRelationBase(ParseObject parent, string key) {
EnsureParentAndKey(parent, key);
}
internal ParseRelationBase(ParseObject parent, string key, string targetClassName)
: this(parent, key) {
this.targetClassName = targetClassName;
}
internal static IObjectSubclassingController SubclassingController {
get {
return ParseCorePlugins.Instance.SubclassingController;
}
}
internal void EnsureParentAndKey(ParseObject parent, string key) {
this.parent = this.parent ?? parent;
this.key = this.key ?? key;
Debug.Assert(this.parent == parent, "Relation retrieved from two different objects");
Debug.Assert(this.key == key, "Relation retrieved from two different keys");
}
internal void Add(ParseObject obj) {
var change = new ParseRelationOperation(new[] { obj }, null);
parent.PerformOperation(key, change);
targetClassName = change.TargetClassName;
}
internal void Remove(ParseObject obj) {
var change = new ParseRelationOperation(null, new[] { obj });
parent.PerformOperation(key, change);
targetClassName = change.TargetClassName;
}
IDictionary<string, object> IJsonConvertible.ToJSON() {
return new Dictionary<string, object> {
{"__type", "Relation"},
{"className", targetClassName}
};
}
internal ParseQuery<T> GetQuery<T>() where T : ParseObject {
if (targetClassName != null) {
return new ParseQuery<T>(targetClassName)
.WhereRelatedTo(parent, key);
}
return new ParseQuery<T>(parent.ClassName)
.RedirectClassName(key)
.WhereRelatedTo(parent, key);
}
internal string TargetClassName {
get {
return targetClassName;
}
set {
targetClassName = value;
}
}
/// <summary>
/// Produces the proper ParseRelation<T> instance for the given classname.
/// </summary>
internal static ParseRelationBase CreateRelation(ParseObject parent,
string key,
string targetClassName) {
// `Expression` is unstable in IL2CPP environment. Let's call the method directly!
#if UNITY
if (isCompiledByIL2CPP) {
return CreateRelation<ParseObject>(parent, key, targetClassName);
}
#endif
var targetType = SubclassingController.GetType(targetClassName) ?? typeof(ParseObject);
Expression<Func<ParseRelation<ParseObject>>> createRelationExpr =
() => CreateRelation<ParseObject>(parent, key, targetClassName);
var createRelationMethod =
((MethodCallExpression)createRelationExpr.Body)
.Method
.GetGenericMethodDefinition()
.MakeGenericMethod(targetType);
return (ParseRelationBase)createRelationMethod.Invoke(null, new object[] { parent, key, targetClassName });
}
private static ParseRelation<T> CreateRelation<T>(ParseObject parent, string key, string targetClassName)
where T : ParseObject {
return new ParseRelation<T>(parent, key, targetClassName);
}
}
/// <summary>
/// Provides access to all of the children of a many-to-many relationship. Each instance of
/// ParseRelation is associated with a particular parent and key.
/// </summary>
/// <typeparam name="T">The type of the child objects.</typeparam>
public sealed class ParseRelation<T> : ParseRelationBase where T : ParseObject {
internal ParseRelation(ParseObject parent, string key) : base(parent, key) { }
internal ParseRelation(ParseObject parent, string key, string targetClassName)
: base(parent, key, targetClassName) { }
/// <summary>
/// Adds an object to this relation. The object must already have been saved.
/// </summary>
/// <param name="obj">The object to add.</param>
public void Add(T obj) {
base.Add(obj);
}
/// <summary>
/// Removes an object from this relation. The object must already have been saved.
/// </summary>
/// <param name="obj">The object to remove.</param>
public void Remove(T obj) {
base.Remove(obj);
}
/// <summary>
/// Gets a query that can be used to query the objects in this relation.
/// </summary>
public ParseQuery<T> Query {
get {
return base.GetQuery<T>();
}
}
}
}
| {
"content_hash": "4ccf37cdb4a62c0c3b4ea57c53454c52",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 120,
"avg_line_length": 33.57324840764331,
"alnum_prop": 0.6562322140011383,
"repo_name": "AmeliaMesdag/Parse-SDK-dotNET",
"id": "2bdef0323facbd54cd95047cf5cb907403393f2a",
"size": "5558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ParseCore/Public/ParseRelation.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "1004636"
},
{
"name": "Java",
"bytes": "26623"
},
{
"name": "Visual Basic",
"bytes": "36080"
}
],
"symlink_target": ""
} |
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require "rails/test_help"
Rails.backtrace_cleaner.remove_silencers!
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
end
| {
"content_hash": "f4fa7b861e4d05d7e88832892c43f96d",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 71,
"avg_line_length": 27.363636363636363,
"alnum_prop": 0.6976744186046512,
"repo_name": "zohararad/coffeekupper",
"id": "5c0c38e5c9551f3a986aea9315090eafcdfd3a20",
"size": "301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Ruby",
"bytes": "18669"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Testing;
namespace Microsoft.AspNetCore.Mvc.Core;
/// <summary>
/// Test the TextBox extensions in <see cref="HtmlHelperInputExtensions" /> class.
/// </summary>
public class HtmlHelperTextBoxExtensionsTest
{
[Fact]
public void TextBox_UsesSpecifiedExpression()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var textBoxResult = helper.TextBox("Property1");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxResult));
}
[Fact]
public void TextBoxFor_UsesSpecifiedExpression()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var textBoxForResult = helper.TextBoxFor(m => m.Property1);
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxForResult));
}
[Fact]
public void TextBox_UsesSpecifiedValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var textBoxResult = helper.TextBox("Property1", value: "myvalue");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[myvalue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxResult));
}
[Fact]
public void TextBox_UsesSpecifiedFormat()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var textBoxResult = helper.TextBox("Property1", value: null, format: "prefix: {0}");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[prefix: propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxResult));
}
[Fact]
public void TextBox_UsesSpecifiedFormatOverridesPropertyValue()
{
// Arrange
var metadataProvider = new EmptyModelMetadataProvider();
var helper = DefaultTemplatesUtilities.GetHtmlHelper(new ViewDataDictionary<TestModel>(metadataProvider));
helper.ViewContext.ClientValidationEnabled = false;
helper.ViewData.Model = new TestModel { Property1 = "propValue" };
// Act
var textBoxResult = helper.TextBox("Property1", value: "myvalue", format: "prefix: {0}");
// Assert
Assert.Equal(
"<input id=\"HtmlEncode[[Property1]]\" name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[prefix: myvalue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxResult));
}
[Fact]
public void TextBox_UsesSpecifiedHtmlAttributes()
{
// Arrange
var htmlAttributes = new
{
attr = "value",
name = "-expression-", // overridden
};
var model = new TestModel
{
Property1 = "propValue"
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
helper.ViewContext.ClientValidationEnabled = false;
// Act
var textBoxResult = helper.TextBox("Property1", "myvalue", htmlAttributes);
// Assert
Assert.Equal(
"<input attr=\"HtmlEncode[[value]]\" id=\"HtmlEncode[[Property1]]\" " +
"name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[myvalue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxResult));
}
[Fact]
public void TextBoxFor_UsesSpecifiedHtmlAttributes()
{
// Arrange
var htmlAttributes = new
{
attr = "value",
name = "-expression-", // overridden
};
var model = new TestModel
{
Property1 = "propValue"
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper(model);
helper.ViewContext.ClientValidationEnabled = false;
// Act
var textBoxForResult = helper.TextBoxFor(m => m.Property1, htmlAttributes);
// Assert
Assert.Equal(
"<input attr=\"HtmlEncode[[value]]\" id=\"HtmlEncode[[Property1]]\" " +
"name=\"HtmlEncode[[Property1]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxForResult));
}
[Fact]
public void TextBoxFor_Throws_IfFullNameEmpty()
{
// Arrange
var expectedMessage = "The name of an HTML field cannot be null or empty. Instead use methods " +
"Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper.Editor or Microsoft.AspNetCore.Mvc.Rendering." +
"IHtmlHelper`1.EditorFor with a non-empty htmlFieldName argument value.";
var htmlAttributes = new
{
attr = "value",
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper("propValue");
helper.ViewContext.ClientValidationEnabled = false;
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => helper.TextBoxFor(m => m, htmlAttributes),
paramName: "expression",
exceptionMessage: expectedMessage);
}
[Fact]
public void TextBoxFor_DoesNotThrow_IfFullNameEmpty_WithNameAttribute()
{
// Arrange
var htmlAttributes = new
{
attr = "value",
name = "-expression-",
};
var helper = DefaultTemplatesUtilities.GetHtmlHelper("propValue");
helper.ViewContext.ClientValidationEnabled = false;
// Act
var textBoxForResult = helper.TextBoxFor(m => m, htmlAttributes);
// Assert
Assert.Equal(
"<input attr=\"HtmlEncode[[value]]\" " +
"name=\"HtmlEncode[[-expression-]]\" type=\"HtmlEncode[[text]]\" value=\"HtmlEncode[[propValue]]\" />",
HtmlContentUtilities.HtmlContentToString(textBoxForResult));
}
private class TestModel
{
public string Property1 { get; set; }
}
}
| {
"content_hash": "593338f6b8d731fe7ff03f1d1b3fb3c5",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 158,
"avg_line_length": 36.490566037735846,
"alnum_prop": 0.6336608066184074,
"repo_name": "aspnet/AspNetCore",
"id": "fab8359e187b6305f615bf9e063a57cbb4896049",
"size": "7738",
"binary": false,
"copies": "1",
"ref": "refs/heads/darc-main-3ce916a7-9d9b-4849-8f14-6703adcb3cb2",
"path": "src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperTextBoxExtensionsTest.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "109"
},
{
"name": "Batchfile",
"bytes": "19526"
},
{
"name": "C",
"bytes": "213916"
},
{
"name": "C#",
"bytes": "47455169"
},
{
"name": "C++",
"bytes": "1900454"
},
{
"name": "CMake",
"bytes": "7955"
},
{
"name": "CSS",
"bytes": "62326"
},
{
"name": "Dockerfile",
"bytes": "3584"
},
{
"name": "F#",
"bytes": "7982"
},
{
"name": "Groovy",
"bytes": "1529"
},
{
"name": "HTML",
"bytes": "1130653"
},
{
"name": "Java",
"bytes": "297552"
},
{
"name": "JavaScript",
"bytes": "2726829"
},
{
"name": "Lua",
"bytes": "4904"
},
{
"name": "Makefile",
"bytes": "220"
},
{
"name": "Objective-C",
"bytes": "222"
},
{
"name": "PowerShell",
"bytes": "241706"
},
{
"name": "Python",
"bytes": "19476"
},
{
"name": "Roff",
"bytes": "6044"
},
{
"name": "Shell",
"bytes": "142293"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "797435"
}
],
"symlink_target": ""
} |
#include "v_statusCondition.h"
#include "v_public.h"
#include "v__observer.h"
#include "v__observable.h"
#include "v__entity.h"
#include "v__status.h"
#include "os_report.h"
v_statusCondition
v_statusConditionNew(
v_entity entity)
{
v_statusCondition _this = NULL;
v_kernel kernel;
if (entity) {
kernel = v_objectKernel(v_object(entity));
_this = v_statusCondition(v_objectNew(kernel,K_STATUSCONDITION));
if (_this != NULL) {
v_observerInit(v_observer(_this));
OSPL_ADD_OBSERVER(entity, _this, V_EVENTMASK_ALL, NULL);
_this->entity = v_publicHandle(v_public(entity));
}
}
return _this;
}
void
v_statusConditionFree(
v_statusCondition _this)
{
v_observable obs;
v_handleResult result;
assert(_this != NULL);
assert(C_TYPECHECK(_this,v_statusCondition));
result = v_handleClaim(_this->entity, (v_object *)&obs);
if (result == V_HANDLE_OK) {
(void)OSPL_REMOVE_OBSERVER(obs, _this, V_EVENTMASK_ALL, NULL);
(void)v_handleRelease(_this->entity);
}
v_observerFree(v_observer(_this));
}
void
v_statusConditionDeinit(
v_statusCondition _this)
{
assert(_this != NULL);
assert(C_TYPECHECK(_this,v_statusCondition));
v_observerDeinit(v_observer(_this));
}
void
v_statusConditionSetMask(
v_statusCondition _this,
v_eventMask mask)
{
v_handleResult result;
v_entity entity;
assert(_this != NULL);
assert(C_TYPECHECK(_this,v_statusCondition));
OSPL_SET_EVENT_MASK(_this, mask);
result = v_handleClaim(_this->entity, (v_object *)&entity);
if (result == V_HANDLE_OK) {
C_STRUCT(v_event) event;
event.kind = v_entityGetTriggerValue(entity);
event.source = v_observable(entity);
event.data = NULL;
v_observerNotify(v_observer(_this), &event, NULL);
(void)v_handleRelease(_this->entity);
}
}
v_eventMask
v_statusConditionGetTriggerValue (
v_statusCondition _this)
{
v_handleResult result;
v_entity entity;
v_eventMask triggerValue = 0;
assert(_this != NULL);
assert(C_TYPECHECK(_this,v_statusCondition));
result = v_handleClaim(_this->entity, (v_object *)&entity);
if (result == V_HANDLE_OK) {
triggerValue = v_entityGetTriggerValue(entity);
triggerValue &= v_observerGetEventMask(v_observer(_this));
(void)v_handleRelease(_this->entity);
}
return triggerValue;
}
| {
"content_hash": "5bb8931df739a4133191ec3b4b828cf0",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 73,
"avg_line_length": 24.7,
"alnum_prop": 0.6356275303643725,
"repo_name": "osrf/opensplice",
"id": "92c7ccd88c1165da6f29d9fed6c4a8935c776fdc",
"size": "3268",
"binary": false,
"copies": "2",
"ref": "refs/heads/osrf-6.9.0",
"path": "src/kernel/code/v_statusCondition.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "16400"
},
{
"name": "Batchfile",
"bytes": "192174"
},
{
"name": "C",
"bytes": "19618578"
},
{
"name": "C#",
"bytes": "2428591"
},
{
"name": "C++",
"bytes": "8036199"
},
{
"name": "CMake",
"bytes": "35186"
},
{
"name": "CSS",
"bytes": "41427"
},
{
"name": "HTML",
"bytes": "457045"
},
{
"name": "Java",
"bytes": "5184488"
},
{
"name": "JavaScript",
"bytes": "540355"
},
{
"name": "LLVM",
"bytes": "13059"
},
{
"name": "Lex",
"bytes": "51476"
},
{
"name": "Makefile",
"bytes": "513684"
},
{
"name": "Objective-C",
"bytes": "38424"
},
{
"name": "Perl",
"bytes": "164028"
},
{
"name": "Python",
"bytes": "915683"
},
{
"name": "Shell",
"bytes": "363583"
},
{
"name": "TeX",
"bytes": "8134"
},
{
"name": "Visual Basic",
"bytes": "290"
},
{
"name": "Yacc",
"bytes": "202848"
}
],
"symlink_target": ""
} |
package com.github.xxbeanxx.cxf;
import java.io.IOException;
import javax.jws.WebService;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
/**
* @author Greg Baker
*/
@WebService(endpointInterface = "com.github.xxbeanxx.cxf.RequestService")
public class RequestServiceImpl implements RequestService {
@Override
public String handleRequest() {
return "SUCCESS";
}
public class UTPasswordCallback implements CallbackHandler {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
}
}
}
| {
"content_hash": "3fa23df0f574352a50eb3841a3506243",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 93,
"avg_line_length": 22.6,
"alnum_prop": 0.7861356932153393,
"repo_name": "xxbeanxx/spring-cxf",
"id": "5911d42b339a699d75f8c91a175e30dbba858d1f",
"size": "678",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/github/xxbeanxx/cxf/RequestServiceImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "21893"
}
],
"symlink_target": ""
} |
package javax.management.relation;
import static com.sun.jmx.defaults.JmxProperties.RELATION_LOGGER;
import static com.sun.jmx.mbeanserver.Util.cast;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import javax.management.Attribute;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanException;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
/**
* The Relation Service is in charge of creating and deleting relation types
* and relations, of handling the consistency and of providing query
* mechanisms.
* <P>It implements the NotificationBroadcaster by extending
* NotificationBroadcasterSupport to send notifications when a relation is
* removed from it.
* <P>It implements the NotificationListener interface to be able to receive
* notifications concerning unregistration of MBeans referenced in relation
* roles and of relation MBeans.
* <P>It implements the MBeanRegistration interface to be able to retrieve
* its ObjectName and MBean Server.
*
* @since 1.5
*/
public class RelationService extends NotificationBroadcasterSupport
implements RelationServiceMBean, MBeanRegistration, NotificationListener {
//
// Private members
//
// Map associating:
// <relation id> -> <RelationSupport object/ObjectName>
// depending if the relation has been created using createRelation()
// method (so internally handled) or is an MBean added as a relation by the
// user
private Map<String,Object> myRelId2ObjMap = new HashMap<String,Object>();
// Map associating:
// <relation id> -> <relation type name>
private Map<String,String> myRelId2RelTypeMap = new HashMap<String,String>();
// Map associating:
// <relation MBean Object Name> -> <relation id>
private Map<ObjectName,String> myRelMBeanObjName2RelIdMap =
new HashMap<ObjectName,String>();
// Map associating:
// <relation type name> -> <RelationType object>
private Map<String,RelationType> myRelType2ObjMap =
new HashMap<String,RelationType>();
// Map associating:
// <relation type name> -> ArrayList of <relation id>
// to list all the relations of a given type
private Map<String,List<String>> myRelType2RelIdsMap =
new HashMap<String,List<String>>();
// Map associating:
// <ObjectName> -> HashMap
// the value HashMap mapping:
// <relation id> -> ArrayList of <role name>
// to track where a given MBean is referenced.
private final Map<ObjectName,Map<String,List<String>>>
myRefedMBeanObjName2RelIdsMap =
new HashMap<ObjectName,Map<String,List<String>>>();
// Flag to indicate if, when a notification is received for the
// unregistration of an MBean referenced in a relation, if an immediate
// "purge" of the relations (look for the relations no
// longer valid) has to be performed , or if that will be performed only
// when the purgeRelations method will be explicitly called.
// true is immediate purge.
private boolean myPurgeFlag = true;
// Internal counter to provide sequence numbers for notifications sent by:
// - the Relation Service
// - a relation handled by the Relation Service
private final AtomicLong atomicSeqNo = new AtomicLong();
// ObjectName used to register the Relation Service in the MBean Server
private ObjectName myObjName = null;
// MBean Server where the Relation Service is registered
private MBeanServer myMBeanServer = null;
// Filter registered in the MBean Server with the Relation Service to be
// informed of referenced MBean unregistrations
private MBeanServerNotificationFilter myUnregNtfFilter = null;
// List of unregistration notifications received (storage used if purge
// of relations when unregistering a referenced MBean is not immediate but
// on user request)
private List<MBeanServerNotification> myUnregNtfList =
new ArrayList<MBeanServerNotification>();
//
// Constructor
//
/**
* Constructor.
*
* @param immediatePurgeFlag flag to indicate when a notification is
* received for the unregistration of an MBean referenced in a relation, if
* an immediate "purge" of the relations (look for the relations no
* longer valid) has to be performed , or if that will be performed only
* when the purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*/
public RelationService(boolean immediatePurgeFlag) {
RELATION_LOGGER.entering(RelationService.class.getName(),
"RelationService");
setPurgeFlag(immediatePurgeFlag);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"RelationService");
return;
}
/**
* Checks if the Relation Service is active.
* Current condition is that the Relation Service must be registered in the
* MBean Server
*
* @exception RelationServiceNotRegisteredException if it is not
* registered
*/
public void isActive()
throws RelationServiceNotRegisteredException {
if (myMBeanServer == null) {
// MBean Server not set by preRegister(): relation service not
// registered
String excMsg =
"Relation Service not registered in the MBean Server.";
throw new RelationServiceNotRegisteredException(excMsg);
}
return;
}
//
// MBeanRegistration interface
//
// Pre-registration: retrieves its ObjectName and MBean Server
//
// No exception thrown.
public ObjectName preRegister(MBeanServer server,
ObjectName name)
throws Exception {
myMBeanServer = server;
myObjName = name;
return name;
}
// Post-registration: does nothing
public void postRegister(Boolean registrationDone) {
return;
}
// Pre-unregistration: does nothing
public void preDeregister()
throws Exception {
return;
}
// Post-unregistration: does nothing
public void postDeregister() {
return;
}
//
// Accessors
//
/**
* Returns the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed , or if that will be performed only when the
* purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*
* @return true if purges are automatic.
*
* @see #setPurgeFlag
*/
public boolean getPurgeFlag() {
return myPurgeFlag;
}
/**
* Sets the flag to indicate if when a notification is received for the
* unregistration of an MBean referenced in a relation, if an immediate
* "purge" of the relations (look for the relations no longer valid)
* has to be performed , or if that will be performed only when the
* purgeRelations method will be explicitly called.
* <P>true is immediate purge.
*
* @param purgeFlag flag
*
* @see #getPurgeFlag
*/
public void setPurgeFlag(boolean purgeFlag) {
myPurgeFlag = purgeFlag;
return;
}
//
// Relation type handling
//
/**
* Creates a relation type (a RelationTypeSupport object) with given
* role infos (provided by the RoleInfo objects), and adds it in the
* Relation Service.
*
* @param relationTypeName name of the relation type
* @param roleInfoArray array of role infos
*
* @exception IllegalArgumentException if null parameter
* @exception InvalidRelationTypeException If:
* <P>- there is already a relation type with that name
* <P>- the same name has been used for two different role infos
* <P>- no role info provided
* <P>- one null role info provided
*/
public void createRelationType(String relationTypeName,
RoleInfo[] roleInfoArray)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeName == null || roleInfoArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"createRelationType", relationTypeName);
// Can throw an InvalidRelationTypeException
RelationType relType =
new RelationTypeSupport(relationTypeName, roleInfoArray);
addRelationTypeInt(relType);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"createRelationType");
return;
}
/**
* Adds given object as a relation type. The object is expected to
* implement the RelationType interface.
*
* @param relationTypeObj relation type object (implementing the
* RelationType interface)
*
* @exception IllegalArgumentException if null parameter or if
* {@link RelationType#getRelationTypeName
* relationTypeObj.getRelationTypeName()} returns null.
* @exception InvalidRelationTypeException if:
* <P>- the same name has been used for two different roles
* <P>- no role info provided
* <P>- one null role info provided
* <P>- there is already a relation type with that name
*/
public void addRelationType(RelationType relationTypeObj)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeObj == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationType");
// Checks the role infos
List<RoleInfo> roleInfoList = relationTypeObj.getRoleInfos();
if (roleInfoList == null) {
String excMsg = "No role info provided.";
throw new InvalidRelationTypeException(excMsg);
}
RoleInfo[] roleInfoArray = new RoleInfo[roleInfoList.size()];
int i = 0;
for (RoleInfo currRoleInfo : roleInfoList) {
roleInfoArray[i] = currRoleInfo;
i++;
}
// Can throw InvalidRelationTypeException
RelationTypeSupport.checkRoleInfos(roleInfoArray);
addRelationTypeInt(relationTypeObj);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationType");
return;
}
/**
* Retrieves names of all known relation types.
*
* @return ArrayList of relation type names (Strings)
*/
public List<String> getAllRelationTypeNames() {
ArrayList<String> result;
synchronized(myRelType2ObjMap) {
result = new ArrayList<String>(myRelType2ObjMap.keySet());
}
return result;
}
/**
* Retrieves list of role infos (RoleInfo objects) of a given relation
* type.
*
* @param relationTypeName name of relation type
*
* @return ArrayList of RoleInfo.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<RoleInfo> getRoleInfos(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleInfos", relationTypeName);
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleInfos");
return relType.getRoleInfos();
}
/**
* Retrieves role info for given role name of a given relation type.
*
* @param relationTypeName name of relation type
* @param roleInfoName name of role
*
* @return RoleInfo object.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
* @exception RoleInfoNotFoundException if the role is not part of the
* relation type.
*/
public RoleInfo getRoleInfo(String relationTypeName,
String roleInfoName)
throws IllegalArgumentException,
RelationTypeNotFoundException,
RoleInfoNotFoundException {
if (relationTypeName == null || roleInfoName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleInfo", new Object[] {relationTypeName, roleInfoName});
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Can throw a RoleInfoNotFoundException
RoleInfo roleInfo = relType.getRoleInfo(roleInfoName);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleInfo");
return roleInfo;
}
/**
* Removes given relation type from Relation Service.
* <P>The relation objects of that type will be removed from the
* Relation Service.
*
* @param relationTypeName name of the relation type to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException If there is no relation type
* with that name
*/
public void removeRelationType(String relationTypeName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationTypeNotFoundException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeRelationType", relationTypeName);
// Checks if the relation type to be removed exists
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Retrieves the relation ids for relations of that type
List<String> relIdList = null;
synchronized(myRelType2RelIdsMap) {
// Note: take a copy of the list as it is a part of a map that
// will be updated by removeRelation() below.
List<String> relIdList1 =
myRelType2RelIdsMap.get(relationTypeName);
if (relIdList1 != null) {
relIdList = new ArrayList<String>(relIdList1);
}
}
// Removes the relation type from all maps
synchronized(myRelType2ObjMap) {
myRelType2ObjMap.remove(relationTypeName);
}
synchronized(myRelType2RelIdsMap) {
myRelType2RelIdsMap.remove(relationTypeName);
}
// Removes all relations of that type
if (relIdList != null) {
for (String currRelId : relIdList) {
// Note: will remove it from myRelId2RelTypeMap :)
//
// Can throw RelationServiceNotRegisteredException (detected
// above)
// Shall not throw a RelationNotFoundException
try {
removeRelation(currRelId);
} catch (RelationNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeRelationType");
return;
}
//
// Relation handling
//
/**
* Creates a simple relation (represented by a RelationSupport object) of
* given relation type, and adds it in the Relation Service.
* <P>Roles are initialized according to the role list provided in
* parameter. The ones not initialized in this way are set to an empty
* ArrayList of ObjectNames.
* <P>A RelationNotification, with type RELATION_BASIC_CREATION, is sent.
*
* @param relationId relation identifier, to identify uniquely the relation
* inside the Relation Service
* @param relationTypeName name of the relation type (has to be created
* in the Relation Service)
* @param roleList role list to initialize roles of the relation (can
* be null).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter, except the role
* list which can be null if no role initialization
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
* @exception InvalidRelationIdException if relation id already used
* @exception RelationTypeNotFoundException if relation type not known in
* Relation Service
* @exception InvalidRoleValueException if:
* <P>- the same role name is used for two different roles
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for that role does not exist
*/
public void createRelation(String relationId,
String relationTypeName,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RoleNotFoundException,
InvalidRelationIdException,
RelationTypeNotFoundException,
InvalidRoleValueException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationId == null ||
relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"createRelation",
new Object[] {relationId, relationTypeName, roleList});
// Creates RelationSupport object
// Can throw InvalidRoleValueException
RelationSupport relObj = new RelationSupport(relationId,
myObjName,
relationTypeName,
roleList);
// Adds relation object as a relation into the Relation Service
// Can throw RoleNotFoundException, InvalidRelationId,
// RelationTypeNotFoundException, InvalidRoleValueException
//
// Cannot throw MBeanException
addRelationInt(true,
relObj,
null,
relationId,
relationTypeName,
roleList);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"createRelation");
return;
}
/**
* Adds an MBean created by the user (and registered by him in the MBean
* Server) as a relation in the Relation Service.
* <P>To be added as a relation, the MBean must conform to the
* following:
* <P>- implement the Relation interface
* <P>- have for RelationService ObjectName the ObjectName of current
* Relation Service
* <P>- have a relation id unique and unused in current Relation Service
* <P>- have for relation type a relation type created in the Relation
* Service
* <P>- have roles conforming to the role info provided in the relation
* type.
*
* @param relationObjectName ObjectName of the relation MBean to be added.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception NoSuchMethodException If the MBean does not implement the
* Relation interface
* @exception InvalidRelationIdException if:
* <P>- no relation identifier in MBean
* <P>- the relation identifier is already used in the Relation Service
* @exception InstanceNotFoundException if the MBean for given ObjectName
* has not been registered
* @exception InvalidRelationServiceException if:
* <P>- no Relation Service name in MBean
* <P>- the Relation Service name in the MBean is not the one of the
* current Relation Service
* @exception RelationTypeNotFoundException if:
* <P>- no relation type name in MBean
* <P>- the relation type name in MBean does not correspond to a relation
* type created in the Relation Service
* @exception InvalidRoleValueException if:
* <P>- the number of referenced MBeans in a role is less than
* expected minimum degree
* <P>- the number of referenced MBeans in a role exceeds expected
* maximum degree
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>- an MBean provided for a role does not exist
* @exception RoleNotFoundException if a value is provided for a role
* that does not exist in the relation type
*/
public void addRelation(ObjectName relationObjectName)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
NoSuchMethodException,
InvalidRelationIdException,
InstanceNotFoundException,
InvalidRelationServiceException,
RelationTypeNotFoundException,
RoleNotFoundException,
InvalidRoleValueException {
if (relationObjectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelation", relationObjectName);
// Can throw RelationServiceNotRegisteredException
isActive();
// Checks that the relation MBean implements the Relation interface.
// It will also check that the provided ObjectName corresponds to a
// registered MBean (else will throw an InstanceNotFoundException)
if ((!(myMBeanServer.isInstanceOf(relationObjectName, "javax.management.relation.Relation")))) {
String excMsg = "This MBean does not implement the Relation interface.";
throw new NoSuchMethodException(excMsg);
}
// Checks there is a relation id in the relation MBean (its uniqueness
// is checked in addRelationInt())
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, and no
// ReflectionException
String relId;
try {
relId = (String)(myMBeanServer.getAttribute(relationObjectName,
"RelationId"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
if (relId == null) {
String excMsg = "This MBean does not provide a relation id.";
throw new InvalidRelationIdException(excMsg);
}
// Checks that the Relation Service where the relation MBean is
// expected to be added is the current one
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
ObjectName relServObjName;
try {
relServObjName = (ObjectName)
(myMBeanServer.getAttribute(relationObjectName,
"RelationServiceName"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
boolean badRelServFlag = false;
if (relServObjName == null) {
badRelServFlag = true;
} else if (!(relServObjName.equals(myObjName))) {
badRelServFlag = true;
}
if (badRelServFlag) {
String excMsg = "The Relation Service referenced in the MBean is not the current one.";
throw new InvalidRelationServiceException(excMsg);
}
// Checks that a relation type has been specified for the relation
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
String relTypeName;
try {
relTypeName = (String)(myMBeanServer.getAttribute(relationObjectName,
"RelationTypeName"));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
}catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (AttributeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
if (relTypeName == null) {
String excMsg = "No relation type provided.";
throw new RelationTypeNotFoundException(excMsg);
}
// Retrieves all roles without considering read mode
// Can throw InstanceNotFoundException (but detected above)
// No MBeanException as no exception raised by this method, no
// ReflectionException
RoleList roleList;
try {
roleList = (RoleList)(myMBeanServer.invoke(relationObjectName,
"retrieveAllRoles",
null,
null));
} catch (MBeanException exc1) {
throw new RuntimeException(
(exc1.getTargetException()).getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
}
// Can throw RoleNotFoundException, InvalidRelationIdException,
// RelationTypeNotFoundException, InvalidRoleValueException
addRelationInt(false,
null,
relationObjectName,
relId,
relTypeName,
roleList);
// Adds relation MBean ObjectName in map
synchronized(myRelMBeanObjName2RelIdMap) {
myRelMBeanObjName2RelIdMap.put(relationObjectName, relId);
}
// Updates flag to specify that the relation is managed by the Relation
// Service
// This flag and setter are inherited from RelationSupport and not parts
// of the Relation interface, so may be not supported.
try {
myMBeanServer.setAttribute(relationObjectName,
new Attribute(
"RelationServiceManagementFlag",
Boolean.TRUE));
} catch (Exception exc) {
// OK : The flag is not supported.
}
// Updates listener information to received notification for
// unregistration of this MBean
List<ObjectName> newRefList = new ArrayList<ObjectName>();
newRefList.add(relationObjectName);
updateUnregistrationListener(newRefList, null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelation");
return;
}
/**
* If the relation is represented by an MBean (created by the user and
* added as a relation in the Relation Service), returns the ObjectName of
* the MBean.
*
* @param relationId relation id identifying the relation
*
* @return ObjectName of the corresponding relation MBean, or null if
* the relation is not an MBean.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException there is no relation associated
* to that id
*/
public ObjectName isRelationMBean(String relationId)
throws IllegalArgumentException,
RelationNotFoundException{
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"isRelationMBean", relationId);
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
if (result instanceof ObjectName) {
return ((ObjectName)result);
} else {
return null;
}
}
/**
* Returns the relation id associated to the given ObjectName if the
* MBean has been added as a relation in the Relation Service.
*
* @param objectName ObjectName of supposed relation
*
* @return relation id (String) or null (if the ObjectName is not a
* relation handled by the Relation Service)
*
* @exception IllegalArgumentException if null parameter
*/
public String isRelation(ObjectName objectName)
throws IllegalArgumentException {
if (objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"isRelation", objectName);
String result = null;
synchronized(myRelMBeanObjName2RelIdMap) {
String relId = myRelMBeanObjName2RelIdMap.get(objectName);
if (relId != null) {
result = relId;
}
}
return result;
}
/**
* Checks if there is a relation identified in Relation Service with given
* relation id.
*
* @param relationId relation id identifying the relation
*
* @return boolean: true if there is a relation, false else
*
* @exception IllegalArgumentException if null parameter
*/
public Boolean hasRelation(String relationId)
throws IllegalArgumentException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"hasRelation", relationId);
try {
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
return true;
} catch (RelationNotFoundException exc) {
return false;
}
}
/**
* Returns all the relation ids for all the relations handled by the
* Relation Service.
*
* @return ArrayList of String
*/
public List<String> getAllRelationIds() {
List<String> result;
synchronized(myRelId2ObjMap) {
result = new ArrayList<String>(myRelId2ObjMap.keySet());
}
return result;
}
/**
* Checks if given Role can be read in a relation of the given type.
*
* @param roleName name of role to be checked
* @param relationTypeName name of the relation type
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be read
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer corresponding to RoleStatus.ROLE_NOT_READABLE
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if the relation type is not
* known in the Relation Service
*/
public Integer checkRoleReading(String roleName,
String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (roleName == null || relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleReading", new Object[] {roleName, relationTypeName});
Integer result;
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
try {
// Can throw a RoleInfoNotFoundException to be transformed into
// returned value RoleStatus.NO_ROLE_WITH_NAME
RoleInfo roleInfo = relType.getRoleInfo(roleName);
result = checkRoleInt(1,
roleName,
null,
roleInfo,
false);
} catch (RoleInfoNotFoundException exc) {
result = Integer.valueOf(RoleStatus.NO_ROLE_WITH_NAME);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleReading");
return result;
}
/**
* Checks if given Role can be set in a relation of given type.
*
* @param role role to be checked
* @param relationTypeName name of relation type
* @param initFlag flag to specify that the checking is done for the
* initialization of a role, write access shall not be verified.
*
* @return an Integer wrapping an integer corresponding to possible
* problems represented as constants in RoleUnresolved:
* <P>- 0 if role can be set
* <P>- integer corresponding to RoleStatus.NO_ROLE_WITH_NAME
* <P>- integer for RoleStatus.ROLE_NOT_WRITABLE
* <P>- integer for RoleStatus.LESS_THAN_MIN_ROLE_DEGREE
* <P>- integer for RoleStatus.MORE_THAN_MAX_ROLE_DEGREE
* <P>- integer for RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS
* <P>- integer for RoleStatus.REF_MBEAN_NOT_REGISTERED
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if unknown relation type
*/
public Integer checkRoleWriting(Role role,
String relationTypeName,
Boolean initFlag)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (role == null ||
relationTypeName == null ||
initFlag == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleWriting",
new Object[] {role, relationTypeName, initFlag});
// Can throw a RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
String roleName = role.getRoleName();
List<ObjectName> roleValue = role.getRoleValue();
boolean writeChkFlag = true;
if (initFlag.booleanValue()) {
writeChkFlag = false;
}
RoleInfo roleInfo;
try {
roleInfo = relType.getRoleInfo(roleName);
} catch (RoleInfoNotFoundException exc) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleWriting");
return Integer.valueOf(RoleStatus.NO_ROLE_WITH_NAME);
}
Integer result = checkRoleInt(2,
roleName,
roleValue,
roleInfo,
writeChkFlag);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleWriting");
return result;
}
/**
* Sends a notification (RelationNotification) for a relation creation.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_CREATION if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_CREATION if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service createRelation() and
* addRelation() methods.
*
* @param relationId relation identifier of the updated relation
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationCreationNotification(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRelationCreationNotification", relationId);
// Message
StringBuilder ntfMsg = new StringBuilder("Creation of relation ");
ntfMsg.append(relationId);
// Can throw RelationNotFoundException
sendNotificationInt(1,
ntfMsg.toString(),
relationId,
null,
null,
null,
null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRelationCreationNotification");
return;
}
/**
* Sends a notification (RelationNotification) for a role update in the
* given relation. The notification type is:
* <P>- RelationNotification.RELATION_BASIC_UPDATE if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_UPDATE if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRoleUpdateNotification(String relationId,
Role newRole,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null ||
newRole == null ||
oldValue == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
if (!(oldValue instanceof ArrayList<?>))
oldValue = new ArrayList<ObjectName>(oldValue);
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRoleUpdateNotification",
new Object[] {relationId, newRole, oldValue});
String roleName = newRole.getRoleName();
List<ObjectName> newRoleVal = newRole.getRoleValue();
// Message
String newRoleValString = Role.roleValueToString(newRoleVal);
String oldRoleValString = Role.roleValueToString(oldValue);
StringBuilder ntfMsg = new StringBuilder("Value of role ");
ntfMsg.append(roleName);
ntfMsg.append(" has changed\nOld value:\n");
ntfMsg.append(oldRoleValString);
ntfMsg.append("\nNew value:\n");
ntfMsg.append(newRoleValString);
// Can throw a RelationNotFoundException
sendNotificationInt(2,
ntfMsg.toString(),
relationId,
null,
roleName,
newRoleVal,
oldValue);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRoleUpdateNotification");
}
/**
* Sends a notification (RelationNotification) for a relation removal.
* The notification type is:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation is an
* object internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is a
* MBean added as a relation.
* <P>The source object is the Relation Service itself.
* <P>It is called in Relation Service removeRelation() method.
*
* @param relationId relation identifier of the updated relation
* @param unregMBeanList List of ObjectNames of MBeans expected
* to be unregistered due to relation removal (can be null)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if there is no relation for given
* relation id
*/
public void sendRelationRemovalNotification(String relationId,
List<ObjectName> unregMBeanList)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendRelationRemovalNotification",
new Object[] {relationId, unregMBeanList});
// Can throw RelationNotFoundException
sendNotificationInt(3,
"Removal of relation " + relationId,
relationId,
unregMBeanList,
null,
null,
null);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendRelationRemovalNotification");
return;
}
/**
* Handles update of the Relation Service role map for the update of given
* role in given relation.
* <P>It is called in relation MBean setRole() (for given role) and
* setRoles() (for each role) methods (implementation provided in
* RelationSupport class).
* <P>It is also called in Relation Service setRole() (for given role) and
* setRoles() (for each role) methods.
* <P>To allow the Relation Service to maintain the consistency (in case
* of MBean unregistration) and to be able to perform queries, this method
* must be called when a role is updated.
*
* @param relationId relation identifier of the updated relation
* @param newRole new role (name and new value)
* @param oldValue old role value (List of ObjectName objects)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception RelationNotFoundException if no relation for given id.
*/
public void updateRoleMap(String relationId,
Role newRole,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException {
if (relationId == null ||
newRole == null ||
oldValue == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"updateRoleMap", new Object[] {relationId, newRole, oldValue});
// Can throw RelationServiceNotRegisteredException
isActive();
// Verifies the relation has been added in the Relation Service
// Can throw a RelationNotFoundException
Object result = getRelation(relationId);
String roleName = newRole.getRoleName();
List<ObjectName> newRoleValue = newRole.getRoleValue();
// Note: no need to test if oldValue not null before cloning,
// tested above.
List<ObjectName> oldRoleValue =
new ArrayList<ObjectName>(oldValue);
// List of ObjectNames of new referenced MBeans
List<ObjectName> newRefList = new ArrayList<ObjectName>();
for (ObjectName currObjName : newRoleValue) {
// Checks if this ObjectName was already present in old value
// Note: use copy (oldRoleValue) instead of original
// oldValue to speed up, as oldRoleValue is decreased
// by removing unchanged references :)
int currObjNamePos = oldRoleValue.indexOf(currObjName);
if (currObjNamePos == -1) {
// New reference to an ObjectName
// Stores this reference into map
// Returns true if new reference, false if MBean already
// referenced
boolean isNewFlag = addNewMBeanReference(currObjName,
relationId,
roleName);
if (isNewFlag) {
// Adds it into list of new reference
newRefList.add(currObjName);
}
} else {
// MBean was already referenced in old value
// Removes it from old value (local list) to ignore it when
// looking for remove MBean references
oldRoleValue.remove(currObjNamePos);
}
}
// List of ObjectNames of MBeans no longer referenced
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
// Each ObjectName remaining in oldRoleValue is an ObjectName no longer
// referenced in new value
for (ObjectName currObjName : oldRoleValue) {
// Removes MBean reference from map
// Returns true if the MBean is no longer referenced in any
// relation
boolean noLongerRefFlag = removeMBeanReference(currObjName,
relationId,
roleName,
false);
if (noLongerRefFlag) {
// Adds it into list of references to be removed
obsRefList.add(currObjName);
}
}
// To avoid having one listener per ObjectName of referenced MBean,
// and to increase performances, there is only one listener recording
// all ObjectNames of interest
updateUnregistrationListener(newRefList, obsRefList);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"updateRoleMap");
return;
}
/**
* Removes given relation from the Relation Service.
* <P>A RelationNotification notification is sent, its type being:
* <P>- RelationNotification.RELATION_BASIC_REMOVAL if the relation was
* only internal to the Relation Service
* <P>- RelationNotification.RELATION_MBEAN_REMOVAL if the relation is
* registered as an MBean.
* <P>For MBeans referenced in such relation, nothing will be done,
*
* @param relationId relation id of the relation to be removed
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation corresponding to
* given relation id
*/
public void removeRelation(String relationId)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
// Can throw RelationServiceNotRegisteredException
isActive();
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeRelation", relationId);
// Checks there is a relation with this id
// Can throw RelationNotFoundException
Object result = getRelation(relationId);
// Removes it from listener filter
if (result instanceof ObjectName) {
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
obsRefList.add((ObjectName)result);
// Can throw a RelationServiceNotRegisteredException
updateUnregistrationListener(null, obsRefList);
}
// Sends a notification
// Note: has to be done FIRST as needs the relation to be still in the
// Relation Service
// No RelationNotFoundException as checked above
// Revisit [cebro] Handle CIM "Delete" and "IfDeleted" qualifiers:
// deleting the relation can mean to delete referenced MBeans. In
// that case, MBeans to be unregistered are put in a list sent along
// with the notification below
// Can throw a RelationNotFoundException (but detected above)
sendRelationRemovalNotification(relationId, null);
// Removes the relation from various internal maps
// - MBean reference map
// Retrieves the MBeans referenced in this relation
// Note: here we cannot use removeMBeanReference() because it would
// require to know the MBeans referenced in the relation. For
// that it would be necessary to call 'getReferencedMBeans()'
// on the relation itself. Ok if it is an internal one, but if
// it is an MBean, it is possible it is already unregistered, so
// not available through the MBean Server.
List<ObjectName> refMBeanList = new ArrayList<ObjectName>();
// List of MBeans no longer referenced in any relation, to be
// removed fom the map
List<ObjectName> nonRefObjNameList = new ArrayList<ObjectName>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
for (ObjectName currRefObjName :
myRefedMBeanObjName2RelIdsMap.keySet()) {
// Retrieves relations where the MBean is referenced
Map<String,List<String>> relIdMap =
myRefedMBeanObjName2RelIdsMap.get(currRefObjName);
if (relIdMap.containsKey(relationId)) {
relIdMap.remove(relationId);
refMBeanList.add(currRefObjName);
}
if (relIdMap.isEmpty()) {
// MBean no longer referenced
// Note: do not remove it here because pointed by the
// iterator!
nonRefObjNameList.add(currRefObjName);
}
}
// Cleans MBean reference map by removing MBeans no longer
// referenced
for (ObjectName currRefObjName : nonRefObjNameList) {
myRefedMBeanObjName2RelIdsMap.remove(currRefObjName);
}
}
// - Relation id to object map
synchronized(myRelId2ObjMap) {
myRelId2ObjMap.remove(relationId);
}
if (result instanceof ObjectName) {
// - ObjectName to relation id map
synchronized(myRelMBeanObjName2RelIdMap) {
myRelMBeanObjName2RelIdMap.remove((ObjectName)result);
}
}
// Relation id to relation type name map
// First retrieves the relation type name
String relTypeName;
synchronized(myRelId2RelTypeMap) {
relTypeName = myRelId2RelTypeMap.get(relationId);
myRelId2RelTypeMap.remove(relationId);
}
// - Relation type name to relation id map
synchronized(myRelType2RelIdsMap) {
List<String> relIdList = myRelType2RelIdsMap.get(relTypeName);
if (relIdList != null) {
// Can be null if called from removeRelationType()
relIdList.remove(relationId);
if (relIdList.isEmpty()) {
// No other relation of that type
myRelType2RelIdsMap.remove(relTypeName);
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeRelation");
return;
}
/**
* Purges the relations.
*
* <P>Depending on the purgeFlag value, this method is either called
* automatically when a notification is received for the unregistration of
* an MBean referenced in a relation (if the flag is set to true), or not
* (if the flag is set to false).
* <P>In that case it is up to the user to call it to maintain the
* consistency of the relations. To be kept in mind that if an MBean is
* unregistered and the purge not done immediately, if the ObjectName is
* reused and assigned to another MBean referenced in a relation, calling
* manually this purgeRelations() method will cause trouble, as will
* consider the ObjectName as corresponding to the unregistered MBean, not
* seeing the new one.
*
* <P>The behavior depends on the cardinality of the role where the
* unregistered MBean is referenced:
* <P>- if removing one MBean reference in the role makes its number of
* references less than the minimum degree, the relation has to be removed.
* <P>- if the remaining number of references after removing the MBean
* reference is still in the cardinality range, keep the relation and
* update it calling its handleMBeanUnregistration() callback.
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server.
*/
public void purgeRelations()
throws RelationServiceNotRegisteredException {
RELATION_LOGGER.entering(RelationService.class.getName(),
"purgeRelations");
// Can throw RelationServiceNotRegisteredException
isActive();
// Revisit [cebro] Handle the CIM "Delete" and "IfDeleted" qualifier:
// if the unregistered MBean has the "IfDeleted" qualifier,
// possible that the relation itself or other referenced MBeans
// have to be removed (then a notification would have to be sent
// to inform that they should be unregistered.
// Clones the list of notifications to be able to still receive new
// notifications while proceeding those ones
List<MBeanServerNotification> localUnregNtfList;
synchronized(myRefedMBeanObjName2RelIdsMap) {
localUnregNtfList =
new ArrayList<MBeanServerNotification>(myUnregNtfList);
// Resets list
myUnregNtfList = new ArrayList<MBeanServerNotification>();
}
// Updates the listener filter to avoid receiving notifications for
// those MBeans again
// Makes also a local "myRefedMBeanObjName2RelIdsMap" map, mapping
// ObjectName -> relId -> roles, to remove the MBean from the global
// map
// List of references to be removed from the listener filter
List<ObjectName> obsRefList = new ArrayList<ObjectName>();
// Map including ObjectNames for unregistered MBeans, with
// referencing relation ids and roles
Map<ObjectName,Map<String,List<String>>> localMBean2RelIdMap =
new HashMap<ObjectName,Map<String,List<String>>>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
for (MBeanServerNotification currNtf : localUnregNtfList) {
ObjectName unregMBeanName = currNtf.getMBeanName();
// Adds the unregsitered MBean in the list of references to
// remove from the listener filter
obsRefList.add(unregMBeanName);
// Retrieves the associated map of relation ids and roles
Map<String,List<String>> relIdMap =
myRefedMBeanObjName2RelIdsMap.get(unregMBeanName);
localMBean2RelIdMap.put(unregMBeanName, relIdMap);
myRefedMBeanObjName2RelIdsMap.remove(unregMBeanName);
}
}
// Updates the listener
// Can throw RelationServiceNotRegisteredException
updateUnregistrationListener(null, obsRefList);
for (MBeanServerNotification currNtf : localUnregNtfList) {
ObjectName unregMBeanName = currNtf.getMBeanName();
// Retrieves the relations where the MBean is referenced
Map<String,List<String>> localRelIdMap =
localMBean2RelIdMap.get(unregMBeanName);
// List of relation ids where the unregistered MBean is
// referenced
for (Map.Entry<String,List<String>> currRel :
localRelIdMap.entrySet()) {
final String currRelId = currRel.getKey();
// List of roles of the relation where the MBean is
// referenced
List<String> localRoleNameList = currRel.getValue();
// Checks if the relation has to be removed or not,
// regarding expected minimum role cardinality and current
// number of references after removal of the current one
// If the relation is kept, calls
// handleMBeanUnregistration() callback of the relation to
// update it
//
// Can throw RelationServiceNotRegisteredException
//
// Shall not throw RelationNotFoundException,
// RoleNotFoundException, MBeanException
try {
handleReferenceUnregistration(currRelId,
unregMBeanName,
localRoleNameList);
} catch (RelationNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RoleNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"purgeRelations");
return;
}
/**
* Retrieves the relations where a given MBean is referenced.
* <P>This corresponds to the CIM "References" and "ReferenceNames"
* operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all relation types
* are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be returned. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the relation ids of the relations
* where the MBean is referenced, and the value is, for each key,
* an ArrayList of role names (as an MBean can be referenced in several
* roles in the same relation).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<String,List<String>>
findReferencingRelations(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException {
if (mbeanName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findReferencingRelations",
new Object[] {mbeanName, relationTypeName, roleName});
Map<String,List<String>> result = new HashMap<String,List<String>>();
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Retrieves the relations referencing the MBean
Map<String,List<String>> relId2RoleNamesMap =
myRefedMBeanObjName2RelIdsMap.get(mbeanName);
if (relId2RoleNamesMap != null) {
// Relation Ids where the MBean is referenced
Set<String> allRelIdSet = relId2RoleNamesMap.keySet();
// List of relation ids of interest regarding the selected
// relation type
List<String> relIdList;
if (relationTypeName == null) {
// Considers all relations
relIdList = new ArrayList<String>(allRelIdSet);
} else {
relIdList = new ArrayList<String>();
// Considers only the relation ids for relations of given
// type
for (String currRelId : allRelIdSet) {
// Retrieves its relation type
String currRelTypeName;
synchronized(myRelId2RelTypeMap) {
currRelTypeName =
myRelId2RelTypeMap.get(currRelId);
}
if (currRelTypeName.equals(relationTypeName)) {
relIdList.add(currRelId);
}
}
}
// Now looks at the roles where the MBean is expected to be
// referenced
for (String currRelId : relIdList) {
// Retrieves list of role names where the MBean is
// referenced
List<String> currRoleNameList =
relId2RoleNamesMap.get(currRelId);
if (roleName == null) {
// All roles to be considered
// Note: no need to test if list not null before
// cloning, MUST be not null else bug :(
result.put(currRelId,
new ArrayList<String>(currRoleNameList));
} else if (currRoleNameList.contains(roleName)) {
// Filters only the relations where the MBean is
// referenced in // given role
List<String> dummyList = new ArrayList<String>();
dummyList.add(roleName);
result.put(currRelId, dummyList);
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findReferencingRelations");
return result;
}
/**
* Retrieves the MBeans associated to given one in a relation.
* <P>This corresponds to CIM Associators and AssociatorNames operations.
*
* @param mbeanName ObjectName of MBean
* @param relationTypeName can be null; if specified, only the relations
* of that type will be considered in the search. Else all
* relation types are considered.
* @param roleName can be null; if specified, only the relations
* where the MBean is referenced in that role will be considered. Else all
* roles are considered.
*
* @return an HashMap, where the keys are the ObjectNames of the MBeans
* associated to given MBean, and the value is, for each key, an ArrayList
* of the relation ids of the relations where the key MBean is
* associated to given one (as they can be associated in several different
* relations).
*
* @exception IllegalArgumentException if null parameter
*/
public Map<ObjectName,List<String>>
findAssociatedMBeans(ObjectName mbeanName,
String relationTypeName,
String roleName)
throws IllegalArgumentException {
if (mbeanName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findAssociatedMBeans",
new Object[] {mbeanName, relationTypeName, roleName});
// Retrieves the map <relation id> -> <role names> for those
// criterias
Map<String,List<String>> relId2RoleNamesMap =
findReferencingRelations(mbeanName,
relationTypeName,
roleName);
Map<ObjectName,List<String>> result =
new HashMap<ObjectName,List<String>>();
for (String currRelId : relId2RoleNamesMap.keySet()) {
// Retrieves ObjectNames of MBeans referenced in this relation
//
// Shall not throw a RelationNotFoundException if incorrect status
// of maps :(
Map<ObjectName,List<String>> objName2RoleNamesMap;
try {
objName2RoleNamesMap = getReferencedMBeans(currRelId);
} catch (RelationNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
// For each MBean associated to given one in a relation, adds the
// association <ObjectName> -> <relation id> into result map
for (ObjectName currObjName : objName2RoleNamesMap.keySet()) {
if (!(currObjName.equals(mbeanName))) {
// Sees if this MBean is already associated to the given
// one in another relation
List<String> currRelIdList = result.get(currObjName);
if (currRelIdList == null) {
currRelIdList = new ArrayList<String>();
currRelIdList.add(currRelId);
result.put(currObjName, currRelIdList);
} else {
currRelIdList.add(currRelId);
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findAssociatedMBeans");
return result;
}
/**
* Returns the relation ids for relations of the given type.
*
* @param relationTypeName relation type name
*
* @return an ArrayList of relation ids.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationTypeNotFoundException if there is no relation type
* with that name.
*/
public List<String> findRelationsOfType(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"findRelationsOfType");
// Can throw RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
List<String> result;
synchronized(myRelType2RelIdsMap) {
List<String> result1 = myRelType2RelIdsMap.get(relationTypeName);
if (result1 == null)
result = new ArrayList<String>();
else
result = new ArrayList<String>(result1);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"findRelationsOfType");
return result;
}
/**
* Retrieves role value for given role name in given relation.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the ArrayList of ObjectName objects being the role value
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if:
* <P>- there is no role with given name
* <P>or
* <P>- the role is not readable.
*
* @see #setRole
*/
public List<ObjectName> getRole(String relationId,
String roleName)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null || roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRole", new Object[] {relationId, roleName});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
List<ObjectName> result;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException
result = cast(
((RelationSupport)relObj).getRoleInt(roleName,
true,
this,
false));
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleName;
String[] signature = new String[1];
signature[0] = "java.lang.String";
// Can throw MBeanException wrapping a RoleNotFoundException:
// throw wrapped exception
//
// Shall not throw InstanceNotFoundException or ReflectionException
try {
List<ObjectName> invokeResult = cast(
myMBeanServer.invoke(((ObjectName)relObj),
"getRole",
params,
signature));
if (invokeResult == null || invokeResult instanceof ArrayList<?>)
result = invokeResult;
else
result = new ArrayList<ObjectName>(invokeResult);
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRole");
return result;
}
/**
* Retrieves values of roles with given names in given relation.
*
* @param relationId relation id
* @param roleNameArray array of names of roles to be retrieved
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* retrieved).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #setRoles
*/
public RoleResult getRoles(String relationId,
String[] roleNameArray)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
if (relationId == null || roleNameArray == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoles", relationId);
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getRolesInt(roleNameArray,
true,
this);
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleNameArray;
String[] signature = new String[1];
try {
signature[0] = (roleNameArray.getClass()).getName();
} catch (Exception exc) {
// OK : This is an array of java.lang.String
// so this should never happen...
}
// Shall not throw InstanceNotFoundException, ReflectionException
// or MBeanException
try {
result = (RoleResult)
(myMBeanServer.invoke(((ObjectName)relObj),
"getRoles",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
throw new
RuntimeException((exc3.getTargetException()).getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRoles");
return result;
}
/**
* Returns all roles present in the relation.
*
* @param relationId relation id
*
* @return a RoleResult object, including a RoleList (for roles
* successfully retrieved) and a RoleUnresolvedList (for roles not
* readable).
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given id
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
*/
public RoleResult getAllRoles(String relationId)
throws IllegalArgumentException,
RelationNotFoundException,
RelationServiceNotRegisteredException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoles", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getAllRolesInt(true, this);
} else {
// Relation MBean
// Shall not throw any Exception
try {
result = (RoleResult)
(myMBeanServer.getAttribute(((ObjectName)relObj),
"AllRoles"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "getRoles");
return result;
}
/**
* Retrieves the number of MBeans currently referenced in the given role.
*
* @param relationId relation id
* @param roleName name of role
*
* @return the number of currently referenced MBeans in that role
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if there is no role with given name
*/
public Integer getRoleCardinality(String relationId,
String roleName)
throws IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null || roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRoleCardinality", new Object[] {relationId, roleName});
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
Integer result;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException
result = ((RelationSupport)relObj).getRoleCardinality(roleName);
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleName;
String[] signature = new String[1];
signature[0] = "java.lang.String";
// Can throw MBeanException wrapping RoleNotFoundException:
// throw wrapped exception
//
// Shall not throw InstanceNotFoundException or ReflectionException
try {
result = (Integer)
(myMBeanServer.invoke(((ObjectName)relObj),
"getRoleCardinality",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (MBeanException exc3) {
Exception wrappedExc = exc3.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRoleCardinality");
return result;
}
/**
* Sets the given role in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service will keep track of the change to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param role role to be set (name and new value)
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
* @exception RoleNotFoundException if the role does not exist or is not
* writable
* @exception InvalidRoleValueException if value provided for role is not
* valid:
* <P>- the number of referenced MBeans in given value is less than
* expected minimum degree
* <P>or
* <P>- the number of referenced MBeans in provided value exceeds expected
* maximum degree
* <P>or
* <P>- one referenced MBean in the value is not an Object of the MBean
* class expected for that role
* <P>or
* <P>- an MBean provided for that role does not exist
*
* @see #getRole
*/
public void setRole(String relationId,
Role role)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException,
RoleNotFoundException,
InvalidRoleValueException {
if (relationId == null || role == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"setRole", new Object[] {relationId, role});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException,
// InvalidRoleValueException and
// RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException
// (as relation exists in the RS, its relation type is known)
try {
((RelationSupport)relObj).setRoleInt(role,
true,
this,
false);
} catch (RelationTypeNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = role;
String[] signature = new String[1];
signature[0] = "javax.management.relation.Role";
// Can throw MBeanException wrapping RoleNotFoundException,
// InvalidRoleValueException
//
// Shall not MBeanException wrapping an MBeanException wrapping
// RelationTypeNotFoundException, or ReflectionException, or
// InstanceNotFoundException
try {
myMBeanServer.setAttribute(((ObjectName)relObj),
new Attribute("Role", role));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
if (wrappedExc instanceof RoleNotFoundException) {
throw ((RoleNotFoundException)wrappedExc);
} else if (wrappedExc instanceof InvalidRoleValueException) {
throw ((InvalidRoleValueException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
} catch (AttributeNotFoundException exc4) {
throw new RuntimeException(exc4.getMessage());
} catch (InvalidAttributeValueException exc5) {
throw new RuntimeException(exc5.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "setRole");
return;
}
/**
* Sets the given roles in given relation.
* <P>Will check the role according to its corresponding role definition
* provided in relation's relation type
* <P>The Relation Service keeps track of the changes to keep the
* consistency of relations by handling referenced MBean unregistrations.
*
* @param relationId relation id
* @param roleList list of roles to be set
*
* @return a RoleResult object, including a RoleList (for roles
* successfully set) and a RoleUnresolvedList (for roles not
* set).
*
* @exception RelationServiceNotRegisteredException if the Relation
* Service is not registered in the MBean Server
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation with given id
*
* @see #getRoles
*/
public RoleResult setRoles(String relationId,
RoleList roleList)
throws RelationServiceNotRegisteredException,
IllegalArgumentException,
RelationNotFoundException {
if (relationId == null || roleList == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"setRoles", new Object[] {relationId, roleList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
RoleResult result;
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException (as relation is
// known, its relation type exists)
try {
result = ((RelationSupport)relObj).setRolesInt(roleList,
true,
this);
} catch (RelationTypeNotFoundException exc) {
throw new RuntimeException(exc.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[1];
params[0] = roleList;
String[] signature = new String[1];
signature[0] = "javax.management.relation.RoleList";
// Shall not throw InstanceNotFoundException or an MBeanException
// or ReflectionException
try {
result = (RoleResult)
(myMBeanServer.invoke(((ObjectName)relObj),
"setRoles",
params,
signature));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
throw new
RuntimeException((exc2.getTargetException()).getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(), "setRoles");
return result;
}
/**
* Retrieves MBeans referenced in the various roles of the relation.
*
* @param relationId relation id
*
* @return a HashMap mapping:
* <P> ObjectName -> ArrayList of String (role
* names)
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public Map<ObjectName,List<String>>
getReferencedMBeans(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getReferencedMBeans", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
Map<ObjectName,List<String>> result;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getReferencedMBeans();
} else {
// Relation MBean
// No Exception
try {
result = cast(
myMBeanServer.getAttribute(((ObjectName)relObj),
"ReferencedMBeans"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getReferencedMBeans");
return result;
}
/**
* Returns name of associated relation type for given relation.
*
* @param relationId relation id
*
* @return the name of the associated relation type.
*
* @exception IllegalArgumentException if null parameter
* @exception RelationNotFoundException if no relation for given
* relation id
*/
public String getRelationTypeName(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelationTypeName", relationId);
// Can throw a RelationNotFoundException
Object relObj = getRelation(relationId);
String result;
if (relObj instanceof RelationSupport) {
// Internal relation
result = ((RelationSupport)relObj).getRelationTypeName();
} else {
// Relation MBean
// No Exception
try {
result = (String)
(myMBeanServer.getAttribute(((ObjectName)relObj),
"RelationTypeName"));
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelationTypeName");
return result;
}
//
// NotificationListener Interface
//
/**
* Invoked when a JMX notification occurs.
* Currently handles notifications for unregistration of MBeans, either
* referenced in a relation role or being a relation itself.
*
* @param notif The notification.
* @param handback An opaque object which helps the listener to
* associate information regarding the MBean emitter (can be null).
*/
public void handleNotification(Notification notif,
Object handback) {
if (notif == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"handleNotification", notif);
if (notif instanceof MBeanServerNotification) {
MBeanServerNotification mbsNtf = (MBeanServerNotification) notif;
String ntfType = notif.getType();
if (ntfType.equals(
MBeanServerNotification.UNREGISTRATION_NOTIFICATION )) {
ObjectName mbeanName =
((MBeanServerNotification)notif).getMBeanName();
// Note: use a flag to block access to
// myRefedMBeanObjName2RelIdsMap only for a quick access
boolean isRefedMBeanFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
if (myRefedMBeanObjName2RelIdsMap.containsKey(mbeanName)) {
// Unregistration of a referenced MBean
synchronized(myUnregNtfList) {
myUnregNtfList.add(mbsNtf);
}
isRefedMBeanFlag = true;
}
if (isRefedMBeanFlag && myPurgeFlag) {
// Immediate purge
// Can throw RelationServiceNotRegisteredException
// but assume that will be fine :)
try {
purgeRelations();
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
// Note: do both tests as a relation can be an MBean and be
// itself referenced in another relation :)
String relId;
synchronized(myRelMBeanObjName2RelIdMap){
relId = myRelMBeanObjName2RelIdMap.get(mbeanName);
}
if (relId != null) {
// Unregistration of a relation MBean
// Can throw RelationTypeNotFoundException,
// RelationServiceNotRegisteredException
//
// Shall not throw RelationTypeNotFoundException or
// InstanceNotFoundException
try {
removeRelation(relId);
} catch (Exception exc) {
throw new RuntimeException(exc.getMessage());
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"handleNotification");
return;
}
//
// NotificationBroadcaster interface
//
/**
* Returns a NotificationInfo object containing the name of the Java class
* of the notification and the notification types sent.
*/
public MBeanNotificationInfo[] getNotificationInfo() {
RELATION_LOGGER.entering(RelationService.class.getName(),
"getNotificationInfo");
String ntfClass = "javax.management.relation.RelationNotification";
String[] ntfTypes = new String[] {
RelationNotification.RELATION_BASIC_CREATION,
RelationNotification.RELATION_MBEAN_CREATION,
RelationNotification.RELATION_BASIC_UPDATE,
RelationNotification.RELATION_MBEAN_UPDATE,
RelationNotification.RELATION_BASIC_REMOVAL,
RelationNotification.RELATION_MBEAN_REMOVAL,
};
String ntfDesc = "Sent when a relation is created, updated or deleted.";
MBeanNotificationInfo ntfInfo =
new MBeanNotificationInfo(ntfTypes, ntfClass, ntfDesc);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getNotificationInfo");
return new MBeanNotificationInfo[] {ntfInfo};
}
//
// Misc
//
// Adds given object as a relation type.
//
// -param relationTypeObj relation type object
//
// -exception IllegalArgumentException if null parameter
// -exception InvalidRelationTypeException if there is already a relation
// type with that name
private void addRelationTypeInt(RelationType relationTypeObj)
throws IllegalArgumentException,
InvalidRelationTypeException {
if (relationTypeObj == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationTypeInt");
String relTypeName = relationTypeObj.getRelationTypeName();
// Checks that there is not already a relation type with that name
// existing in the Relation Service
try {
// Can throw a RelationTypeNotFoundException (in fact should ;)
RelationType relType = getRelationType(relTypeName);
if (relType != null) {
String excMsg = "There is already a relation type in the Relation Service with name ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relTypeName);
throw new InvalidRelationTypeException(excMsgStrB.toString());
}
} catch (RelationTypeNotFoundException exc) {
// OK : The RelationType could not be found.
}
// Adds the relation type
synchronized(myRelType2ObjMap) {
myRelType2ObjMap.put(relTypeName, relationTypeObj);
}
if (relationTypeObj instanceof RelationTypeSupport) {
((RelationTypeSupport)relationTypeObj).setRelationServiceFlag(true);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationTypeInt");
return;
}
// Retrieves relation type with given name
//
// -param relationTypeName expected name of a relation type created in the
// Relation Service
//
// -return RelationType object corresponding to given name
//
// -exception IllegalArgumentException if null parameter
// -exception RelationTypeNotFoundException if no relation type for that
// name created in Relation Service
//
RelationType getRelationType(String relationTypeName)
throws IllegalArgumentException,
RelationTypeNotFoundException {
if (relationTypeName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelationType", relationTypeName);
// No null relation type accepted, so can use get()
RelationType relType;
synchronized(myRelType2ObjMap) {
relType = (myRelType2ObjMap.get(relationTypeName));
}
if (relType == null) {
String excMsg = "No relation type created in the Relation Service with the name ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relationTypeName);
throw new RelationTypeNotFoundException(excMsgStrB.toString());
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelationType");
return relType;
}
// Retrieves relation corresponding to given relation id.
// Returns either:
// - a RelationSupport object if the relation is internal
// or
// - the ObjectName of the corresponding MBean
//
// -param relationId expected relation id
//
// -return RelationSupport object or ObjectName of relation with given id
//
// -exception IllegalArgumentException if null parameter
// -exception RelationNotFoundException if no relation for that
// relation id created in Relation Service
//
Object getRelation(String relationId)
throws IllegalArgumentException,
RelationNotFoundException {
if (relationId == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"getRelation", relationId);
// No null relation accepted, so can use get()
Object rel;
synchronized(myRelId2ObjMap) {
rel = myRelId2ObjMap.get(relationId);
}
if (rel == null) {
String excMsg = "No relation associated to relation id " + relationId;
throw new RelationNotFoundException(excMsg);
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"getRelation");
return rel;
}
// Adds a new MBean reference (reference to an ObjectName) in the
// referenced MBean map (myRefedMBeanObjName2RelIdsMap).
//
// -param objectName ObjectName of new referenced MBean
// -param relationId relation id of the relation where the MBean is
// referenced
// -param roleName name of the role where the MBean is referenced
//
// -return boolean:
// - true if the MBean was not referenced before, so really a new
// reference
// - false else
//
// -exception IllegalArgumentException if null parameter
private boolean addNewMBeanReference(ObjectName objectName,
String relationId,
String roleName)
throws IllegalArgumentException {
if (objectName == null ||
relationId == null ||
roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addNewMBeanReference",
new Object[] {objectName, relationId, roleName});
boolean isNewFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Checks if the MBean was already referenced
// No null value allowed, use get() directly
Map<String,List<String>> mbeanRefMap =
myRefedMBeanObjName2RelIdsMap.get(objectName);
if (mbeanRefMap == null) {
// MBean not referenced in any relation yet
isNewFlag = true;
// List of roles where the MBean is referenced in given
// relation
List<String> roleNames = new ArrayList<String>();
roleNames.add(roleName);
// Map of relations where the MBean is referenced
mbeanRefMap = new HashMap<String,List<String>>();
mbeanRefMap.put(relationId, roleNames);
myRefedMBeanObjName2RelIdsMap.put(objectName, mbeanRefMap);
} else {
// MBean already referenced in at least another relation
// Checks if already referenced in another role in current
// relation
List<String> roleNames = mbeanRefMap.get(relationId);
if (roleNames == null) {
// MBean not referenced in current relation
// List of roles where the MBean is referenced in given
// relation
roleNames = new ArrayList<String>();
roleNames.add(roleName);
// Adds new reference done in current relation
mbeanRefMap.put(relationId, roleNames);
} else {
// MBean already referenced in current relation in another
// role
// Adds new reference done
roleNames.add(roleName);
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addNewMBeanReference");
return isNewFlag;
}
// Removes an obsolete MBean reference (reference to an ObjectName) in
// the referenced MBean map (myRefedMBeanObjName2RelIdsMap).
//
// -param objectName ObjectName of MBean no longer referenced
// -param relationId relation id of the relation where the MBean was
// referenced
// -param roleName name of the role where the MBean was referenced
// -param allRolesFlag flag, if true removes reference to MBean for all
// roles in the relation, not only for the one above
//
// -return boolean:
// - true if the MBean is no longer reference in any relation
// - false else
//
// -exception IllegalArgumentException if null parameter
private boolean removeMBeanReference(ObjectName objectName,
String relationId,
String roleName,
boolean allRolesFlag)
throws IllegalArgumentException {
if (objectName == null ||
relationId == null ||
roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"removeMBeanReference",
new Object[] {objectName, relationId, roleName, allRolesFlag});
boolean noLongerRefFlag = false;
synchronized(myRefedMBeanObjName2RelIdsMap) {
// Retrieves the set of relations (designed via their relation ids)
// where the MBean is referenced
// Note that it is possible that the MBean has already been removed
// from the internal map: this is the case when the MBean is
// unregistered, the role is updated, then we arrive here.
Map<String,List<String>> mbeanRefMap =
(myRefedMBeanObjName2RelIdsMap.get(objectName));
if (mbeanRefMap == null) {
// The MBean is no longer referenced
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeMBeanReference");
return true;
}
List<String> roleNames = null;
if (!allRolesFlag) {
// Now retrieves the roles of current relation where the MBean
// was referenced
roleNames = mbeanRefMap.get(relationId);
// Removes obsolete reference to role
int obsRefIdx = roleNames.indexOf(roleName);
if (obsRefIdx != -1) {
roleNames.remove(obsRefIdx);
}
}
// Checks if there is still at least one role in current relation
// where the MBean is referenced
if (roleNames.isEmpty() || allRolesFlag) {
// MBean no longer referenced in current relation: removes
// entry
mbeanRefMap.remove(relationId);
}
// Checks if the MBean is still referenced in at least on relation
if (mbeanRefMap.isEmpty()) {
// MBean no longer referenced in any relation: removes entry
myRefedMBeanObjName2RelIdsMap.remove(objectName);
noLongerRefFlag = true;
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"removeMBeanReference");
return noLongerRefFlag;
}
// Updates the listener registered to the MBean Server to be informed of
// referenced MBean unregistrations
//
// -param newRefList ArrayList of ObjectNames for new references done
// to MBeans (can be null)
// -param obsoleteRefList ArrayList of ObjectNames for obsolete references
// to MBeans (can be null)
//
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server.
private void updateUnregistrationListener(List<ObjectName> newRefList,
List<ObjectName> obsoleteRefList)
throws RelationServiceNotRegisteredException {
if (newRefList != null && obsoleteRefList != null) {
if (newRefList.isEmpty() && obsoleteRefList.isEmpty()) {
// Nothing to do :)
return;
}
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"updateUnregistrationListener",
new Object[] {newRefList, obsoleteRefList});
// Can throw RelationServiceNotRegisteredException
isActive();
if (newRefList != null || obsoleteRefList != null) {
boolean newListenerFlag = false;
if (myUnregNtfFilter == null) {
// Initialize it to be able to synchronise it :)
myUnregNtfFilter = new MBeanServerNotificationFilter();
newListenerFlag = true;
}
synchronized(myUnregNtfFilter) {
// Enables ObjectNames in newRefList
if (newRefList != null) {
for (ObjectName newObjName : newRefList)
myUnregNtfFilter.enableObjectName(newObjName);
}
if (obsoleteRefList != null) {
// Disables ObjectNames in obsoleteRefList
for (ObjectName obsObjName : obsoleteRefList)
myUnregNtfFilter.disableObjectName(obsObjName);
}
// Under test
if (newListenerFlag) {
try {
myMBeanServer.addNotificationListener(
MBeanServerDelegate.DELEGATE_NAME,
this,
myUnregNtfFilter,
null);
} catch (InstanceNotFoundException exc) {
throw new
RelationServiceNotRegisteredException(exc.getMessage());
}
}
// End test
// if (!newListenerFlag) {
// The Relation Service was already registered as a
// listener:
// removes it
// Shall not throw InstanceNotFoundException (as the
// MBean Server Delegate is expected to exist) or
// ListenerNotFoundException (as it has been checked above
// that the Relation Service is registered)
// try {
// myMBeanServer.removeNotificationListener(
// MBeanServerDelegate.DELEGATE_NAME,
// this);
// } catch (InstanceNotFoundException exc1) {
// throw new RuntimeException(exc1.getMessage());
// } catch (ListenerNotFoundException exc2) {
// throw new
// RelationServiceNotRegisteredException(exc2.getMessage());
// }
// }
// Adds Relation Service with current filter
// Can throw InstanceNotFoundException if the Relation
// Service is not registered, to be transformed into
// RelationServiceNotRegisteredException
//
// Assume that there will not be any InstanceNotFoundException
// for the MBean Server Delegate :)
// try {
// myMBeanServer.addNotificationListener(
// MBeanServerDelegate.DELEGATE_NAME,
// this,
// myUnregNtfFilter,
// null);
// } catch (InstanceNotFoundException exc) {
// throw new
// RelationServiceNotRegisteredException(exc.getMessage());
// }
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"updateUnregistrationListener");
return;
}
// Adds a relation (being either a RelationSupport object or an MBean
// referenced using its ObjectName) in the Relation Service.
// Will send a notification RelationNotification with type:
// - RelationNotification.RELATION_BASIC_CREATION for internal relation
// creation
// - RelationNotification.RELATION_MBEAN_CREATION for an MBean being added
// as a relation.
//
// -param relationBaseFlag flag true if the relation is a RelationSupport
// object, false if it is an MBean
// -param relationObj RelationSupport object (if relation is internal)
// -param relationObjName ObjectName of the MBean to be added as a relation
// (only for the relation MBean)
// -param relationId relation identifier, to uniquely identify the relation
// inside the Relation Service
// -param relationTypeName name of the relation type (has to be created
// in the Relation Service)
// -param roleList role list to initialize roles of the relation
// (can be null)
//
// -exception IllegalArgumentException if null paramater
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RoleNotFoundException if a value is provided for a role
// that does not exist in the relation type
// -exception InvalidRelationIdException if relation id already used
// -exception RelationTypeNotFoundException if relation type not known in
// Relation Service
// -exception InvalidRoleValueException if:
// - the same role name is used for two different roles
// - the number of referenced MBeans in given value is less than
// expected minimum degree
// - the number of referenced MBeans in provided value exceeds expected
// maximum degree
// - one referenced MBean in the value is not an Object of the MBean
// class expected for that role
// - an MBean provided for that role does not exist
private void addRelationInt(boolean relationBaseFlag,
RelationSupport relationObj,
ObjectName relationObjName,
String relationId,
String relationTypeName,
RoleList roleList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RoleNotFoundException,
InvalidRelationIdException,
RelationTypeNotFoundException,
InvalidRoleValueException {
if (relationId == null ||
relationTypeName == null ||
(relationBaseFlag &&
(relationObj == null ||
relationObjName != null)) ||
(!relationBaseFlag &&
(relationObjName == null ||
relationObj != null))) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"addRelationInt", new Object[] {relationBaseFlag, relationObj,
relationObjName, relationId, relationTypeName, roleList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Checks if there is already a relation with given id
try {
// Can throw a RelationNotFoundException (in fact should :)
Object rel = getRelation(relationId);
if (rel != null) {
// There is already a relation with that id
String excMsg = "There is already a relation with id ";
StringBuilder excMsgStrB = new StringBuilder(excMsg);
excMsgStrB.append(relationId);
throw new InvalidRelationIdException(excMsgStrB.toString());
}
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
// Retrieves the relation type
// Can throw RelationTypeNotFoundException
RelationType relType = getRelationType(relationTypeName);
// Checks that each provided role conforms to its role info provided in
// the relation type
// First retrieves a local list of the role infos of the relation type
// to see which roles have not been initialized
// Note: no need to test if list not null before cloning, not allowed
// to have an empty relation type.
List<RoleInfo> roleInfoList = new ArrayList<RoleInfo>(relType.getRoleInfos());
if (roleList != null) {
for (Role currRole : roleList.asList()) {
String currRoleName = currRole.getRoleName();
List<ObjectName> currRoleValue = currRole.getRoleValue();
// Retrieves corresponding role info
// Can throw a RoleInfoNotFoundException to be converted into a
// RoleNotFoundException
RoleInfo roleInfo;
try {
roleInfo = relType.getRoleInfo(currRoleName);
} catch (RoleInfoNotFoundException exc) {
throw new RoleNotFoundException(exc.getMessage());
}
// Checks that role conforms to role info,
Integer status = checkRoleInt(2,
currRoleName,
currRoleValue,
roleInfo,
false);
int pbType = status.intValue();
if (pbType != 0) {
// A problem has occurred: throws appropriate exception
// here InvalidRoleValueException
throwRoleProblemException(pbType, currRoleName);
}
// Removes role info for that list from list of role infos for
// roles to be defaulted
int roleInfoIdx = roleInfoList.indexOf(roleInfo);
// Note: no need to check if != -1, MUST be there :)
roleInfoList.remove(roleInfoIdx);
}
}
// Initializes roles not initialized by roleList
// Can throw InvalidRoleValueException
initializeMissingRoles(relationBaseFlag,
relationObj,
relationObjName,
relationId,
relationTypeName,
roleInfoList);
// Creation of relation successfull!!!!
// Updates internal maps
// Relation id to object map
synchronized(myRelId2ObjMap) {
if (relationBaseFlag) {
// Note: do not clone relation object, created by us :)
myRelId2ObjMap.put(relationId, relationObj);
} else {
myRelId2ObjMap.put(relationId, relationObjName);
}
}
// Relation id to relation type name map
synchronized(myRelId2RelTypeMap) {
myRelId2RelTypeMap.put(relationId,
relationTypeName);
}
// Relation type to relation id map
synchronized(myRelType2RelIdsMap) {
List<String> relIdList =
myRelType2RelIdsMap.get(relationTypeName);
boolean firstRelFlag = false;
if (relIdList == null) {
firstRelFlag = true;
relIdList = new ArrayList<String>();
}
relIdList.add(relationId);
if (firstRelFlag) {
myRelType2RelIdsMap.put(relationTypeName, relIdList);
}
}
// Referenced MBean to relation id map
// Only role list parameter used, as default initialization of roles
// done automatically in initializeMissingRoles() sets each
// uninitialized role to an empty value.
for (Role currRole : roleList.asList()) {
// Creates a dummy empty ArrayList of ObjectNames to be the old
// role value :)
List<ObjectName> dummyList = new ArrayList<ObjectName>();
// Will not throw a RelationNotFoundException (as the RelId2Obj map
// has been updated above) so catch it :)
try {
updateRoleMap(relationId, currRole, dummyList);
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
}
// Sends a notification for relation creation
// Will not throw RelationNotFoundException so catch it :)
try {
sendRelationCreationNotification(relationId);
} catch (RelationNotFoundException exc) {
// OK : The Relation could not be found.
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"addRelationInt");
return;
}
// Checks that given role conforms to given role info.
//
// -param chkType type of check:
// - 1: read, just check read access
// - 2: write, check value and write access if writeChkFlag
// -param roleName role name
// -param roleValue role value
// -param roleInfo corresponding role info
// -param writeChkFlag boolean to specify a current write access and
// to check it
//
// -return Integer with value:
// - 0: ok
// - RoleStatus.NO_ROLE_WITH_NAME
// - RoleStatus.ROLE_NOT_READABLE
// - RoleStatus.ROLE_NOT_WRITABLE
// - RoleStatus.LESS_THAN_MIN_ROLE_DEGREE
// - RoleStatus.MORE_THAN_MAX_ROLE_DEGREE
// - RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS
// - RoleStatus.REF_MBEAN_NOT_REGISTERED
//
// -exception IllegalArgumentException if null parameter
private Integer checkRoleInt(int chkType,
String roleName,
List<ObjectName> roleValue,
RoleInfo roleInfo,
boolean writeChkFlag)
throws IllegalArgumentException {
if (roleName == null ||
roleInfo == null ||
(chkType == 2 && roleValue == null)) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"checkRoleInt", new Object[] {chkType, roleName,
roleValue, roleInfo, writeChkFlag});
// Compares names
String expName = roleInfo.getName();
if (!(roleName.equals(expName))) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return Integer.valueOf(RoleStatus.NO_ROLE_WITH_NAME);
}
// Checks read access if required
if (chkType == 1) {
boolean isReadable = roleInfo.isReadable();
if (!isReadable) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return Integer.valueOf(RoleStatus.ROLE_NOT_READABLE);
} else {
// End of check :)
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(0);
}
}
// Checks write access if required
if (writeChkFlag) {
boolean isWritable = roleInfo.isWritable();
if (!isWritable) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.ROLE_NOT_WRITABLE);
}
}
int refNbr = roleValue.size();
// Checks minimum cardinality
boolean chkMinFlag = roleInfo.checkMinDegree(refNbr);
if (!chkMinFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.LESS_THAN_MIN_ROLE_DEGREE);
}
// Checks maximum cardinality
boolean chkMaxFlag = roleInfo.checkMaxDegree(refNbr);
if (!chkMaxFlag) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.MORE_THAN_MAX_ROLE_DEGREE);
}
// Verifies that each referenced MBean is registered in the MBean
// Server and that it is an instance of the class specified in the
// role info, or of a subclass of it
// Note that here again this is under the assumption that
// referenced MBeans, relation MBeans and the Relation Service are
// registered in the same MBean Server.
String expClassName = roleInfo.getRefMBeanClassName();
for (ObjectName currObjName : roleValue) {
// Checks it is registered
if (currObjName == null) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
}
// Checks if it is of the correct class
// Can throw an InstanceNotFoundException, if MBean not registered
try {
boolean classSts = myMBeanServer.isInstanceOf(currObjName,
expClassName);
if (!classSts) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS);
}
} catch (InstanceNotFoundException exc) {
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(RoleStatus.REF_MBEAN_NOT_REGISTERED);
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"checkRoleInt");
return new Integer(0);
}
// Initializes roles associated to given role infos to default value (empty
// ArrayList of ObjectNames) in given relation.
// It will succeed for every role except if the role info has a minimum
// cardinality greater than 0. In that case, an InvalidRoleValueException
// will be raised.
//
// -param relationBaseFlag flag true if the relation is a RelationSupport
// object, false if it is an MBean
// -param relationObj RelationSupport object (if relation is internal)
// -param relationObjName ObjectName of the MBean to be added as a relation
// (only for the relation MBean)
// -param relationId relation id
// -param relationTypeName name of the relation type (has to be created
// in the Relation Service)
// -param roleInfoList list of role infos for roles to be defaulted
//
// -exception IllegalArgumentException if null paramater
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception InvalidRoleValueException if role must have a non-empty
// value
// Revisit [cebro] Handle CIM qualifiers as REQUIRED to detect roles which
// should have been initialized by the user
private void initializeMissingRoles(boolean relationBaseFlag,
RelationSupport relationObj,
ObjectName relationObjName,
String relationId,
String relationTypeName,
List<RoleInfo> roleInfoList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
InvalidRoleValueException {
if ((relationBaseFlag &&
(relationObj == null ||
relationObjName != null)) ||
(!relationBaseFlag &&
(relationObjName == null ||
relationObj != null)) ||
relationId == null ||
relationTypeName == null ||
roleInfoList == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"initializeMissingRoles", new Object[] {relationBaseFlag,
relationObj, relationObjName, relationId, relationTypeName,
roleInfoList});
// Can throw RelationServiceNotRegisteredException
isActive();
// For each role info (corresponding to a role not initialized by the
// role list provided by the user), try to set in the relation a role
// with an empty list of ObjectNames.
// A check is performed to verify that the role can be set to an
// empty value, according to its minimum cardinality
for (RoleInfo currRoleInfo : roleInfoList) {
String roleName = currRoleInfo.getName();
// Creates an empty value
List<ObjectName> emptyValue = new ArrayList<ObjectName>();
// Creates a role
Role role = new Role(roleName, emptyValue);
if (relationBaseFlag) {
// Internal relation
// Can throw InvalidRoleValueException
//
// Will not throw RoleNotFoundException (role to be
// initialized), or RelationNotFoundException, or
// RelationTypeNotFoundException
try {
relationObj.setRoleInt(role, true, this, false);
} catch (RoleNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RelationNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
} catch (RelationTypeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
}
} else {
// Relation is an MBean
// Use standard setRole()
Object[] params = new Object[1];
params[0] = role;
String[] signature = new String[1];
signature[0] = "javax.management.relation.Role";
// Can throw MBeanException wrapping
// InvalidRoleValueException. Returns the target exception to
// be homogeneous.
//
// Will not throw MBeanException (wrapping
// RoleNotFoundException or MBeanException) or
// InstanceNotFoundException, or ReflectionException
//
// Again here the assumption is that the Relation Service and
// the relation MBeans are registered in the same MBean Server.
try {
myMBeanServer.setAttribute(relationObjName,
new Attribute("Role", role));
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
if (wrappedExc instanceof InvalidRoleValueException) {
throw ((InvalidRoleValueException)wrappedExc);
} else {
throw new RuntimeException(wrappedExc.getMessage());
}
} catch (AttributeNotFoundException exc4) {
throw new RuntimeException(exc4.getMessage());
} catch (InvalidAttributeValueException exc5) {
throw new RuntimeException(exc5.getMessage());
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"initializeMissingRoles");
return;
}
// Throws an exception corresponding to a given problem type
//
// -param pbType possible problem, defined in RoleUnresolved
// -param roleName role name
//
// -exception IllegalArgumentException if null parameter
// -exception RoleNotFoundException for problems:
// - NO_ROLE_WITH_NAME
// - ROLE_NOT_READABLE
// - ROLE_NOT_WRITABLE
// -exception InvalidRoleValueException for problems:
// - LESS_THAN_MIN_ROLE_DEGREE
// - MORE_THAN_MAX_ROLE_DEGREE
// - REF_MBEAN_OF_INCORRECT_CLASS
// - REF_MBEAN_NOT_REGISTERED
static void throwRoleProblemException(int pbType,
String roleName)
throws IllegalArgumentException,
RoleNotFoundException,
InvalidRoleValueException {
if (roleName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
// Exception type: 1 = RoleNotFoundException
// 2 = InvalidRoleValueException
int excType = 0;
String excMsgPart = null;
switch (pbType) {
case RoleStatus.NO_ROLE_WITH_NAME:
excMsgPart = " does not exist in relation.";
excType = 1;
break;
case RoleStatus.ROLE_NOT_READABLE:
excMsgPart = " is not readable.";
excType = 1;
break;
case RoleStatus.ROLE_NOT_WRITABLE:
excMsgPart = " is not writable.";
excType = 1;
break;
case RoleStatus.LESS_THAN_MIN_ROLE_DEGREE:
excMsgPart = " has a number of MBean references less than the expected minimum degree.";
excType = 2;
break;
case RoleStatus.MORE_THAN_MAX_ROLE_DEGREE:
excMsgPart = " has a number of MBean references greater than the expected maximum degree.";
excType = 2;
break;
case RoleStatus.REF_MBEAN_OF_INCORRECT_CLASS:
excMsgPart = " has an MBean reference to an MBean not of the expected class of references for that role.";
excType = 2;
break;
case RoleStatus.REF_MBEAN_NOT_REGISTERED:
excMsgPart = " has a reference to null or to an MBean not registered.";
excType = 2;
break;
}
// No default as we must have been in one of those cases
StringBuilder excMsgStrB = new StringBuilder(roleName);
excMsgStrB.append(excMsgPart);
String excMsg = excMsgStrB.toString();
if (excType == 1) {
throw new RoleNotFoundException(excMsg);
} else if (excType == 2) {
throw new InvalidRoleValueException(excMsg);
}
}
// Sends a notification of given type, with given parameters
//
// -param intNtfType integer to represent notification type:
// - 1 : create
// - 2 : update
// - 3 : delete
// -param message human-readable message
// -param relationId relation id of the created/updated/deleted relation
// -param unregMBeanList list of ObjectNames of referenced MBeans
// expected to be unregistered due to relation removal (only for removal,
// due to CIM qualifiers, can be null)
// -param roleName role name
// -param roleNewValue role new value (ArrayList of ObjectNames)
// -param oldValue old role value (ArrayList of ObjectNames)
//
// -exception IllegalArgument if null parameter
// -exception RelationNotFoundException if no relation for given id
private void sendNotificationInt(int intNtfType,
String message,
String relationId,
List<ObjectName> unregMBeanList,
String roleName,
List<ObjectName> roleNewValue,
List<ObjectName> oldValue)
throws IllegalArgumentException,
RelationNotFoundException {
if (message == null ||
relationId == null ||
(intNtfType != 3 && unregMBeanList != null) ||
(intNtfType == 2 &&
(roleName == null ||
roleNewValue == null ||
oldValue == null))) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"sendNotificationInt", new Object[] {intNtfType, message,
relationId, unregMBeanList, roleName, roleNewValue, oldValue});
// Relation type name
// Note: do not use getRelationTypeName() as if it is a relation MBean
// it is already unregistered.
String relTypeName;
synchronized(myRelId2RelTypeMap) {
relTypeName = (myRelId2RelTypeMap.get(relationId));
}
// ObjectName (for a relation MBean)
// Can also throw a RelationNotFoundException, but detected above
ObjectName relObjName = isRelationMBean(relationId);
String ntfType = null;
if (relObjName != null) {
switch (intNtfType) {
case 1:
ntfType = RelationNotification.RELATION_MBEAN_CREATION;
break;
case 2:
ntfType = RelationNotification.RELATION_MBEAN_UPDATE;
break;
case 3:
ntfType = RelationNotification.RELATION_MBEAN_REMOVAL;
break;
}
} else {
switch (intNtfType) {
case 1:
ntfType = RelationNotification.RELATION_BASIC_CREATION;
break;
case 2:
ntfType = RelationNotification.RELATION_BASIC_UPDATE;
break;
case 3:
ntfType = RelationNotification.RELATION_BASIC_REMOVAL;
break;
}
}
// Sequence number
Long seqNo = atomicSeqNo.incrementAndGet();
// Timestamp
Date currDate = new Date();
long timeStamp = currDate.getTime();
RelationNotification ntf = null;
if (ntfType.equals(RelationNotification.RELATION_BASIC_CREATION) ||
ntfType.equals(RelationNotification.RELATION_MBEAN_CREATION) ||
ntfType.equals(RelationNotification.RELATION_BASIC_REMOVAL) ||
ntfType.equals(RelationNotification.RELATION_MBEAN_REMOVAL))
// Creation or removal
ntf = new RelationNotification(ntfType,
this,
seqNo.longValue(),
timeStamp,
message,
relationId,
relTypeName,
relObjName,
unregMBeanList);
else if (ntfType.equals(RelationNotification.RELATION_BASIC_UPDATE)
||
ntfType.equals(RelationNotification.RELATION_MBEAN_UPDATE))
{
// Update
ntf = new RelationNotification(ntfType,
this,
seqNo.longValue(),
timeStamp,
message,
relationId,
relTypeName,
relObjName,
roleName,
roleNewValue,
oldValue);
}
sendNotification(ntf);
RELATION_LOGGER.exiting(RelationService.class.getName(),
"sendNotificationInt");
return;
}
// Checks, for the unregistration of an MBean referenced in the roles given
// in parameter, if the relation has to be removed or not, regarding
// expected minimum role cardinality and current number of
// references in each role after removal of the current one.
// If the relation is kept, calls handleMBeanUnregistration() callback of
// the relation to update it.
//
// -param relationId relation id
// -param objectName ObjectName of the unregistered MBean
// -param roleNameList list of names of roles where the unregistered
// MBean is referenced.
//
// -exception IllegalArgumentException if null parameter
// -exception RelationServiceNotRegisteredException if the Relation
// Service is not registered in the MBean Server
// -exception RelationNotFoundException if unknown relation id
// -exception RoleNotFoundException if one role given as parameter does
// not exist in the relation
private void handleReferenceUnregistration(String relationId,
ObjectName objectName,
List<String> roleNameList)
throws IllegalArgumentException,
RelationServiceNotRegisteredException,
RelationNotFoundException,
RoleNotFoundException {
if (relationId == null ||
roleNameList == null ||
objectName == null) {
String excMsg = "Invalid parameter.";
throw new IllegalArgumentException(excMsg);
}
RELATION_LOGGER.entering(RelationService.class.getName(),
"handleReferenceUnregistration",
new Object[] {relationId, objectName, roleNameList});
// Can throw RelationServiceNotRegisteredException
isActive();
// Retrieves the relation type name of the relation
// Can throw RelationNotFoundException
String currRelTypeName = getRelationTypeName(relationId);
// Retrieves the relation
// Can throw RelationNotFoundException, but already detected above
Object relObj = getRelation(relationId);
// Flag to specify if the relation has to be deleted
boolean deleteRelFlag = false;
for (String currRoleName : roleNameList) {
if (deleteRelFlag) {
break;
}
// Retrieves number of MBeans currently referenced in role
// BEWARE! Do not use getRole() as role may be not readable
//
// Can throw RelationNotFoundException (but already checked),
// RoleNotFoundException
int currRoleRefNbr =
(getRoleCardinality(relationId, currRoleName)).intValue();
// Retrieves new number of element in role
int currRoleNewRefNbr = currRoleRefNbr - 1;
// Retrieves role info for that role
//
// Shall not throw RelationTypeNotFoundException or
// RoleInfoNotFoundException
RoleInfo currRoleInfo;
try {
currRoleInfo = getRoleInfo(currRelTypeName,
currRoleName);
} catch (RelationTypeNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (RoleInfoNotFoundException exc2) {
throw new RuntimeException(exc2.getMessage());
}
// Checks with expected minimum number of elements
boolean chkMinFlag = currRoleInfo.checkMinDegree(currRoleNewRefNbr);
if (!chkMinFlag) {
// The relation has to be deleted
deleteRelFlag = true;
}
}
if (deleteRelFlag) {
// Removes the relation
removeRelation(relationId);
} else {
// Updates each role in the relation using
// handleMBeanUnregistration() callback
//
// BEWARE: this roleNameList list MUST BE A COPY of a role name
// list for a referenced MBean in a relation, NOT a
// reference to an original one part of the
// myRefedMBeanObjName2RelIdsMap!!!! Because each role
// which name is in that list will be updated (potentially
// using setRole(). So the Relation Service will update the
// myRefedMBeanObjName2RelIdsMap to refelect the new role
// value!
for (String currRoleName : roleNameList) {
if (relObj instanceof RelationSupport) {
// Internal relation
// Can throw RoleNotFoundException (but already checked)
//
// Shall not throw
// RelationTypeNotFoundException,
// InvalidRoleValueException (value was correct, removing
// one reference shall not invalidate it, else detected
// above)
try {
((RelationSupport)relObj).handleMBeanUnregistrationInt(
objectName,
currRoleName,
true,
this);
} catch (RelationTypeNotFoundException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (InvalidRoleValueException exc4) {
throw new RuntimeException(exc4.getMessage());
}
} else {
// Relation MBean
Object[] params = new Object[2];
params[0] = objectName;
params[1] = currRoleName;
String[] signature = new String[2];
signature[0] = "javax.management.ObjectName";
signature[1] = "java.lang.String";
// Shall not throw InstanceNotFoundException, or
// MBeanException (wrapping RoleNotFoundException or
// MBeanException or InvalidRoleValueException) or
// ReflectionException
try {
myMBeanServer.invoke(((ObjectName)relObj),
"handleMBeanUnregistration",
params,
signature);
} catch (InstanceNotFoundException exc1) {
throw new RuntimeException(exc1.getMessage());
} catch (ReflectionException exc3) {
throw new RuntimeException(exc3.getMessage());
} catch (MBeanException exc2) {
Exception wrappedExc = exc2.getTargetException();
throw new RuntimeException(wrappedExc.getMessage());
}
}
}
}
RELATION_LOGGER.exiting(RelationService.class.getName(),
"handleReferenceUnregistration");
return;
}
}
| {
"content_hash": "b66d78b8ed4b2115fffa86d1639c321b",
"timestamp": "",
"source": "github",
"line_count": 3767,
"max_line_length": 118,
"avg_line_length": 39.81550305282718,
"alnum_prop": 0.585991932526586,
"repo_name": "haikuowuya/android_system_code",
"id": "20d3c1da7261b382e4a3d8ca3a3405229c32db59",
"size": "150200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/javax/management/relation/RelationService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "182432"
},
{
"name": "Java",
"bytes": "124952631"
}
],
"symlink_target": ""
} |
package org.apache.drill.metastore.metadata;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.exec.record.metadata.ColumnMetadata;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.metastore.components.tables.TableMetadataUnit;
import org.apache.drill.metastore.statistics.ColumnStatistics;
import org.apache.drill.metastore.statistics.StatisticsKind;
import java.util.Map;
/**
* Represents a metadata for the non-interesting columns. Since the refresh command doesn't store the non-interesting
* columns stats in the cache file, there is a need to mark column statistics of non-interesting as unknown to
* differentiate the non-interesting columns from non-existent columns. Since the sole purpose of this class is to store
* column statistics for non-interesting columns, some methods like getSchema, get, getColumn are not applicable
* to NonInterestingColumnsMetadata.
*/
public class NonInterestingColumnsMetadata implements Metadata {
private final Map<SchemaPath, ColumnStatistics> columnsStatistics;
public NonInterestingColumnsMetadata(Map<SchemaPath, ColumnStatistics> columnsStatistics) {
this.columnsStatistics = columnsStatistics;
}
@Override
public Map<SchemaPath, ColumnStatistics> getColumnsStatistics() {
return columnsStatistics;
}
@Override
public ColumnStatistics getColumnStatistics(SchemaPath columnName) {
return columnsStatistics.get(columnName);
}
@Override
public TupleMetadata getSchema() {
return null;
}
@Override
public <V> V getStatistic(StatisticsKind<V> statisticsKind) {
return null;
}
@Override
public boolean containsExactStatistics(StatisticsKind statisticsKind) {
return false;
}
@Override
@SuppressWarnings("unchecked")
public <V> V getStatisticsForColumn(SchemaPath columnName, StatisticsKind<V> statisticsKind) {
return (V) columnsStatistics.get(columnName).get(statisticsKind);
}
@Override
public ColumnMetadata getColumn(SchemaPath name) {
return null;
}
@Override
public TableInfo getTableInfo() {
return null;
}
@Override
public MetadataInfo getMetadataInfo() {
return null;
}
@Override
public TableMetadataUnit toMetadataUnit() {
return null;
}
}
| {
"content_hash": "f5f83ce0372480755e2445ebce400085",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 120,
"avg_line_length": 29.727272727272727,
"alnum_prop": 0.7767584097859327,
"repo_name": "kkhatua/drill",
"id": "6944ab0319821531628cd2f0bccf154b169b9719",
"size": "3090",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metastore/metastore-api/src/main/java/org/apache/drill/metastore/metadata/NonInterestingColumnsMetadata.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "21592"
},
{
"name": "Batchfile",
"bytes": "7655"
},
{
"name": "C",
"bytes": "31425"
},
{
"name": "C++",
"bytes": "589768"
},
{
"name": "CMake",
"bytes": "24879"
},
{
"name": "CSS",
"bytes": "15036"
},
{
"name": "Dockerfile",
"bytes": "1440"
},
{
"name": "FreeMarker",
"bytes": "187657"
},
{
"name": "Java",
"bytes": "28600327"
},
{
"name": "JavaScript",
"bytes": "81650"
},
{
"name": "PLSQL",
"bytes": "2685"
},
{
"name": "Python",
"bytes": "5388"
},
{
"name": "Shell",
"bytes": "101018"
},
{
"name": "TSQL",
"bytes": "6340"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "583231c229a867db5b40c3e4441a23c3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "e828ee15a7f5e87efaae5cb5c9d487d42c9eb865",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Onagraceae/Oenothera/Oenothera hirsuta/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
define( [ "jquery", "../animationComplete", "./transition" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $ ) {
$.mobile.SerialTransition = function() {
this.init.apply(this, arguments);
};
$.extend($.mobile.SerialTransition.prototype, $.mobile.Transition.prototype, {
sequential: true,
beforeDoneOut: function() {
if ( this.$from ) {
this.cleanFrom();
}
},
beforeStartOut: function( screenHeight, reverseClass, none ) {
this.$from.animationComplete($.proxy(function() {
this.doneOut( screenHeight, reverseClass, none );
}, this ));
}
});
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
| {
"content_hash": "8efbe99fd477098a52aaed03bc29b214",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 82,
"avg_line_length": 24.79310344827586,
"alnum_prop": 0.6578581363004172,
"repo_name": "ericsteele/retrospec.js",
"id": "5f7363f80266e2ae2e119f7a99db23c899199cd5",
"size": "913",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "test/input/projects/jquery-mobile/rev-1.4.5-2ef45a1/js/transitions/serial.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "32031"
},
{
"name": "HTML",
"bytes": "10865060"
},
{
"name": "JavaScript",
"bytes": "142079535"
},
{
"name": "PHP",
"bytes": "125510"
}
],
"symlink_target": ""
} |
#ifndef SRC_COMPONENTS_INCLUDE_POLICY_POLICY_REGULAR_POLICY_POLICY_MANAGER_H_
#define SRC_COMPONENTS_INCLUDE_POLICY_POLICY_REGULAR_POLICY_POLICY_MANAGER_H_
#include <vector>
#include <cstdint>
#include "utils/callable.h"
#include "policy/policy_types.h"
#include "policy/policy_table/types.h"
#include "policy/policy_listener.h"
#include "policy/usage_statistics/statistics_manager.h"
#ifdef SDL_REMOTE_CONTROL
#include "policy/access_remote.h"
#endif // SDL_REMOTE_CONTROL
namespace policy {
class PolicySettings;
typedef utils::SharedPtr<utils::Callable> StatusNotifier;
class PolicyManager : public usage_statistics::StatisticsManager {
public:
virtual ~PolicyManager() {}
/**
* @brief set_listener set new policy listener instance
* @param listener new policy listener
*/
virtual void set_listener(PolicyListener* listener) = 0;
/**
* @brief Inits Policy Table
* @param file_name path to preloaded PT file
* @param settings pointer to policy init settings
* @return true if init is successful
*/
virtual bool InitPT(const std::string& file_name,
const PolicySettings* settings) = 0;
/**
* @brief Updates Policy Table from binary message received from
* mobile device. Saves to Policy Table diff between Policy Table
* sent in snapshot and received Policy Table.
* @param file name of file with update policy table
* @param pt_content PTU as binary string
* @return true if successfully
*/
virtual bool LoadPT(const std::string& file,
const BinaryMessage& pt_content) = 0;
/**
* @brief Resets Policy Table
* @param file_name Path to preloaded PT file
* @return true if successfully
*/
virtual bool ResetPT(const std::string& file_name) = 0;
/**
* @brief GetLockScreenIcon allows to obtain lock screen icon url;
* @return url which point to the resourse where lock screen icon could be
*obtained.
*/
virtual std::string GetLockScreenIconUrl() const = 0;
/**
* @brief Gets all URLs for sending PTS to from PT itself.
* @param service_type Service specifies user of URL
* @param out_end_points output vector of urls
*/
virtual void GetUpdateUrls(const std::string& service_type,
EndpointUrls& out_end_points) = 0;
virtual void GetUpdateUrls(const uint32_t service_type,
EndpointUrls& out_end_points) = 0;
/**
* @brief PTU is needed, for this PTS has to be formed and sent.
*/
virtual bool RequestPTUpdate() = 0;
/**
* @brief Check if specified RPC for specified application
* has permission to be executed in specified HMI Level
* and also its permitted params.
* @param device_id Id of device of application
* @param app_id Id of application provided during registration
* @param hmi_level Current HMI Level of application
* @param rpc Name of RPC
* @param rpc_params List of RPC params
* @param result containing flag if HMI Level is allowed and list of
* allowed params.
*/
virtual void CheckPermissions(const PTString& device_id,
const PTString& app_id,
const PTString& hmi_level,
const PTString& rpc,
const RPCParams& rpc_params,
CheckPermissionResult& result) = 0;
/**
* @brief Changes isConsentNeeded for app pending permissions, in case
* user set permissions before app activation.
* @param Unique app id
* @param Current permissions for app
*/
virtual void CheckPendingPermissionsChanges(
const std::string& policy_app_id,
const std::vector<FunctionalGroupPermission>& current_permissions) = 0;
/**
* @brief Clear all record of user consents. Used during Factory Reset.
* @return bool Success of operation
*/
virtual bool ResetUserConsent() = 0;
/**
* @brief Returns current status of policy table for HMI
* @return Current status of policy table
*/
virtual std::string GetPolicyTableStatus() const = 0;
/**
* @brief Checks is PT exceeded kilometers
* @param kilometers current kilometers at odometer
* @return true if exceeded
*/
virtual void KmsChanged(int kilometers) = 0;
/**
* @brief Increments counter of ignition cycles
*/
virtual void IncrementIgnitionCycles() = 0;
/**
* @brief Exchange by hmi or mobile request
* @return Current status of policy table
*/
virtual std::string ForcePTExchange() = 0;
/**
* @brief Exchange by user request
* @return Current status of policy table
*/
virtual std::string ForcePTExchangeAtUserRequest() = 0;
/**
* @brief Gets timeout to wait before next retry updating PT
* If timeout is less or equal to zero then the retry sequence is not need.
* @return timeout in seconds
*/
virtual uint32_t NextRetryTimeout() = 0;
/**
* @brief Gets timeout to wait until receive response
* @return timeout in seconds
*/
virtual uint32_t TimeoutExchangeMSec() = 0;
/**
* @brief List of timeouts in seconds between retries
* when attempt to update PT fails
* @return List of delays between attempts.
*/
virtual const std::vector<int> RetrySequenceDelaysSeconds() = 0;
/**
* @brief Handler of exceeding timeout of exchanging policy table
*/
virtual void OnExceededTimeout() = 0;
/**
* @brief Handler of PTS sending out
*/
virtual void OnUpdateStarted() = 0;
/**
* @brief Gets user consent for mobile device data connection
* @param device_id Unique device identifier
* @return status of device consent
*/
virtual DeviceConsent GetUserConsentForDevice(
const std::string& device_id) const = 0;
/**
* @brief Gets user consent for application
* @param device_id Device id
* @param policy_app_id Unique application id
* @param permissions Array of functional groups permissions
*/
virtual void GetUserConsentForApp(
const std::string& device_id,
const std::string& policy_app_id,
std::vector<FunctionalGroupPermission>& permissions) = 0;
/**
* @brief Set user consent for mobile device data connection
* @param device_id Unique device identifier
* @param is_allowed User consent for usage device data connection
*/
virtual void SetUserConsentForDevice(const std::string& device_id,
bool is_allowed) = 0;
/**
* @brief Update Application Policies as reaction
* on User allowing/disallowing device this app is running on.
* @param app_id Unique application id
* @param is_device_allowed true if user allowing device otherwise false
* @return true if operation was successful
*/
virtual bool ReactOnUserDevConsentForApp(const std::string app_id,
bool is_device_allowed) = 0;
/**
* @brief Sets counter value that passed for receiving PT UPdate.
*/
virtual void PTUpdatedAt(Counters counter, int value) = 0;
/**
* @brief Retrieves data from app_policies about app on its registration:
* @param application_id - id of registered app
* @param nicknames Synonyms for application
* @param app_hmi_types Section on HMI where app can appear (Navigation, Phone
* etc)
*/
virtual bool GetInitialAppData(const std::string& application_id,
StringArray* nicknames = NULL,
StringArray* app_hmi_types = NULL) = 0;
/**
* @brief Add's device to policy table
* @param device_id Device mac address
* @param connection_type Device connection type
*/
virtual void AddDevice(const std::string& device_id,
const std::string& connection_type) = 0;
/**
* @brief Stores device parameters received during application registration
* to policy table
* @param device_id Device mac address
* @param device_info Received device parameters
*/
virtual void SetDeviceInfo(const std::string& device_id,
const DeviceInfo& device_info) = 0;
/**
* @brief Set user consent for application functional groups
* @param permissions User-defined application group pemissions.
* The permissions is not const reference because it may contains
* valid data as well as invalid. So we will remove all invalid data
* from this structure.
*/
virtual void SetUserConsentForApp(const PermissionConsent& permissions) = 0;
/**
* @brief Get default HMI level for application
* @param policy_app_id Unique application id
* @param default_hmi Default HMI level for application or empty, if value
* was not set
* @return true, if succedeed, otherwise - false
*/
virtual bool GetDefaultHmi(const std::string& policy_app_id,
std::string* default_hmi) const = 0;
/**
* @brief Get priority for application
* @param policy_app_id Unique application id
* @param priority Priority for application or empty, if value was not set
* @return true, if succedeed, otherwise - false
*/
virtual bool GetPriority(const std::string& policy_app_id,
std::string* priority) const = 0;
/**
* @brief Get user friendly messages for given RPC messages and language
* @param message_codes RPC message codes
* @param language Language
* @return Array of structs with appropriate message parameters
*/
virtual std::vector<UserFriendlyMessage> GetUserFriendlyMessages(
const std::vector<std::string>& message_code,
const std::string& language) = 0;
/**
* @brief Checks if the application is revoked
* @param app_id application id
* @return true if application is revoked
*/
virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
/**
* @brief Get resulting RPCs permissions for application which started on
* specific device
* @param device_id Device id
* @param policy_app_id Unique application id
* @param permissions Array of functional groups permissions
*/
virtual void GetPermissionsForApp(
const std::string& device_id,
const std::string& policy_app_id,
std::vector<FunctionalGroupPermission>& permissions) = 0;
/**
* @brief Gets specific application permissions changes since last policy
* table update
* @param policy_app_id Unique application id
* @return Permissions changes
*/
virtual AppPermissions GetAppPermissionsChanges(
const std::string& policy_app_id) = 0;
/**
* @brief Removes specific application permissions changes
* @param app_id Unique application id
*/
virtual void RemovePendingPermissionChanges(const std::string& app_id) = 0;
/**
* @brief Return device id, which hosts specific application
* @param policy_app_id Application id, which is required to update device id
*/
virtual std::string& GetCurrentDeviceId(
const std::string& policy_app_id) const = 0;
/**
* @brief Set current system language
* @param language Language
*/
virtual void SetSystemLanguage(const std::string& language) = 0;
/**
* @brief Set data from GetSystemInfo response to policy table
* @param ccpu_version CCPU version
* @param wers_country_code WERS country code
* @param language System language
*/
virtual void SetSystemInfo(const std::string& ccpu_version,
const std::string& wers_country_code,
const std::string& language) = 0;
/**
* @brief Send OnPermissionsUpdated for choosen application
* @param application_id Unique application id
*/
virtual void SendNotificationOnPermissionsUpdated(
const std::string& application_id) = 0;
/**
* @brief Marks device as upaired
* @param device_id id device
*/
virtual void MarkUnpairedDevice(const std::string& device_id) = 0;
/**
* @brief Adds, application to the db or update existed one
* run PTU if policy update is necessary for application.
* @param application_id Unique application id
* @param hmi_types application HMI types
* @return function that will notify update manager about new application
*/
virtual StatusNotifier AddApplication(
const std::string& application_id,
const rpc::policy_table_interface_base::AppHmiTypes& hmi_types) = 0;
/**
* @brief Removes unpaired device records and related records from DB
* @return true, if succedeed, otherwise - false
*/
virtual bool CleanupUnpairedDevices() = 0;
/**
* @brief Check if app can keep context.
* @param app_id Unique application id
* @return true if app can keep context, otherwise - false
*/
virtual bool CanAppKeepContext(const std::string& app_id) const = 0;
/**
* @brief Check if app can steal focus.
* @param app_id Unique application id
* @return true if app can steal focus, otherwise - false
*/
virtual bool CanAppStealFocus(const std::string& app_id) const = 0;
/**
* @brief Runs necessary operations, which is depends on external system
* state, e.g. getting system-specific parameters which are need to be
* filled into policy table
*/
virtual void OnSystemReady() = 0;
/**
* @brief Get number of notification by priority
* @param priority Specified priority
* @return notification number
*/
virtual uint32_t GetNotificationsNumber(
const std::string& priority) const = 0;
/**
* @brief Allows to update Vehicle Identification Number in policy table.
* @param new value for the parameter.
*/
virtual void SetVINValue(const std::string& value) = 0;
/**
* @brief Checks, if application has policy assigned w/o data consent
* @param policy_app_id Unique application id
* @return true, if policy assigned w/o data consent, otherwise -false
*/
virtual bool IsPredataPolicy(const std::string& policy_app_id) const = 0;
/**
* @brief Returns heart beat timeout
* @param app_id application id
* @return if timeout was set then value in milliseconds greater zero
* otherwise heart beat for specific application isn't set
*/
virtual uint32_t HeartBeatTimeout(const std::string& app_id) const = 0;
/**
* @brief SaveUpdateStatusRequired allows to save update status.
* @param is_update_needed true if update needed
*/
virtual void SaveUpdateStatusRequired(bool is_update_needed) = 0;
/**
* @brief Handler on applications search started
*/
virtual void OnAppsSearchStarted() = 0;
/**
* @brief Handler on applications search completed
* @param trigger_ptu contains true if PTU should be triggered
*/
virtual void OnAppsSearchCompleted(const bool trigger_ptu) = 0;
/**
* @brief Gets request types for application
* @param policy_app_id Unique application id
* @return request types of application
*/
virtual const std::vector<std::string> GetAppRequestTypes(
const std::string policy_app_id) const = 0;
/**
* @brief Get information about vehicle
* @return vehicle information
*/
virtual const VehicleInfo GetVehicleInfo() const = 0;
/**
* @brief OnAppRegisteredOnMobile allows to handle event when application were
* succesfully registered on mobile device.
* It will send OnAppPermissionSend notification and will try to start PTU. *
* @param application_id registered application.
*/
virtual void OnAppRegisteredOnMobile(const std::string& application_id) = 0;
virtual void OnDeviceSwitching(const std::string& device_id_from,
const std::string& device_id_to) = 0;
/**
* @brief RetrieveCertificate Allows to obtain certificate in order
* to start secure connection.
* @return The certificate in PKCS#7 format.
*/
virtual std::string RetrieveCertificate() const = 0;
/**
* @brief HasCertificate check whether policy table has certificate
* int module_config section.
* @return true in case certificate exists, false otherwise
*/
virtual bool HasCertificate() const = 0;
/**
* @brief Getter for policy settings
* @return policy settings instance
*/
virtual const PolicySettings& get_settings() const = 0;
/**
* @brief Finds the next URL that must be sent on OnSystemRequest retry
* @param urls vector of vectors that contain urls for each application
* @return Pair of policy application id and application url id from the
* urls vector
*/
virtual AppIdURL GetNextUpdateUrl(const EndpointUrls& urls) = 0;
#ifdef SDL_REMOTE_CONTROL
/**
* @brief Assigns new HMI types for specified application
* @param application_id Unique application id
* @param hmi_types new HMI types list
*/
virtual void SetDefaultHmiTypes(const std::string& application_id,
const std::vector<int>& hmi_types) = 0;
/**
* @brief Gets HMI types
* @param application_id ID application
* @param app_types list to save HMI types
* @return true if policy has specific policy for this application
*/
virtual bool GetHMITypes(const std::string& application_id,
std::vector<int>* app_types) = 0;
/**
* @brief Checks if module for application is present in policy table
* @param app_id id of application
* @param module type
* @return true if module is present, otherwise - false
*/
virtual bool CheckModule(const PTString& app_id, const PTString& module) = 0;
/**
* @brief Send OnPermissionsChange notification to mobile app
* when it's permissions are changed.
* @param device_id Device on which app is running
* @param application_id ID of app whose permissions are changed
*/
virtual void SendAppPermissionsChanged(const std::string& device_id,
const std::string& application_id) = 0;
/**
* @brief Gets all allowed module types
* @param policy_app_id unique identifier of application
* @param modules list of allowed module types
* @return true if application has allowed modules
*/
virtual bool GetModuleTypes(const std::string& policy_app_id,
std::vector<std::string>* modules) const = 0;
/**
* @brief Setter for access_remote instance
* @param access_remote pointer to new access_remote instance
*/
virtual void set_access_remote(
utils::SharedPtr<AccessRemote> access_remote) = 0;
#endif // SDL_REMOTE_CONTROL
/**
* @brief Checks if there is existing URL in the EndpointUrls vector with
* index saved in the policy manager and if not, it moves to the next
* application index
* @param rs contains the application index and url index from the
* urls vector that are to be sent on the next OnSystemRequest
* @param urls vector of vectors that contain urls for each application
* @return Pair of application index and url index
*/
virtual AppIdURL RetrySequenceUrl(const struct RetrySequenceURL& rs,
const EndpointUrls& urls) const = 0;
protected:
/**
* @brief Checks is PT exceeded IgnitionCycles
* @return true if exceeded
*/
virtual bool ExceededIgnitionCycles() = 0;
/**
* @brief Checks is PT exceeded days
* @return true if exceeded
*/
virtual bool ExceededDays() = 0;
/**
* @brief StartPTExchange allows to start PTU. The function will check
* if one is required and starts the update flow in only case when previous
* condition is true.
*/
virtual void StartPTExchange() = 0;
};
} // namespace policy
extern "C" policy::PolicyManager* CreateManager();
extern "C" void DeleteManager(policy::PolicyManager*);
#endif // SRC_COMPONENTS_INCLUDE_POLICY_POLICY_REGULAR_POLICY_POLICY_MANAGER_H_
| {
"content_hash": "5c2a74402ea506d9aa3c05b3a1943917",
"timestamp": "",
"source": "github",
"line_count": 580,
"max_line_length": 80,
"avg_line_length": 34.1,
"alnum_prop": 0.6793912427950248,
"repo_name": "APCVSRepo/sdl_core",
"id": "3e90cfc094e5aa9e84311262a1d64cdf8b60404c",
"size": "21290",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/include/policy/policy_regular/policy/policy_manager.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "10491"
},
{
"name": "C++",
"bytes": "18387258"
},
{
"name": "CMake",
"bytes": "417637"
},
{
"name": "HTML",
"bytes": "1138"
},
{
"name": "M4",
"bytes": "25347"
},
{
"name": "Makefile",
"bytes": "139997"
},
{
"name": "PLpgSQL",
"bytes": "12824"
},
{
"name": "Python",
"bytes": "779378"
},
{
"name": "Shell",
"bytes": "692158"
}
],
"symlink_target": ""
} |
'''
Split methylation BigQuery table into chromosomes
'''
import pprint
import sys
import json
from apiclient.errors import HttpError
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
from oauth2client.client import AccessTokenRefreshError
import time
from bigquery_etl.utils.logging_manager import configure_logging
# TODO change this to single auth script (GOOGLE_APPLICATION_CREDENTIALS)
# still is still in progress
def get_service():
# Grab the application's default credentials from the environment.
credentials = GoogleCredentials.get_application_default()
# Construct the service object for interacting with the BigQuery API.
bigquery = discovery.build('bigquery', 'v2', credentials=credentials)
return bigquery
def split_table_by_chr(chromosome, project_id, dataset_id, log):
# this is a new connection to the new project
bigquery_service = get_service()
jobCollection = bigquery_service.jobs()
try:
query_request = bigquery_service.jobs()
# maybe there is a nice way to format this one?
query = """\
SELECT data.ParticipantBarcode AS ParticipantBarcode, data.SampleBarcode AS SampleBarcode, data.SampleTypeLetterCode AS SampleTypeLetterCode, \
data.AliquotBarcode AS AliquotBarcode, data.Platform AS Platform, data.Study AS Study, data.Probe_Id AS Probe_Id, data.Beta_Value as Beta_Value
FROM \
( \
SELECT IlmnID \
FROM [platform_reference.methylation_annotation] \
WHERE ( CHR == "{0}")\
) AS ids \
JOIN EACH \
(\
SELECT * \
FROM [{1}.Methylation] \
) AS data \
ON ids.IlmnID == data.Probe_Id""".format(chromosome, dataset_id)
log.info('importing chromosome %s\n%s' % (chromosome, query))
# query_data = {'query': query}
query_data = {
'configuration': {
'query': {
'query': query,
'useQueryCache': False,
'destinationTable': {
'projectId': project_id,
'datasetId': dataset_id,
'tableId': 'Methylation_chr{0}'.format(chromosome)
},
'createDisposition': 'CREATE_IF_NEEDED',
'writeDisposition': 'WRITE_EMPTY',
'allowLargeResults': True
}
}
}
insertResponse = query_request.insert(projectId=project_id, body=query_data).execute()
# Ping for status until it is done, with a short pause between calls.
while True:
result = jobCollection.get(projectId=project_id,
jobId=insertResponse['jobReference']['jobId']).execute()
status = result['status']
if 'DONE' == status['state']:
if 'errorResult' in status and status['errorResult']:
log.error('an error occurred completing import at \'%s\': %s \'%s\' for chormosome %s' %
(status['errorResult']['location'], status['errorResult']['reason'], status['errorResult']['message'], chromosome))
else:
log.info('completed import chromosome %s' % (chromosome))
break
if 'errors' in status and status['errors'] and 0 < len(status['errors']):
for error in status['errors']:
log.warning('\terror while importing chromosome %s: %s' % (chromosome, error))
log.info('\tWaiting for the import to complete for chromosome %s...' % (chromosome))
time.sleep(20)
except HttpError as err:
print 'Error:', pprint.pprint(err.content)
except AccessTokenRefreshError:
print ("Credentials have been revoked or expired, please re-run"
"the application to re-authorize")
def main(config, log):
log.info('start splitting methylation data by chromosome')
project_id = config['project_id']
dataset_id = config['bq_dataset']
chromosomes = map(str,range(1,23)) + ['X', 'Y']
# chromosomes = map(lambda orig_string: 'chr' + orig_string, chr_nums)
for chromosome in chromosomes:
split_table_by_chr(chromosome, project_id, dataset_id, log)
log.info('done splitting methylation data by chromosome')
if __name__ == '__main__':
# setup logging
with open(sys.argv[1]) as configfile:
config = json.load(configfile)
log = configure_logging('methylation_split', "logs/methylation_transform_split" + '.log')
main(config, log)
| {
"content_hash": "846d5549d9044fd51f369b6a90e0babe",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 160,
"avg_line_length": 43.5,
"alnum_prop": 0.6028097062579821,
"repo_name": "isb-cgc/ISB-CGC-data-proc",
"id": "572f84f7c51c084109df6cea781029ea1fcc9847",
"size": "5310",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "tcga_etl_pipeline/methylation/split_table.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Perl",
"bytes": "6576"
},
{
"name": "Python",
"bytes": "1169886"
},
{
"name": "Shell",
"bytes": "1068"
}
],
"symlink_target": ""
} |
extern "C" {
// This sampler imitates the open-source "brightness" tool at
// https://github.com/nriley/brightness.
// Since this sampler doesn't care about older MacOSen, multiple displays
// or other complications that tool has to consider, retrieving the brightness
// level boils down to calling this function for the main display.
extern int DisplayServicesGetBrightness(CGDirectDisplayID id,
float* brightness);
}
namespace power_sampler {
MainDisplaySampler::~MainDisplaySampler() = default;
// static
std::unique_ptr<MainDisplaySampler> MainDisplaySampler::Create() {
return base::WrapUnique(new MainDisplaySampler(CGMainDisplayID()));
}
std::string MainDisplaySampler::GetName() {
return kSamplerName;
}
Sampler::DatumNameUnits MainDisplaySampler::GetDatumNameUnits() {
DatumNameUnits ret;
// Display brightness is in units of 0-100% of max brightness.
ret.insert(std::make_pair("brightness", "%"));
ret.insert(std::make_pair("sleeping", "bool"));
return ret;
}
Sampler::Sample MainDisplaySampler::GetSample(base::TimeTicks sample_time) {
Sampler::Sample sample;
auto result = GetDisplayBrightness();
if (result.has_value())
sample.emplace("brightness", result.value() * 100.0);
sample.emplace("sleeping", GetIsDisplaySleeping());
return sample;
}
bool MainDisplaySampler::GetIsDisplaySleeping() {
return CGDisplayIsAsleep(main_display_);
}
absl::optional<float> MainDisplaySampler::GetDisplayBrightness() {
float brightness = 0.0;
int err = DisplayServicesGetBrightness(main_display_, &brightness);
if (err != 0)
return absl::nullopt;
return brightness;
}
MainDisplaySampler::MainDisplaySampler(CGDirectDisplayID main_display)
: main_display_(main_display) {}
} // namespace power_sampler
| {
"content_hash": "cf1a10b7ef0367e12d4dbcc401432e2e",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 78,
"avg_line_length": 30.491525423728813,
"alnum_prop": 0.7348526959421902,
"repo_name": "ric2b/Vivaldi-browser",
"id": "fc77d806df9c53b8dcbeca987e8db304c7089628",
"size": "2065",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/tools/mac/power/power_sampler/main_display_sampler.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/menu_background"
android:orientation="vertical" >
<ListView
android:id="@+id/menu_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="@color/list_item_divider"
android:dividerHeight="1dp" />
</LinearLayout> | {
"content_hash": "c8dfd75b08712593ea61922571373841",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 72,
"avg_line_length": 35.375,
"alnum_prop": 0.6837455830388692,
"repo_name": "zqingyang521/qingyang",
"id": "d77cbaeb5f29843d3a22e655833cebbf34c0d6fa",
"size": "566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "QingYangDemo/res/layout/pop_menu.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "182600"
}
],
"symlink_target": ""
} |
package org.apache.camel.component.freemarker;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
/**
* Unit test for wiki documentation
*/
public class FreemarkerLetterTest extends CamelTestSupport {
// START SNIPPET: e1
private Exchange createLetter() {
Exchange exchange = context.getEndpoint("direct:a").createExchange();
Message msg = exchange.getIn();
msg.setHeader("firstName", "Claus");
msg.setHeader("lastName", "Ibsen");
msg.setHeader("item", "Camel in Action");
msg.setBody("PS: Next beer is on me, James");
return exchange;
}
@Test
public void testFreemarkerLetter() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body().contains("Dear Ibsen, Claus");
mock.message(0).body().contains("Thanks for the order of Camel in Action.");
template.send("direct:a", createLetter());
mock.assertIsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:a")
.to("freemarker:org/apache/camel/component/freemarker/letter.ftl")
.to("mock:result");
}
};
}
// END SNIPPET: e1
}
| {
"content_hash": "d2897b65f4d369588aaa5ef6d0e7f452",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 90,
"avg_line_length": 30.53846153846154,
"alnum_prop": 0.6397984886649875,
"repo_name": "apache/camel",
"id": "68df8fccfd8c0cf9826d1963a128ce59328e4d0c",
"size": "2390",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "components/camel-freemarker/src/test/java/org/apache/camel/component/freemarker/FreemarkerLetterTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6695"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Dockerfile",
"bytes": "5676"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "412301"
},
{
"name": "HTML",
"bytes": "213802"
},
{
"name": "Java",
"bytes": "114936384"
},
{
"name": "JavaScript",
"bytes": "103655"
},
{
"name": "Jsonnet",
"bytes": "1734"
},
{
"name": "Kotlin",
"bytes": "41869"
},
{
"name": "Mustache",
"bytes": "525"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Ruby",
"bytes": "88"
},
{
"name": "Shell",
"bytes": "15327"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "699"
},
{
"name": "XSLT",
"bytes": "276597"
}
],
"symlink_target": ""
} |
TAGNAME=`git tag --contains=HEAD`
if [ "$TAGNAME" == "" ]; then
echo "bad git tag!"
exit 1
fi
cargo clean && cargo doc --no-deps
git branch -D gh-pages | :
git checkout -b gh-pages github/gh-pages
ls | grep -v target | xargs rm -rf
mv target/doc/* .
rm -rf target
git add *
git commit -m "update Document $TAGNAME"
git checkout master
| {
"content_hash": "e9e599256e5cda399c293886ee1d36de",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 40,
"avg_line_length": 22.933333333333334,
"alnum_prop": 0.6627906976744186,
"repo_name": "harre-orz/rust_asio",
"id": "73e26b00c430fe31b7dad18fbce9e7670696573c",
"size": "358",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy-doc.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Rust",
"bytes": "422741"
},
{
"name": "Shell",
"bytes": "358"
}
],
"symlink_target": ""
} |
/**
* Animate position of widget
*/
core.Class("unify.fx.Rotate", {
include: [unify.fx.core.Base],
construct : function(widget) {
unify.fx.core.Base.call(this, widget);
},
members : {
__mod : null,
__anim : null,
__resetPoint: null,
_setup : function() {
var to = this.getValue();
var from = this.__resetPoint = this._widget.getOwnStyle("transform");
var matcher = new RegExp("rotate\\(([^)]+)deg\\)");
var parsed = matcher.exec(from);
var mod;
if (parsed && parsed.length == 2) {
mod = this.__mod = parseFloat(parsed[1]);
} else {
mod = this.__mod = 0;
}
this.__anim = to - mod;
},
_reset : function(value) {
this._widget.setOwnStyle({
transform: value||""
});
},
_getResetValue : function() {
return this.__resetPoint;
},
_render : function(percent, now, render) {
if (!render) {
return;
}
var mod = this.__mod;
var anim = this.__anim;
this._widget.setPostLayout("rotate(" + (mod + anim * percent) + "deg)");
}
}
}); | {
"content_hash": "1b0e16d0e74eeb0bc48e8861380d7b1b",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 75,
"avg_line_length": 19.314814814814813,
"alnum_prop": 0.5580057526366251,
"repo_name": "unify/unify",
"id": "2b66fa2fcc23728ed77cb4232faec5c87c23a333",
"size": "1395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "unify/framework/source/class/unify/fx/Rotate.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6082"
},
{
"name": "Java",
"bytes": "309"
},
{
"name": "JavaScript",
"bytes": "881183"
},
{
"name": "Objective-C",
"bytes": "2895"
},
{
"name": "Perl",
"bytes": "108"
},
{
"name": "Python",
"bytes": "29297"
},
{
"name": "Ruby",
"bytes": "557048"
},
{
"name": "Shell",
"bytes": "1532"
}
],
"symlink_target": ""
} |
@interface OEXTextStyle ()
@property (assign, nonatomic) NSTextAlignment alignment;
@property (strong, nonatomic) UIColor* color;
@property (assign, nonatomic) OEXLetterSpacing letterSpacing;
@property (assign, nonatomic) NSLineBreakMode lineBreakMode;
@property (assign, nonatomic) CGFloat paragraphSpacing;
@property (assign, nonatomic) CGFloat paragraphSpacingBefore;
@property (assign, nonatomic) OEXTextSize size;
@property (assign, nonatomic) OEXTextWeight weight;
@end
@implementation OEXTextStyle
- (id)initWithWeight:(OEXTextWeight)weight size:(OEXTextSize)size color:(UIColor*)color {
self = [super init];
if(self != nil) {
self.color = color;
self.weight = weight;
self.size = size;
self.letterSpacing = OEXLetterSpacingNormal;
self.lineBreakMode = NSLineBreakByTruncatingTail;
self.alignment = NSTextAlignmentNatural;
}
return self;
}
- (id)init {
NSAssert(NO, @"Please call the designated initializer: initWithWeight:size:color:");
return [self initWithWeight:OEXTextWeightNormal size:OEXTextSizeBase color:nil];
}
- (BOOL)isEqual:(id)object {
OEXTextStyle* style = OEXSafeCastAsClass(object, OEXTextStyle);
return style != nil
&& [style.color isEqual:self.color]
&& style.size == self.size
&& style.weight == self.weight
&& style.paragraphSpacingBefore == self.paragraphSpacingBefore
&& style.paragraphSpacing == self.paragraphSpacing
&& style.letterSpacing == self.letterSpacing
&& style.alignment == self.alignment
&& style.lineBreakMode == self.lineBreakMode;
}
- (OEXTextStyle*(^)(OEXTextWeight weight))withWeight {
return ^(OEXTextWeight weight) {
OEXMutableTextStyle* style = self.mutableCopy;
style.weight = weight;
return style;
};
}
- (OEXTextStyle*(^)(OEXTextSize size))withSize {
return ^(OEXTextSize size) {
OEXMutableTextStyle* style = self.mutableCopy;
style.size = size;
return style;
};
}
- (OEXTextStyle*(^)(UIColor* color))withColor {
return ^(UIColor* color) {
OEXMutableTextStyle* style = self.mutableCopy;
style.color = color;
return style;
};
}
- (instancetype)copyWithZone:(NSZone *)zone {
return [self mutableCopyWithZone:zone];
}
- (instancetype)mutableCopyWithZone:(NSZone *)zone {
OEXMutableTextStyle* copy = [[OEXMutableTextStyle allocWithZone:zone] initWithWeight:self.weight size:self.size color:self.color];
copy.alignment = self.alignment;
copy.letterSpacing = self.letterSpacing;
copy.lineBreakMode = self.lineBreakMode;
copy.paragraphSpacing = self.paragraphSpacing;
copy.paragraphSpacingBefore = self.paragraphSpacingBefore;
return copy;
}
+ (CGFloat)pointSizeForTextSize:(OEXTextSize)size {
switch (size) {
case OEXTextSizeBase: return 16;
case OEXTextSizeXXXXLarge: return 38;
case OEXTextSizeXXXLarge: return 28;
case OEXTextSizeXXLarge: return 24;
case OEXTextSizeXLarge: return 21;
case OEXTextSizeLarge: return 18;
case OEXTextSizeXXXSmall: return 10;
case OEXTextSizeXXSmall: return 11;
case OEXTextSizeXSmall: return 12;
case OEXTextSizeSmall: return 14;
}
}
- (UIFont*)fontWithWeight:(OEXTextWeight)weight size:(OEXTextSize)size {
CGFloat pointSize = [[self class] pointSizeForTextSize:size];
switch (weight) {
case OEXTextWeightNormal:
return [[OEXStyles sharedStyles] sansSerifOfSize:pointSize] ?: [UIFont systemFontOfSize:pointSize];
case OEXTextWeightLight:
return [[OEXStyles sharedStyles] lightSansSerifOfSize:pointSize] ?: [UIFont systemFontOfSize:pointSize];
case OEXTextWeightSemiBold:
return [[OEXStyles sharedStyles] semiBoldSansSerifOfSize:pointSize] ?: [UIFont boldSystemFontOfSize:pointSize];
case OEXTextWeightBold:
return [[OEXStyles sharedStyles] boldSansSerifOfSize:pointSize] ?: [UIFont boldSystemFontOfSize:pointSize];
}
}
- (NSNumber*)kerningForLetterSpacing:(OEXLetterSpacing)spacing {
switch (spacing) {
case OEXLetterSpacingNormal: return nil;
case OEXLetterSpacingLoose: return @(0.95);
case OEXLetterSpacingXLoose: return @(2);
case OEXLetterSpacingXXLoose: return @(3);
case OEXLetterSpacingTight: return @(-.95);
case OEXLetterSpacingXTight: return @(-2);
case OEXLetterSpacingXXTight: return @(-3);
}
}
- (NSDictionary*)attributes {
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = self.lineBreakMode;
style.paragraphSpacing = self.paragraphSpacing;
style.paragraphSpacingBefore = self.paragraphSpacingBefore;
style.alignment = self.alignment;
NSMutableDictionary* attributes = [[NSMutableDictionary alloc] init];
[attributes setObjectOrNil:[self fontWithWeight:self.weight size:self.size] forKey:NSFontAttributeName];
[attributes setObjectOrNil:self.color forKey:NSForegroundColorAttributeName];
[attributes setObject:style forKey:NSParagraphStyleAttributeName];
if (self.letterSpacing != OEXLetterSpacingNormal) {
[attributes setObjectOrNil:[self kerningForLetterSpacing:self.letterSpacing] forKey:NSKernAttributeName];
}
return attributes;
}
- (NSAttributedString*)attributedStringWithText:(NSString *)text {
return [[NSAttributedString alloc] initWithString:text ?: @"" attributes:self.attributes];
}
@end
@implementation OEXMutableTextStyle
@dynamic alignment;
@dynamic color;
@dynamic letterSpacing;
@dynamic lineBreakMode;
@dynamic paragraphSpacing;
@dynamic paragraphSpacingBefore;
@dynamic size;
@dynamic weight;
@end
| {
"content_hash": "a55dfdf7b3bf2721741d12fa8ce3b306",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 134,
"avg_line_length": 34.872727272727275,
"alnum_prop": 0.7167188043100452,
"repo_name": "adoosii/edx-app-ios",
"id": "51190985e6fb37a691fbe5984f14c5917489e636",
"size": "5987",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/OEXTextStyle.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "2926"
},
{
"name": "CSS",
"bytes": "1401"
},
{
"name": "HTML",
"bytes": "208520"
},
{
"name": "Objective-C",
"bytes": "1560450"
},
{
"name": "Ruby",
"bytes": "2445"
},
{
"name": "Swift",
"bytes": "887468"
}
],
"symlink_target": ""
} |
module HTTP
class Request
class Writer
# CRLF is the universal HTTP delimiter
CRLF = "\r\n"
# Types valid to be used as body source
VALID_BODY_TYPES = [String, NilClass, Enumerable]
def initialize(socket, body, headers, headerstart) # rubocop:disable ParameterLists
@body = body
@socket = socket
@headers = headers
@request_header = [headerstart]
validate_body_type!
end
# Adds headers to the request header from the headers array
def add_headers
@headers.each do |field, value|
@request_header << "#{field}: #{value}"
end
end
# Stream the request to a socket
def stream
send_request_header
send_request_body
end
# Adds the headers to the header array for the given request body we are working
# with
def add_body_type_headers
if @body.is_a?(String) && !@headers['Content-Length']
@request_header << "Content-Length: #{@body.bytesize}"
elsif @body.is_a?(Enumerable) && 'chunked' != @headers['Transfer-Encoding']
fail(RequestError, 'invalid transfer encoding')
end
end
# Joins the headers specified in the request into a correctly formatted
# http request header string
def join_headers
# join the headers array with crlfs, stick two on the end because
# that ends the request header
@request_header.join(CRLF) + (CRLF) * 2
end
def send_request_header
add_headers
add_body_type_headers
header = join_headers
@socket << header
end
def send_request_body
if @body.is_a?(String)
@socket << @body
elsif @body.is_a?(Enumerable)
@body.each do |chunk|
@socket << chunk.bytesize.to_s(16) << CRLF
@socket << chunk << CRLF
end
@socket << '0' << CRLF * 2
end
end
private
def validate_body_type!
return if VALID_BODY_TYPES.any? { |type| @body.is_a? type }
fail RequestError, "body of wrong type: #{@body.class}"
end
end
end
end
| {
"content_hash": "22ada3e9a09e91c9292a3573175f87b4",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 89,
"avg_line_length": 27.974683544303797,
"alnum_prop": 0.5733031674208144,
"repo_name": "rubygem/website",
"id": "7586cf3a7b90e678599cd3bbfcc5b8caa9b24d18",
"size": "2210",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gems/ruby/2.2.0/gems/http-0.7.1/lib/http/request/writer.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "455330"
},
{
"name": "C",
"bytes": "1730986"
},
{
"name": "C++",
"bytes": "111879"
},
{
"name": "CSS",
"bytes": "782833"
},
{
"name": "CoffeeScript",
"bytes": "91"
},
{
"name": "Cucumber",
"bytes": "22093"
},
{
"name": "Groff",
"bytes": "4034"
},
{
"name": "HTML",
"bytes": "24610"
},
{
"name": "Java",
"bytes": "1129744"
},
{
"name": "JavaScript",
"bytes": "823233"
},
{
"name": "Liquid",
"bytes": "70"
},
{
"name": "Logos",
"bytes": "1171"
},
{
"name": "Makefile",
"bytes": "67894"
},
{
"name": "Ragel in Ruby Host",
"bytes": "140816"
},
{
"name": "Ruby",
"bytes": "9931961"
},
{
"name": "Shell",
"bytes": "377702"
},
{
"name": "TeX",
"bytes": "230259"
}
],
"symlink_target": ""
} |
Passwords microservice implements a REST compatible API, that can be accessed on configured port.
All input and output data is serialized in JSON format. Errors are returned in [standard format]().
* [UserPasswordV1 class](#class1)
* [POST /passwords/set_password](#operation1)
* [POST /passwords/delete_password](#operation2)
* [POST /passwords/authenticate](#operation3)
* [POST /passwords/change_password](#operation4)
* [POST /passwords/reset_password](#operation5)
* [POST /passwords/recover_password](#operation6)
## Data types
### <a name="class1"></a> UserPasswordV1 class
Represents a user password with his ID, name, password and key settings.
It also tracks authentication attempts and recovery codes.
**Properties:**
- id: string - unique user id
- password: string - SHA256 hash for user password (password isn't stored for security)
- locked: boolean - true if user account was temporary locked after few failed authentication attempts
- lock_time: Date - date and time when lock expires
- fail_count: int - number of sequential failed attempts
- fail_time: Date - date and time of the last failed attempt
- rec_code: string - password recovery code that was sent to user in email message
- rec\_expire\_time: Date - date and time when password recovery code expires
- custom_hdr: Object - custom data summary that is always returned (in list and details)
- custom_dat: Object - custom data details that is returned only when a single object is returned (details)
## Operations
### <a name="operation1"></a> Method: 'POST', route '/passwords/set_password'
Sets a password for a new user in the system
**Request body:**
- user_id: string - unique user id
- password: string - user password
**Response body:**
Occured error or null for success
### <a name="operation2"></a> Method: 'DELETE', route '/passwords/delete_password'
Deletes user password from the system (use it carefully!)
**Request body:**
- user_id: string - unique user id
**Response body:**
Occurred error or null for success
### <a name="operation3"></a> Method: 'POST', route '/passwords/authenticate'
Authenticates user using ID/password combination and returns user account.
The user can identified either by unique id or primary email.
**Request body:**
- user_id: string - (optional) unique user id
- password: string - user password
**Response body:**
- authenticated: bool - True for authenticated and False or error for failure
### <a name="operation4"></a> Method: 'POST', route '/passwords/change_password'
Changes user password by providing old password.
**Request body:**
- user_id: string - unique user id
- old_password: string - old user password
- new_password: string - new user password
**Response body:**
Occurred error or null for success
### <a name="operation5"></a> Method: 'POST', route '/passwords/reset_password'
Resets user password by providing recovery code
**Request body:**
- user_id: string - unique user id
- password: string - new user password
- code: string - password recovery code
**Response body:**
Occurred error or null for success
### <a name="operation6"></a> Method: 'POST', route '/passwors/recover_password'
Generates password recovery code for the user and sends it via email
**Request body:**
- user_id: string - unique user id
**Response body:**
Occurred error or null for success
| {
"content_hash": "eb0a0c1683bd009d18bcba47c8218894",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 107,
"avg_line_length": 34.08163265306123,
"alnum_prop": 0.7392215568862276,
"repo_name": "pip-services-users/pip-services-passwords-node",
"id": "917bb6e7b8742078516682b88592172b7d7c1262",
"size": "3403",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/HttpProtocolV1.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "869"
},
{
"name": "JavaScript",
"bytes": "102364"
},
{
"name": "PowerShell",
"bytes": "6307"
},
{
"name": "TypeScript",
"bytes": "102177"
}
],
"symlink_target": ""
} |
'use strict';
import bluebird from 'bluebird';
/**
* @hidden
*/
const instanceTypes = require('../ec2info.json');
/**
* Returns an array of all instance types and details.
* @memberof module:Macro
* @returns {Array}
*/
export function getInstanceTypeList() {
return instanceTypes;
}
/**
* Returns an array of just the instance type names available in AWS.
* @memberof module:Macro
* @returns {Array}
*/
export function getInstanceTypeNameList() {
const results: string[] = [];
instanceTypes.forEach((instanceType: any) => {
results.push(instanceType.instance_type);
});
return results;
}
/**
* Returns a map of all instance types and details.
* @memberof module:Macro
* @returns {{}}
*/
export function getInstanceTypeMap() {
const results: any = {};
instanceTypes.forEach((instanceType: any) => {
results[instanceType.instance_type] = instanceType;
});
return results;
}
/**
* Returns an array of the names of all regions in AWS.
* @memberof module:Macro
* @returns {string[]}
*/
export function getRegions() {
return [
'us-east-1',
'us-east-2',
'us-west-1',
'us-west-2',
'ca-central-1',
'eu-west-1',
'eu-west-2',
'eu-central-1',
'ap-south-1',
'ap-southeast-1',
'ap-southeast-2',
'ap-northeast-1',
'ap-northeast-2',
'sa-east-1',
'cn-north-1',
'us-gov-west-1'
];
}
/**
* Returns an AMI Map that can be added to a Mapping.
* @memberof module:Macro
* @param filters
* @param regions
* @returns {Promise.<TResult>}
*/
export function getAMIMap(filters: any, regions: any, aws: any) {
return bluebird
.map(regions, (region: any) => {
const ec2Client = new aws.EC2({ region: region });
return bluebird
.map(filters, (filterSet: any) => {
return ec2Client
.describeImages({
Filters: filterSet.Filters
})
.promise()
.then((ami: any) => {
const set: any = {};
if (ami.Images[0]) {
set[filterSet.Name] = ami.Images[0].ImageId
? ami.Images[0].ImageId
: 'NOT_SUPPORTED';
} else {
set[filterSet.Name] = 'NOT_SUPPORTED';
}
return set;
});
})
.then((results: any) => {
results = results.reduce((prev: any, current: any) => {
const key = Object.keys(current)[0];
prev[key] = current[key];
return prev;
}, {});
return { region: region, images: results };
});
})
.then((results: any) => {
const final: any = {};
results.forEach((result: any) => {
final[result.region] = result.images;
});
return final;
});
}
| {
"content_hash": "bbb6734da6ca6cb7b3e1a2544327d2a5",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 69,
"avg_line_length": 23.923076923076923,
"alnum_prop": 0.5537692032868882,
"repo_name": "arminhammer/wolkenkratzer",
"id": "de380474aadbfb3e8fa16a4d457745e0c32705e6",
"size": "2799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/macros/ec2meta.macro.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "41352"
},
{
"name": "Shell",
"bytes": "6731"
},
{
"name": "TypeScript",
"bytes": "1357768"
}
],
"symlink_target": ""
} |
package strreverse
import "testing"
func TestReverse(t *testing.T) {
original := []string{"Hello World!", "This is the best day of my life", "It's a beautiful world"}
reverse := []string{"!dlroW olleH", "efil ym fo yad tseb eht si sihT", "dlrow lufituaeb a s'tI"}
for i, s := range original {
if r := Reverse(s); r != reverse[i] {
t.Errorf("Reverse of %s is not %s, it is %s", s, r, reverse[i])
}
}
}
| {
"content_hash": "9f42d156224e4b04a296b087edabe976",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 101,
"avg_line_length": 32,
"alnum_prop": 0.5825892857142857,
"repo_name": "callmekatootie/strreverse",
"id": "372081f39c0a842136b717a0992fbe9fd7f1c0c3",
"size": "448",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reverse_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "681"
}
],
"symlink_target": ""
} |
using System;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenTelemetry.Instrumentation.Http;
using OpenTelemetry.Instrumentation.Http.Implementation;
using OpenTelemetry.Internal;
namespace OpenTelemetry.Trace
{
/// <summary>
/// Extension methods to simplify registering of HttpClient instrumentation.
/// </summary>
public static class TracerProviderBuilderExtensions
{
/// <summary>
/// Enables HttpClient instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(this TracerProviderBuilder builder)
=> AddHttpClientInstrumentation(builder, name: null, configureHttpClientInstrumentationOptions: null);
/// <summary>
/// Enables HttpClient instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
/// <param name="configureHttpClientInstrumentationOptions">Callback action for configuring <see cref="HttpClientInstrumentationOptions"/>.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions)
=> AddHttpClientInstrumentation(builder, name: null, configureHttpClientInstrumentationOptions);
/// <summary>
/// Enables HttpClient instrumentation.
/// </summary>
/// <param name="builder"><see cref="TracerProviderBuilder"/> being configured.</param>
/// <param name="name">Name which is used when retrieving options.</param>
/// <param name="configureHttpClientInstrumentationOptions">Callback action for configuring <see cref="HttpClientInstrumentationOptions"/>.</param>
/// <returns>The instance of <see cref="TracerProviderBuilder"/> to chain the calls.</returns>
public static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
string name,
Action<HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions)
{
Guard.ThrowIfNull(builder);
name ??= Options.DefaultName;
if (configureHttpClientInstrumentationOptions != null)
{
builder.ConfigureServices(services => services.Configure(name, configureHttpClientInstrumentationOptions));
}
return builder.ConfigureBuilder((sp, builder) =>
{
var options = sp.GetRequiredService<IOptionsMonitor<HttpClientInstrumentationOptions>>().Get(name);
#if NETFRAMEWORK
HttpWebRequestActivitySource.Options = options;
builder.AddSource(HttpWebRequestActivitySource.ActivitySourceName);
#else
AddHttpClientInstrumentation(builder, new HttpClientInstrumentation(options));
#endif
});
}
#if !NETFRAMEWORK
internal static TracerProviderBuilder AddHttpClientInstrumentation(
this TracerProviderBuilder builder,
HttpClientInstrumentation instrumentation)
{
if (HttpHandlerDiagnosticListener.IsNet7OrGreater)
{
builder.AddSource(HttpHandlerDiagnosticListener.HttpClientActivitySourceName);
}
else
{
builder.AddSource(HttpHandlerDiagnosticListener.ActivitySourceName);
builder.AddLegacySource("System.Net.Http.HttpRequestOut");
}
return builder.AddInstrumentation(() => instrumentation);
}
#endif
}
}
| {
"content_hash": "a61aa8c2c8ae563ac780ff4680f64319",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 155,
"avg_line_length": 45.54545454545455,
"alnum_prop": 0.6858782435129741,
"repo_name": "open-telemetry/opentelemetry-dotnet",
"id": "c900da51f612e78a69ab95441f81fa4e7b1e3ae7",
"size": "4711",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/OpenTelemetry.Instrumentation.Http/TracerProviderBuilderExtensions.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "490"
},
{
"name": "C#",
"bytes": "3223001"
},
{
"name": "Dockerfile",
"bytes": "3114"
},
{
"name": "Jinja",
"bytes": "4557"
},
{
"name": "PowerShell",
"bytes": "4732"
},
{
"name": "Python",
"bytes": "4416"
},
{
"name": "Shell",
"bytes": "1534"
}
],
"symlink_target": ""
} |
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 口碑广告系统分佣规则(比例)
*
* @author auto create
* @since 1.0, 2017-01-17 10:33:12
*/
public class KbAdvertCommissionClausePercentageResponse extends AlipayObject {
private static final long serialVersionUID = 4345561535776275845L;
/**
* 分佣比例(100以内精度2位的非负小数)
*/
@ApiField("commission_rate")
private String commissionRate;
/**
* 封顶金额(精度2位的非负小数)
*/
@ApiField("max_limit")
private String maxLimit;
public String getCommissionRate() {
return this.commissionRate;
}
public void setCommissionRate(String commissionRate) {
this.commissionRate = commissionRate;
}
public String getMaxLimit() {
return this.maxLimit;
}
public void setMaxLimit(String maxLimit) {
this.maxLimit = maxLimit;
}
}
| {
"content_hash": "e7106d3edadec0bd4d5909445d1be6e8",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 78,
"avg_line_length": 19.976190476190474,
"alnum_prop": 0.7389749702026222,
"repo_name": "wendal/alipay-sdk",
"id": "821d1a99ba4fd17fcd0e3d58098a527204e1a055",
"size": "919",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/alipay/api/domain/KbAdvertCommissionClausePercentageResponse.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "5737833"
},
{
"name": "Python",
"bytes": "368"
}
],
"symlink_target": ""
} |
/*
* This software is licensed under the Apache License, Version 2.0
* (the "License") agreement; 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.
*/
/**
* @author D. Ashmore
*
*/
package org.moneta.config.web; | {
"content_hash": "ceed777e070fd87c4ddd2eabdae64638",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 81,
"avg_line_length": 37.388888888888886,
"alnum_prop": 0.7102526002971769,
"repo_name": "Derek-Ashmore/moneta",
"id": "6e25b6e521661a55a668b8b191b1415d91aedd85",
"size": "673",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "moneta-web/src/main/java/org/moneta/config/web/package-info.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "186419"
}
],
"symlink_target": ""
} |
seajs.use(['jquery','mp3'],function(){
factory();
})
function factory(){
'use strict';
require('./index.css');
var Star = require('./Star');
var Dot = require('./Dot');
//初始化DOM
var template = require("./index.jade"); //返回一个函数
var html = template();
$('.container').html(html);//最好不要用body,这样将script标签清掉了,但是不影响页面运行,因为js已经加载
//播放器功能
var song = [
{
'cover' : require('../public/images/girl.jpg'),
'src' : './mp3/Gravity.mp3',
'title' : 'Gravity'
},
{
'cover' : require('../public/images/girl.jpg'),
'src' : './mp3/Gravity.mp3',
'title' : 'Gravity2'
}
];
var audioFn = audioPlay({
song : song,
autoPlay : true //是否立即播放第一首,autoPlay为true且song为空,会alert文本提示并退出
});
/* 向歌单中添加新曲目,第二个参数true为新增后立即播放该曲目,false则不播放 */
audioFn.newSong({
'cover' : require('../public/images/girl.jpg'),
'src' : './mp3/Gravity.mp3',
'title' : 'Gravity3'
},false);
//星空效果
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
WIDTH,
HEIGHT,
mouseMoving = false,
mouseMoveChecker,
mouseX,
mouseY,
stars = [],
initStarsPopulation = 80,
dots,
dotsMinDist = 2,
maxDistFromCursor = 50;
window['dots'] = dots = [];
setCanvasSize();
init();
function setCanvasSize() {
WIDTH = document.documentElement.clientWidth,
HEIGHT = document.documentElement.clientHeight;
canvas.setAttribute("width", WIDTH);
canvas.setAttribute("height", HEIGHT);
}
function init() {
ctx.strokeStyle = "white";
ctx.shadowColor = "white";
for (var i = 0; i < initStarsPopulation; i++) {
stars[i] = new Star(i, Math.floor(Math.random()*WIDTH), Math.floor(Math.random()*HEIGHT),ctx);
//stars[i].draw();
}
ctx.shadowBlur = 0;
animate();
}
function animate() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
for (var i in stars) {
stars[i].move();
}
for (var i in dots) {
dots[i].move();
}
drawIfMouseMoving();
requestAnimationFrame(animate);
}
window.onmousemove = function(e){
mouseMoving = true;
mouseX = e.clientX;
mouseY = e.clientY;
clearInterval(mouseMoveChecker);
mouseMoveChecker = setTimeout(function() {
mouseMoving = false;
}, 100);
}
function drawIfMouseMoving(){
if (!mouseMoving) return;
if (dots.length == 0) {
dots[0] = new Dot(0, mouseX, mouseY,ctx,dots);
dots[0].draw();
return;
}
var previousDot = getPreviousDot(dots.length, 1);
var prevX = previousDot.x;
var prevY = previousDot.y;
var diffX = Math.abs(prevX - mouseX);
var diffY = Math.abs(prevY - mouseY);
if (diffX < dotsMinDist || diffY < dotsMinDist) return;
var xVariation = Math.random() > .5 ? -1 : 1;
xVariation = xVariation*Math.floor(Math.random()*maxDistFromCursor)+1;
var yVariation = Math.random() > .5 ? -1 : 1;
yVariation = yVariation*Math.floor(Math.random()*maxDistFromCursor)+1;
dots[dots.length] = new Dot(dots.length, mouseX+xVariation, mouseY+yVariation,ctx,dots);
dots[dots.length-1].draw();
dots[dots.length-1].link();
}
function getPreviousDot(id, stepback) {
if (id == 0 || id - stepback < 0) return false;
if (typeof dots[id - stepback] != "undefined") return dots[id - stepback];
else return false;//getPreviousDot(id - stepback);
}
//setInterval(drawIfMouseMoving, 17);
} | {
"content_hash": "b7ab2387ae880ce34817f47887ccb91f",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 97,
"avg_line_length": 26.45736434108527,
"alnum_prop": 0.6144154702607677,
"repo_name": "fromatlantis/nojs",
"id": "720a7fc1113ed7063e255a83b1ebedeeb8d58552",
"size": "3619",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ming-kit/views/index.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94561"
},
{
"name": "HTML",
"bytes": "58135"
},
{
"name": "Java",
"bytes": "10760"
},
{
"name": "JavaScript",
"bytes": "7084865"
},
{
"name": "Objective-C",
"bytes": "4407"
},
{
"name": "Python",
"bytes": "1631"
},
{
"name": "Vue",
"bytes": "15224"
}
],
"symlink_target": ""
} |
/* Desc: A class to log data
* Author: Nate Koenig
* Date: 1 Jun 2010
*/
#ifndef _LOGRECORD_HH_
#define _LOGRECORD_HH_
#include <fstream>
#include <string>
#include <map>
#include <boost/thread.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/insert_linebreaks.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <boost/filesystem.hpp>
#include "gazebo/common/UpdateInfo.hh"
#include "gazebo/common/Event.hh"
#include "gazebo/common/SingletonT.hh"
#define GZ_LOG_VERSION "1.0"
namespace gazebo
{
namespace common
{
/// addtogroup gazebo_common
/// \{
/// \class LogRecord LogRecord.hh common/common.hh
/// \brief Handles logging of data to disk
///
/// The LogRecord class is a Singleton that manages data logging of any
/// entity within a running simulation. An entity may be a World, Model,
/// or any of their child entities. This class only writes log files,
/// see LogPlay for playback functionality.
///
/// State information for an entity may be logged through the LogRecord::Add
/// function, and stopped through the LogRecord::Remove function. Data may
/// be logged into a single file, or split into many separate files by
/// specifying different filenames for the LogRecord::Add function.
///
/// The LogRecord is updated at the start of each simulation step. This
/// guarantees that all data is stored.
///
/// \sa Logplay, State
class LogRecord : public SingletonT<LogRecord>
{
/// \brief Constructor
private: LogRecord();
/// \brief Destructor
private: virtual ~LogRecord();
/// \brief Initialize logging into a subdirectory.
///
/// Init may only be called once, False will be returned if called
/// multiple times.
/// \param[in] _subdir Directory to record to
/// \return True if successful.
public: bool Init(const std::string &_subdir);
/// \brief Add an object to a log file.
///
/// Add a new object to a log. An object can be any valid named object
/// in simulation, including the world itself. Duplicate additions are
/// ignored. Objects can be added to the same file by
/// specifying the same _filename.
/// \param[in] _name Name of the object to log.
/// \param[in] _filename Filename of the log file.
/// \param[in] _logCallback Function used to log data for the object.
/// Typically an object will have a log function that outputs data to
/// the provided ofstream.
/// \throws Exception
public: void Add(const std::string &_name, const std::string &_filename,
boost::function<bool (std::ostringstream &)> _logCallback);
/// \brief Remove an entity from a log
///
/// Removes an entity from the logger. The stops data recording for
/// the entity and all its children. For example, specifying a world
/// will stop all data logging.
/// \param[in] _name Name of the log
/// \return True if the entity existed and was removed. False if the
/// entity was not registered with the logger.
public: bool Remove(const std::string &_name);
/// \brief Stop the logger.
public: void Stop();
/// \brief Set whether logging should pause. A paused state means the
/// log file is still open, but data is not written to it.
/// \param[in] _paused True to pause data logging.
/// \sa LogRecord::GetPaused
public: void SetPaused(bool _paused);
/// \brief Get whether logging is paused.
/// \return True if logging is paused.
/// \sa LogRecord::SetPaused
public: bool GetPaused() const;
/// \brief Get whether logging is running.
/// \return True if logging has been started.
public: bool GetRunning() const;
/// \brief Start the logger.
/// \param[in] _encoding The type of encoding (txt, or bz2).
public: bool Start(const std::string &_encoding="bz2");
/// \brief Get the encoding used.
/// \return Either [txt, or bz2], where txt is plain txt and bz2 is
/// bzip2 compressed data with Base64 encoding.
public: const std::string &GetEncoding() const;
/// \brief Get the filename for a log object.
/// \param[in] _name Name of the log object.
/// \return Filename, empty string if not found.
public: std::string GetFilename(const std::string &_name) const;
/// \brief Get the file size for a log object.
/// \param[in] _name Name of the log object.
/// \return Size in bytes.
public: unsigned int GetFileSize(const std::string &_name) const;
/// \brief Set the base path.
/// \param[in] _path Path to the new logging location.
public: void SetBasePath(const std::string &_path);
/// \brief Get the base path for a log recording.
/// \return Path for log recording.
public: std::string GetBasePath() const;
/// \brief Get the run time in sim time.
/// \return Run sim time.
public: common::Time GetRunTime() const;
/// \brief Finialize, and shutdown.
public: void Fini();
/// \brief Return true if an Update has not yet been completed.
/// \return True if an Update has not yet been completed.
public: bool GetFirstUpdate() const;
/// \brief Update the log files
///
/// Captures the current state of all registered entities, and outputs
/// the data to their respective log files.
private: void Update(const common::UpdateInfo &_info);
/// \brief Run the Write loop.
private: void Run();
/// \brief Clear and delete the log buffers.
private: void ClearLogs();
/// \brief Write the header to file.
// private: void WriteHeader();
/// \cond
private: class Log
{
/// \brief Constructor
/// \param[in] _parent Pointer to the LogRecord parent.
/// \param[in] _relativeFilename The name of the log file to
/// generate, sans the complete path.
/// \param[in] _logCB Callback function, which is used to get log
/// data.
public: Log(LogRecord *_parent, const std::string &_relativeFilename,
boost::function<bool (std::ostringstream &)> _logCB);
/// \brief Destructor
public: virtual ~Log();
/// \brief Start the log.
/// \param[in] _path The complete path in which to put the log file.
public: void Start(const boost::filesystem::path &_path);
/// \brief Write data to disk.
public: void Write();
/// \brief Update the data buffer.
/// \return The size of the data buffer.
public: unsigned int Update();
/// \brief Clear the data buffer.
public: void ClearBuffer();
/// \brief Get the byte size of the buffer.
/// \return Buffer byte size.
public: unsigned int GetBufferSize();
/// \brief Get the relative filename. This is the filename passed
/// to the constructor.
/// \return The relative filename.
public: std::string GetRelativeFilename() const;
/// \brief Get the complete filename.
/// \return The complete filename.
public: std::string GetCompleteFilename() const;
/// \brief Pointer to the log record parent.
public: LogRecord *parent;
/// \brief Callback from which to get data.
public: boost::function<bool (std::ostringstream &)> logCB;
/// \brief Data buffer.
public: std::string buffer;
/// \brief The log file.
public: std::ofstream logFile;
/// \brief Relative log filename.
public: std::string relativeFilename;
private: boost::filesystem::path completePath;
};
/// \endcond
/// \def Log_M
/// \brief Map of names to logs.
private: typedef std::map<std::string, Log*> Log_M;
/// \brief All the log objects.
private: Log_M logs;
/// \brief Iterator used to update the log objects.
private: Log_M::iterator updateIter;
/// \brief Convenience iterator to the end of the log objects map.
private: Log_M::iterator logsEnd;
/// \brief Event connected to the World update.
private: event::ConnectionPtr updateConnection;
/// \brief True if logging is running.
private: bool running;
/// \brief Thread used to write data to disk.
private: boost::thread *writeThread;
/// \brief Mutext to protect writing.
private: mutable boost::mutex writeMutex;
/// \brief Mutex to protect logging control.
private: boost::mutex controlMutex;
/// \brief Used by the write thread to know when data needs to be
/// written to disk
private: boost::condition_variable dataAvailableCondition;
/// \brief The base pathname for all the logs.
private: boost::filesystem::path logBasePath;
/// \brief The complete pathname for all the logs.
private: boost::filesystem::path logCompletePath;
/// \brief Subdirectory for log files. This is appended to
/// logBasePath.
private: std::string logSubDir;
/// \brief Encoding format for each chunk.
private: std::string encoding;
/// \brief True if initialized.
private: bool initialized;
/// \brief True to pause recording.
private: bool paused;
/// \brief Used to indicate the first update callback.
private: bool firstUpdate;
/// \brief Flag used to stop the write thread.
private: bool stopThread;
/// \brief Start simulation time.
private: common::Time startTime;
/// \brief Current simulation time.
private: common::Time currTime;
/// \brief This is a singleton
private: friend class SingletonT<LogRecord>;
};
/// \}
}
}
#endif
| {
"content_hash": "41ddf49587d0a7c7ba77d4dd6422ef92",
"timestamp": "",
"source": "github",
"line_count": 292,
"max_line_length": 80,
"avg_line_length": 34.397260273972606,
"alnum_prop": 0.6277379530067703,
"repo_name": "thomas-moulard/gazebo-deb",
"id": "c5eeaa7ce29fc2cd181d49824f5b9b07ab7f36df",
"size": "10660",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gazebo/common/LogRecord.hh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "652008"
},
{
"name": "C++",
"bytes": "6417236"
},
{
"name": "JavaScript",
"bytes": "25255"
}
],
"symlink_target": ""
} |
function __processArg(obj, key) {
var arg = null;
if (obj) {
arg = obj[key] || null;
delete obj[key];
}
return arg;
}
function Controller() {
require("/alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "index";
this.args = arguments[0] || {};
if (arguments[0]) {
__processArg(arguments[0], "__parentSymbol");
__processArg(arguments[0], "$model");
__processArg(arguments[0], "__itemTemplate");
}
var $ = this;
var exports = {};
exports.destroy = function() {};
_.extend($, $.__views);
exports.showContacts = function(e) {
Ti.API.info("showContacts: " + e.source.title);
};
$.welcomeNav.open();
_.extend($, exports);
}
var Alloy = require("/alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller; | {
"content_hash": "a5a4263b96d6356a92dd189c8c08d3e3",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 100,
"avg_line_length": 28,
"alnum_prop": 0.578125,
"repo_name": "brentonhouse/brentonhouse.alloy",
"id": "6d0455e77c3330e7a67973fe43f024a727638221",
"size": "896",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "test/apps/testing/ALOY-667/_generated/android/alloy/controllers/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3828"
},
{
"name": "CoffeeScript",
"bytes": "872"
},
{
"name": "HTML",
"bytes": "5471"
},
{
"name": "JavaScript",
"bytes": "3336722"
},
{
"name": "Python",
"bytes": "5251"
}
],
"symlink_target": ""
} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.mskcc.shenkers.control.track;
import javafx.beans.property.BooleanProperty;
/**
*
* @author sol
*/
public interface DomainFlippable {
public BooleanProperty flipDomainProperty();
}
| {
"content_hash": "e62f3f6afcf5505adc611348319e8898",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 79,
"avg_line_length": 24.1875,
"alnum_prop": 0.7493540051679587,
"repo_name": "shenkers/ComparativeBrowser",
"id": "59495ef2b22faf0744588488415fd9e56c6e8cbf",
"size": "387",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/mskcc/shenkers/control/track/DomainFlippable.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "828"
},
{
"name": "Java",
"bytes": "1031401"
}
],
"symlink_target": ""
} |
**Namespace:** [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public int DraftVersionVisibility { get; set; }
```
### Property Value
Type: System.Int32
## See also
- [ListInstance](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.ListInstance.md)
- [OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508](OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.md)
| {
"content_hash": "78ea8931991d977ec72299ff4e56d43f",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 148,
"avg_line_length": 36.4,
"alnum_prop": 0.7783882783882784,
"repo_name": "PaoloPia/PnP-Guidance",
"id": "bf3cc7299ecbca0cf624bd826c61ee8a4f7212f9",
"size": "595",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "sitescore/OfficeDevPnP.Core.Framework.Provisioning.Providers.Xml.V201508.ListInstance.DraftVersionVisibility.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PowerShell",
"bytes": "783"
}
],
"symlink_target": ""
} |
class Admin::ResourcesController < Admin::DesignController
verify :params => :filename, :only => [:edit, :update],
:add_flash => { :error => 'Resource required' },
:redirect_to => { :controller => 'design', :action => 'index' }
verify :method => :post, :params => :data, :only => :update,
:add_flash => { :error => 'Resource required' },
:redirect_to => { :action => 'edit' }
verify :method => :post, :params => :resource, :only => :upload,
:add_flash => { :error => 'Resource required' },
:redirect_to => { :controller => 'design', :action => 'index' }
def index
redirect_to :controller => 'design'
end
def edit
@resource = @theme.resources[params[:filename]]
end
def update
@theme.resources.write params[:filename], params[:data]
expire_resource(params[:filename])
render :update do |page|
page.call 'Flash.notice', 'Resource updated successfully'
end
end
def upload
if request.get?
redirect_to :controller => 'design', :action => 'index'
return
end
if params[:resource] && Asset.image?(params[:resource].content_type.strip) && (1..1.megabyte).include?(params[:resource].size)
@resource = @theme.resources.write File.basename(params[:resource].original_filename), params[:resource].read
expire_resource(@resource.basename)
flash[:notice] = "'#{@resource.basename}' was uploaded successfully."
else
flash[:error] = "A bad or nonexistant image was uploaded."
end
redirect_to url_for_theme(:controller => 'design', :action => 'index')
end
def remove
if request.get?
redirect_to :action => 'edit'
return
end
@resource = @theme.resources[params[:filename]]
expire_resource(@resource.basename)
render :update do |page|
@resource.unlink if @resource.file?
page.visual_effect :fade, params[:context], :duration => 0.3
end
end
protected
def expire_resource(filename)
if current_theme?
self.class.expire_page('/' << @theme.resources[filename].relative_path_from(site.attachment_path).to_s)
end
end
end
| {
"content_hash": "51c5d00530dab4690cffac120fac9864",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 130,
"avg_line_length": 34.111111111111114,
"alnum_prop": 0.6263378315495579,
"repo_name": "mephistorb/mephisto",
"id": "9327a93b7bc24c3aa98a8cc26bc97f294bf7f339",
"size": "2149",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "app/controllers/admin/resources_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "34756"
},
{
"name": "Ruby",
"bytes": "457083"
}
],
"symlink_target": ""
} |
class <#name#> {
<#properties and methods#>
} | {
"content_hash": "253a6cf8d7bf10f366d3010896795e90",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 30,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.5918367346938775,
"repo_name": "zubko/xcode-snippets",
"id": "e781c1c0c7b41dcaf5ea3e4e4a5b2b8c4a3f7df5",
"size": "383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "swift_class.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "19363"
}
],
"symlink_target": ""
} |
* Add coverage for specific country (by Joshua Wise).
## 1.2
* Add `browserslist.coverage()` method.
* Add `--coverage` and `-c` argument to CLI.
* Add `-v` argument support to CLI.
* Better error handling in CLI.
## 1.1.3
* Fix jspm support (by Sean Anderson).
## 1.1.2
* Fix jspm support (by Sean Anderson).
## 1.1.1
* Fix space-less `>10%` and `>10% in my stats` queries.
* Normalize error messages.
* Remove development files from npm package.
## 1.1
* Added query against custom browser usage data (by Daniel Rey).
## 1.0.1
* Update Firefox ESR (by Rouven Weßling).
## 1.0
* Remove Opera 12.1 from default query.
* Add `not` keyword and exclude browsers by query.
* Add Microsoft Edge support (by Andrey Polischuk).
* Add CLI for debug and non-JS usage (by Luke Horvat).
* Use own class in Browserslist errors.
## 0.5
* Add version ranges `IE 6-9` (by Ben Briggs).
## 0.4
* Add `config` option and `BROWSERSLIST_CONFIG` environment variable support.
* Add symlink config support.
## 0.3.3
* Fix DynJS compatibility (by Nick Howes).
## 0.3.2
* Fix joined versions on versions query (by Vincent De Oliveira).
## 0.3.1
* Fix global variable leak (by Peter Müller).
## 0.3
* Takes criterias from `BROWSERSLIST` environment variable.
## 0.2
* Return Can I Use joined versions as `ios_saf 7.0-7.1`.
## 0.1.3
* Better work with Can I Use joined versions like `ios_saf 7.0-7.1`.
* Browserslist now understands `ios_saf 7.0` or `ios_saf 7`.
## 0.1.2
* Do not create global `browserslist` var (by Maxime Thirouin).
## 0.1.1
* Sort browsers by name and version.
## 0.1
* Initial release.
| {
"content_hash": "a85d1cd85f870be0874f3611ea3fdddd",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 77,
"avg_line_length": 24.242424242424242,
"alnum_prop": 0.689375,
"repo_name": "Zach417/churchetto-web",
"id": "85b2396439f8cdebdcc45df41a55ed71f449fa2d",
"size": "1609",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "node_modules/gulp-autoprefixer/node_modules/autoprefixer/node_modules/browserslist/CHANGELOG.md",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5879"
},
{
"name": "HTML",
"bytes": "57446"
},
{
"name": "JavaScript",
"bytes": "4977430"
},
{
"name": "Shell",
"bytes": "301"
}
],
"symlink_target": ""
} |
/*Problem 15. Hexadecimal to Decimal Number
Using loops write a program that converts a hexadecimal integer number to its decimal form.
The input is entered as string. The output should be a variable of type long.
Do not use the built-in .NET functionality.*/
using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter a hexadecimal integer number :");
string hex = Console.ReadLine();
long number = 0;
long power = 1;
for (int i = hex.Length - 1; i >= 0; i--)
{
int sign;
switch (hex[i])
{
case 'A': sign = 10;
break;
case 'B': sign = 11;
break;
case 'C': sign = 12;
break;
case 'D': sign = 13;
break;
case 'E': sign = 14;
break;
case 'F': sign = 15;
break;
default: sign = hex[i] - 48;
break;
}
number += sign * power;
power *= 16;
}
Console.WriteLine(number);
}
}
| {
"content_hash": "4d73f96c8d39d6f4a10a1dbcb261ea6a",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 91,
"avg_line_length": 30.136363636363637,
"alnum_prop": 0.4019607843137255,
"repo_name": "MarinMarinov/C-Sharp-Part1",
"id": "88167076ff8bad203533c18f9cb1ae93d0cd06d4",
"size": "1328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "06. Homework - Loops/Problem15HexadecimalToDecimalNumber/Problem15HexadecimalToDecimalNumber.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "200948"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<bean id="app.config.appSettings" class="java.util.HashMap" scope="singleton" >
<constructor-arg>
<map>
<entry key="base.system" value="${base.system}" />
<entry key="base.mainSystem" value="${base.mainSystem}" />
<entry key="base.encryptorKey1" value="${base.encryptorKey1}" />
<entry key="base.encryptorKey2" value="${base.encryptorKey2}" />
<entry key="baseSupperAction.errorContent" value="${base.page.errorContent}" />
<entry key="baseSupperAction.dojoLocal" value="${base.page.dojoLocal}" />
<entry key="baseSupperAction.dojoAjaxTimeout" value="${base.page.dojoAjaxTimeout}" />
<entry key="baseSupperAction.dojoAjaxSync" value="${base.page.dojoAjaxSync}" />
<entry key="baseSupperAction.verMsg" value="${base.page.verMsg}" />
<entry key="baseSupperAction.jsVerBuild" value="${base.page.jsVerBuild}" />
<entry key="base.uploadDir" value="${base.uploadDir}" />
<entry key="base.deployJasperReportDir" value="${base.deployJasperReportDir}" />
<entry key="cxf.JAXRSServerFactoryBean.address" value="${cxf.JAXRSServerFactoryBean.address}" />
<entry key="googleMap.enable" value="${googleMap.enable}" />
<entry key="googleMap.url" value="${googleMap.url}" />
<entry key="googleMap.key" value="${googleMap.key}" />
<entry key="googleMap.defaultLat" value="${googleMap.defaultLat}" />
<entry key="googleMap.defaultLng" value="${googleMap.defaultLng}" />
<entry key="googleMap.language" value="${googleMap.language}" />
<entry key="googleMap.clientLocationEnable" value="${googleMap.clientLocationEnable}" />
<entry key="leafletMap.defaultLat" value="${leafletMap.defaultLat}" />
<entry key="leafletMap.defaultLng" value="${leafletMap.defaultLng}" />
<entry key="mapBox.accessToken" value="${mapBox.accessToken}" />
<entry key="twitter.enable" value="${twitter.enable}" />
<entry key="base.loginCaptchaCodeEnable" value="${base.loginCaptchaCodeEnable}" />
<entry key="base.applicationSiteHostUpdateMode" value="${base.applicationSiteHostUpdateMode}" />
</map>
</constructor-arg>
</bean>
</beans> | {
"content_hash": "4732c6ce3b3f2ca32b114332536d2498",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 118,
"avg_line_length": 66.84444444444445,
"alnum_prop": 0.6735372340425532,
"repo_name": "billchen198318/bamboobsc",
"id": "231fd2dbac37cd758eddc7e52da304461019b873",
"size": "3008",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core-base/resource/applicationContext/core/applicationContext-appSettings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "232"
},
{
"name": "CSS",
"bytes": "32196"
},
{
"name": "FreeMarker",
"bytes": "187687"
},
{
"name": "Groovy",
"bytes": "35207"
},
{
"name": "Java",
"bytes": "36620734"
},
{
"name": "SQLPL",
"bytes": "1487"
},
{
"name": "Shell",
"bytes": "498"
},
{
"name": "TSQL",
"bytes": "838169"
}
],
"symlink_target": ""
} |
/*************************************************************************/
/* baked_light.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */
/* */
/* 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. */
/*************************************************************************/
#ifndef BAKED_LIGHT_H
#define BAKED_LIGHT_H
#include "resource.h"
#include "scene/resources/texture.h"
class BakedLight : public Resource {
OBJ_TYPE( BakedLight, Resource);
public:
enum Mode {
MODE_OCTREE,
MODE_LIGHTMAPS
};
enum Format {
FORMAT_RGB,
FORMAT_HDR8,
FORMAT_HDR16
};
enum BakeFlags {
BAKE_DIFFUSE,
BAKE_SPECULAR,
BAKE_TRANSLUCENT,
BAKE_CONSERVE_ENERGY,
BAKE_LINEAR_COLOR,
BAKE_MAX
};
private:
RID baked_light;
Mode mode;
struct LightMap {
Size2i gen_size;
Ref<Texture> texture;
};
Vector< LightMap> lightmaps;
//bake vars
int cell_subdiv;
int lattice_subdiv;
float plot_size;
float energy_multiply;
float gamma_adjust;
float cell_extra_margin;
float edge_damp;
float normal_damp;
float tint;
float ao_radius;
float ao_strength;
float saturation;
int bounces;
bool transfer_only_uv2;
Format format;
bool flags[BAKE_MAX];
void _update_lightmaps();
Array _get_lightmap_data() const;
void _set_lightmap_data(Array p_array);
protected:
bool _set(const StringName& p_name, const Variant& p_value);
bool _get(const StringName& p_name,Variant &r_ret) const;
void _get_property_list( List<PropertyInfo> *p_list) const;
static void _bind_methods();
public:
void set_cell_subdivision(int p_subdiv);
int get_cell_subdivision() const;
void set_initial_lattice_subdiv(int p_size);
int get_initial_lattice_subdiv() const;
void set_plot_size(float p_size);
float get_plot_size() const;
void set_bounces(int p_size);
int get_bounces() const;
void set_energy_multiplier(float p_multiplier);
float get_energy_multiplier() const;
void set_gamma_adjust(float p_adjust);
float get_gamma_adjust() const;
void set_cell_extra_margin(float p_margin);
float get_cell_extra_margin() const;
void set_edge_damp(float p_margin);
float get_edge_damp() const;
void set_normal_damp(float p_margin);
float get_normal_damp() const;
void set_tint(float p_margin);
float get_tint() const;
void set_saturation(float p_saturation);
float get_saturation() const;
void set_ao_radius(float p_ao_radius);
float get_ao_radius() const;
void set_ao_strength(float p_ao_strength);
float get_ao_strength() const;
void set_realtime_color_enabled(const bool p_enabled);
bool get_realtime_color_enabled() const;
void set_realtime_color(const Color& p_realtime_color);
Color get_realtime_color() const;
void set_realtime_energy(const float p_realtime_energy);
float get_realtime_energy() const;
void set_bake_flag(BakeFlags p_flags,bool p_enable);
bool get_bake_flag(BakeFlags p_flags) const;
void set_format(Format p_margin);
Format get_format() const;
void set_transfer_lightmaps_only_to_uv2(bool p_enable);
bool get_transfer_lightmaps_only_to_uv2() const;
void set_mode(Mode p_mode);
Mode get_mode() const;
void set_octree(const DVector<uint8_t>& p_octree);
DVector<uint8_t> get_octree() const;
void set_light(const DVector<uint8_t>& p_light);
DVector<uint8_t> get_light() const;
void set_sampler_octree(const DVector<int>& p_sampler_octree);
DVector<int> get_sampler_octree() const;
void add_lightmap(const Ref<Texture> &p_texture,Size2 p_gen_size=Size2(256,256));
void set_lightmap_gen_size(int p_idx,const Size2& p_size);
Size2 get_lightmap_gen_size(int p_idx) const;
void set_lightmap_texture(int p_idx,const Ref<Texture> &p_texture);
Ref<Texture> get_lightmap_texture(int p_idx) const;
void erase_lightmap(int p_idx);
int get_lightmaps_count() const;
void clear_lightmaps();
virtual RID get_rid() const;
BakedLight();
~BakedLight();
};
VARIANT_ENUM_CAST(BakedLight::Format);
VARIANT_ENUM_CAST(BakedLight::Mode);
VARIANT_ENUM_CAST(BakedLight::BakeFlags);
#endif // BAKED_LIGHT_H
| {
"content_hash": "fbca340e5eee13beb4070b8d912bb3bf",
"timestamp": "",
"source": "github",
"line_count": 199,
"max_line_length": 82,
"avg_line_length": 29.366834170854272,
"alnum_prop": 0.6196098562628337,
"repo_name": "Hodes/godot",
"id": "16806d29e35bc22c2996846060b8c48f373fdd92",
"size": "5844",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "scene/resources/baked_light.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "292605"
},
{
"name": "C++",
"bytes": "11137462"
},
{
"name": "Java",
"bytes": "488299"
},
{
"name": "Objective-C",
"bytes": "30531"
},
{
"name": "Objective-C++",
"bytes": "142302"
},
{
"name": "PHP",
"bytes": "184052"
},
{
"name": "Python",
"bytes": "133223"
},
{
"name": "Shell",
"bytes": "266"
}
],
"symlink_target": ""
} |
package org.pentaho.di.trans.steps.orabulkloader;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.pentaho.di.core.injection.BaseMetadataInjectionTest;
import org.pentaho.di.junit.rules.RestorePDIEngineEnvironment;
public class OraBulkLoaderMetaInjectionTest extends BaseMetadataInjectionTest<OraBulkLoaderMeta> {
@ClassRule public static RestorePDIEngineEnvironment env = new RestorePDIEngineEnvironment();
@Before
public void setup() {
setup( new OraBulkLoaderMeta() );
}
@Test
public void test() throws Exception {
check( "SCHEMA_NAME", ()-> meta.getSchemaName() );
check( "TABLE_NAME", ()-> meta.getTableName() );
check( "SQLLDR_PATH", ()-> meta.getSqlldr() );
check( "CONTROL_FILE", ()-> meta.getControlFile() );
check( "DATA_FILE", ()-> meta.getDataFile() );
check( "LOG_FILE",()-> meta.getLogFile() );
check( "BAD_FILE",()-> meta.getBadFile());
check( "DISCARD_FILE", ()-> meta.getDiscardFile());
check( "FIELD_TABLE", ()-> meta.getFieldTable()[0] );
check( "FIELD_STREAM", ()-> meta.getFieldStream()[0] );
check( "FIELD_DATEMASK", ()-> meta.getDateMask()[0] );
check( "COMMIT_SIZE", ()-> meta.getCommitSize() );
check( "BIND_SIZE", ()-> meta.getBindSize() );
check( "READ_SIZE", ()-> meta.getReadSize() );
check( "MAX_ERRORS", ()-> meta.getMaxErrors() );
check( "LOAD_METHOD",()-> meta.getLoadMethod() );
check( "LOAD_ACTION",()-> meta.getLoadAction() );
check( "ENCODING", ()-> meta.getEncoding() );
check( "ORACLE_CHARSET_NAME", ()-> meta.getCharacterSetName() );
check( "DIRECT_PATH", ()-> meta.isDirectPath() );
check( "ERASE_FILES", ()-> meta.isEraseFiles() );
check( "DB_NAME_OVERRIDE", ()-> meta.getDbNameOverride() );
check( "FAIL_ON_WARNING",()-> meta.isFailOnWarning() );
check( "FAIL_ON_ERROR", ()-> meta.isFailOnError() );
check( "PARALLEL", ()-> meta.isParallel() );
check( "RECORD_TERMINATOR", ()-> meta.getAltRecordTerm() );
check( "CONNECTION_NAME", ()-> "My Connection", "My Connection" );
}
}
| {
"content_hash": "334742ac531aa9f188251e3ef52af55f",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 98,
"avg_line_length": 43.5,
"alnum_prop": 0.64272030651341,
"repo_name": "wseyler/pentaho-kettle",
"id": "6d8336c4eca7a0cfa6acbf6a6fde8c47fa1cbe86",
"size": "3000",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "plugins/oracle-bulk-loader/impl/src/test/java/org/pentaho/di/trans/steps/orabulkloader/OraBulkLoaderMetaInjectionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "45618"
},
{
"name": "CSS",
"bytes": "37792"
},
{
"name": "GAP",
"bytes": "4005"
},
{
"name": "HTML",
"bytes": "43001"
},
{
"name": "Java",
"bytes": "45312148"
},
{
"name": "JavaScript",
"bytes": "511961"
},
{
"name": "Shell",
"bytes": "48803"
}
],
"symlink_target": ""
} |
import { EventsKey } from '../events';
import BaseEvent from '../events/Event';
import MapBrowserEvent from '../MapBrowserEvent';
import { ObjectEvent } from '../Object';
import PointerInteraction from './Pointer';
export interface Options {
duration?: number;
}
export default class PinchZoom extends PointerInteraction {
constructor(opt_options?: Options);
/**
* Handle pointer down events.
*/
handleDownEvent(mapBrowserEvent: MapBrowserEvent<UIEvent>): boolean;
/**
* Handle pointer drag events.
*/
handleDragEvent(mapBrowserEvent: MapBrowserEvent<UIEvent>): void;
/**
* Handle pointer up events.
*/
handleUpEvent(mapBrowserEvent: MapBrowserEvent<UIEvent>): boolean;
on(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
once(type: string | string[], listener: (p0: any) => any): EventsKey | EventsKey[];
un(type: string | string[], listener: (p0: any) => any): void;
on(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
once(type: 'change', listener: (evt: BaseEvent) => void): EventsKey;
un(type: 'change', listener: (evt: BaseEvent) => void): void;
on(type: 'change:active', listener: (evt: ObjectEvent) => void): EventsKey;
once(type: 'change:active', listener: (evt: ObjectEvent) => void): EventsKey;
un(type: 'change:active', listener: (evt: ObjectEvent) => void): void;
on(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
once(type: 'error', listener: (evt: BaseEvent) => void): EventsKey;
un(type: 'error', listener: (evt: BaseEvent) => void): void;
on(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
once(type: 'propertychange', listener: (evt: ObjectEvent) => void): EventsKey;
un(type: 'propertychange', listener: (evt: ObjectEvent) => void): void;
}
| {
"content_hash": "bf3b8cae3ea10b8b5fe363f77f6502b6",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 87,
"avg_line_length": 47.94871794871795,
"alnum_prop": 0.660427807486631,
"repo_name": "georgemarshall/DefinitelyTyped",
"id": "b0e766b2cd159cbf4d7970107b3160306a939ad1",
"size": "1870",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "types/ol/interaction/PinchZoom.d.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "16338312"
},
{
"name": "Ruby",
"bytes": "40"
},
{
"name": "Shell",
"bytes": "73"
},
{
"name": "TypeScript",
"bytes": "17728346"
}
],
"symlink_target": ""
} |
/**
*
* $Id$
*/
package org.wso2.developerstudio.datamapper.validation;
/**
* A sample validator interface for {@link org.wso2.developerstudio.datamapper.DataMapperNode}.
* This doesn't really do anything, and it's not a real EMF artifact.
* It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended.
* This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false.
*/
public interface DataMapperNodeValidator {
boolean validate();
}
| {
"content_hash": "f719a8fc4afd29b5f77ceeead088e5ce",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 135,
"avg_line_length": 32.05882352941177,
"alnum_prop": 0.7596330275229358,
"repo_name": "susinda/devstudio-tooling-esb",
"id": "a166aef7cb1f940c9474ee57910824b127d15304",
"size": "545",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "plugins/org.wso2.developerstudio.visualdatamapper/src/org/wso2/developerstudio/datamapper/validation/DataMapperNodeValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "41190583"
},
{
"name": "Shell",
"bytes": "6640"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>
Their fence is an attack on all of us
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<?php include "../../legacy-includes/Script.htmlf" ?>
</head>
<body bgcolor="#FFFFCC" text="000000" link="990000" vlink="660000" alink="003366" leftmargin="0" topmargin="0">
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="474"><a name="Top"></a><?php include "../../legacy-includes/TopLogo.htmlf" ?></td>
<td width="270"><?php include "../../legacy-includes/TopAd.htmlf" ?>
</td></tr></table>
<table width="744" cellspacing="0" cellpadding="0" border="0">
<tr><td width="18" bgcolor="FFCC66"></td>
<td width="108" bgcolor="FFCC66" valign=top><?php include "../../legacy-includes/LeftButtons.htmlf" ?></td>
<td width="18"></td>
<td width="480" valign="top">
<?php include "../../legacy-includes/BodyInsert.htmlf" ?>
<P><font face="Arial, Helvetica, sans-serif" size="2"><b>WHAT DO SOCIALISTS SAY?</b></font><br>
<font face="Times New Roman, Times, serif" size="5"><b>Their fence is an attack on all of us</b></font></P>
<P><font face="Times New Roman, Times, serif" size="2"><b>by ELIZABETH SCHULTE</b></font><font face="Arial, Helvetica, sans-serif" size="2"> | September 14, 2001 | Pages 8 and 9</font></P>
<font face="Times New Roman, Times, serif" size="3"><P>D.C. POLICE Chief Charles Ramsey says he needs a nine-foot-high fence and thousands of cops to "keep the peace" when protesters come to Washington to demonstrate against the IMF and World Bank. But that's par for the course today.</P>
<P>The idea that global justice protesters should be treated like criminals has become a familiar theme for authorities from Seattle to Quebec City to Genoa. And for their media mouthpieces.</P>
<P>When 23-year-old protester Carlo Giuliani was gunned down at the G8 protests in Genoa in July, <I>Time</I> magazine called it a message to his fellow protesters: "You reap what you sow." Sickening.</P>
<P>U.S. leaders like to claim that this is the world's greatest "democracy," where every citizen has the "right to protest" if they see injustice. Meanwhile, they're criminalizing protest with barricades and police in the capital of that so-called democracy. But this isn't a new tactic.</P>
<P>The U.S. has a long history of criminalizing protest--from persecuting union militants to jailing opponents of the First World War, from wiretapping Martin Luther King to hounding the Black Panthers. The state bends the rules of what is legal and illegal to meet its needs--and the interests of the ruling class it serves.</P>
<P>So striking workers have the right to set up a picket line in front of their workplace. But if the picket becomes effective--say, by turning away scabs--management can get an injunction to limit the number of picketers. The vast majority of rights that we have today were won because people organized to fight for them--even if that meant breaking unjust laws.</P>
<P>The civil rights movement of the 1950s and 1960s is a perfect example. When Rosa Parks refused to give up her bus seat to a white, she became a criminal in the eyes of 1950s Alabama. She was breaking the law. But the law was segregation--a racist law that had to be broken to be abolished.</P>
<P>When Parks' action inspired other African Americans to organize the Montgomery Bus Boycott, they became criminals, too. Police issued traffic tickets and arrested hundreds of Black drivers who organized carpools for bus boycotters.</P>
<P>Then came the mass arrests on charges of "conspiracy against the bus company." But when racist gangs attacked the Black boycotters and bombed their churches, the police did nothing.</P>
<P>This sort of double standard has been repeated throughout history. "The war in Vietnam," historian Howard Zinn wrote in 1969, "is a particularly vivid example of how we cannot depend on the normal processes of 'law and order,' of the election process, of letters to the <I>Times,</I> to stop a series of especially brutal acts against the Vietnamese and against our own sons...The greatest danger for American democracy is not from the protesters. That democracy is too poorly realized for us to consider critics--even rebels--as the chief problem. Its fulfillment requires us all, living in an ossified system which sustains too much killing and too much selfishness, to join the protest."</P>
<P>D.C. officials claim that the fence they're building is for a few "bad" protesters. But they're building it as an attack on all of us.</P>
<P>That's why we have to mobilize the largest numbers possible to protest the real criminals in D.C.--the IMF, the World Bank and the politicians who protect them. We have to start by saying protesting is not a crime!</P>
<?php include "../../legacy-includes/BottomNavLinks.htmlf" ?>
<td width="12"></td>
<td width="108" valign="top">
<?php include "../../legacy-includes/RightAdFolder.htmlf" ?>
</td>
</tr>
</table>
</body>
</html>
| {
"content_hash": "1422ba4df55b41dbedfa991147d1ef90",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 697,
"avg_line_length": 88.76785714285714,
"alnum_prop": 0.7449205391269362,
"repo_name": "ISO-tech/sw-d8",
"id": "dddbd167d5574258d4fc12c8ff0fc14514bd087b",
"size": "4971",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/2001/377/377_09_FenceAsAttack.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "30677"
},
{
"name": "Gherkin",
"bytes": "3374"
},
{
"name": "HTML",
"bytes": "269460"
},
{
"name": "Hack",
"bytes": "35936"
},
{
"name": "JavaScript",
"bytes": "104527"
},
{
"name": "PHP",
"bytes": "53430607"
},
{
"name": "SCSS",
"bytes": "50217"
},
{
"name": "Shell",
"bytes": "8234"
},
{
"name": "Twig",
"bytes": "57403"
}
],
"symlink_target": ""
} |
export default function () {
this.transition(this.use('fade'));
}
| {
"content_hash": "9f3fd672efbb8eb58c8838c3517979b6",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 36,
"avg_line_length": 22.666666666666668,
"alnum_prop": 0.6764705882352942,
"repo_name": "html-next/flexi",
"id": "2f2bbd471df326b890502c6aeeb1468f9daf2a30",
"size": "68",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "packages/flexi-sustain/tests/dummy/app/transitions.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6712"
},
{
"name": "Handlebars",
"bytes": "56088"
},
{
"name": "JavaScript",
"bytes": "125712"
},
{
"name": "SCSS",
"bytes": "27458"
}
],
"symlink_target": ""
} |
=========================
Sample metering_agent.ini
=========================
This sample configuration can also be viewed in `the raw format
<../../_static/config-samples/metering_agent.conf.sample>`_.
.. literalinclude:: ../../_static/config-samples/metering_agent.conf.sample
| {
"content_hash": "64cd1545ad2b3d9721656c0d40b4b47f",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 75,
"avg_line_length": 35.125,
"alnum_prop": 0.6120996441281139,
"repo_name": "noironetworks/neutron",
"id": "8bb735f9e0bf7f2c4d215d67446b39afc62c2843",
"size": "281",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "doc/source/configuration/samples/metering-agent.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1047"
},
{
"name": "Python",
"bytes": "11420614"
},
{
"name": "Shell",
"bytes": "38791"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>descente-infinie: 16 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.1 / descente-infinie - 8.5.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
descente-infinie
<small>
8.5.0
<span class="label label-success">16 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-09-12 23:10:41 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-09-12 23:10:41 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.5.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.05.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.05.0 Official 4.05.0 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "matej.kosik@inria.fr"
homepage: "https://github.com/coq-contribs/descente-infinie"
license: "GPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/DescenteInfinie"]
depends: [
"ocaml"
"coq" {>= "8.5" & < "8.6~"}
]
tags: [ "keyword:induction" "keyword:infinite descent" "category:Miscellaneous/Coq Extensions" "date:2010-02" ]
authors: [ "Li Mengran <limengra@comp.nus.edu.sg>" "Razvan Voicu <razvan@comp.nus.edu.sg>" ]
bug-reports: "https://github.com/coq-contribs/descente-infinie/issues"
dev-repo: "git+https://github.com/coq-contribs/descente-infinie.git"
synopsis: "The Descente Infinie Tactic"
description:
"This is a tactic plugin for coq. The tactic helps to prove inductive lemmas by fixpoint functions. A manual for the tactic can be found on its homepage listed above."
flags: light-uninstall
url {
src:
"https://github.com/coq-contribs/descente-infinie/archive/v8.5.0.tar.gz"
checksum: "md5=e2ca9349d3e6d90aae6c6a300d87968e"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-descente-infinie.8.5.0 coq.8.5.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-descente-infinie.8.5.0 coq.8.5.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>12 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-descente-infinie.8.5.0 coq.8.5.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>16 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 138 K</p>
<ul>
<li>103 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DescenteInfinie/di_plugin.cmxs</code></li>
<li>24 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DescenteInfinie/di_plugin.cma</code></li>
<li>8 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DescenteInfinie/di.cmi</code></li>
<li>3 K <code>../ocaml-base-compiler.4.05.0/lib/coq/user-contrib/DescenteInfinie/di_plugin_mod.cmi</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-descente-infinie.8.5.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "77f28ef5e6a3b3ecd81faa3a449a0a9b",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 179,
"avg_line_length": 45.01840490797546,
"alnum_prop": 0.5493322431180158,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "303a7f96d5492bd5c1debf9c4ce2e69251926bf2",
"size": "7363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.05.0-2.0.1/released/8.5.1/descente-infinie/8.5.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.