text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Signup
*/
exports.signup = function(req, res) {
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
// Init Variables
var user = new User(req.body);
var message = null;
// Add missing user fields
user.provider = 'local';
// Then save the user
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
};
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
})(req, res, next);
};
/**
* Signout
*/
exports.signout = function(req, res) {
req.logout();
res.redirect('/');
};
/**
* OAuth callback
*/
exports.oauthCallback = function(strategy) {
return function(req, res, next) {
passport.authenticate(strategy, function(err, user, redirectURL) {
if (err || !user) {
return res.redirect('/#!/signin');
}
req.login(user, function(err) {
if (err) {
return res.redirect('/#!/signin');
}
return res.redirect(redirectURL || '/');
});
})(req, res, next);
};
};
/**
* Helper function to save or update a OAuth user profile
*/
exports.saveOAuthUserProfile = function(req, providerUserProfile, done) {
if (!req.user) {
// Define a search query fields
var searchMainProviderIdentifierField = 'providerData.' + providerUserProfile.providerIdentifierField;
var searchAdditionalProviderIdentifierField = 'additionalProvidersData.' + providerUserProfile.provider + '.' + providerUserProfile.providerIdentifierField;
// Define main provider search query
var mainProviderSearchQuery = {};
mainProviderSearchQuery.provider = providerUserProfile.provider;
mainProviderSearchQuery[searchMainProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define additional provider search query
var additionalProviderSearchQuery = {};
additionalProviderSearchQuery[searchAdditionalProviderIdentifierField] = providerUserProfile.providerData[providerUserProfile.providerIdentifierField];
// Define a search query to find existing user with current provider profile
var searchQuery = {
$or: [mainProviderSearchQuery, additionalProviderSearchQuery]
};
User.findOne(searchQuery, function(err, user) {
if (err) {
return done(err);
} else {
if (!user) {
var possibleUsername = providerUserProfile.username || ((providerUserProfile.email) ? providerUserProfile.email.split('@')[0] : '');
User.findUniqueUsername(possibleUsername, null, function(availableUsername) {
user = new User({
firstName: providerUserProfile.firstName,
lastName: providerUserProfile.lastName,
username: availableUsername,
displayName: providerUserProfile.displayName,
email: providerUserProfile.email,
provider: providerUserProfile.provider,
providerData: providerUserProfile.providerData
});
// And save the user
user.save(function(err) {
return done(err, user);
});
});
} else {
return done(err, user);
}
}
});
} else {
// User is already logged in, join the provider data to the existing user
var user = req.user;
// Check if user exists, is not signed in using this provider, and doesn't have that provider data already configured
if (user.provider !== providerUserProfile.provider && (!user.additionalProvidersData || !user.additionalProvidersData[providerUserProfile.provider])) {
// Add the provider data to the additional provider data field
if (!user.additionalProvidersData) user.additionalProvidersData = {};
user.additionalProvidersData[providerUserProfile.provider] = providerUserProfile.providerData;
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
// And save the user
user.save(function(err) {
return done(err, user, '/#!/settings/accounts');
});
} else {
return done(new Error('User is already connected using this provider'), user);
}
}
};
/**
* Remove OAuth provider
*/
exports.removeOAuthProvider = function(req, res, next) {
var user = req.user;
var provider = req.param('provider');
if (user && provider) {
// Delete the additional provider
if (user.additionalProvidersData[provider]) {
delete user.additionalProvidersData[provider];
// Then tell mongoose that we've updated the additionalProvidersData field
user.markModified('additionalProvidersData');
}
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
}
}; | {'content_hash': 'f9627de7c3a0e3bd14a259205e4610ae', 'timestamp': '', 'source': 'github', 'line_count': 205, 'max_line_length': 158, 'avg_line_length': 27.492682926829268, 'alnum_prop': 0.682931156848829, 'repo_name': 'timsvoice/verdantree_mean', 'id': '68e165963bdf1be934b9ae1a128a322efaa3ac9e', 'size': '5636', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/users/users.authentication.server.controller.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '233345'}, {'name': 'HTML', 'bytes': '137557'}, {'name': 'JavaScript', 'bytes': '357924'}, {'name': 'Shell', 'bytes': '414'}]} |
#ifndef BLOBS_H
#define BLOBS_H
/*----------------------------------------------------------------------
I n c l u d e s
----------------------------------------------------------------------*/
#include "vecfuncs.h"
#include "tessclas.h"
/*----------------------------------------------------------------------
T y p e s
----------------------------------------------------------------------*/
typedef struct
{ /* Widths of pieces */
int num_chars;
int widths[1];
} WIDTH_RECORD;
/*----------------------------------------------------------------------
M a c r o s
----------------------------------------------------------------------*/
/**********************************************************************
* free_widths
*
* Free the memory taken up by a width array.
**********************************************************************/
#define free_widths(w) \
if (w) memfree (w)
/*----------------------------------------------------------------------
F u n c t i o n s
----------------------------------------------------------------------*/
void blob_origin(TBLOB *blob, /*blob to compute on */
TPOINT *origin); /*return value */
/*blob to compute on */
void blob_bounding_box(TBLOB *blob,
register TPOINT *topleft, /*bounding box */
register TPOINT *botright);
void blobs_bounding_box(TBLOB *blobs, TPOINT *topleft, TPOINT *botright);
void blobs_origin(TBLOB *blobs, /*blob to compute on */
TPOINT *origin); /*return value */
/*blob to compute on */
WIDTH_RECORD *blobs_widths(TBLOB *blobs);
int count_blobs(TBLOB *blobs);
void delete_word(TWERD *word);
void delete_edgepts(register EDGEPT *edgepts);
/*
#if defined(__STDC__) || defined(__cplusplus)
# define _ARGS(s) s
#else
# define _ARGS(s) ()
#endif*/
/* blobs.c
void blob_origin
_ARGS((BLOB *blob,
TPOINT *origin));
void blob_bounding_box
_ARGS((BLOB *blob,
TPOINT *topleft,
TPOINT *botright));
void blobs_bounding_box
_ARGS((BLOB *blobs,
TPOINT *topleft,
TPOINT *botright));
void blobs_origin
_ARGS((BLOB *blobs,
TPOINT *origin));
WIDTH_RECORD *blobs_widths
_ARGS((BLOB *blobs));
int count_blobs
_ARGS((BLOB *blobs));
void delete_word
_ARGS((TWERD *word));
void delete_edgepts
_ARGS((EDGEPT *edgepts));
#undef _ARGS
*/
#endif
| {'content_hash': '96ec5a192e1ae5816e5384f005dd8c97', 'timestamp': '', 'source': 'github', 'line_count': 96, 'max_line_length': 74, 'avg_line_length': 26.270833333333332, 'alnum_prop': 0.40523394131641555, 'repo_name': 'danauclair/CardScan', 'id': '16c64b423ae3f7dd693576e286749db7d685cb73', 'size': '3632', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'tesseract-ocr/ccstruct/blobs.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2032861'}, {'name': 'C++', 'bytes': '3669754'}, {'name': 'Java', 'bytes': '79863'}, {'name': 'Objective-C', 'bytes': '288051'}, {'name': 'Shell', 'bytes': '255043'}]} |
package clustermesh
import (
"fmt"
"github.com/cilium/cilium/pkg/controller"
"github.com/cilium/cilium/pkg/kvstore/store"
"github.com/cilium/cilium/pkg/lock"
nodeStore "github.com/cilium/cilium/pkg/node/store"
"github.com/cilium/cilium/pkg/option"
)
const (
// configNotificationsChannelSize is the size of the channel used to
// notify a clustermesh of configuration changes
configNotificationsChannelSize = 512
)
// Configuration is the configuration that must be provided to
// NewClusterMesh()
type Configuration struct {
// Name is the name of the remote cluster cache. This is for logging
// purposes only
Name string
// ConfigDirectory is the path to the directory that will be watched for etcd
// configuration files to appear
ConfigDirectory string
// NodeKeyCreator is the function used to create node instances as
// nodes are being discovered in remote clusters
NodeKeyCreator store.KeyCreator
// ServiceMerger is the interface responsible to merge service and
// endpoints into an existing cache
ServiceMerger ServiceMerger
nodeObserver store.Observer
}
// NodeObserver returns the node store observer of the configuration
func (c *Configuration) NodeObserver() store.Observer {
if c.nodeObserver != nil {
return c.nodeObserver
}
return &nodeStore.NodeObserver{}
}
// ClusterMesh is a cache of multiple remote clusters
type ClusterMesh struct {
// conf is the configuration, it is immutable after NewClusterMesh()
conf Configuration
mutex lock.RWMutex
clusters map[string]*remoteCluster
controllers *controller.Manager
configWatcher *configDirectoryWatcher
// globalServices is a list of all global services. The datastructure
// is protected by its own mutex inside of the structure.
globalServices *globalServiceCache
}
// NewClusterMesh creates a new remote cluster cache based on the
// provided configuration
func NewClusterMesh(c Configuration) (*ClusterMesh, error) {
cm := &ClusterMesh{
conf: c,
clusters: map[string]*remoteCluster{},
controllers: controller.NewManager(),
globalServices: newGlobalServiceCache(),
}
w, err := createConfigDirectoryWatcher(c.ConfigDirectory, cm)
if err != nil {
return nil, fmt.Errorf("unable to create config directory watcher: %s", err)
}
cm.configWatcher = w
if err := cm.configWatcher.watch(); err != nil {
return nil, err
}
return cm, nil
}
// Close stops watching for remote cluster configuration files to appear and
// will close all connections to remote clusters
func (cm *ClusterMesh) Close() {
cm.mutex.Lock()
defer cm.mutex.Unlock()
if cm.configWatcher != nil {
cm.configWatcher.close()
}
for name, cluster := range cm.clusters {
cluster.onRemove()
delete(cm.clusters, name)
}
cm.controllers.RemoveAllAndWait()
}
func (cm *ClusterMesh) newRemoteCluster(name, path string) *remoteCluster {
return &remoteCluster{
name: name,
configPath: path,
mesh: cm,
changed: make(chan bool, configNotificationsChannelSize),
controllers: controller.NewManager(),
}
}
func (cm *ClusterMesh) add(name, path string) {
if name == option.Config.ClusterName {
log.WithField(fieldClusterName, name).Debug("Ignoring configuration for own cluster")
return
}
inserted := false
cm.mutex.Lock()
cluster, ok := cm.clusters[name]
if !ok {
cluster = cm.newRemoteCluster(name, path)
cm.clusters[name] = cluster
inserted = true
}
cm.mutex.Unlock()
log.WithField(fieldClusterName, name).Debug("Remote cluster configuration added")
if inserted {
cluster.onInsert()
} else {
// signal a change in configuration
cluster.changed <- true
}
}
func (cm *ClusterMesh) remove(name string) {
cm.mutex.Lock()
if cluster, ok := cm.clusters[name]; ok {
cluster.onRemove()
delete(cm.clusters, name)
cm.globalServices.onClusterDelete(name)
}
cm.mutex.Unlock()
log.WithField(fieldClusterName, name).Debug("Remote cluster configuration removed")
}
// NumReadyClusters returns the number of remote clusters to which a connection
// has been established
func (cm *ClusterMesh) NumReadyClusters() int {
cm.mutex.RLock()
defer cm.mutex.RUnlock()
nready := 0
for _, cm := range cm.clusters {
if cm.isReady() {
nready++
}
}
return nready
}
| {'content_hash': '55ccb497465129d5475afdc663ad69e5', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 87, 'avg_line_length': 25.111764705882354, 'alnum_prop': 0.7350667603654252, 'repo_name': 'scanf/cilium', 'id': 'd87637f04415caa07cf3cb55ff4d75ad108504ec', 'size': '4864', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/clustermesh/clustermesh.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '660212'}, {'name': 'C++', 'bytes': '6177'}, {'name': 'Dockerfile', 'bytes': '4492'}, {'name': 'Go', 'bytes': '4476462'}, {'name': 'Makefile', 'bytes': '25535'}, {'name': 'Perl 6', 'bytes': '4948'}, {'name': 'Python', 'bytes': '10259'}, {'name': 'Ruby', 'bytes': '11622'}, {'name': 'Shell', 'bytes': '225848'}, {'name': 'TeX', 'bytes': '416'}, {'name': 'sed', 'bytes': '4191'}]} |
from lxml import etree
import webob
from nova.api.openstack.compute.contrib import quotas
from nova.api.openstack import wsgi
from nova import test
from nova.tests.api.openstack import fakes
def quota_set(id):
return {'quota_set': {'id': id, 'metadata_items': 128,
'ram': 51200, 'floating_ips': 10, 'fixed_ips': 10,
'instances': 10, 'injected_files': 5, 'cores': 20,
'injected_file_content_bytes': 10240,
'security_groups': 10, 'security_group_rules': 20,
'key_pairs': 100, 'injected_file_path_bytes': 255}}
class QuotaSetsTest(test.TestCase):
def setUp(self):
super(QuotaSetsTest, self).setUp()
self.controller = quotas.QuotaSetsController()
def test_format_quota_set(self):
raw_quota_set = {
'instances': 10,
'cores': 20,
'ram': 51200,
'floating_ips': 10,
'fixed_ips': 10,
'metadata_items': 128,
'injected_files': 5,
'injected_file_path_bytes': 255,
'injected_file_content_bytes': 10240,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}
quota_set = self.controller._format_quota_set('1234', raw_quota_set)
qs = quota_set['quota_set']
self.assertEqual(qs['id'], '1234')
self.assertEqual(qs['instances'], 10)
self.assertEqual(qs['cores'], 20)
self.assertEqual(qs['ram'], 51200)
self.assertEqual(qs['floating_ips'], 10)
self.assertEqual(qs['fixed_ips'], 10)
self.assertEqual(qs['metadata_items'], 128)
self.assertEqual(qs['injected_files'], 5)
self.assertEqual(qs['injected_file_path_bytes'], 255)
self.assertEqual(qs['injected_file_content_bytes'], 10240)
self.assertEqual(qs['security_groups'], 10)
self.assertEqual(qs['security_group_rules'], 20)
self.assertEqual(qs['key_pairs'], 100)
def test_quotas_defaults(self):
uri = '/v2/fake_tenant/os-quota-sets/fake_tenant/defaults'
req = fakes.HTTPRequest.blank(uri)
res_dict = self.controller.defaults(req, 'fake_tenant')
expected = {'quota_set': {
'id': 'fake_tenant',
'instances': 10,
'cores': 20,
'ram': 51200,
'floating_ips': 10,
'fixed_ips': 10,
'metadata_items': 128,
'injected_files': 5,
'injected_file_path_bytes': 255,
'injected_file_content_bytes': 10240,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}}
self.assertEqual(res_dict, expected)
def test_quotas_show_as_admin(self):
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/1234',
use_admin_context=True)
res_dict = self.controller.show(req, 1234)
self.assertEqual(res_dict, quota_set('1234'))
def test_quotas_show_as_unauthorized_user(self):
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/1234')
self.assertRaises(webob.exc.HTTPForbidden, self.controller.show,
req, 1234)
def test_quotas_update_as_admin(self):
body = {'quota_set': {'instances': 50, 'cores': 50,
'ram': 51200, 'floating_ips': 10,
'fixed_ips': 10, 'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'injected_file_path_bytes': 255,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100, 'fixed_ips': 10}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',
use_admin_context=True)
res_dict = self.controller.update(req, 'update_me', body)
self.assertEqual(res_dict, body)
def test_quotas_update_as_user(self):
body = {'quota_set': {'instances': 50, 'cores': 50,
'ram': 51200, 'floating_ips': 10,
'fixed_ips': 10, 'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me')
self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,
req, 'update_me', body)
def test_quotas_update_invalid_key(self):
body = {'quota_set': {'instances2': -2, 'cores': -2,
'ram': -2, 'floating_ips': -2,
'metadata_items': -2, 'injected_files': -2,
'injected_file_content_bytes': -2}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
req, 'update_me', body)
def test_quotas_update_invalid_limit(self):
body = {'quota_set': {'instances': -2, 'cores': -2,
'ram': -2, 'floating_ips': -2, 'fixed_ips': -2,
'metadata_items': -2, 'injected_files': -2,
'injected_file_content_bytes': -2}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',
use_admin_context=True)
self.assertRaises(webob.exc.HTTPBadRequest, self.controller.update,
req, 'update_me', body)
def test_quotas_update_invalid_value(self):
expected_resp = {'quota_set': {
'instances': 50, 'cores': 50,
'ram': 51200, 'floating_ips': 10,
'fixed_ips': 10, 'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'injected_file_path_bytes': 255,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}}
# when PUT JSON format with empty string for quota
body = {'quota_set': {'instances': 50, 'cores': 50,
'ram': '', 'floating_ips': 10,
'fixed_ips': 10, 'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'injected_file_path_bytes': 255,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',
use_admin_context=True)
res_dict = self.controller.update(req, 'update_me', body)
self.assertEqual(res_dict, expected_resp)
# when PUT XML format with empty string for quota
body = {'quota_set': {'instances': 50, 'cores': 50,
'ram': {}, 'floating_ips': 10,
'fixed_ips': 10, 'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240,
'injected_file_path_bytes': 255,
'security_groups': 10,
'security_group_rules': 20,
'key_pairs': 100}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me',
use_admin_context=True)
res_dict = self.controller.update(req, 'update_me', body)
self.assertEqual(res_dict, expected_resp)
class QuotaXMLSerializerTest(test.TestCase):
def setUp(self):
super(QuotaXMLSerializerTest, self).setUp()
self.serializer = quotas.QuotaTemplate()
self.deserializer = wsgi.XMLDeserializer()
def test_serializer(self):
exemplar = dict(quota_set=dict(
id='project_id',
metadata_items=10,
injected_file_path_bytes=255,
injected_file_content_bytes=20,
ram=50,
floating_ips=60,
fixed_ips=10,
instances=70,
injected_files=80,
security_groups=10,
security_group_rules=20,
key_pairs=100,
cores=90))
text = self.serializer.serialize(exemplar)
tree = etree.fromstring(text)
self.assertEqual('quota_set', tree.tag)
self.assertEqual('project_id', tree.get('id'))
self.assertEqual(len(exemplar['quota_set']) - 1, len(tree))
for child in tree:
self.assertTrue(child.tag in exemplar['quota_set'])
self.assertEqual(int(child.text), exemplar['quota_set'][child.tag])
def test_deserializer(self):
exemplar = dict(quota_set=dict(
metadata_items='10',
injected_file_content_bytes='20',
ram='50',
floating_ips='60',
fixed_ips='10',
instances='70',
injected_files='80',
security_groups='10',
security_group_rules='20',
key_pairs='100',
cores='90'))
intext = ("<?xml version='1.0' encoding='UTF-8'?>\n"
'<quota_set>'
'<metadata_items>10</metadata_items>'
'<injected_file_content_bytes>20'
'</injected_file_content_bytes>'
'<ram>50</ram>'
'<floating_ips>60</floating_ips>'
'<fixed_ips>10</fixed_ips>'
'<instances>70</instances>'
'<injected_files>80</injected_files>'
'<security_groups>10</security_groups>'
'<security_group_rules>20</security_group_rules>'
'<key_pairs>100</key_pairs>'
'<cores>90</cores>'
'</quota_set>')
result = self.deserializer.deserialize(intext)['body']
self.assertEqual(result, exemplar)
| {'content_hash': '8a33e8eee7bb919266b1b17fca917837', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 79, 'avg_line_length': 43.4, 'alnum_prop': 0.48921658986175115, 'repo_name': 'maheshp/novatest', 'id': '1ff7e60abc08bd34209c01186d289375fa67abc1', 'size': '11531', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'nova/tests/api/openstack/compute/contrib/test_quotas.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '7403'}, {'name': 'Python', 'bytes': '8947329'}, {'name': 'Shell', 'bytes': '17067'}]} |
String utilities to be used with a [KOCO](https://github.com/cbcrc/generator-koco) project.
[See API reference](https://github.com/cbcrc/koco-string-utilities/wiki/API-reference-documentation)
## Installation
```bash
bower install koco-string-utilities
```
## Usage with KOCO
This is a shared module that is used in many other module. The convention is to configure an alias in the `require.configs.js` with the name `string-utilities` like so:
```javascript
paths: {
...
'string-utilities': 'bower_components/koco-string-utilities/src/string-utilities'
...
}
```
| {'content_hash': '6edfb4cbd355c98684a108642ea58297', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 168, 'avg_line_length': 27.428571428571427, 'alnum_prop': 0.7413194444444444, 'repo_name': 'cbcrc/koco-string-utilities', 'id': '80655ea68c11a778294ebe0e5baf693f9cd61a1f', 'size': '600', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2246'}]} |
package com.github.nyrkovalex.get.me;
import com.github.nyrkovalex.get.me.api.GetMe;
import com.github.nyrkovalex.get.me.git.Git;
import com.github.nyrkovalex.get.me.json.Description;
import com.github.nyrkovalex.get.me.json.Jsons;
import com.github.nyrkovalex.get.me.json.Parser;
import com.github.nyrkovalex.get.me.param.Params;
import com.github.nyrkovalex.get.me.param.RepoUrl;
import com.github.nyrkovalex.get.me.param.WrongUsageException;
import com.github.nyrkovalex.seed.logging.Logging;
import com.github.nyrkovalex.seed.plugins.Plugins;
import com.gtihub.nyrkovalex.seed.nio.Fs;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
final class App {
private static final GetMe.Environment GETME_ENVIRONMENT = GetMe.environment();
private static final Plugins.Loader LOADER = Plugins.loader();
private static final Logger LOG = Logging.logger(App.class);
private static final String DESCRIPTOR_FILENAME = "get.me.json";
public static void main(String... args) throws Exception {
Params params;
try {
params = Params.from(args);
} catch (WrongUsageException e) {
System.out.println(e.getMessage());
System.exit(1);
return;
}
Logging.init(params.isDebug(), App.class);
App getMe = new App(params);
getMe.run();
}
private final Params params;
private final Git.Cloner cloner = Git.cloner();
private final Parser parser = Jsons.parser();
private final Fs fileSys = Fs.instance();
private App(Params params) {
this.params = params;
}
private void run() throws Exception {
for (RepoUrl url : params.getUrls()) {
buildTarget(url, params.isDebug());
}
}
private void buildTarget(RepoUrl url, boolean debug) throws Exception {
Path tempDir = fileSys.tempDir("get.me-");
try {
cloner.clone(url.getUrl())
.branch(url.getBranch())
.enableOutput(params.isDebug())
.to(tempDir);
Path descriptorFile = tempDir.resolve(DESCRIPTOR_FILENAME);
List<Description> parsed = parser.parseDescription(descriptorFile);
for (Description p : parsed) {
runPlugin(new PluginExecutionContext(tempDir, debug), p);
}
} finally {
fileSys.deleteWithContents(tempDir);
}
}
// We don't know the generic argument type here,
// it's client's job to provide correct class for JSON deserialization
@SuppressWarnings({ "rawtypes", "unchecked" })
private void runPlugin(GetMe.ExecutionContext context, Description builderDescription)
throws ReflectiveOperationException, GetMe.PluginException {
GetMe.Plugin plugin = loadPlugin(builderDescription);
LOG.info(() -> "Running " + builderDescription.className());
Optional builderParams = builderDescription.params(plugin.paramsClass());
plugin.exec(context, builderParams);
}
private GetMe.Plugin loadPlugin(Description builderDescription) throws ReflectiveOperationException {
LOG.fine(() -> String.format(
"Loading %s from %s", builderDescription.className(), GETME_ENVIRONMENT.pluginsHome()));
Plugins.Repo repo = LOADER.repo(GETME_ENVIRONMENT.pluginsHome());
return repo.instanceOf(builderDescription.className(), GetMe.Plugin.class);
}
private static class PluginExecutionContext implements GetMe.ExecutionContext {
private final Path cwd;
private final boolean debug;
private PluginExecutionContext(Path cwd, boolean debug) {
this.cwd = cwd;
this.debug = debug;
}
@Override
public boolean isDebug() {
return debug;
}
@Override
public Path getCwd() {
return cwd;
}
}
}
| {'content_hash': '2ebea8437630bbc0eee9b265d00a4c4a', 'timestamp': '', 'source': 'github', 'line_count': 112, 'max_line_length': 102, 'avg_line_length': 31.419642857142858, 'alnum_prop': 0.7442455242966752, 'repo_name': 'nyrkovalex/get.me', 'id': '2fc407c7520c3a3dca69e0da7fdcc6fdf9e210c4', 'size': '3519', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/github/nyrkovalex/get/me/App.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '28179'}]} |
#include <vlib/vlib.h>
#include <vnet/ip/format.h>
#include <vnet/ip/lookup.h>
#include <vnet/adj/adj.h>
#include <vnet/dpo/load_balance.h>
#include <vnet/dpo/drop_dpo.h>
#include <vnet/fib/fib_entry.h>
#include <vnet/fib/fib_walk.h>
#include <vnet/fib/fib_entry_src.h>
#include <vnet/fib/fib_entry_cover.h>
#include <vnet/fib/fib_table.h>
#include <vnet/fib/fib_internal.h>
#include <vnet/fib/fib_attached_export.h>
#include <vnet/fib/fib_path_ext.h>
/*
* Array of strings/names for the FIB sources
*/
static const char *fib_source_names[] = FIB_SOURCES;
static const char *fib_attribute_names[] = FIB_ENTRY_ATTRIBUTES;
/*
* Pool for all fib_entries
*/
static fib_entry_t *fib_entry_pool;
fib_entry_t *
fib_entry_get (fib_node_index_t index)
{
return (pool_elt_at_index(fib_entry_pool, index));
}
static fib_node_t *
fib_entry_get_node (fib_node_index_t index)
{
return ((fib_node_t*)fib_entry_get(index));
}
fib_node_index_t
fib_entry_get_index (const fib_entry_t * fib_entry)
{
return (fib_entry - fib_entry_pool);
}
static fib_protocol_t
fib_entry_get_proto (const fib_entry_t * fib_entry)
{
return (fib_entry->fe_prefix.fp_proto);
}
fib_forward_chain_type_t
fib_entry_get_default_chain_type (const fib_entry_t *fib_entry)
{
switch (fib_entry->fe_prefix.fp_proto)
{
case FIB_PROTOCOL_IP4:
return (FIB_FORW_CHAIN_TYPE_UNICAST_IP4);
case FIB_PROTOCOL_IP6:
return (FIB_FORW_CHAIN_TYPE_UNICAST_IP6);
case FIB_PROTOCOL_MPLS:
if (MPLS_EOS == fib_entry->fe_prefix.fp_eos)
/*
* If the entry being asked is a eos-MPLS label entry,
* then use the payload-protocol field, that we stashed there
* for just this purpose
*/
return (fib_forw_chain_type_from_dpo_proto(
fib_entry->fe_prefix.fp_payload_proto));
else
return (FIB_FORW_CHAIN_TYPE_MPLS_NON_EOS);
}
return (FIB_FORW_CHAIN_TYPE_UNICAST_IP4);
}
u8 *
format_fib_entry (u8 * s, va_list * args)
{
fib_forward_chain_type_t fct;
fib_entry_attribute_t attr;
fib_path_ext_t *path_ext;
fib_entry_t *fib_entry;
fib_entry_src_t *src;
fib_node_index_t fei;
fib_source_t source;
u32 n_covered;
int level;
fei = va_arg (*args, fib_node_index_t);
level = va_arg (*args, int);
fib_entry = fib_entry_get(fei);
s = format (s, "%U", format_fib_prefix, &fib_entry->fe_prefix);
if (level >= FIB_ENTRY_FORMAT_DETAIL)
{
s = format (s, " fib:%d", fib_entry->fe_fib_index);
s = format (s, " index:%d", fib_entry_get_index(fib_entry));
s = format (s, " locks:%d", fib_entry->fe_node.fn_locks);
FOR_EACH_SRC_ADDED(fib_entry, src, source,
({
s = format (s, "\n src:%s ",
fib_source_names[source]);
s = fib_entry_src_format(fib_entry, source, s);
s = format (s, " refs:%d ", src->fes_ref_count);
if (FIB_ENTRY_FLAG_NONE != src->fes_entry_flags) {
s = format(s, "flags:");
FOR_EACH_FIB_ATTRIBUTE(attr) {
if ((1<<attr) & src->fes_entry_flags) {
s = format (s, "%s,", fib_attribute_names[attr]);
}
}
}
s = format (s, "\n");
if (FIB_NODE_INDEX_INVALID != src->fes_pl)
{
s = fib_path_list_format(src->fes_pl, s);
}
if (NULL != src->fes_path_exts)
{
s = format(s, " Extensions:");
vec_foreach(path_ext, src->fes_path_exts)
{
s = format(s, "\n %U", format_fib_path_ext, path_ext);
}
}
}));
n_covered = fib_entry_cover_get_size(fib_entry);
if (n_covered > 0) {
s = format(s, "\n tracking %d covered: ", n_covered);
s = fib_entry_cover_list_format(fib_entry, s);
}
s = fib_ae_import_format(fib_entry, s);
s = fib_ae_export_format(fib_entry, s);
s = format (s, "\n forwarding: ");
}
else
{
s = format (s, "\n");
}
fct = fib_entry_get_default_chain_type(fib_entry);
if (!dpo_id_is_valid(&fib_entry->fe_lb))
{
s = format (s, " UNRESOLVED\n");
return (s);
}
else
{
s = format(s, " %U-chain\n %U",
format_fib_forw_chain_type, fct,
format_dpo_id,
&fib_entry->fe_lb,
2);
s = format(s, "\n");
if (level >= FIB_ENTRY_FORMAT_DETAIL2)
{
fib_entry_delegate_type_t fdt;
fib_entry_delegate_t *fed;
FOR_EACH_DELEGATE_CHAIN(fib_entry, fdt, fed,
{
s = format(s, " %U-chain\n %U",
format_fib_forw_chain_type,
fib_entry_delegate_type_to_chain_type(fdt),
format_dpo_id, &fed->fd_dpo, 2);
s = format(s, "\n");
});
}
}
if (level >= FIB_ENTRY_FORMAT_DETAIL2)
{
s = format(s, "\nchildren:");
s = fib_node_children_format(fib_entry->fe_node.fn_children, s);
}
return (s);
}
static fib_entry_t*
fib_entry_from_fib_node (fib_node_t *node)
{
#if CLIB_DEBUG > 0
ASSERT(FIB_NODE_TYPE_ENTRY == node->fn_type);
#endif
return ((fib_entry_t*)node);
}
static void
fib_entry_last_lock_gone (fib_node_t *node)
{
fib_entry_delegate_type_t fdt;
fib_entry_delegate_t *fed;
fib_entry_t *fib_entry;
fib_entry = fib_entry_from_fib_node(node);
FOR_EACH_DELEGATE_CHAIN(fib_entry, fdt, fed,
{
dpo_reset(&fed->fd_dpo);
fib_entry_delegate_remove(fib_entry, fdt);
});
FIB_ENTRY_DBG(fib_entry, "last-lock");
fib_node_deinit(&fib_entry->fe_node);
// FIXME -RR Backwalk
ASSERT(0 == vec_len(fib_entry->fe_delegates));
vec_free(fib_entry->fe_delegates);
vec_free(fib_entry->fe_srcs);
pool_put(fib_entry_pool, fib_entry);
}
static fib_entry_src_t*
fib_entry_get_best_src_i (const fib_entry_t *fib_entry)
{
fib_entry_src_t *bsrc;
/*
* the enum of sources is deliberately arranged in priority order
*/
if (0 == vec_len(fib_entry->fe_srcs))
{
bsrc = NULL;
}
else
{
bsrc = vec_elt_at_index(fib_entry->fe_srcs, 0);
}
return (bsrc);
}
static fib_source_t
fib_entry_src_get_source (const fib_entry_src_t *esrc)
{
if (NULL != esrc)
{
return (esrc->fes_src);
}
return (FIB_SOURCE_MAX);
}
static fib_entry_flag_t
fib_entry_src_get_flags (const fib_entry_src_t *esrc)
{
if (NULL != esrc)
{
return (esrc->fes_entry_flags);
}
return (FIB_ENTRY_FLAG_NONE);
}
fib_entry_flag_t
fib_entry_get_flags (fib_node_index_t fib_entry_index)
{
return (fib_entry_get_flags_i(fib_entry_get(fib_entry_index)));
}
/*
* fib_entry_back_walk_notify
*
* A back walk has reach this entry.
*/
static fib_node_back_walk_rc_t
fib_entry_back_walk_notify (fib_node_t *node,
fib_node_back_walk_ctx_t *ctx)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_from_fib_node(node);
if (FIB_NODE_BW_REASON_FLAG_EVALUATE & ctx->fnbw_reason ||
FIB_NODE_BW_REASON_FLAG_ADJ_UPDATE & ctx->fnbw_reason ||
FIB_NODE_BW_REASON_FLAG_ADJ_DOWN & ctx->fnbw_reason ||
FIB_NODE_BW_REASON_FLAG_INTERFACE_UP & ctx->fnbw_reason ||
FIB_NODE_BW_REASON_FLAG_INTERFACE_DOWN & ctx->fnbw_reason ||
FIB_NODE_BW_REASON_FLAG_INTERFACE_DELETE & ctx->fnbw_reason)
{
fib_entry_src_action_reactivate(fib_entry,
fib_entry_get_best_source(
fib_entry_get_index(fib_entry)));
}
/*
* all other walk types can be reclassifed to a re-evaluate to
* all recursive dependents.
* By reclassifying we ensure that should any of these walk types meet
* they can be merged.
*/
ctx->fnbw_reason = FIB_NODE_BW_REASON_FLAG_EVALUATE;
/*
* ... and nothing is forced sync from now on.
*/
ctx->fnbw_flags &= ~FIB_NODE_BW_FLAG_FORCE_SYNC;
/*
* propagate the backwalk further if we haven't already reached the
* maximum depth.
*/
fib_walk_sync(FIB_NODE_TYPE_ENTRY,
fib_entry_get_index(fib_entry),
ctx);
return (FIB_NODE_BACK_WALK_CONTINUE);
}
static void
fib_entry_show_memory (void)
{
u32 n_srcs = 0, n_exts = 0;
fib_entry_src_t *esrc;
fib_entry_t *entry;
fib_show_memory_usage("Entry",
pool_elts(fib_entry_pool),
pool_len(fib_entry_pool),
sizeof(fib_entry_t));
pool_foreach(entry, fib_entry_pool,
({
n_srcs += vec_len(entry->fe_srcs);
vec_foreach(esrc, entry->fe_srcs)
{
n_exts += vec_len(esrc->fes_path_exts);
}
}));
fib_show_memory_usage("Entry Source",
n_srcs, n_srcs, sizeof(fib_entry_src_t));
fib_show_memory_usage("Entry Path-Extensions",
n_exts, n_exts,
sizeof(fib_path_ext_t));
}
/*
* The FIB path-list's graph node virtual function table
*/
static const fib_node_vft_t fib_entry_vft = {
.fnv_get = fib_entry_get_node,
.fnv_last_lock = fib_entry_last_lock_gone,
.fnv_back_walk = fib_entry_back_walk_notify,
.fnv_mem_show = fib_entry_show_memory,
};
/**
* @brief Contribute the set of Adjacencies that this entry forwards with
* to build the uRPF list of its children
*/
void
fib_entry_contribute_urpf (fib_node_index_t entry_index,
index_t urpf)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(entry_index);
return (fib_path_list_contribute_urpf(fib_entry->fe_parent, urpf));
}
/*
* fib_entry_contribute_forwarding
*
* Get an lock the forwarding information (DPO) contributed by the FIB entry.
*/
void
fib_entry_contribute_forwarding (fib_node_index_t fib_entry_index,
fib_forward_chain_type_t fct,
dpo_id_t *dpo)
{
fib_entry_delegate_t *fed;
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
if (fct == fib_entry_get_default_chain_type(fib_entry))
{
dpo_copy(dpo, &fib_entry->fe_lb);
}
else
{
fed = fib_entry_delegate_get(fib_entry,
fib_entry_chain_type_to_delegate_type(fct));
if (NULL == fed)
{
fed = fib_entry_delegate_find_or_add(
fib_entry,
fib_entry_chain_type_to_delegate_type(fct));
/*
* on-demand create eos/non-eos.
* There is no on-demand delete because:
* - memory versus complexity & reliability:
* leaving unrequired [n]eos LB arounds wastes memory, cleaning
* then up on the right trigger is more code. i favour the latter.
*/
fib_entry_src_mk_lb(fib_entry,
fib_entry_get_best_src_i(fib_entry),
fct,
&fed->fd_dpo);
}
dpo_copy(dpo, &fed->fd_dpo);
}
}
const dpo_id_t *
fib_entry_contribute_ip_forwarding (fib_node_index_t fib_entry_index)
{
fib_forward_chain_type_t fct;
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
fct = fib_entry_get_default_chain_type(fib_entry);
ASSERT((fct == FIB_FORW_CHAIN_TYPE_UNICAST_IP4 ||
fct == FIB_FORW_CHAIN_TYPE_UNICAST_IP6));
return (&fib_entry->fe_lb);
}
adj_index_t
fib_entry_get_adj (fib_node_index_t fib_entry_index)
{
const dpo_id_t *dpo;
dpo = fib_entry_contribute_ip_forwarding(fib_entry_index);
dpo = load_balance_get_bucket(dpo->dpoi_index, 0);
if (dpo_is_adj(dpo))
{
return (dpo->dpoi_index);
}
return (ADJ_INDEX_INVALID);
}
fib_node_index_t
fib_entry_get_path_list (fib_node_index_t fib_entry_index)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
return (fib_entry->fe_parent);
}
u32
fib_entry_child_add (fib_node_index_t fib_entry_index,
fib_node_type_t child_type,
fib_node_index_t child_index)
{
return (fib_node_child_add(FIB_NODE_TYPE_ENTRY,
fib_entry_index,
child_type,
child_index));
};
void
fib_entry_child_remove (fib_node_index_t fib_entry_index,
u32 sibling_index)
{
fib_node_child_remove(FIB_NODE_TYPE_ENTRY,
fib_entry_index,
sibling_index);
if (0 == fib_node_get_n_children(FIB_NODE_TYPE_ENTRY,
fib_entry_index))
{
/*
* if there are no children left then there is no reason to keep
* the non-default forwarding chains. those chains are built only
* because the children want them.
*/
fib_entry_delegate_type_t fdt;
fib_entry_delegate_t *fed;
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
FOR_EACH_DELEGATE_CHAIN(fib_entry, fdt, fed,
{
dpo_reset(&fed->fd_dpo);
fib_entry_delegate_remove(fib_entry, fdt);
});
}
}
static fib_entry_t *
fib_entry_alloc (u32 fib_index,
const fib_prefix_t *prefix,
fib_node_index_t *fib_entry_index)
{
fib_entry_t *fib_entry;
fib_prefix_t *fep;
pool_get(fib_entry_pool, fib_entry);
memset(fib_entry, 0, sizeof(*fib_entry));
fib_node_init(&fib_entry->fe_node,
FIB_NODE_TYPE_ENTRY);
fib_entry->fe_fib_index = fib_index;
/*
* the one time we need to update the const prefix is when
* the entry is first created
*/
fep = (fib_prefix_t*)&(fib_entry->fe_prefix);
*fep = *prefix;
if (FIB_PROTOCOL_MPLS == fib_entry->fe_prefix.fp_proto)
{
fep->fp_len = 21;
if (MPLS_NON_EOS == fep->fp_eos)
{
fep->fp_payload_proto = DPO_PROTO_MPLS;
}
ASSERT(DPO_PROTO_NONE != fib_entry->fe_prefix.fp_payload_proto);
}
dpo_reset(&fib_entry->fe_lb);
*fib_entry_index = fib_entry_get_index(fib_entry);
FIB_ENTRY_DBG(fib_entry, "alloc");
return (fib_entry);
}
static void
fib_entry_post_flag_update_actions (fib_entry_t *fib_entry,
fib_source_t source,
fib_entry_flag_t old_flags)
{
/*
* handle changes to attached export for import entries
*/
int is_import = (FIB_ENTRY_FLAG_IMPORT & fib_entry_get_flags_i(fib_entry));
int was_import = (FIB_ENTRY_FLAG_IMPORT & old_flags);
if (!was_import && is_import)
{
/*
* transition from not exported to exported
*/
/*
* there is an assumption here that the entry resolves via only
* one interface and that it is the cross VRF interface.
*/
u32 sw_if_index = fib_path_list_get_resolving_interface(fib_entry->fe_parent);
fib_attached_export_import(fib_entry,
fib_table_get_index_for_sw_if_index(
fib_entry_get_proto(fib_entry),
sw_if_index));
}
else if (was_import && !is_import)
{
/*
* transition from exported to not exported
*/
fib_attached_export_purge(fib_entry);
}
/*
* else
* no change. nothing to do.
*/
/*
* handle changes to attached export for export entries
*/
int is_attached = (FIB_ENTRY_FLAG_ATTACHED & fib_entry_get_flags_i(fib_entry));
int was_attached = (FIB_ENTRY_FLAG_ATTACHED & old_flags);
if (!was_attached && is_attached)
{
/*
* transition to attached. time to export
*/
// FIXME
}
// else FIXME
}
static void
fib_entry_post_install_actions (fib_entry_t *fib_entry,
fib_source_t source,
fib_entry_flag_t old_flags)
{
fib_entry_post_flag_update_actions(fib_entry, source, old_flags);
fib_entry_src_action_installed(fib_entry, source);
}
fib_node_index_t
fib_entry_create (u32 fib_index,
const fib_prefix_t *prefix,
fib_source_t source,
fib_entry_flag_t flags,
const fib_route_path_t *paths)
{
fib_node_index_t fib_entry_index;
fib_entry_t *fib_entry;
ASSERT(0 < vec_len(paths));
fib_entry = fib_entry_alloc(fib_index, prefix, &fib_entry_index);
/*
* since this is a new entry create, we don't need to check for winning
* sources - there is only one.
*/
fib_entry = fib_entry_src_action_add(fib_entry, source, flags,
drop_dpo_get(
fib_proto_to_dpo(
fib_entry_get_proto(fib_entry))));
fib_entry_src_action_path_swap(fib_entry,
source,
flags,
paths);
/*
* handle possible realloc's by refetching the pointer
*/
fib_entry = fib_entry_get(fib_entry_index);
fib_entry_src_action_activate(fib_entry, source);
fib_entry_post_install_actions(fib_entry, source, FIB_ENTRY_FLAG_NONE);
return (fib_entry_index);
}
fib_node_index_t
fib_entry_create_special (u32 fib_index,
const fib_prefix_t *prefix,
fib_source_t source,
fib_entry_flag_t flags,
const dpo_id_t *dpo)
{
fib_node_index_t fib_entry_index;
fib_entry_t *fib_entry;
/*
* create and initiliase the new enty
*/
fib_entry = fib_entry_alloc(fib_index, prefix, &fib_entry_index);
/*
* create the path-list
*/
fib_entry = fib_entry_src_action_add(fib_entry, source, flags, dpo);
fib_entry_src_action_activate(fib_entry, source);
fib_entry_post_install_actions(fib_entry, source, FIB_ENTRY_FLAG_NONE);
return (fib_entry_index);
}
static void
fib_entry_post_update_actions (fib_entry_t *fib_entry,
fib_source_t source,
fib_entry_flag_t old_flags)
{
/*
* backwalk to children to inform then of the change to forwarding.
*/
fib_node_back_walk_ctx_t bw_ctx = {
.fnbw_reason = FIB_NODE_BW_REASON_FLAG_EVALUATE,
};
fib_walk_sync(FIB_NODE_TYPE_ENTRY, fib_entry_get_index(fib_entry), &bw_ctx);
/*
* then inform any covered prefixes
*/
fib_entry_cover_update_notify(fib_entry);
fib_entry_post_install_actions(fib_entry, source, old_flags);
}
static void
fib_entry_source_change (fib_entry_t *fib_entry,
fib_source_t best_source,
fib_source_t new_source,
fib_entry_flag_t old_flags)
{
/*
* if the path list for the source passed is invalid,
* then we need to create a new one. else we are updating
* an existing.
*/
if (new_source < best_source)
{
/*
* we have a new winning source.
*/
fib_entry_src_action_deactivate(fib_entry, best_source);
fib_entry_src_action_activate(fib_entry, new_source);
}
else if (new_source > best_source)
{
/*
* the new source loses. nothing to do here.
* the data from the source is saved in the path-list created
*/
return;
}
else
{
/*
* the new source is one this entry already has.
* But the path-list was updated, which will contribute new forwarding,
* so install it.
*/
fib_entry_src_action_deactivate(fib_entry, new_source);
fib_entry_src_action_activate(fib_entry, new_source);
}
fib_entry_post_update_actions(fib_entry, new_source, old_flags);
}
void
fib_entry_special_add (fib_node_index_t fib_entry_index,
fib_source_t source,
fib_entry_flag_t flags,
const dpo_id_t *dpo)
{
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
fib_entry = fib_entry_get(fib_entry_index);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
fib_entry = fib_entry_src_action_add(fib_entry, source, flags, dpo);
fib_entry_source_change(fib_entry, best_source, source, bflags);
}
void
fib_entry_special_update (fib_node_index_t fib_entry_index,
fib_source_t source,
fib_entry_flag_t flags,
const dpo_id_t *dpo)
{
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
fib_entry = fib_entry_get(fib_entry_index);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
fib_entry = fib_entry_src_action_update(fib_entry, source, flags, dpo);
fib_entry_source_change(fib_entry, best_source, source, bflags);
}
void
fib_entry_path_add (fib_node_index_t fib_entry_index,
fib_source_t source,
fib_entry_flag_t flags,
const fib_route_path_t *rpath)
{
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
ASSERT(1 == vec_len(rpath));
fib_entry = fib_entry_get(fib_entry_index);
ASSERT(NULL != fib_entry);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
fib_entry = fib_entry_src_action_path_add(fib_entry, source, flags, rpath);
/*
* if the path list for the source passed is invalid,
* then we need to create a new one. else we are updating
* an existing.
*/
if (source < best_source)
{
/*
* we have a new winning source.
*/
fib_entry_src_action_deactivate(fib_entry, best_source);
fib_entry_src_action_activate(fib_entry, source);
}
else if (source > best_source)
{
/*
* the new source loses. nothing to do here.
* the data from the source is saved in the path-list created
*/
return;
}
else
{
/*
* the new source is one this entry already has.
* But the path-list was updated, which will contribute new forwarding,
* so install it.
*/
fib_entry_src_action_deactivate(fib_entry, source);
fib_entry_src_action_activate(fib_entry, source);
}
fib_entry_post_update_actions(fib_entry, source, bflags);
}
/*
* fib_entry_path_remove
*
* remove a path from the entry.
* return the fib_entry's index if it is still present, INVALID otherwise.
*/
fib_entry_src_flag_t
fib_entry_path_remove (fib_node_index_t fib_entry_index,
fib_source_t source,
const fib_route_path_t *rpath)
{
fib_entry_src_flag_t sflag;
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
ASSERT(1 == vec_len(rpath));
fib_entry = fib_entry_get(fib_entry_index);
ASSERT(NULL != fib_entry);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
sflag = fib_entry_src_action_path_remove(fib_entry, source, rpath);
/*
* if the path list for the source passed is invalid,
* then we need to create a new one. else we are updating
* an existing.
*/
if (source < best_source )
{
/*
* Que! removing a path from a source that is better than the
* one this entry is using.
*/
ASSERT(0);
}
else if (source > best_source )
{
/*
* the source is not the best. nothing to do.
*/
return (FIB_ENTRY_SRC_FLAG_ADDED);
}
else
{
/*
* removing a path from the path-list we were using.
*/
if (!(FIB_ENTRY_SRC_FLAG_ADDED & sflag))
{
/*
* the last path from the source was removed.
* fallback to lower source
*/
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
if (FIB_SOURCE_MAX == best_source) {
/*
* no more sources left. this entry is toast.
*/
fib_entry_src_action_uninstall(fib_entry);
fib_entry_post_flag_update_actions(fib_entry, source, bflags);
return (FIB_ENTRY_SRC_FLAG_NONE);
}
else
{
fib_entry_src_action_activate(fib_entry, best_source);
source = best_source;
}
}
else
{
/*
* re-install the new forwarding information
*/
fib_entry_src_action_deactivate(fib_entry, source);
fib_entry_src_action_activate(fib_entry, source);
}
}
fib_entry_post_update_actions(fib_entry, source, bflags);
/*
* still have sources
*/
return (FIB_ENTRY_SRC_FLAG_ADDED);
}
/*
* fib_entry_special_remove
*
* remove a special source from the entry.
* return the fib_entry's index if it is still present, INVALID otherwise.
*/
fib_entry_src_flag_t
fib_entry_special_remove (fib_node_index_t fib_entry_index,
fib_source_t source)
{
fib_entry_src_flag_t sflag;
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
fib_entry = fib_entry_get(fib_entry_index);
ASSERT(NULL != fib_entry);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
sflag = fib_entry_src_action_remove(fib_entry, source);
/*
* if the path list for the source passed is invalid,
* then we need to create a new one. else we are updating
* an existing.
*/
if (source < best_source )
{
/*
* Que! removing a path from a source that is better than the
* one this entry is using. This can only mean it is a source
* this prefix does not have.
*/
return (FIB_ENTRY_SRC_FLAG_ADDED);
}
else if (source > best_source ) {
/*
* the source is not the best. nothing to do.
*/
return (FIB_ENTRY_SRC_FLAG_ADDED);
}
else
{
if (!(FIB_ENTRY_SRC_FLAG_ADDED & sflag))
{
/*
* the source was removed. use the next best.
*/
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
if (FIB_SOURCE_MAX == best_source) {
/*
* no more sources left. this entry is toast.
*/
fib_entry_src_action_uninstall(fib_entry);
fib_entry_post_flag_update_actions(fib_entry, source, bflags);
return (FIB_ENTRY_SRC_FLAG_NONE);
}
else
{
fib_entry_src_action_activate(fib_entry, best_source);
source = best_source;
}
}
else
{
/*
* re-install the new forwarding information
*/
fib_entry_src_action_reactivate(fib_entry, source);
}
}
fib_entry_post_update_actions(fib_entry, source, bflags);
/*
* still have sources
*/
return (FIB_ENTRY_SRC_FLAG_ADDED);
}
/**
* fib_entry_delete
*
* The source is withdrawing all the paths it provided
*/
fib_entry_src_flag_t
fib_entry_delete (fib_node_index_t fib_entry_index,
fib_source_t source)
{
return (fib_entry_special_remove(fib_entry_index, source));
}
/**
* fib_entry_update
*
* The source has provided a new set of paths that will replace the old.
*/
void
fib_entry_update (fib_node_index_t fib_entry_index,
fib_source_t source,
fib_entry_flag_t flags,
const fib_route_path_t *paths)
{
fib_source_t best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
fib_entry = fib_entry_get(fib_entry_index);
ASSERT(NULL != fib_entry);
bsrc = fib_entry_get_best_src_i(fib_entry);
best_source = fib_entry_src_get_source(bsrc);
bflags = fib_entry_src_get_flags(bsrc);
fib_entry_src_action_path_swap(fib_entry,
source,
flags,
paths);
/*
* handle possible realloc's by refetching the pointer
*/
fib_entry = fib_entry_get(fib_entry_index);
/*
* if the path list for the source passed is invalid,
* then we need to create a new one. else we are updating
* an existing.
*/
if (source < best_source)
{
/*
* we have a new winning source.
*/
fib_entry_src_action_deactivate(fib_entry, best_source);
fib_entry_src_action_activate(fib_entry, source);
}
else if (source > best_source) {
/*
* the new source loses. nothing to do here.
* the data from the source is saved in the path-list created
*/
return;
}
else
{
/*
* the new source is one this entry already has.
* But the path-list was updated, which will contribute new forwarding,
* so install it.
*/
fib_entry_src_action_deactivate(fib_entry, source);
fib_entry_src_action_activate(fib_entry, source);
}
fib_entry_post_update_actions(fib_entry, source, bflags);
}
/*
* fib_entry_cover_changed
*
* this entry is tracking its cover and that cover has changed.
*/
void
fib_entry_cover_changed (fib_node_index_t fib_entry_index)
{
fib_entry_src_cover_res_t res = {
.install = !0,
.bw_reason = FIB_NODE_BW_REASON_FLAG_NONE,
};
fib_source_t source, best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *esrc;
u32 index;
bflags = FIB_ENTRY_FLAG_NONE;
best_source = FIB_SOURCE_FIRST;
fib_entry = fib_entry_get(fib_entry_index);
fib_attached_export_cover_change(fib_entry);
/*
* propagate the notificuation to each of the added sources
*/
index = 0;
FOR_EACH_SRC_ADDED(fib_entry, esrc, source,
({
if (0 == index)
{
/*
* only the best source gets to set the back walk flags
*/
res = fib_entry_src_action_cover_change(fib_entry, source);
bflags = fib_entry_src_get_flags(esrc);
best_source = fib_entry_src_get_source(esrc);
}
else
{
fib_entry_src_action_cover_change(fib_entry, source);
}
index++;
}));
if (res.install)
{
fib_entry_src_action_reactivate(fib_entry,
fib_entry_src_get_source(
fib_entry_get_best_src_i(fib_entry)));
fib_entry_post_install_actions(fib_entry, best_source, bflags);
}
else
{
fib_entry_src_action_uninstall(fib_entry);
}
if (FIB_NODE_BW_REASON_FLAG_NONE != res.bw_reason)
{
/*
* time for walkies fido.
*/
fib_node_back_walk_ctx_t bw_ctx = {
.fnbw_reason = res.bw_reason,
};
fib_walk_sync(FIB_NODE_TYPE_ENTRY, fib_entry_index, &bw_ctx);
}
}
/*
* fib_entry_cover_updated
*
* this entry is tracking its cover and that cover has been updated
* (i.e. its forwarding information has changed).
*/
void
fib_entry_cover_updated (fib_node_index_t fib_entry_index)
{
fib_entry_src_cover_res_t res = {
.install = !0,
.bw_reason = FIB_NODE_BW_REASON_FLAG_NONE,
};
fib_source_t source, best_source;
fib_entry_flag_t bflags;
fib_entry_t *fib_entry;
fib_entry_src_t *esrc;
u32 index;
bflags = FIB_ENTRY_FLAG_NONE;
best_source = FIB_SOURCE_FIRST;
fib_entry = fib_entry_get(fib_entry_index);
fib_attached_export_cover_update(fib_entry);
/*
* propagate the notificuation to each of the added sources
*/
index = 0;
FOR_EACH_SRC_ADDED(fib_entry, esrc, source,
({
if (0 == index)
{
/*
* only the best source gets to set the back walk flags
*/
res = fib_entry_src_action_cover_update(fib_entry, source);
bflags = fib_entry_src_get_flags(esrc);
best_source = fib_entry_src_get_source(esrc);
}
else
{
fib_entry_src_action_cover_update(fib_entry, source);
}
index++;
}));
if (res.install)
{
fib_entry_src_action_reactivate(fib_entry,
fib_entry_src_get_source(
fib_entry_get_best_src_i(fib_entry)));
fib_entry_post_install_actions(fib_entry, best_source, bflags);
}
else
{
fib_entry_src_action_uninstall(fib_entry);
}
if (FIB_NODE_BW_REASON_FLAG_NONE != res.bw_reason)
{
/*
* time for walkies fido.
*/
fib_node_back_walk_ctx_t bw_ctx = {
.fnbw_reason = res.bw_reason,
};
fib_walk_sync(FIB_NODE_TYPE_ENTRY, fib_entry_index, &bw_ctx);
}
}
int
fib_entry_recursive_loop_detect (fib_node_index_t entry_index,
fib_node_index_t **entry_indicies)
{
fib_entry_t *fib_entry;
int was_looped, is_looped;
fib_entry = fib_entry_get(entry_index);
if (FIB_NODE_INDEX_INVALID != fib_entry->fe_parent)
{
fib_node_index_t *entries = *entry_indicies;
vec_add1(entries, entry_index);
was_looped = fib_path_list_is_looped(fib_entry->fe_parent);
is_looped = fib_path_list_recursive_loop_detect(fib_entry->fe_parent,
&entries);
*entry_indicies = entries;
if (!!was_looped != !!is_looped)
{
/*
* re-evaluate all the entry's forwarding
* NOTE: this is an inplace modify
*/
fib_entry_delegate_type_t fdt;
fib_entry_delegate_t *fed;
FOR_EACH_DELEGATE_CHAIN(fib_entry, fdt, fed,
{
fib_entry_src_mk_lb(fib_entry,
fib_entry_get_best_src_i(fib_entry),
fib_entry_delegate_type_to_chain_type(fdt),
&fed->fd_dpo);
});
}
}
else
{
/*
* the entry is currently not linked to a path-list. this happens
* when it is this entry that is re-linking path-lists and has thus
* broken the loop
*/
is_looped = 0;
}
return (is_looped);
}
u32
fib_entry_get_resolving_interface (fib_node_index_t entry_index)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(entry_index);
return (fib_path_list_get_resolving_interface(fib_entry->fe_parent));
}
fib_source_t
fib_entry_get_best_source (fib_node_index_t entry_index)
{
fib_entry_t *fib_entry;
fib_entry_src_t *bsrc;
fib_entry = fib_entry_get(entry_index);
bsrc = fib_entry_get_best_src_i(fib_entry);
return (fib_entry_src_get_source(bsrc));
}
static int
fib_ip4_address_compare (const ip4_address_t * a1,
const ip4_address_t * a2)
{
/*
* IP addresses are unsiged ints. the return value here needs to be signed
* a simple subtraction won't cut it.
* If the addresses are the same, the sort order is undefiend, so phoey.
*/
return ((clib_net_to_host_u32(a1->data_u32) >
clib_net_to_host_u32(a2->data_u32) ) ?
1 : -1);
}
static int
fib_ip6_address_compare (const ip6_address_t * a1,
const ip6_address_t * a2)
{
int i;
for (i = 0; i < ARRAY_LEN (a1->as_u16); i++)
{
int cmp = (clib_net_to_host_u16 (a1->as_u16[i]) -
clib_net_to_host_u16 (a2->as_u16[i]));
if (cmp != 0)
return cmp;
}
return 0;
}
static int
fib_entry_cmp (fib_node_index_t fib_entry_index1,
fib_node_index_t fib_entry_index2)
{
fib_entry_t *fib_entry1, *fib_entry2;
int cmp = 0;
fib_entry1 = fib_entry_get(fib_entry_index1);
fib_entry2 = fib_entry_get(fib_entry_index2);
switch (fib_entry1->fe_prefix.fp_proto)
{
case FIB_PROTOCOL_IP4:
cmp = fib_ip4_address_compare(&fib_entry1->fe_prefix.fp_addr.ip4,
&fib_entry2->fe_prefix.fp_addr.ip4);
break;
case FIB_PROTOCOL_IP6:
cmp = fib_ip6_address_compare(&fib_entry1->fe_prefix.fp_addr.ip6,
&fib_entry2->fe_prefix.fp_addr.ip6);
break;
case FIB_PROTOCOL_MPLS:
cmp = (fib_entry1->fe_prefix.fp_label - fib_entry2->fe_prefix.fp_label);
if (0 == cmp)
{
cmp = (fib_entry1->fe_prefix.fp_eos - fib_entry2->fe_prefix.fp_eos);
}
break;
}
if (0 == cmp) {
cmp = (fib_entry1->fe_prefix.fp_len - fib_entry2->fe_prefix.fp_len);
}
return (cmp);
}
int
fib_entry_cmp_for_sort (void *i1, void *i2)
{
fib_node_index_t *fib_entry_index1 = i1, *fib_entry_index2 = i2;
return (fib_entry_cmp(*fib_entry_index1,
*fib_entry_index2));
}
void
fib_entry_lock (fib_node_index_t fib_entry_index)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
fib_node_lock(&fib_entry->fe_node);
}
void
fib_entry_unlock (fib_node_index_t fib_entry_index)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
fib_node_unlock(&fib_entry->fe_node);
}
void
fib_entry_module_init (void)
{
fib_node_register_type (FIB_NODE_TYPE_ENTRY, &fib_entry_vft);
}
void
fib_entry_encode (fib_node_index_t fib_entry_index,
fib_route_path_encode_t **api_rpaths)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
fib_path_list_walk(fib_entry->fe_parent, fib_path_encode, api_rpaths);
}
void
fib_entry_get_prefix (fib_node_index_t fib_entry_index,
fib_prefix_t *pfx)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
*pfx = fib_entry->fe_prefix;
}
u32
fib_entry_get_fib_index (fib_node_index_t fib_entry_index)
{
fib_entry_t *fib_entry;
fib_entry = fib_entry_get(fib_entry_index);
return (fib_entry->fe_fib_index);
}
u32
fib_entry_pool_size (void)
{
return (pool_elts(fib_entry_pool));
}
static clib_error_t *
show_fib_entry_command (vlib_main_t * vm,
unformat_input_t * input,
vlib_cli_command_t * cmd)
{
fib_node_index_t fei;
if (unformat (input, "%d", &fei))
{
/*
* show one in detail
*/
if (!pool_is_free_index(fib_entry_pool, fei))
{
vlib_cli_output (vm, "%d@%U",
fei,
format_fib_entry, fei,
FIB_ENTRY_FORMAT_DETAIL2);
}
else
{
vlib_cli_output (vm, "entry %d invalid", fei);
}
}
else
{
/*
* show all
*/
vlib_cli_output (vm, "FIB Entries:");
pool_foreach_index(fei, fib_entry_pool,
({
vlib_cli_output (vm, "%d@%U",
fei,
format_fib_entry, fei,
FIB_ENTRY_FORMAT_BRIEF);
}));
}
return (NULL);
}
VLIB_CLI_COMMAND (show_fib_entry, static) = {
.path = "show fib entry",
.function = show_fib_entry_command,
.short_help = "show fib entry",
};
| {'content_hash': '04a0f288ba019a8d3750a0659cb22d4c', 'timestamp': '', 'source': 'github', 'line_count': 1491, 'max_line_length': 84, 'avg_line_length': 24.846411804158283, 'alnum_prop': 0.6055984451762674, 'repo_name': 'licko/vpp-1701-licko', 'id': '3aa3632c596b6f675e71ba5fdfc50ec3ed36c779', 'size': '37659', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vnet/vnet/fib/fib_entry.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '14862'}, {'name': 'C', 'bytes': '11299176'}, {'name': 'C++', 'bytes': '606713'}, {'name': 'CSS', 'bytes': '794'}, {'name': 'Emacs Lisp', 'bytes': '99891'}, {'name': 'Java', 'bytes': '120676'}, {'name': 'Lua', 'bytes': '80051'}, {'name': 'M4', 'bytes': '56951'}, {'name': 'Makefile', 'bytes': '205226'}, {'name': 'Objective-C', 'bytes': '15373'}, {'name': 'Python', 'bytes': '581371'}, {'name': 'Ruby', 'bytes': '3461'}, {'name': 'Shell', 'bytes': '36809'}, {'name': 'Yacc', 'bytes': '3034'}]} |
var React = require("react");
var Home = React.createClass({
render: function() {
return (
<h2 className="text-center">
Search by Github User Name
</h2>
)
}
});
module.exports = Home; | {'content_hash': '456ed467925f29daa8e1d0596cff94bc', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 33, 'avg_line_length': 16.153846153846153, 'alnum_prop': 0.5952380952380952, 'repo_name': 'ganeswararaosundarapu/GithubNoteTaker', 'id': 'c6d291b49a0b0992feb780e1957f0ccee5702458', 'size': '210', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/components/home.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '1680'}, {'name': 'JavaScript', 'bytes': '1009775'}]} |
/*
* 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 com.beans;
import com.util.LawyerOfficeUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import org.primefaces.event.TabChangeEvent;
import procuradoria.crud.ProcuradoriaMethods;
import procuradoria.map.Uzatasign;
import procuradoria.map.Uzatcaso;
import procuradoria.map.Uzatmateri;
/**
*
* @author Ivan
*/
@ManagedBean
@ViewScoped
public class AdminCasosBean {
/**
* Creates a new instance of AdminCasosBean
*/
private String patterFindCaso;
private String valueFindCaso;
private String valueFindCaso2;
private String valueFindCaso3;
private String valueFindCaso4;
private List<Uzatasign> casosAsigandos;
private ArrayList<SelectItem> ItemsMaterias;
private BigDecimal idMateria;
public AdminCasosBean() {
HttpServletRequest origRequest
= (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
String urlRequest = origRequest.getRequestURI().toString();
urlRequest = urlRequest.replace("/LawyerOfficeApp/faces/views/", "");
if (!urlRequest.equals("ver_caso_abo.xhtml")) {
this.init();
} else {
this.casosAsigandos = null;
this.ItemsMaterias = new ArrayList<SelectItem>();
this.loadlistMaterias();
}
}
private void init() {
this.casosAsigandos = new ArrayList<Uzatasign>();
this.loadCasosAsignados();
}
public void loadCasosAsignados() {
this.casosAsigandos = ProcuradoriaMethods.FindCasosAdminLazy(this.getUserIdAttribute(), BigDecimal.ONE, BigDecimal.ONE);
}
public void loadlistMaterias() {
ArrayList<Uzatmateri> selectItemsMat = ProcuradoriaMethods.ListMaterias();
this.getItemsMaterias().clear();
SelectItem si;
for (int i = 0; i < selectItemsMat.size(); i++) {
si = new SelectItem(selectItemsMat.get(i).getUzatmateriaId(), selectItemsMat.get(i).getUzatmateriaDescripcion());
this.getItemsMaterias().add(si);
}
this.getItemsMaterias().remove(0);
}
private String getUserAttribute() {
String UserAttribute = "";
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
if (session == null) {
} else {
Object IdBanner = session.getAttribute("uzatfuncionarioId");
UserAttribute = IdBanner.toString();
}
return UserAttribute;
}
private BigDecimal getUserIdAttribute() {
String UserAttribute = "";
BigDecimal id = new BigDecimal(BigInteger.ZERO);
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
if (session == null) {
} else {
Object IdBanner = session.getAttribute("uzatfuncionarioId");
UserAttribute = IdBanner.toString();
id = new BigDecimal(UserAttribute);
}
return id;
}
public void openfase(ActionEvent event, BigDecimal uzatcasoId) {
RequestContext context = RequestContext.getCurrentInstance();
String ruta = LawyerOfficeUtil.getURL_Login() + "views/fases_caso.xhtml";
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().
put("uzatcasoId", uzatcasoId);
context.addCallbackParam("loggedIn", true);
context.addCallbackParam("ruta", ruta);
}
public void openfaseOnlySee(ActionEvent event, BigDecimal uzatcasoId) {
RequestContext context = RequestContext.getCurrentInstance();
String ruta = LawyerOfficeUtil.getURL_Login() + "views/ver_caso_busq.xhtml";
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().
put("uzatcasoId", uzatcasoId);
context.addCallbackParam("loggedIn", true);
context.addCallbackParam("ruta", ruta);
}
public Boolean StateFlagOnOff(BigDecimal flag) {
Boolean State = false;
if (flag.equals(new BigDecimal(1))) {
State = true;
}
return State;
}
public void buscarCasoByNumCausa(ActionEvent actionEvent) {
if (valueFindCaso.equals("")) {
this.loadCasosAsignados();
} else {
this.casosAsigandos = ProcuradoriaMethods.FindCasosAdminLazyByNumCausa(this.getUserIdAttribute(), BigDecimal.ONE, BigDecimal.ONE, valueFindCaso);
if (this.casosAsigandos == null) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "No se encuentran casos relacionados con dicho número de causa.");
}
}
}
public void buscarCasoByNumCausaGeneral(ActionEvent actionEvent) {
if (this.valueFindCaso.equals("")) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "Ingrese el número de causa a ser buscado.");
this.casosAsigandos = null;
} else {
this.casosAsigandos = ProcuradoriaMethods.FindCasosAdminLazyByNumCausaGen(BigDecimal.ONE, valueFindCaso);
if (this.casosAsigandos.size() == 0) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "No se encuentran casos relacionados con dicho número de causa.");
}
}
}
public void buscarCasoByNumCausaMateria(ActionEvent actionEvent) {
if (this.valueFindCaso2.equals("")) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "Ingrese el número de causa a ser buscado.");
this.casosAsigandos = null;
} else {
if (!this.getIdMateria().equals(new BigDecimal(BigInteger.ZERO))) {
this.casosAsigandos = ProcuradoriaMethods.FindCasosAdminLazyByNumCausaMateria(BigDecimal.ONE, this.valueFindCaso2,this.idMateria);
if (this.casosAsigandos.size() == 0) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "No se encuentran casos relacionados con dicho número de causa y materia.");
}
} else {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "Seleccione la materia.");
}
}
}
public void buscarCasoByVinculacion(ActionEvent actionEvent) {
if (this.getValueFindCaso3().equals("")) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "Ingrese la cédula del abogado.");
this.casosAsigandos = null;
} else {
if (!this.valueFindCaso4.equals("")) {
this.casosAsigandos = ProcuradoriaMethods.FindCasosAdminLazyByVinculacion(this.valueFindCaso3,this.valueFindCaso4);
if (this.casosAsigandos.size() == 0) {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "No se encuentran casos relacionados con dicho número de causa y cédula.");
}
} else {
generateMessage(FacesMessage.SEVERITY_INFO, "Error", "Ingrese el número de causa a ser buscado.");
}
}
}
public void onTabChange(TabChangeEvent event) {
this.patterFindCaso = "";
this.valueFindCaso = "";
this.valueFindCaso2 = "";
this.setIdMateria(new BigDecimal(BigInteger.ZERO));
}
public void generateMessage(FacesMessage.Severity Tipo, String Header, String Mensaje) {
FacesMessage message = new FacesMessage(Tipo, Header, Mensaje);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public List<Uzatasign> getCasosAsigandos() {
return casosAsigandos;
}
public void setCasosAsigandos(List<Uzatasign> casosAsigandos) {
this.casosAsigandos = casosAsigandos;
}
public String getPatterFindCaso() {
return patterFindCaso;
}
public void setPatterFindCaso(String patterFindCaso) {
this.patterFindCaso = patterFindCaso;
}
public String getValueFindCaso() {
return valueFindCaso;
}
public void setValueFindCaso(String valueFindCaso) {
this.valueFindCaso = valueFindCaso;
}
public ArrayList<SelectItem> getItemsMaterias() {
return ItemsMaterias;
}
public void setItemsMaterias(ArrayList<SelectItem> ItemsMaterias) {
this.ItemsMaterias = ItemsMaterias;
}
public BigDecimal getIdMateria() {
return idMateria;
}
public void setIdMateria(BigDecimal idMateria) {
this.idMateria = idMateria;
}
public String getValueFindCaso2() {
return valueFindCaso2;
}
public void setValueFindCaso2(String valueFindCaso2) {
this.valueFindCaso2 = valueFindCaso2;
}
public String getValueFindCaso3() {
return valueFindCaso3;
}
public void setValueFindCaso3(String valueFindCaso3) {
this.valueFindCaso3 = valueFindCaso3;
}
public String getValueFindCaso4() {
return valueFindCaso4;
}
public void setValueFindCaso4(String valueFindCaso4) {
this.valueFindCaso4 = valueFindCaso4;
}
}
| {'content_hash': '7ea5fe4d9010756c2a1e01f9d21ea6c6', 'timestamp': '', 'source': 'github', 'line_count': 272, 'max_line_length': 157, 'avg_line_length': 36.786764705882355, 'alnum_prop': 0.6468119128522887, 'repo_name': 'LawyerOffice/LawyerOfficeApp', 'id': 'bca1e350737fb63cc6479d217ee66fc6474ed35f', 'size': '10015', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/java/com/beans/AdminCasosBean.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '7012'}, {'name': 'HTML', 'bytes': '193351'}, {'name': 'Java', 'bytes': '155275'}, {'name': 'JavaScript', 'bytes': '294'}]} |
<?xml version="1.0"?>
<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd" version="2.0">
<portlet>
<portlet-name>contactportlet</portlet-name>
<display-name>ContactPortlet</display-name>
<portlet-class>com.mpwc.contact.ContactPortlet</portlet-class>
<init-param>
<name>view-template</name>
<value>/jsp/view.jsp</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>view</portlet-mode>
</supports>
<supported-locale>es_ES</supported-locale>
<supported-locale>ca_ES</supported-locale>
<resource-bundle>
content.Language-ext
</resource-bundle>
<portlet-info>
<title>ContactPortlet</title>
<short-title>ContactPortlet</short-title>
<keywords></keywords>
</portlet-info>
<security-role-ref>
<role-name>administrator</role-name>
</security-role-ref>
<security-role-ref>
<role-name>guest</role-name>
</security-role-ref>
<security-role-ref>
<role-name>power-user</role-name>
</security-role-ref>
<security-role-ref>
<role-name>user</role-name>
</security-role-ref>
</portlet>
</portlet-app> | {'content_hash': '555882b4ff1e9c33fa2c433917b2ff7e', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 275, 'avg_line_length': 32.73170731707317, 'alnum_prop': 0.7041728763040238, 'repo_name': 'rsicart/mpwc-contact', 'id': '5a4486924afb7b62e3a2372a84bff0fa696fef2e', 'size': '1342', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docroot/WEB-INF/portlet.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '15939'}, {'name': 'JavaScript', 'bytes': '0'}]} |
namespace llvm {
class StringRef;
/// This class provides a symbol table of name/type pairs with operations to
/// support constructing, searching and iterating over the symbol table. The
/// class derives from AbstractTypeUser so that the contents of the symbol
/// table can be updated when abstract types become concrete.
class TypeSymbolTable : public AbstractTypeUser {
/// @name Types
/// @{
public:
/// @brief A mapping of names to types.
typedef std::map<const std::string, const Type*> TypeMap;
/// @brief An iterator over the TypeMap.
typedef TypeMap::iterator iterator;
/// @brief A const_iterator over the TypeMap.
typedef TypeMap::const_iterator const_iterator;
/// @}
/// @name Constructors
/// @{
public:
TypeSymbolTable():LastUnique(0) {}
~TypeSymbolTable();
/// @}
/// @name Accessors
/// @{
public:
/// Generates a unique name for a type based on the \p BaseName by
/// incrementing an integer and appending it to the name, if necessary
/// @returns the unique name
/// @brief Get a unique name for a type
std::string getUniqueName(StringRef BaseName) const;
/// This method finds the type with the given \p name in the type map
/// and returns it.
/// @returns null if the name is not found, otherwise the Type
/// associated with the \p name.
/// @brief Lookup a type by name.
Type *lookup(StringRef name) const;
/// Lookup the type associated with name.
/// @returns end() if the name is not found, or an iterator at the entry for
/// Type.
iterator find(StringRef Name) {
return tmap.find(Name);
}
/// Lookup the type associated with name.
/// @returns end() if the name is not found, or an iterator at the entry for
/// Type.
const_iterator find(StringRef Name) const {
return tmap.find(Name);
}
/// @returns true iff the symbol table is empty.
/// @brief Determine if the symbol table is empty
inline bool empty() const { return tmap.empty(); }
/// @returns the size of the symbol table
/// @brief The number of name/type pairs is returned.
inline unsigned size() const { return unsigned(tmap.size()); }
/// This function can be used from the debugger to display the
/// content of the symbol table while debugging.
/// @brief Print out symbol table on stderr
void dump() const;
/// @}
/// @name Iteration
/// @{
public:
/// Get an iterator to the start of the symbol table
inline iterator begin() { return tmap.begin(); }
/// @brief Get a const_iterator to the start of the symbol table
inline const_iterator begin() const { return tmap.begin(); }
/// Get an iterator to the end of the symbol table.
inline iterator end() { return tmap.end(); }
/// Get a const_iterator to the end of the symbol table.
inline const_iterator end() const { return tmap.end(); }
/// @}
/// @name Mutators
/// @{
public:
/// Inserts a type into the symbol table with the specified name. There can be
/// a many-to-one mapping between names and types. This method allows a type
/// with an existing entry in the symbol table to get a new name.
/// @brief Insert a type under a new name.
void insert(StringRef Name, const Type *Typ);
/// Remove a type at the specified position in the symbol table.
/// @returns the removed Type.
/// @returns the Type that was erased from the symbol table.
Type* remove(iterator TI);
/// @}
/// @name AbstractTypeUser Methods
/// @{
private:
/// This function is called when one of the types in the type plane
/// is refined.
virtual void refineAbstractType(const DerivedType *OldTy, const Type *NewTy);
/// This function markes a type as being concrete (defined).
virtual void typeBecameConcrete(const DerivedType *AbsTy);
/// @}
/// @name Internal Data
/// @{
private:
TypeMap tmap; ///< This is the mapping of names to types.
mutable uint32_t LastUnique; ///< Counter for tracking unique names
/// @}
};
} // End llvm namespace
#endif
| {'content_hash': '2dd27fee38fc4b882b70e71e45005cf4', 'timestamp': '', 'source': 'github', 'line_count': 133, 'max_line_length': 80, 'avg_line_length': 29.60902255639098, 'alnum_prop': 0.6866429659725749, 'repo_name': 'wrmsr/lljvm', 'id': '26b1dbf2df41298d785c86414bb958ad345e4890', 'size': '4566', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'thirdparty/llvm/include/llvm/TypeSymbolTable.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '4870'}, {'name': 'C++', 'bytes': '91265'}, {'name': 'Java', 'bytes': '149125'}, {'name': 'Lua', 'bytes': '177'}, {'name': 'Makefile', 'bytes': '21245'}, {'name': 'Python', 'bytes': '8641'}, {'name': 'Shell', 'bytes': '218'}]} |
import { Component } from '@angular/core';
import { NavParams, IONIC_DIRECTIVES, ModalController } from 'ionic-angular';
import { SmsService } from './sms.service';
import { AnalyticsService } from '../../../services/analytics/analytics.service';
import { TitleSeparationComponent } from '../../../components/title-separation/title-separation';
import { ProductCore } from '../product';
import { categoryEnum } from '../../../config/constants';
import { ToastService } from '../../../services/toast/toast.service';
@Component({
templateUrl: 'build/pages/products/sms/sms.html',
directives: [IONIC_DIRECTIVES, TitleSeparationComponent],
providers: [SmsService],
})
export class SmsPage extends ProductCore {
sms: any;
error: boolean = false;
loading: boolean = true;
category = categoryEnum.SMS;
constructor(
private smsService: SmsService,
public navParams: NavParams,
modalCtrl: ModalController,
public analytics: AnalyticsService,
public toast: ToastService
) {
super(modalCtrl, navParams);
this.analytics.trackView('product:sms');
this.subscription = this.smsService.getAll(this.serviceName)
.finally(() => this.loading = false)
.subscribe(
(sms) => this.sms = sms,
(err) => {
this.error = true;
this.toast.error(`Une erreur est survenue lors du chargement : ${JSON.parse(err._body).message}`).present();
}
);
}
}
| {'content_hash': '3256e09fde7a839d1da64e6f786b631d', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 118, 'avg_line_length': 34.97560975609756, 'alnum_prop': 0.6757322175732218, 'repo_name': 'antleblanc/my-infra', 'id': '769135268159e3469b987aad44722c5062dc2234', 'size': '1434', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/pages/products/sms/sms.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '22132'}, {'name': 'HTML', 'bytes': '120893'}, {'name': 'JavaScript', 'bytes': '7436'}, {'name': 'TypeScript', 'bytes': '180541'}]} |
package previous_priorities
import (
"bytes"
"errors"
"fmt"
"net"
"net/mail"
"net/url"
"regexp"
"sort"
"strings"
"time"
"unicode/utf8"
"google.golang.org/protobuf/types/known/anypb"
)
// ensure the imports are used
var (
_ = bytes.MinRead
_ = errors.New("")
_ = fmt.Print
_ = utf8.UTFMax
_ = (*regexp.Regexp)(nil)
_ = (*strings.Reader)(nil)
_ = net.IPv4len
_ = time.Duration(0)
_ = (*url.URL)(nil)
_ = (*mail.Address)(nil)
_ = anypb.Any{}
_ = sort.Sort
)
// Validate checks the field values on PreviousPrioritiesConfig with the rules
// defined in the proto definition for this message. If any rules are
// violated, the first error encountered is returned, or nil if there are no violations.
func (m *PreviousPrioritiesConfig) Validate() error {
return m.validate(false)
}
// ValidateAll checks the field values on PreviousPrioritiesConfig with the
// rules defined in the proto definition for this message. If any rules are
// violated, the result is a list of violation errors wrapped in
// PreviousPrioritiesConfigMultiError, or nil if none found.
func (m *PreviousPrioritiesConfig) ValidateAll() error {
return m.validate(true)
}
func (m *PreviousPrioritiesConfig) validate(all bool) error {
if m == nil {
return nil
}
var errors []error
if m.GetUpdateFrequency() <= 0 {
err := PreviousPrioritiesConfigValidationError{
field: "UpdateFrequency",
reason: "value must be greater than 0",
}
if !all {
return err
}
errors = append(errors, err)
}
if len(errors) > 0 {
return PreviousPrioritiesConfigMultiError(errors)
}
return nil
}
// PreviousPrioritiesConfigMultiError is an error wrapping multiple validation
// errors returned by PreviousPrioritiesConfig.ValidateAll() if the designated
// constraints aren't met.
type PreviousPrioritiesConfigMultiError []error
// Error returns a concatenation of all the error messages it wraps.
func (m PreviousPrioritiesConfigMultiError) Error() string {
var msgs []string
for _, err := range m {
msgs = append(msgs, err.Error())
}
return strings.Join(msgs, "; ")
}
// AllErrors returns a list of validation violation errors.
func (m PreviousPrioritiesConfigMultiError) AllErrors() []error { return m }
// PreviousPrioritiesConfigValidationError is the validation error returned by
// PreviousPrioritiesConfig.Validate if the designated constraints aren't met.
type PreviousPrioritiesConfigValidationError struct {
field string
reason string
cause error
key bool
}
// Field function returns field value.
func (e PreviousPrioritiesConfigValidationError) Field() string { return e.field }
// Reason function returns reason value.
func (e PreviousPrioritiesConfigValidationError) Reason() string { return e.reason }
// Cause function returns cause value.
func (e PreviousPrioritiesConfigValidationError) Cause() error { return e.cause }
// Key function returns key value.
func (e PreviousPrioritiesConfigValidationError) Key() bool { return e.key }
// ErrorName returns error name.
func (e PreviousPrioritiesConfigValidationError) ErrorName() string {
return "PreviousPrioritiesConfigValidationError"
}
// Error satisfies the builtin error interface
func (e PreviousPrioritiesConfigValidationError) Error() string {
cause := ""
if e.cause != nil {
cause = fmt.Sprintf(" | caused by: %v", e.cause)
}
key := ""
if e.key {
key = "key for "
}
return fmt.Sprintf(
"invalid %sPreviousPrioritiesConfig.%s: %s%s",
key,
e.field,
e.reason,
cause)
}
var _ error = PreviousPrioritiesConfigValidationError{}
var _ interface {
Field() string
Reason() string
Key() bool
Cause() error
ErrorName() string
} = PreviousPrioritiesConfigValidationError{}
| {'content_hash': 'd2987641df312b4dadfa4db6f17b3b6f', 'timestamp': '', 'source': 'github', 'line_count': 146, 'max_line_length': 88, 'avg_line_length': 25.30821917808219, 'alnum_prop': 0.7342354533152909, 'repo_name': 'envoyproxy/go-control-plane', 'id': 'f360c64f33e05e97ae95724c2df81da43de23117', 'size': '3834', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'envoy/config/retry/previous_priorities/previous_priorities_config.pb.validate.go', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '196712'}, {'name': 'Makefile', 'bytes': '2864'}, {'name': 'Shell', 'bytes': '7333'}, {'name': 'Starlark', 'bytes': '128'}]} |
import datetime
from time import strftime, gmtime
import sys
import os
import pickle
from bs4 import BeautifulSoup
import requests
from argparse import ArgumentParser
from getpass import getpass
import json
class BigFixArgParser(ArgumentParser):
name = "Usage: detect-new-components.py [options]"
base_usage = """Options:
-h, --help Print this help message and exit
-s, --server SERVER[:PORT] REST API server and port
-u, --user REST API user
-p, --password REST API password
-k, --insecure Don't verify the HTTPS Connection to the server
Optional arguments:
-c, --cacheFile cacheFile
Name a file to cache components that are detected already
(default: priorComponents.dict)
-o, --outputProperties "id" "operting system" ...
properties of new [bes computer] to output
(default: "agent version" "name" "ip address")
-i, --identifyProperties "cpu" "id" "operating system" ...
properties of [bes computer] whose change indicate a new component
(default: "cpu" "id" "operating system")
-m, --misc_relevance "relevance statement"
Bool relevance expression to filter which new components to output
(default: "true")
(example: "operating system of it contains Win")
"""
def __init__(self):
description = "Detects new components that has joined the environment since last run"
super(BigFixArgParser, self).__init__(add_help=False,
usage=self.base_usage, description=description)
self.add_argument('-u', '--user', required=True)
self.add_argument('-p', '--password', required=False)
self.add_argument('-s', '--server', required=True)
self.add_argument('-k', '--insecure', action='store_true')
#optional arguments:
self.add_argument('-c', '--cacheFile', required=False, nargs='?',
default="priorComponents.dict", const="priorComponents.dict")
self.add_argument('-o', '--outputProperties', required=False, nargs='*',
default=["agent version","name","ip address"])
self.add_argument('-i', '--identifyProperties', required=False, nargs='*',
default=["cpu", "id", "operating system"])
self.add_argument('-m', '--misc_relevance', required=False, nargs='?',
default="true", const="true")
self.tool_usage = None
self.password = None
def parse_args(self):
combined_usage = self.base_usage
if self.tool_usage is not None:
combined_usage += "\n" + self.tool_usage
self.usage = "{0}\n\n{1}\n\n{2}".format(self.name,
self.description, combined_usage)
if '-h' in sys.argv or '--help' in sys.argv:
print(self.usage)
sys.exit()
args = super(BigFixArgParser, self).parse_args()
if not args.password:
prompt = "Enter password for user '{0}': ".format(args.user)
args.password = getpass(prompt)
if ':' not in args.server:
args.server = args.server + ':52311'
return args
def checkNotInCache(identifiersList):
identifier = "".join(identifiersList)
if identifier in db['seenComputers']:
return False
else:
db['seenComputers'].add(identifier)
return True
defaultDB = {
"updateDate":strftime("%d %b %Y %H:%M:%S GMT", gmtime(0)),
"seenComputers":set()
}
db = defaultDB
def main():
global db
""" Parse the args """
args = BigFixArgParser().parse_args()
""" Database Setup """
if (os.access(args.cacheFile, os.F_OK) \
and not os.access(args.cacheFile, os.R_OK | os.W_OK)):
#Cache exists, but RW is forbidden
print "Error: Access to cache file", args.cacheFile, "blocked. Exiting"
sys.exit(1);
elif os.access(args.cacheFile, os.F_OK):
#Cache exists and is readable.
try:
db = pickle.load(open(args.cacheFile, 'r+'))
except Exception:
print "Error: Cache format corrupted. Exiting"
sys.exit(1);
else:
#cache does not exist.
db = defaultDB;
""" Construct a query string """
#along the lines of:
#'(id of it, name of it, [property] of it...)
# of (bes computers whose (evaluating relevance) )'
requestProperties = args.outputProperties + args.identifyProperties
out = [prop + " of it" for prop in requestProperties]
outStr = "("+ ", ".join(out) + ")" #--> "(id of it, name of it)"
q = outStr \
+' of (bes computers whose (last report time of it > "'
+db['updateDate']+'" as time and '+args.misc_relevance+') )'
""" Query the Server """
res = requests.get(
url ="https://"+args.server+"/api/query/?relevance="+q,
auth =(args.user, args.password),
verify=not args.insecure)
db['updateDate'] = strftime("%d %b %Y %H:%M:%S GMT", gmtime())
#update the last checked date.
""" Analyze Response """
soup = BeautifulSoup(res.text)
n_out = len(args.outputProperties)
for resultTuple in soup.findAll('tuple'):
result = [x.string for x in resultTuple.findAll('answer')]
""" Foreach machine: Filter with Cache """
if checkNotInCache(result[n_out:]):
print "\t".join(result[:n_out])
""" Dump Cache back to disk """
pickle.dump(db, open(args.cacheFile, 'w+'), protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
main() | {'content_hash': '059f2c94783d461f8052a4f319300621', 'timestamp': '', 'source': 'github', 'line_count': 161, 'max_line_length': 89, 'avg_line_length': 32.714285714285715, 'alnum_prop': 0.6322384659198785, 'repo_name': 'bigfix/tools', 'id': 'f02c73294349a923b26b43f36f71c574f6701a54', 'size': '5267', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'detect-new-components/detect-new-components.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '57542'}]} |
import {
moduleFor,
test
} from 'ember-qunit';
moduleFor('view:quiz/q1-4', 'QuizQ14View');
// Replace this with your real tests.
test('it exists', function() {
var view = this.subject();
ok(view);
});
| {'content_hash': '23d84c11de6ba7e886e424f565b5f805', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 43, 'avg_line_length': 17.583333333333332, 'alnum_prop': 0.6445497630331753, 'repo_name': 'codepreneur/decisions', 'id': 'dd5a9951ab6ab1c7111b0c77852966cf9562b78c', 'size': '211', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'client/tests/unit/views/quiz/q1-4-test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AppleScript', 'bytes': '1208'}, {'name': 'C', 'bytes': '4468'}, {'name': 'C#', 'bytes': '152875'}, {'name': 'C++', 'bytes': '58325'}, {'name': 'CSS', 'bytes': '106990'}, {'name': 'Java', 'bytes': '1219009'}, {'name': 'JavaScript', 'bytes': '1291380'}, {'name': 'Objective-C', 'bytes': '756702'}, {'name': 'PHP', 'bytes': '4421'}, {'name': 'Pascal', 'bytes': '1164'}, {'name': 'Puppet', 'bytes': '35424'}, {'name': 'Ruby', 'bytes': '218073'}, {'name': 'Shell', 'bytes': '40833'}]} |
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/notifier.h>
#include <linux/of.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/reboot.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <linux/watchdog.h>
#define WDOG_CONTROL_REG_OFFSET 0x00
#define WDOG_CONTROL_REG_WDT_EN_MASK 0x01
#define WDOG_TIMEOUT_RANGE_REG_OFFSET 0x04
#define WDOG_TIMEOUT_RANGE_TOPINIT_SHIFT 4
#define WDOG_CURRENT_COUNT_REG_OFFSET 0x08
#define WDOG_COUNTER_RESTART_REG_OFFSET 0x0c
#define WDOG_COUNTER_RESTART_KICK_VALUE 0x76
/* The maximum TOP (timeout period) value that can be set in the watchdog. */
#define DW_WDT_MAX_TOP 15
#define DW_WDT_DEFAULT_SECONDS 30
static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
"(default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
#define WDT_TIMEOUT (HZ / 2)
static struct {
void __iomem *regs;
struct clk *clk;
unsigned long in_use;
unsigned long next_heartbeat;
struct timer_list timer;
int expect_close;
struct notifier_block restart_handler;
} dw_wdt;
static inline int dw_wdt_is_enabled(void)
{
return readl(dw_wdt.regs + WDOG_CONTROL_REG_OFFSET) &
WDOG_CONTROL_REG_WDT_EN_MASK;
}
static inline int dw_wdt_top_in_seconds(unsigned top)
{
/*
* There are 16 possible timeout values in 0..15 where the number of
* cycles is 2 ^ (16 + i) and the watchdog counts down.
*/
return (1U << (16 + top)) / clk_get_rate(dw_wdt.clk);
}
static int dw_wdt_get_top(void)
{
int top = readl(dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET) & 0xF;
return dw_wdt_top_in_seconds(top);
}
static inline void dw_wdt_set_next_heartbeat(void)
{
dw_wdt.next_heartbeat = jiffies + dw_wdt_get_top() * HZ;
}
static void dw_wdt_keepalive(void)
{
writel(WDOG_COUNTER_RESTART_KICK_VALUE, dw_wdt.regs +
WDOG_COUNTER_RESTART_REG_OFFSET);
}
static int dw_wdt_set_top(unsigned top_s)
{
int i, top_val = DW_WDT_MAX_TOP;
/*
* Iterate over the timeout values until we find the closest match. We
* always look for >=.
*/
for (i = 0; i <= DW_WDT_MAX_TOP; ++i)
if (dw_wdt_top_in_seconds(i) >= top_s) {
top_val = i;
break;
}
/*
* Set the new value in the watchdog. Some versions of dw_wdt
* have have TOPINIT in the TIMEOUT_RANGE register (as per
* CP_WDT_DUAL_TOP in WDT_COMP_PARAMS_1). On those we
* effectively get a pat of the watchdog right here.
*/
writel(top_val | top_val << WDOG_TIMEOUT_RANGE_TOPINIT_SHIFT,
dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET);
/*
* Add an explicit pat to handle versions of the watchdog that
* don't have TOPINIT. This won't hurt on versions that have
* it.
*/
dw_wdt_keepalive();
dw_wdt_set_next_heartbeat();
return dw_wdt_top_in_seconds(top_val);
}
static int dw_wdt_restart_handle(struct notifier_block *this,
unsigned long mode, void *cmd)
{
u32 val;
writel(0, dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET);
val = readl(dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);
if (val & WDOG_CONTROL_REG_WDT_EN_MASK)
writel(WDOG_COUNTER_RESTART_KICK_VALUE, dw_wdt.regs +
WDOG_COUNTER_RESTART_REG_OFFSET);
else
writel(WDOG_CONTROL_REG_WDT_EN_MASK,
dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);
/* wait for reset to assert... */
mdelay(500);
return NOTIFY_DONE;
}
static void dw_wdt_ping(unsigned long data)
{
if (time_before(jiffies, dw_wdt.next_heartbeat) ||
(!nowayout && !dw_wdt.in_use)) {
dw_wdt_keepalive();
mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);
} else
pr_crit("keepalive missed, machine will reset\n");
}
static int dw_wdt_open(struct inode *inode, struct file *filp)
{
if (test_and_set_bit(0, &dw_wdt.in_use))
return -EBUSY;
/* Make sure we don't get unloaded. */
__module_get(THIS_MODULE);
if (!dw_wdt_is_enabled()) {
/*
* The watchdog is not currently enabled. Set the timeout to
* something reasonable and then start it.
*/
dw_wdt_set_top(DW_WDT_DEFAULT_SECONDS);
writel(WDOG_CONTROL_REG_WDT_EN_MASK,
dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);
}
dw_wdt_set_next_heartbeat();
return nonseekable_open(inode, filp);
}
static ssize_t dw_wdt_write(struct file *filp, const char __user *buf,
size_t len, loff_t *offset)
{
if (!len)
return 0;
if (!nowayout) {
size_t i;
dw_wdt.expect_close = 0;
for (i = 0; i < len; ++i) {
char c;
if (get_user(c, buf + i))
return -EFAULT;
if (c == 'V') {
dw_wdt.expect_close = 1;
break;
}
}
}
dw_wdt_set_next_heartbeat();
dw_wdt_keepalive();
mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);
return len;
}
static u32 dw_wdt_time_left(void)
{
return readl(dw_wdt.regs + WDOG_CURRENT_COUNT_REG_OFFSET) /
clk_get_rate(dw_wdt.clk);
}
static const struct watchdog_info dw_wdt_ident = {
.options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT |
WDIOF_MAGICCLOSE,
.identity = "Synopsys DesignWare Watchdog",
};
static long dw_wdt_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
unsigned long val;
int timeout;
switch (cmd) {
case WDIOC_GETSUPPORT:
return copy_to_user((void __user *)arg, &dw_wdt_ident,
sizeof(dw_wdt_ident)) ? -EFAULT : 0;
case WDIOC_GETSTATUS:
case WDIOC_GETBOOTSTATUS:
return put_user(0, (int __user *)arg);
case WDIOC_KEEPALIVE:
dw_wdt_set_next_heartbeat();
return 0;
case WDIOC_SETTIMEOUT:
if (get_user(val, (int __user *)arg))
return -EFAULT;
timeout = dw_wdt_set_top(val);
return put_user(timeout , (int __user *)arg);
case WDIOC_GETTIMEOUT:
return put_user(dw_wdt_get_top(), (int __user *)arg);
case WDIOC_GETTIMELEFT:
/* Get the time left until expiry. */
if (get_user(val, (int __user *)arg))
return -EFAULT;
return put_user(dw_wdt_time_left(), (int __user *)arg);
default:
return -ENOTTY;
}
}
static int dw_wdt_release(struct inode *inode, struct file *filp)
{
clear_bit(0, &dw_wdt.in_use);
if (!dw_wdt.expect_close) {
del_timer(&dw_wdt.timer);
if (!nowayout)
pr_crit("unexpected close, system will reboot soon\n");
else
pr_crit("watchdog cannot be disabled, system will reboot soon\n");
}
dw_wdt.expect_close = 0;
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int dw_wdt_suspend(struct device *dev)
{
clk_disable_unprepare(dw_wdt.clk);
return 0;
}
static int dw_wdt_resume(struct device *dev)
{
int err = clk_prepare_enable(dw_wdt.clk);
if (err)
return err;
dw_wdt_keepalive();
return 0;
}
#endif /* CONFIG_PM_SLEEP */
static SIMPLE_DEV_PM_OPS(dw_wdt_pm_ops, dw_wdt_suspend, dw_wdt_resume);
static const struct file_operations wdt_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.open = dw_wdt_open,
.write = dw_wdt_write,
.unlocked_ioctl = dw_wdt_ioctl,
.release = dw_wdt_release
};
static struct miscdevice dw_wdt_miscdev = {
.fops = &wdt_fops,
.name = "watchdog",
.minor = WATCHDOG_MINOR,
};
static int dw_wdt_drv_probe(struct platform_device *pdev)
{
int ret;
struct resource *mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
dw_wdt.regs = devm_ioremap_resource(&pdev->dev, mem);
if (IS_ERR(dw_wdt.regs))
return PTR_ERR(dw_wdt.regs);
dw_wdt.clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(dw_wdt.clk))
return PTR_ERR(dw_wdt.clk);
ret = clk_prepare_enable(dw_wdt.clk);
if (ret)
return ret;
ret = misc_register(&dw_wdt_miscdev);
if (ret)
goto out_disable_clk;
dw_wdt.restart_handler.notifier_call = dw_wdt_restart_handle;
dw_wdt.restart_handler.priority = 128;
ret = register_restart_handler(&dw_wdt.restart_handler);
if (ret)
pr_warn("cannot register restart handler\n");
dw_wdt_set_next_heartbeat();
setup_timer(&dw_wdt.timer, dw_wdt_ping, 0);
mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);
return 0;
out_disable_clk:
clk_disable_unprepare(dw_wdt.clk);
return ret;
}
static int dw_wdt_drv_remove(struct platform_device *pdev)
{
unregister_restart_handler(&dw_wdt.restart_handler);
misc_deregister(&dw_wdt_miscdev);
clk_disable_unprepare(dw_wdt.clk);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id dw_wdt_of_match[] = {
{ .compatible = "snps,dw-wdt", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, dw_wdt_of_match);
#endif
static struct platform_driver dw_wdt_driver = {
.probe = dw_wdt_drv_probe,
.remove = dw_wdt_drv_remove,
.driver = {
.name = "dw_wdt",
.of_match_table = of_match_ptr(dw_wdt_of_match),
.pm = &dw_wdt_pm_ops,
},
};
module_platform_driver(dw_wdt_driver);
MODULE_AUTHOR("Jamie Iles");
MODULE_DESCRIPTION("Synopsys DesignWare Watchdog Driver");
MODULE_LICENSE("GPL");
| {'content_hash': '454a54e96bce66d2182e90a6b556a171', 'timestamp': '', 'source': 'github', 'line_count': 385, 'max_line_length': 80, 'avg_line_length': 23.036363636363635, 'alnum_prop': 0.6759499379862443, 'repo_name': 'mikedlowis-prototypes/albase', 'id': '8fefa4ad46d4d0a5fa928bf3c5694388b473e91b', 'size': '9723', 'binary': False, 'copies': '45', 'ref': 'refs/heads/master', 'path': 'source/kernel/drivers/watchdog/dw_wdt.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '10263145'}, {'name': 'Awk', 'bytes': '55187'}, {'name': 'Batchfile', 'bytes': '31438'}, {'name': 'C', 'bytes': '551654518'}, {'name': 'C++', 'bytes': '11818066'}, {'name': 'CMake', 'bytes': '122998'}, {'name': 'Clojure', 'bytes': '945'}, {'name': 'DIGITAL Command Language', 'bytes': '232099'}, {'name': 'GDB', 'bytes': '18113'}, {'name': 'Gherkin', 'bytes': '5110'}, {'name': 'HTML', 'bytes': '18291'}, {'name': 'Lex', 'bytes': '58937'}, {'name': 'M4', 'bytes': '561745'}, {'name': 'Makefile', 'bytes': '7082768'}, {'name': 'Objective-C', 'bytes': '634652'}, {'name': 'POV-Ray SDL', 'bytes': '546'}, {'name': 'Perl', 'bytes': '1229221'}, {'name': 'Perl6', 'bytes': '11648'}, {'name': 'Python', 'bytes': '316536'}, {'name': 'Roff', 'bytes': '4201130'}, {'name': 'Shell', 'bytes': '2436879'}, {'name': 'SourcePawn', 'bytes': '2711'}, {'name': 'TeX', 'bytes': '182745'}, {'name': 'UnrealScript', 'bytes': '12824'}, {'name': 'Visual Basic', 'bytes': '11568'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '146537'}]} |
<!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_112) on Fri Jun 16 09:55:16 MST 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.infinispan.Dialect (Public javadocs 2017.6.1 API)</title>
<meta name="date" content="2017-06-16">
<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 Class org.wildfly.swarm.config.infinispan.Dialect (Public javadocs 2017.6.1 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/infinispan/class-use/Dialect.html" target="_top">Frames</a></li>
<li><a href="Dialect.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.infinispan.Dialect" class="title">Uses of Class<br>org.wildfly.swarm.config.infinispan.Dialect</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.infinispan">org.wildfly.swarm.config.infinispan</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.infinispan.cache_container">org.wildfly.swarm.config.infinispan.cache_container</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.infinispan">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> in <a href="../../../../../../org/wildfly/swarm/config/infinispan/package-summary.html">org.wildfly.swarm.config.infinispan</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/infinispan/package-summary.html">org.wildfly.swarm.config.infinispan</a> that return <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td>
<td class="colLast"><span class="typeNameLabel">Dialect.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html#valueOf-java.lang.String-">valueOf</a></span>(<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a>[]</code></td>
<td class="colLast"><span class="typeNameLabel">Dialect.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html#values--">values</a></span>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.wildfly.swarm.config.infinispan.cache_container">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> in <a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> that return <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td>
<td class="colLast"><span class="typeNameLabel">MixedJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/MixedJDBCStore.html#dialect--">dialect</a></span>()</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td>
<td class="colLast"><span class="typeNameLabel">BinaryJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html#dialect--">dialect</a></span>()</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></code></td>
<td class="colLast"><span class="typeNameLabel">StringJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html#dialect--">dialect</a></span>()</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/package-summary.html">org.wildfly.swarm.config.infinispan.cache_container</a> with parameters of type <a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/MixedJDBCStore.html" title="type parameter in MixedJDBCStore">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">MixedJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/MixedJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> value)</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html" title="type parameter in BinaryJDBCStore">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">BinaryJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/BinaryJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> value)</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html" title="type parameter in StringJDBCStore">T</a></code></td>
<td class="colLast"><span class="typeNameLabel">StringJDBCStore.</span><code><span class="memberNameLink"><a href="../../../../../../org/wildfly/swarm/config/infinispan/cache_container/StringJDBCStore.html#dialect-org.wildfly.swarm.config.infinispan.Dialect-">dialect</a></span>(<a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Dialect</a> value)</code>
<div class="block">The dialect of this datastore.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/wildfly/swarm/config/infinispan/Dialect.html" title="enum in org.wildfly.swarm.config.infinispan">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">WildFly Swarm API, 2017.6.1</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/wildfly/swarm/config/infinispan/class-use/Dialect.html" target="_top">Frames</a></li>
<li><a href="Dialect.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 © 2017 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {'content_hash': 'e517b1f00319fa341fc810577f7b0029', 'timestamp': '', 'source': 'github', 'line_count': 240, 'max_line_length': 438, 'avg_line_length': 56.4125, 'alnum_prop': 0.667479134352611, 'repo_name': 'wildfly-swarm/wildfly-swarm-javadocs', 'id': '94e5187e996484695f24fd9ad2b4a116bb27cc77', 'size': '13539', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': '2017.6.1/apidocs/org/wildfly/swarm/config/infinispan/class-use/Dialect.html', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
from datetime import datetime, timezone
from backend.web.context_processors import render_time_context_processor
def test_render_time_context_processor() -> None:
render_time_context = render_time_context_processor()
render_time = render_time_context["render_time"]
assert type(render_time) is datetime
assert render_time.tzinfo == timezone.utc # pyre-ignore[16]
| {'content_hash': '114799fd9cbf2921b29cb48949d88956', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 72, 'avg_line_length': 38.3, 'alnum_prop': 0.7545691906005222, 'repo_name': 'the-blue-alliance/the-blue-alliance', 'id': '467881a954d3b9c0c3f138d1fb1723d9e8e23f0e', 'size': '383', 'binary': False, 'copies': '1', 'ref': 'refs/heads/py3', 'path': 'src/backend/web/tests/context_processors_test.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '359032'}, {'name': 'Dockerfile', 'bytes': '2503'}, {'name': 'HTML', 'bytes': '5877313'}, {'name': 'JavaScript', 'bytes': '755910'}, {'name': 'Less', 'bytes': '244218'}, {'name': 'PHP', 'bytes': '10727'}, {'name': 'Pug', 'bytes': '1857'}, {'name': 'Python', 'bytes': '4321885'}, {'name': 'Ruby', 'bytes': '4677'}, {'name': 'Shell', 'bytes': '27698'}]} |
DsaTab
======
![DsaTab](Web/function.jpg)
An android app to handle your [DSA][2] Pen&Paper roleplaying characters.
DsaTab requires Android 4.1 and is compatible with the newest version of [Helden-Software][1] 5.5.2
Get the current version (only in german) from the [google play store][3], old release can be found in the [releases](https://github.com/gandulf/DsaTab/tree/master/Releases) folder:
[![Get it on Google Play](http://www.android.com/images/brand/get_it_on_play_logo_small.png)](http://play.google.com/store/apps/details?id=com.dsatab)
Screenshot showing the first character and talents tab, for more images goto the google play store:
![DsaTab Screenshot](Web/screen.png)
## How to use DsaTab
DsaTab builds upon the software [Helden-Software][1] and enables you to take your character with you on your android smartphone or tablet.
* Create your character using Helden-Software
* Export your hero as a xml file
* Start DsaTab on smartphone to see where the dsatab folder is created (settings).
* Copy the xml file to your smartphone/tablet into the SD-CARD/dsatab folder. You could also use dropbox or another synchonization tool to sync the files to your smartphone and change the path to the folder in the dsatab settings.
* Start DsaTab again and load your character.
* Don't forget to save the character to keep changes made in DsaTab for the next session.
## Development
This Project is developed using Android Studio. Gradle dependencies should take care of any used libraries.
## License
Copyright 2012 Gandulf Kohlweiss
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.
## Disclaimer
„DAS SCHWARZE AUGE, AVENTURIEN, DERE, MYRANOR, THARUN, UTHURIA und RIESLAND sind eingetragene Marken der
Significant Fantasy Medienrechte GbR. Ohne vorherige schriftliche Genehmigung der Ulisses Medien und Spiel
Distribution GmbH ist eine Verwendung der genannten Markenzeichen nicht gestattet.“
## Credits
Herkunft der Bilder für das Funktionsbild sind:
* Anja Di Paolo
* Anna Steinbauer
* Bildmaterial aus dem DSA MMORPG Herokon Online der Silver Style Studios GmbH
[1]: http://www.helden-software.de/
[2]: http://www.dasschwarzeauge.de/
[3]: https://play.google.com/store/apps/details?id=com.dsatab
[5]: https://github.com/gandulf/GuiLib
[6]: https://github.com/nhaarman/ListViewAnimations
[7]: https://github.com/chrisbanes/PhotoView
[8]: https://github.com/Espiandev/ShowcaseView
[9]: https://github.com/castorflex/FlipImageView
[10]: https://github.com/paramvir-b/AndroidGridViewCompatLib
| {'content_hash': '276565fda8d5a811ac8596747bdaf899', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 230, 'avg_line_length': 45.76119402985075, 'alnum_prop': 0.7635355512067841, 'repo_name': 'gandulf/DsaTab', 'id': '2465621c1b04657f14d85dfc30ecb5409badb0c1', 'size': '3071', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '199628'}, {'name': 'Java', 'bytes': '1680271'}]} |
All URIs are relative to *http://localhost:8080/engine-rest*
Method | HTTP request | Description
------------- | ------------- | -------------
[**getProcessEngineNames**](EngineApi.md#getProcessEngineNames) | **GET** /engine |
<a name="getProcessEngineNames"></a>
# **getProcessEngineNames**
> List<ProcessEngineDto> getProcessEngineNames()
Retrieves the names of all process engines available on your platform. **Note**: You cannot prepend `/engine/{name}` to this method.
### Example
```java
// Import classes:
import com.camunda.consulting.openapi.client.handler.ApiClient;
import com.camunda.consulting.openapi.client.handler.ApiException;
import com.camunda.consulting.openapi.client.handler.Configuration;
import com.camunda.consulting.openapi.client.handler.models.*;
import com.camunda.consulting.openapi.client.handler.EngineApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://localhost:8080/engine-rest");
EngineApi apiInstance = new EngineApi(defaultClient);
try {
List<ProcessEngineDto> result = apiInstance.getProcessEngineNames();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling EngineApi#getProcessEngineNames");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**List<ProcessEngineDto>**](ProcessEngineDto.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | Request successful. | - |
| {'content_hash': '27fa379b0aa6d81a56b4fe3fb424c891', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 142, 'avg_line_length': 31.16923076923077, 'alnum_prop': 0.6964461994076999, 'repo_name': 'camunda/camunda-consulting', 'id': 'aa697417f0a4768a349c23a8276bfa18925f0642', 'size': '2039', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'snippets/camunda-openapi-client/camunda-openapi-client/docs/EngineApi.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5006'}, {'name': 'CSS', 'bytes': '501980'}, {'name': 'FreeMarker', 'bytes': '496'}, {'name': 'HTML', 'bytes': '761706'}, {'name': 'Java', 'bytes': '1450805'}, {'name': 'JavaScript', 'bytes': '5864490'}, {'name': 'PLSQL', 'bytes': '62024'}, {'name': 'Shell', 'bytes': '14267'}]} |
package com.pie.tlatoani.Core.Registration;
import ch.njol.skript.classes.ClassInfo;
import ch.njol.util.Pair;
import com.google.common.collect.ImmutableList;
import com.pie.tlatoani.Core.Static.MainCommand;
import com.pie.tlatoani.Util.Collections.ImmutableListCollector;
import org.bukkit.command.CommandSender;
import java.util.*;
/**
* Created by Tlatoani on 8/17/17.
*/
public abstract class DocumentationElement {
public final String name;
public final String category;
public final ImmutableList<String> syntaxes;
public final ImmutableList<String> description;
public final String originVersion;
public final ImmutableList<String> requiredPlugins;
public final ImmutableList<ImmutableList<String>> examples;
public enum ElementType {
EFFECT("Effect"),
CONDITION("Condition"),
EXPRESSION("Expression"),
EVENT("Event"),
TYPE("Type"),
SCOPE("Scope");
public final String toString;
ElementType(String toString) {
this.toString = toString;
}
public String toString() {
return toString;
}
}
public abstract ElementType getType();
public abstract void display(CommandSender sender);
protected void displayHeader(CommandSender sender) {
sender.sendMessage(MainCommand.formatMundoSKInfo(category + " " + getType(), name));
sender.sendMessage(MainCommand.formatMundoSKInfo("Since", "MundoSK " + originVersion));
if (requiredPlugins.size() > 0) {
sender.sendMessage(MainCommand.formatMundoSKInfo("Required Plugins", String.join(" ", requiredPlugins)));
}
}
protected void displaySyntax(CommandSender sender) {
if (syntaxes.size() == 1) {
sender.sendMessage(MainCommand.formatMundoSKInfo("Syntax", syntaxes.get(0)));
} else {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Syntaxes");
for (String syntax : syntaxes) {
sender.sendMessage(MainCommand.ALT_CHAT_COLOR + syntax);
}
}
}
protected void displayDesc(CommandSender sender) {
if (description.size() == 1) {
sender.sendMessage(MainCommand.formatMundoSKInfo("Description", description.get(0)));
} else {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Description");
for (String descLine : description) {
sender.sendMessage(MainCommand.ALT_CHAT_COLOR + descLine);
}
}
}
protected void displayExamples(CommandSender sender) {
for (int i = 1; i <= examples.size(); i++) {
ImmutableList<String> example = examples.get(i - 1);
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Example " + i);
for (int line = 1; line <= example.size(); line++) {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "" + String.format(Locale.US, "%02d", line) + " " + MainCommand.ALT_CHAT_COLOR + example.get(line - 1));
}
}
}
@Override
public String toString() {
return "DocumentationElement(" + category + " " + getType() + ": " + name + ")";
}
private DocumentationElement(String name, String category, String[] syntaxes, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples) {
this.name = name;
this.category = category;
this.syntaxes = Arrays
.stream(syntaxes)
.map(syntax -> syntax.replaceAll("\\d+¦", "")) //Borrowed from Tuke_Nuke's TuSKe from the SsyntaxInfo class's fixPattern() method
.collect(new ImmutableListCollector<>());
this.description = ImmutableList.copyOf(description);
this.originVersion = originVersion;
this.requiredPlugins = ImmutableList.copyOf(requiredPlugins);
this.examples = examples
.stream()
.map(ImmutableList::copyOf)
.collect(new ImmutableListCollector<>());
}
public static class Effect extends DocumentationElement {
@Override
public DocumentationElement.ElementType getType() {
return ElementType.EFFECT;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
displaySyntax(sender);
displayDesc(sender);
displayExamples(sender);
}
public Effect(String name, String category, String[] syntaxes, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
}
}
public static class Condition extends DocumentationElement {
public final ImmutableList<Changer> changers;
public Condition(String name, String category, String[] syntaxes, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples, Collection<DocumentationBuilder.Changer> changerBuilders) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
this.changers = changerBuilders.stream().map(builder -> builder.build(this)).collect(new ImmutableListCollector<>());
}
@Override
public DocumentationElement.ElementType getType() {
return ElementType.CONDITION;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
displaySyntax(sender);
displayDesc(sender);
if (changers.size() > 0) {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Changers");
for (Changer changer : changers) {
changer.display(sender);
}
}
displayExamples(sender);
}
}
public static class Expression extends DocumentationElement {
public final ClassInfo type;
public final ImmutableList<Changer> changers;
public Expression(String name, String category, String[] syntaxes, String[] description, String originVersion, ClassInfo type, String[] requiredPlugins, List<String[]> examples, List<DocumentationBuilder.Changer> changerBuilders) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
this.type = type;
this.changers = changerBuilders.stream().map(builder -> builder.build(this)).collect(new ImmutableListCollector<>());
}
@Override
public DocumentationElement.ElementType getType() {
return ElementType.EXPRESSION;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
sender.sendMessage(MainCommand.formatMundoSKInfo("Type", type.getDocName()));
displaySyntax(sender);
displayDesc(sender);
if (changers.size() > 0) {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Changers");
for (Changer changer : changers) {
changer.display(sender);
}
}
displayExamples(sender);
}
}
public static class Changer {
public final DocumentationElement parent;
public final ch.njol.skript.classes.Changer.ChangeMode mode;
public final Optional<Pair<ClassInfo, Boolean>> type;
public final String description;
public final String originVersion;
public Changer(DocumentationElement parent, ch.njol.skript.classes.Changer.ChangeMode mode, Optional<Pair<ClassInfo, Boolean>> type, String description, String originVersion) {
this.parent = parent;
this.mode = mode;
this.type = type;
this.description = description;
this.originVersion = originVersion;
}
public static String modeSyntax(ch.njol.skript.classes.Changer.ChangeMode mode) {
switch (mode) {
case ADD:
case REMOVE:
case RESET:
return mode.name().toLowerCase();
case SET:
return "set to";
case DELETE:
return "clear/delete";
case REMOVE_ALL:
return "remove all";
}
throw new IllegalArgumentException("Mode: " + mode);
}
public void display(CommandSender sender) {
String typeSyntax = type.map(pair -> " " + pair.getFirst().getCodeName() + (pair.getSecond() ? "" : "s")).orElse("");
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + modeSyntax(mode) + typeSyntax + (originVersion.equals(parent.originVersion) ? "" : MainCommand.TRI_CHAT_COLOR + " Since " + originVersion) + MainCommand.ALT_CHAT_COLOR + " " + description);
}
}
public static class Event extends DocumentationElement {
public final boolean cancellable;
public final ImmutableList<EventValue> eventValues;
public Event(String name, String category, String[] syntaxes, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples, boolean cancellable, Collection<DocumentationBuilder.EventValue> eventValueBuilders) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
this.cancellable = cancellable;
this.eventValues = eventValueBuilders.stream().map(builder -> builder.build(this)).collect(new ImmutableListCollector<>());
}
@Override
public DocumentationElement.ElementType getType() {
return ElementType.EVENT;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
sender.sendMessage(MainCommand.formatMundoSKInfo("Cancellable", cancellable ? "Yes" : "No"));
displaySyntax(sender);
displayDesc(sender);
if (eventValues.size() > 0) {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "Event Values");
for (EventValue eventValue : eventValues) {
eventValue.display(sender);
}
}
displayExamples(sender);
}
}
public static class EventValue {
public final Event parent;
public final ClassInfo type;
public final String description;
public final String originVersion;
public EventValue(Event parent, ClassInfo type, String description, String originVersion) {
this.parent = parent;
this.type = type;
this.description = description;
this.originVersion = originVersion;
}
public void display(CommandSender sender) {
sender.sendMessage(MainCommand.PRIMARY_CHAT_COLOR + "event-" + type.getCodeName() + (originVersion.equals(parent.originVersion) ? "" : MainCommand.TRI_CHAT_COLOR + " Since " + originVersion) + MainCommand.ALT_CHAT_COLOR + " " + description);
}
}
public static class Type extends DocumentationElement {
public final ImmutableList<String> usages;
public Type(String name, String category, String[] syntaxes, String[] usages, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
this.usages = ImmutableList.copyOf(usages);
}
@Override
public ElementType getType() {
return ElementType.TYPE;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
displaySyntax(sender);
sender.sendMessage(MainCommand.formatMundoSKInfo("Usages", usages.size() == 0 ? "Cannot be written in scripts" : String.join(", ", usages)));
displayDesc(sender);
displayExamples(sender);
}
}
public static class Scope extends DocumentationElement {
@Override
public DocumentationElement.ElementType getType() {
return ElementType.EFFECT;
}
@Override
public void display(CommandSender sender) {
displayHeader(sender);
displaySyntax(sender);
displayDesc(sender);
displayExamples(sender);
}
public Scope(String name, String category, String[] syntaxes, String[] description, String originVersion, String[] requiredPlugins, List<String[]> examples) {
super(name, category, syntaxes, description, originVersion, requiredPlugins, examples);
}
}
}
| {'content_hash': 'd302e36607e6418329ca257b38101bd9', 'timestamp': '', 'source': 'github', 'line_count': 315, 'max_line_length': 253, 'avg_line_length': 40.87619047619047, 'alnum_prop': 0.6264367816091954, 'repo_name': 'MundoSK/MundoSK', 'id': '27171ac5c33f0055364909bce5009a07bb1df322', 'size': '12877', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/com/pie/tlatoani/Core/Registration/DocumentationElement.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2127376'}]} |
package com.dremio.exec.context;
/**
* Marker interface to provide ability to
* add additional context
*/
public interface AdditionalContext {
}
| {'content_hash': '73f66621bcb2e4dd93d3dddbdf2e289c', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 41, 'avg_line_length': 16.666666666666668, 'alnum_prop': 0.7466666666666667, 'repo_name': 'dremio/dremio-oss', 'id': '6a63529ff2ab5f264f37a6229f2cc820e65f42ce', 'size': '760', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'common/src/main/java/com/dremio/exec/context/AdditionalContext.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '47376'}, {'name': 'Dockerfile', 'bytes': '1668'}, {'name': 'FreeMarker', 'bytes': '132156'}, {'name': 'GAP', 'bytes': '15936'}, {'name': 'HTML', 'bytes': '6544'}, {'name': 'Java', 'bytes': '39679012'}, {'name': 'JavaScript', 'bytes': '5439822'}, {'name': 'Less', 'bytes': '547002'}, {'name': 'SCSS', 'bytes': '95688'}, {'name': 'Shell', 'bytes': '16063'}, {'name': 'TypeScript', 'bytes': '887739'}]} |
package main
import (
"encoding/json"
"github.com/streadway/amqp"
"log"
"time"
)
func Consume(uri string, doneChan chan bool) {
log.Println("Consuming...")
connection, err := amqp.Dial(uri)
if err != nil {
println(err.Error())
panic(err.Error())
}
defer connection.Close()
channel, err1 := connection.Channel()
if err1 != nil {
println(err1.Error())
panic(err1.Error())
}
defer channel.Close()
q := MakeQueue(channel)
msgs, err3 := channel.Consume(q.Name, "", true, false, false, false, nil)
if err3 != nil {
panic(err3)
}
for d := range msgs {
doneChan <- true
var thisMessage MqMessage
err4 := json.Unmarshal(d.Body, &thisMessage)
if err4 != nil {
log.Printf("Error unmarshalling! %s", err.Error())
}
log.Printf("Message age: %s", time.Since(thisMessage.TimeNow))
}
log.Println("done recieving")
}
| {'content_hash': '9948b263eb4eba4b5e28852aa1146571', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 74, 'avg_line_length': 18.565217391304348, 'alnum_prop': 0.6522248243559718, 'repo_name': 'nbari/go-sandbox', 'id': 'a0c586daefb0865d6c17c563637d47cb13c8cd3d', 'size': '854', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'rabbitmq/rabbit-mq-stress-tester/consumer.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'GAP', 'bytes': '539'}, {'name': 'Go', 'bytes': '258509'}, {'name': 'HTML', 'bytes': '209'}, {'name': 'JSONiq', 'bytes': '726'}, {'name': 'Lua', 'bytes': '1508'}, {'name': 'Makefile', 'bytes': '2274'}, {'name': 'Python', 'bytes': '96'}, {'name': 'Shell', 'bytes': '1958'}, {'name': 'Smarty', 'bytes': '343'}]} |
package io.janusproject.tests.kernel.bic;
import static org.junit.Assert.*;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.util.Collection;
import java.util.UUID;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import io.janusproject.kernel.bic.BehaviorsSkill;
import io.janusproject.kernel.bic.InternalEventBusCapacity;
import io.janusproject.kernel.bic.SchedulesSkill;
import io.janusproject.tests.testutils.AbstractJanusTest;
import io.sarl.core.InnerContextAccess;
import io.sarl.core.Schedules;
import io.sarl.lang.core.Address;
import io.sarl.lang.core.Agent;
import io.sarl.lang.core.AgentContext;
import io.sarl.lang.core.AgentTrait;
import io.sarl.lang.core.Behavior;
import io.sarl.lang.core.BuiltinCapacitiesProvider;
import io.sarl.lang.core.Capacities;
import io.sarl.lang.core.Capacity;
import io.sarl.lang.core.Event;
import io.sarl.lang.core.EventListener;
import io.sarl.lang.core.EventSpace;
import io.sarl.lang.core.EventSpaceSpecification;
import io.sarl.lang.core.Scope;
import io.sarl.lang.core.Skill;
import io.sarl.lang.core.SpaceID;
import io.sarl.lang.util.ClearableReference;
import io.sarl.tests.api.Nullable;
import io.sarl.util.Scopes;
/**
* @author $Author: sgalland$
* @version $FullVersion$
* @mavengroupid $GroupId$
* @mavenartifactid $ArtifactId$
*/
@SuppressWarnings("all")
public class BehaviorsSkillTest extends AbstractJanusTest {
@Nullable
private EventListener eventListener;
@Nullable
private InternalEventBusCapacity busCapacity;
@Nullable
private InnerContextAccess innerCapacity;
@Nullable
private SchedulesSkill schedulesCapacity;
@Nullable
private EventSpace innerSpace;
@Nullable
private Address address;
@Nullable
private BehaviorsSkill skill;
@Nullable
private Skill1 specificCapacity;
@Nullable
private TestAgent agent;
@Before
public void setUp() throws Exception {
this.eventListener = Mockito.mock(EventListener.class);
this.address = new Address(new SpaceID(UUID.randomUUID(), UUID.randomUUID(), EventSpaceSpecification.class),
UUID.randomUUID());
this.busCapacity = Mockito.mock(InternalEventBusCapacity.class);
Mockito.when(this.busCapacity.asEventListener()).thenReturn(this.eventListener);
this.innerSpace = Mockito.mock(EventSpace.class);
Mockito.when(this.innerSpace.getAddress(ArgumentMatchers.any(UUID.class))).thenReturn(this.address);
AgentContext innerContext = Mockito.mock(AgentContext.class);
Mockito.when(innerContext.getDefaultSpace()).thenReturn(this.innerSpace);
this.innerCapacity = Mockito.mock(InnerContextAccess.class);
Mockito.when(this.innerCapacity.getInnerContext()).thenReturn(innerContext);
this.schedulesCapacity = Mockito.mock(SchedulesSkill.class);
this.agent = new TestAgent(this);
this.skill = this.reflect.newInstance(BehaviorsSkill.class, this.agent, this.address);
this.specificCapacity = new Skill1(this.agent);
}
@Test
public void asEventListener() {
assertSame(this.eventListener, this.skill.asEventListener());
}
@Test
public void registerBehavior() {
Behavior b = new TestBehavior(this.agent);
b = spy(b);
assertSame(b, this.skill.registerBehavior(b));
ArgumentCaptor<Behavior> argument1 = ArgumentCaptor.forClass(Behavior.class);
ArgumentCaptor<Boolean> argument2 = ArgumentCaptor.forClass(Boolean.class);
ArgumentCaptor<Function1<? super Event, ? extends Boolean>> argument3 = ArgumentCaptor.forClass(Function1.class);
Mockito.verify(this.busCapacity).registerEventListener(argument1.capture(), argument2.capture(), argument3.capture());
assertSame(b, argument1.getValue());
assertTrue(argument2.getValue());
assertNull(argument3.getValue());
}
@Test
public void registerBehavior_null() {
Behavior b = new TestBehavior(this.agent);
b = spy(b);
assertSame(b, this.skill.registerBehavior(b, null));
ArgumentCaptor<Behavior> argument1 = ArgumentCaptor.forClass(Behavior.class);
ArgumentCaptor<Boolean> argument2 = ArgumentCaptor.forClass(Boolean.class);
ArgumentCaptor<Function1<? super Event, ? extends Boolean>> argument3 = ArgumentCaptor.forClass(Function1.class);
Mockito.verify(this.busCapacity).registerEventListener(argument1.capture(), argument2.capture(), argument3.capture());
assertSame(b, argument1.getValue());
assertTrue(argument2.getValue());
assertNull(argument3.getValue());
}
@Test
public void registerBehavior_validFilter() {
Behavior b = new TestBehavior(this.agent);
b = spy(b);
Function1<? super Event, ? extends Boolean> filter = (event) -> true;
assertSame(b, this.skill.registerBehavior(b, filter));
ArgumentCaptor<Behavior> argument1 = ArgumentCaptor.forClass(Behavior.class);
ArgumentCaptor<Boolean> argument2 = ArgumentCaptor.forClass(Boolean.class);
ArgumentCaptor<Function1<? super Event, ? extends Boolean>> argument3 = ArgumentCaptor.forClass(Function1.class);
Mockito.verify(this.busCapacity).registerEventListener(argument1.capture(), argument2.capture(), argument3.capture());
assertSame(b, argument1.getValue());
assertTrue(argument2.getValue());
assertSame(filter, argument3.getValue());
}
@Test
public void registerBehavior_invalidFilter() {
Behavior b = new TestBehavior(this.agent);
b = spy(b);
Function1<? super Event, ? extends Boolean> filter = (event) -> false;
assertSame(b, this.skill.registerBehavior(b, filter));
ArgumentCaptor<Behavior> argument1 = ArgumentCaptor.forClass(Behavior.class);
ArgumentCaptor<Boolean> argument2 = ArgumentCaptor.forClass(Boolean.class);
ArgumentCaptor<Function1<? super Event, ? extends Boolean>> argument3 = ArgumentCaptor.forClass(Function1.class);
Mockito.verify(this.busCapacity).registerEventListener(argument1.capture(), argument2.capture(), argument3.capture());
assertSame(b, argument1.getValue());
assertTrue(argument2.getValue());
assertSame(filter, argument3.getValue());
}
@Test
public void unregisterBehavior() {
Behavior b = new TestBehavior(this.agent);
b = spy(b);
this.skill.registerBehavior(b);
//
assertSame(b, this.skill.unregisterBehavior(b));
ArgumentCaptor<Behavior> argument1 = ArgumentCaptor.forClass(Behavior.class);
ArgumentCaptor<Boolean> argument2 = ArgumentCaptor.forClass(Boolean.class);
Mockito.verify(this.busCapacity, Mockito.times(1)).unregisterEventListener(argument1.capture(), argument2.capture());
assertSame(b, argument1.getValue());
assertTrue(argument2.getValue());
}
@Test
public void hasRegisteredBehavior() {
Mockito.doReturn(false).when(this.busCapacity).hasRegisteredEventListener(ArgumentMatchers.any());
assertFalse(this.skill.hasRegisteredBehavior());
//
Mockito.doReturn(true).when(this.busCapacity).hasRegisteredEventListener(ArgumentMatchers.any());
assertTrue(this.skill.hasRegisteredBehavior());
}
@Test
public void getRegisteredBehaviors() {
Mockito.doReturn(0).when(this.busCapacity).getRegisteredEventListeners(ArgumentMatchers.any(), ArgumentMatchers.any());
assertContains(this.skill.getRegisteredBehaviors());
//
Object behaviorListener = new TestBehavior(this.agent);
Mockito.doAnswer((it) -> {
((Collection) it.getArgument(1)).add(behaviorListener);
return 1;
}).when(this.busCapacity).getRegisteredEventListeners(ArgumentMatchers.any(), ArgumentMatchers.any());
assertContains(this.skill.getRegisteredBehaviors(), behaviorListener);
}
@Test
public void wake_noScope() {
Event event = mock(Event.class);
this.skill.wake(event);
ArgumentCaptor<Event> argument1 = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Scope<Address>> argument2 = ArgumentCaptor.forClass(Scope.class);
Mockito.verify(this.innerSpace).emit(argument1.capture(), argument2.capture());
assertSame(event, argument1.getValue());
assertNull(argument2.getValue());
ArgumentCaptor<Address> argument3 = ArgumentCaptor.forClass(Address.class);
Mockito.verify(event).setSource(argument3.capture());
assertEquals(this.address, argument3.getValue());
}
@Test
public void wake_scope_all() {
Event event = mock(Event.class);
this.skill.wake(event, Scopes.allParticipants());
ArgumentCaptor<Event> argument1 = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Scope<Address>> argument2 = ArgumentCaptor.forClass(Scope.class);
Mockito.verify(this.innerSpace).emit(argument1.capture(), argument2.capture());
assertSame(event, argument1.getValue());
assertNotNull(argument2.getValue());
assertSame(Scopes.allParticipants(), argument2.getValue());
ArgumentCaptor<Address> argument3 = ArgumentCaptor.forClass(Address.class);
Mockito.verify(event).setSource(argument3.capture());
assertEquals(this.address, argument3.getValue());
}
@Test
public void wake_scope_any() {
Event event = mock(Event.class);
SpaceID spaceID = new SpaceID(UUID.randomUUID(), UUID.randomUUID(), null);
Scope<Address> scope = Scopes.addresses(new Address(spaceID, UUID.randomUUID()));
this.skill.wake(event, scope);
ArgumentCaptor<Event> argument1 = ArgumentCaptor.forClass(Event.class);
ArgumentCaptor<Scope<Address>> argument2 = ArgumentCaptor.forClass(Scope.class);
Mockito.verify(this.innerSpace).emit(argument1.capture(), argument2.capture());
assertSame(event, argument1.getValue());
assertNotNull(argument2.getValue());
assertSame(scope, argument2.getValue());
ArgumentCaptor<Address> argument3 = ArgumentCaptor.forClass(Address.class);
Mockito.verify(event).setSource(argument3.capture());
assertEquals(this.address, argument3.getValue());
}
@Test
public void contextAwareCapacityCall() throws Exception {
TestBehavior b = new TestBehavior(this.agent);
//
b.runContextAwareCapacityCallTest();
//
assertNotNull(this.specificCapacity.caller);
assertSame(b, this.specificCapacity.caller);
}
public static interface Capacity1 extends Capacity {
void callCapacity();
public static class ContextAwareCapacityWrapper<C extends Capacity1> extends Capacity.ContextAwareCapacityWrapper<C> implements Capacity1 {
public ContextAwareCapacityWrapper(C capacity, AgentTrait caller) {
super(capacity, caller);
}
public void callCapacity() {
try {
ensureCallerInLocalThread();
this.capacity.callCapacity();
} finally {
resetCallerInLocalThread();
}
}
}
}
public static class Skill1 extends Skill implements Capacity1 {
public Object caller;
public Skill1(Agent agent) {
super(agent);
}
@Override
public void callCapacity() {
Object caller = Capacities.getCaller();
this.caller = caller;
}
}
public static class TestAgent extends Agent {
private final BehaviorsSkillTest test;
public TestAgent(BehaviorsSkillTest test) {
super(Mockito.mock(BuiltinCapacitiesProvider.class), UUID.randomUUID(), null);
this.test = test;
}
@Override
protected ClearableReference<Skill> $getSkill(Class<? extends Capacity> capacity) {
if (Capacity1.class.equals(capacity))
return new ClearableReference(this.test.specificCapacity);
if (InternalEventBusCapacity.class.equals(capacity))
return new ClearableReference(this.test.busCapacity);
if (InnerContextAccess.class.equals(capacity))
return new ClearableReference(this.test.innerCapacity);
if (Schedules.class.equals(capacity))
return new ClearableReference(this.test.schedulesCapacity);
return new ClearableReference<>(null);
}
}
public static class TestBehavior extends Behavior {
public TestBehavior(Agent owner) {
super(owner);
}
public void runContextAwareCapacityCallTest() {
Capacity1 skill = getSkill(Capacity1.class);
assertNotNull(skill);
assertInstanceOf(Capacity1.ContextAwareCapacityWrapper.class, skill);
Capacity1 original = ((Capacity1.ContextAwareCapacityWrapper<?>) skill).getDelegate();
assertInstanceOf(Skill1.class, original);
Skill1 skill1 = (Skill1) original;
skill.callCapacity();
assertSame(this, skill1.caller);
}
}
} | {'content_hash': '181bb9b78edac4632c6770efbdcce021', 'timestamp': '', 'source': 'github', 'line_count': 334, 'max_line_length': 141, 'avg_line_length': 36.24251497005988, 'alnum_prop': 0.7701776125567947, 'repo_name': 'jgfoster/sarl', 'id': '7ff1ab18b55c2e87434ed984a62983bb939f2fd8', 'size': '12864', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sre/io.janusproject/io.janusproject.tests/src/test/java/io/janusproject/tests/kernel/bic/BehaviorsSkillTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '178'}, {'name': 'GAP', 'bytes': '1483810'}, {'name': 'HTML', 'bytes': '287'}, {'name': 'Java', 'bytes': '16931375'}, {'name': 'JavaScript', 'bytes': '5968'}, {'name': 'Shell', 'bytes': '7592'}, {'name': 'TeX', 'bytes': '11189'}]} |
using System;
// ReSharper disable MemberCanBePrivate.Global
namespace Sprache
{
/// <summary>
/// Represents a position in the input.
/// </summary>
public class Position : IEquatable<Position>
{
/// <summary>
/// Initializes a new instance of the <see cref="Position" /> class.
/// </summary>
/// <param name="pos">The position.</param>
/// <param name="line">The line number.</param>
/// <param name="column">The column.</param>
public Position(int pos, int line, int column)
{
Pos = pos;
Line = line;
Column = column;
}
/// <summary>
/// Creates an new <see cref="Position"/> instance from a given <see cref="IInput"/> object.
/// </summary>
/// <param name="input">The current input.</param>
/// <returns>A new <see cref="Position"/> instance.</returns>
public static Position FromInput(IInput input)
{
return new Position(input.Position, input.Line, input.Column);
}
/// <summary>
/// Gets the current positon.
/// </summary>
public int Pos
{
get;
}
/// <summary>
/// Gets the current line number.
/// </summary>
public int Line
{
get;
}
/// <summary>
/// Gets the current column.
/// </summary>
public int Column
{
get;
}
/// <summary>
/// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="Position" />.
/// </summary>
/// <returns>
/// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="Position" />; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
return Equals(obj as Position);
}
/// <summary>
/// Indicates whether the current <see cref="Position" /> is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(Position other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Pos == other.Pos
&& Line == other.Line
&& Column == other.Column;
}
/// <summary>
/// Indicates whether the left <see cref="Position" /> is equal to the right <see cref="Position" />.
/// </summary>
/// <param name="left">The left <see cref="Position" />.</param>
/// <param name="right">The right <see cref="Position" />.</param>
/// <returns>true if both objects are equal.</returns>
public static bool operator ==(Position left, Position right)
{
return Equals(left, right);
}
/// <summary>
/// Indicates whether the left <see cref="Position" /> is not equal to the right <see cref="Position" />.
/// </summary>
/// <param name="left">The left <see cref="Position" />.</param>
/// <param name="right">The right <see cref="Position" />.</param>
/// <returns>true if the objects are not equal.</returns>
public static bool operator !=(Position left, Position right)
{
return !Equals(left, right);
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="Position" />.
/// </returns>
public override int GetHashCode()
{
var h = 31;
h = h * 13 + Pos;
h = h * 13 + Line;
h = h * 13 + Column;
return h;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
public override string ToString()
{
return string.Format("Line {0}, Column {1}", Line, Column);
}
}
}
| {'content_hash': '549fbec6f056f86c64134dad0a0133e4', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 130, 'avg_line_length': 33.791044776119406, 'alnum_prop': 0.5183303886925795, 'repo_name': 'sprache/Sprache', 'id': 'b58285c59c5ed4ab683b48981bfb54e055f6a4b7', 'size': '4530', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/Sprache/Position.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '149643'}, {'name': 'PowerShell', 'bytes': '1451'}]} |
package jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import jdbc.tool.ConnectionOperation;
import vo.Author;
public class UpdateWrite {
private static final String NEW_WRITE_RELATIONSHIP = "INSERT INTO `write` (doc_id, author_id) VALUES (?,?)";
public static boolean newWriteRelatonship(String docId, List<Author> authorList) {
Connection conn;
if ((conn = ConnectionOperation.getConnection()) == null) {
return false;
}
PreparedStatement ps;
try {
ps = conn.prepareStatement(NEW_WRITE_RELATIONSHIP);
ps.setString(1, docId);
} catch (SQLException e1) {
e1.printStackTrace();
ConnectionOperation.close(conn);
return false;
}
boolean result = true;
for (Author author : authorList) {
ResultSet rs = QueryAuthor.getAuthorByName(author.getAuName());
try {
if (rs != null && rs.next()) {
author.setAuId(rs.getString(1));
} else {
UpdateAuthor.newAuthor(author);
}
} catch (SQLException e) {
e.printStackTrace();
ConnectionOperation.close(rs);
return false;
}
try {
ps.setString(2, author.getAuId());
if (ps.executeUpdate() != 1) {
result = false;
break;
}
} catch (SQLException e) {
e.printStackTrace();
result = false;
break;
}
}
ConnectionOperation.close(ps);
return result;
}
}
| {'content_hash': 'ece83be05e82440bc8bffebb6756c5b8', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 109, 'avg_line_length': 25.859649122807017, 'alnum_prop': 0.6485753052917232, 'repo_name': 'rs843/CS631Phase3', 'id': 'e12170ec2f3742230c3f860a44ea62de30134b2d', 'size': '1474', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/jdbc/UpdateWrite.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '125080'}]} |
<!DOCTYPE html><html><head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta name="description">
<meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon">
<link rel="icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon">
<title>OpenTl.Schema - API - TChannelDifferenceTooLong.UnreadCount Property</title>
<link href="/OpenTl.Schema/assets/css/mermaid.css" rel="stylesheet">
<link href="/OpenTl.Schema/assets/css/highlight.css" rel="stylesheet">
<link href="/OpenTl.Schema/assets/css/bootstrap/bootstrap.css" rel="stylesheet">
<link href="/OpenTl.Schema/assets/css/adminlte/AdminLTE.css" rel="stylesheet">
<link href="/OpenTl.Schema/assets/css/theme/theme.css" rel="stylesheet">
<link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet">
<link href="/OpenTl.Schema/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="/OpenTl.Schema/assets/css/override.css" rel="stylesheet">
<script src="/OpenTl.Schema/assets/js/jquery-2.2.3.min.js"></script>
<script src="/OpenTl.Schema/assets/js/bootstrap.min.js"></script>
<script src="/OpenTl.Schema/assets/js/app.min.js"></script>
<script src="/OpenTl.Schema/assets/js/highlight.pack.js"></script>
<script src="/OpenTl.Schema/assets/js/jquery.slimscroll.min.js"></script>
<script src="/OpenTl.Schema/assets/js/jquery.sticky-kit.min.js"></script>
<script src="/OpenTl.Schema/assets/js/mermaid.min.js"></script>
<!--[if lt IE 9]>
<script src="/OpenTl.Schema/assets/js/html5shiv.min.js"></script>
<script src="/OpenTl.Schema/assets/js/respond.min.js"></script>
<![endif]-->
</head>
<body class="hold-transition wyam layout-boxed ">
<div class="top-banner"></div>
<div class="wrapper with-container">
<!-- Header -->
<header class="main-header">
<a href="/OpenTl.Schema/" class="logo">
<span>OpenTl.Schema</span>
</a>
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button">
<span class="sr-only">Toggle side menu</span>
<i class="fa fa-chevron-circle-right"></i>
</a>
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
<span class="sr-only">Toggle side menu</span>
<i class="fa fa-chevron-circle-down"></i>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse pull-left" id="navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="/OpenTl.Schema/about.html">About This Project</a></li>
<li class="active"><a href="/OpenTl.Schema/api">API</a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
<!-- Navbar Right Menu -->
</nav>
</header>
<!-- Left side column. contains the logo and sidebar -->
<aside class="main-sidebar ">
<section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200">
<div id="infobar-headings"><h6>On This Page</h6><p><a href="#Syntax">Syntax</a></p>
<p><a href="#Attributes">Attributes</a></p>
<p><a href="#Value">Value</a></p>
<hr class="infobar-hidden">
</div>
</section>
<section class="sidebar">
<script src="/OpenTl.Schema/assets/js/lunr.min.js"></script>
<script src="/OpenTl.Schema/assets/js/searchIndex.js"></script>
<div class="sidebar-form">
<div class="input-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search Types...">
<span class="input-group-btn">
<button class="btn btn-flat"><i class="fa fa-search"></i></button>
</span>
</div>
</div>
<div id="search-results">
</div>
<script>
function runSearch(query){
$("#search-results").empty();
if( query.length < 2 ){
return;
}
var results = searchModule.search("*" + query + "*");
var listHtml = "<ul class='sidebar-menu'>";
listHtml += "<li class='header'>Type Results</li>";
if(results.length == 0 ){
listHtml += "<li>No results found</li>";
} else {
for(var i = 0; i < results.length; ++i){
var res = results[i];
listHtml += "<li><a href='" + res.url + "'>" + htmlEscape(res.title) + "</a></li>";
}
}
listHtml += "</ul>";
$("#search-results").append(listHtml);
}
$(document).ready(function(){
$("#search").on('input propertychange paste', function() {
runSearch($("#search").val());
});
});
function htmlEscape(html) {
return document.createElement('div')
.appendChild(document.createTextNode(html))
.parentNode
.innerHTML;
}
</script>
<hr>
<ul class="sidebar-menu">
<li class="header">Namespace</li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates">OpenTl<wbr>.Schema<wbr>.Updates</a></li>
<li class="header">Type</li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong">T<wbr>Channel<wbr>Difference<wbr>Too<wbr>Long</a></li>
<li role="separator" class="divider"></li>
<li class="header">Property Members</li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/54EB3007.html">Chats</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/9DAF8DC6.html">Final</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/E1B25D21.html">Flags</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/55B4CAE1.html">Messages</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/DD261B29.html">Pts</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/7CE94241.html">ReadInboxMaxId</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/42906668.html">ReadOutboxMaxId</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/F378BAFC.html">Timeout</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/5FB01A01.html">TopMessage</a></li>
<li class="selected"><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/B69EA203.html">UnreadCount</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/FFB2F3F4.html">UnreadMentionsCount</a></li>
<li><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/B256DB3E.html">Users</a></li>
</ul>
</section>
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<section class="content-header">
<h3><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong">T<wbr>Channel<wbr>Difference<wbr>Too<wbr>Long</a>.</h3>
<h1>UnreadCount <small>Property</small></h1>
</section>
<section class="content">
<div class="panel panel-default">
<div class="panel-body">
<dl class="dl-horizontal">
<dt>Namespace</dt>
<dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates">OpenTl<wbr>.Schema<wbr>.Updates</a></dd>
<dt>Containing Type</dt>
<dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong">T<wbr>Channel<wbr>Difference<wbr>Too<wbr>Long</a></dd>
</dl>
</div>
</div>
<h1 id="Syntax">Syntax</h1>
<pre><code>[SerializationOrder(7)]
public int UnreadCount { get; set; }</code></pre>
<h1 id="Attributes">Attributes</h1>
<div class="box">
<div class="box-body no-padding table-responsive">
<table class="table table-striped table-hover two-cols">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>Serialization<wbr>Order<wbr>Attribute</td>
<td></td>
</tr>
</tbody></table>
</div>
</div>
<h1 id="Value">Value</h1>
<div class="box">
<div class="box-body no-padding table-responsive">
<table class="table table-striped table-hover two-cols">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td>int</td>
<td></td>
</tr>
</tbody></table>
</div>
</div>
</section>
</div>
<!-- Footer -->
<footer class="main-footer">
</footer>
</div>
<div class="wrapper bottom-wrapper">
<footer class="bottom-footer">
Generated by <a href="https://wyam.io">Wyam</a>
</footer>
</div>
<a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a>
<script>
// Close the sidebar if we select an anchor link
$(".main-sidebar a[href^='#']:not('.expand')").click(function(){
$(document.body).removeClass('sidebar-open');
});
$(document).load(function() {
mermaid.initialize(
{
flowchart:
{
htmlLabels: false,
useMaxWidth:false
}
});
mermaid.init(undefined, ".mermaid")
$('svg').addClass('img-responsive');
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
});
hljs.initHighlightingOnLoad();
// Back to top
$(window).scroll(function() {
if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px
$('#return-to-top').fadeIn(1000); // Fade in the arrow
} else {
$('#return-to-top').fadeOut(1000); // Else fade out the arrow
}
});
$('#return-to-top').click(function() { // When arrow is clicked
$('body,html').animate({
scrollTop : 0 // Scroll to top of body
}, 500);
});
</script>
</body></html> | {'content_hash': '967c5fa72c607cbd3d6196e309093bf0', 'timestamp': '', 'source': 'github', 'line_count': 288, 'max_line_length': 148, 'avg_line_length': 42.05902777777778, 'alnum_prop': 0.5313299760587799, 'repo_name': 'OpenTl/OpenTl.Schema', 'id': '778656d01031ebd5ee9ec8a699f731c91ba93381', 'size': '12115', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/OpenTl.Schema.Updates/TChannelDifferenceTooLong/B69EA203.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '810786'}, {'name': 'F#', 'bytes': '19501'}, {'name': 'PowerShell', 'bytes': '1288'}]} |
'use strict';
goog.provide('Blockly.Msg.fr');
goog.require('Blockly.Msg');
Blockly.Msg.ADD_COMMENT = "Ajouter un commentaire";
Blockly.Msg.CHANGE_VALUE_TITLE = "Modifier la valeur :";
Blockly.Msg.CLEAN_UP = "Nettoyer les blocs";
Blockly.Msg.COLLAPSE_ALL = "Réduire les blocs";
Blockly.Msg.COLLAPSE_BLOCK = "Réduire le bloc";
Blockly.Msg.COLOUR_BLEND_COLOUR1 = "couleur 1";
Blockly.Msg.COLOUR_BLEND_COLOUR2 = "couleur 2";
Blockly.Msg.COLOUR_BLEND_HELPURL = "http://meyerweb.com/eric/tools/color-blend/";
Blockly.Msg.COLOUR_BLEND_RATIO = "taux";
Blockly.Msg.COLOUR_BLEND_TITLE = "mélanger";
Blockly.Msg.COLOUR_BLEND_TOOLTIP = "Mélange deux couleurs dans une proportion donnée (de 0.0 à 1.0).";
Blockly.Msg.COLOUR_PICKER_HELPURL = "https://fr.wikipedia.org/wiki/Couleur";
Blockly.Msg.COLOUR_PICKER_TOOLTIP = "Choisir une couleur dans la palette.";
Blockly.Msg.COLOUR_RANDOM_HELPURL = "http://randomcolour.com"; // untranslated
Blockly.Msg.COLOUR_RANDOM_TITLE = "couleur aléatoire";
Blockly.Msg.COLOUR_RANDOM_TOOLTIP = "Choisir une couleur au hasard.";
Blockly.Msg.COLOUR_RGB_BLUE = "bleu";
Blockly.Msg.COLOUR_RGB_GREEN = "vert";
Blockly.Msg.COLOUR_RGB_HELPURL = "http://www.december.com/html/spec/colorper.html";
Blockly.Msg.COLOUR_RGB_RED = "rouge";
Blockly.Msg.COLOUR_RGB_TITLE = "colorier avec";
Blockly.Msg.COLOUR_RGB_TOOLTIP = "Créer une couleur avec la quantité spécifiée de rouge, vert et bleu. Les valeurs doivent être comprises entre 0 et 100.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_HELPURL = "https://github.com/google/blockly/wiki/Loops#loop-termination-blocks"; // untranslated
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_BREAK = "quitter la boucle";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_OPERATOR_CONTINUE = "passer à l’itération de boucle suivante";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_BREAK = "Sortir de la boucle englobante.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_TOOLTIP_CONTINUE = "Sauter le reste de cette boucle, et poursuivre avec l’itération suivante.";
Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING = "Attention : Ce bloc ne devrait être utilisé que dans une boucle.";
Blockly.Msg.CONTROLS_FOREACH_HELPURL = "https://github.com/google/blockly/wiki/Loops#for-each"; // untranslated
Blockly.Msg.CONTROLS_FOREACH_TITLE = "pour chaque élément %1 dans la liste %2";
Blockly.Msg.CONTROLS_FOREACH_TOOLTIP = "Pour chaque élément d’une liste, assigner la valeur de l’élément à la variable '%1', puis exécuter des instructions.";
Blockly.Msg.CONTROLS_FOR_HELPURL = "https://github.com/google/blockly/wiki/Loops#count-with"; // untranslated
Blockly.Msg.CONTROLS_FOR_TITLE = "compter avec %1 de %2 à %3 par %4";
Blockly.Msg.CONTROLS_FOR_TOOLTIP = "Faire prendre à la variable « %1 » les valeurs depuis le nombre de début jusqu’au nombre de fin, en s’incrémentant du pas spécifié, et exécuter les instructions spécifiées.";
Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "Ajouter une condition au bloc si.";
Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "Ajouter une condition finale fourre-tout au bloc si.";
Blockly.Msg.CONTROLS_IF_HELPURL = "https://github.com/google/blockly/wiki/IfElse"; // untranslated
Blockly.Msg.CONTROLS_IF_IF_TOOLTIP = "Ajouter, supprimer ou réordonner les sections pour reconfigurer ce bloc si.";
Blockly.Msg.CONTROLS_IF_MSG_ELSE = "sinon";
Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "sinon si";
Blockly.Msg.CONTROLS_IF_MSG_IF = "si";
Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "Si une valeur est vraie, alors exécuter certains ordres.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "Si une valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, exécuter le second bloc d’ordres.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "Si la première valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, si la seconde valeur est vraie, exécuter le second bloc d’ordres.";
Blockly.Msg.CONTROLS_IF_TOOLTIP_4 = "Si la première valeur est vraie, alors exécuter le premier bloc d’ordres. Sinon, si la seconde valeur est vraie, exécuter le second bloc d’ordres. Si aucune des valeurs n’est vraie, exécuter le dernier bloc d’ordres.";
Blockly.Msg.CONTROLS_REPEAT_HELPURL = "http://fr.wikipedia.org/wiki/Boucle_for";
Blockly.Msg.CONTROLS_REPEAT_INPUT_DO = "faire";
Blockly.Msg.CONTROLS_REPEAT_TITLE = "répéter %1 fois";
Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "Exécuter des instructions plusieurs fois.";
Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL = "https://github.com/google/blockly/wiki/Loops#repeat"; // untranslated
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_UNTIL = "répéter jusqu’à";
Blockly.Msg.CONTROLS_WHILEUNTIL_OPERATOR_WHILE = "répéter tant que";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "Tant qu’une valeur est fausse, alors exécuter des instructions.";
Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "Tant qu’une valeur est vraie, alors exécuter des instructions.";
Blockly.Msg.DELETE_ALL_BLOCKS = "Supprimer ces %1 blocs ?";
Blockly.Msg.DELETE_BLOCK = "Supprimer le bloc";
Blockly.Msg.DELETE_X_BLOCKS = "Supprimer %1 blocs";
Blockly.Msg.DISABLE_BLOCK = "Désactiver le bloc";
Blockly.Msg.DUPLICATE_BLOCK = "Dupliquer";
Blockly.Msg.ENABLE_BLOCK = "Activer le bloc";
Blockly.Msg.EXPAND_ALL = "Développer les blocs";
Blockly.Msg.EXPAND_BLOCK = "Développer le bloc";
Blockly.Msg.EXTERNAL_INPUTS = "Entrées externes";
Blockly.Msg.HELP = "Aide";
Blockly.Msg.INLINE_INPUTS = "Entrées en ligne";
Blockly.Msg.LISTS_CREATE_EMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-empty-list"; // untranslated
Blockly.Msg.LISTS_CREATE_EMPTY_TITLE = "créer une liste vide";
Blockly.Msg.LISTS_CREATE_EMPTY_TOOLTIP = "Renvoyer une liste, de longueur 0, ne contenant aucun enregistrement";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TITLE_ADD = "liste";
Blockly.Msg.LISTS_CREATE_WITH_CONTAINER_TOOLTIP = "Ajouter, supprimer, ou réordonner les sections pour reconfigurer ce bloc de liste.";
Blockly.Msg.LISTS_CREATE_WITH_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with";
Blockly.Msg.LISTS_CREATE_WITH_INPUT_WITH = "créer une liste avec";
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TOOLTIP = "Ajouter un élément à la liste.";
Blockly.Msg.LISTS_CREATE_WITH_TOOLTIP = "Créer une liste avec un nombre quelconque d’éléments.";
Blockly.Msg.LISTS_GET_INDEX_FIRST = "premier";
Blockly.Msg.LISTS_GET_INDEX_FROM_END = "# depuis la fin";
Blockly.Msg.LISTS_GET_INDEX_FROM_START = "#"; // untranslated
Blockly.Msg.LISTS_GET_INDEX_GET = "obtenir";
Blockly.Msg.LISTS_GET_INDEX_GET_REMOVE = "obtenir et supprimer";
Blockly.Msg.LISTS_GET_INDEX_LAST = "dernier";
Blockly.Msg.LISTS_GET_INDEX_RANDOM = "aléatoire";
Blockly.Msg.LISTS_GET_INDEX_REMOVE = "supprimer";
Blockly.Msg.LISTS_GET_INDEX_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FIRST = "Renvoie le premier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_FROM = "Renvoie l’élément à la position indiquée dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_LAST = "Renvoie le dernier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_RANDOM = "Renvoie un élément au hasard dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FIRST = "Supprime et renvoie le premier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_FROM = "Supprime et renvoie l’élément à la position indiquée dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_LAST = "Supprime et renvoie le dernier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_GET_REMOVE_RANDOM = "Supprime et renvoie un élément au hasard dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FIRST = "Supprime le premier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_FROM = "Supprime l’élément à la position indiquée dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_LAST = "Supprime le dernier élément dans une liste.";
Blockly.Msg.LISTS_GET_INDEX_TOOLTIP_REMOVE_RANDOM = "Supprime un élément au hasard dans une liste.";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_END = "jusqu’à # depuis la fin";
Blockly.Msg.LISTS_GET_SUBLIST_END_FROM_START = "jusqu’à #";
Blockly.Msg.LISTS_GET_SUBLIST_END_LAST = "jusqu’à la fin";
Blockly.Msg.LISTS_GET_SUBLIST_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-a-sublist"; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_START_FIRST = "obtenir la sous-liste depuis le début";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_END = "obtenir la sous-liste depuis # depuis la fin";
Blockly.Msg.LISTS_GET_SUBLIST_START_FROM_START = "obtenir la sous-liste depuis #";
Blockly.Msg.LISTS_GET_SUBLIST_TAIL = ""; // untranslated
Blockly.Msg.LISTS_GET_SUBLIST_TOOLTIP = "Crée une copie de la partie spécifiée d’une liste.";
Blockly.Msg.LISTS_INDEX_FROM_END_TOOLTIP = "%1 est le dernier élément.";
Blockly.Msg.LISTS_INDEX_FROM_START_TOOLTIP = "%1 est le premier élément.";
Blockly.Msg.LISTS_INDEX_OF_FIRST = "trouver la première occurrence de l’élément";
Blockly.Msg.LISTS_INDEX_OF_HELPURL = "https://github.com/google/blockly/wiki/Lists#getting-items-from-a-list"; // untranslated
Blockly.Msg.LISTS_INDEX_OF_LAST = "trouver la dernière occurrence de l’élément";
Blockly.Msg.LISTS_INDEX_OF_TOOLTIP = "Renvoie l’index de la première/dernière occurrence de l’élément dans la liste. Renvoie %1 si l'élément n'est pas trouvé.";
Blockly.Msg.LISTS_INLIST = "dans la liste";
Blockly.Msg.LISTS_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Lists#is-empty"; // untranslated
Blockly.Msg.LISTS_ISEMPTY_TITLE = "%1 est vide";
Blockly.Msg.LISTS_ISEMPTY_TOOLTIP = "Renvoie vrai si la liste est vide.";
Blockly.Msg.LISTS_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Lists#length-of"; // untranslated
Blockly.Msg.LISTS_LENGTH_TITLE = "longueur de %1";
Blockly.Msg.LISTS_LENGTH_TOOLTIP = "Renvoie la longueur d’une liste.";
Blockly.Msg.LISTS_REPEAT_HELPURL = "https://github.com/google/blockly/wiki/Lists#create-list-with"; // untranslated
Blockly.Msg.LISTS_REPEAT_TITLE = "créer une liste avec l’élément %1 répété %2 fois";
Blockly.Msg.LISTS_REPEAT_TOOLTIP = "Crée une liste consistant en la valeur fournie répétée le nombre de fois indiqué.";
Blockly.Msg.LISTS_SET_INDEX_HELPURL = "https://github.com/google/blockly/wiki/Lists#in-list--set"; // untranslated
Blockly.Msg.LISTS_SET_INDEX_INPUT_TO = "comme";
Blockly.Msg.LISTS_SET_INDEX_INSERT = "insérer en";
Blockly.Msg.LISTS_SET_INDEX_SET = "mettre";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FIRST = "Insère l’élément au début d’une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_FROM = "Insère l’élément à la position indiquée dans une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_LAST = "Ajouter l’élément à la fin d’une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_INSERT_RANDOM = "Insère l’élément au hasard dans une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FIRST = "Fixe le premier élément dans une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_FROM = "Met à jour l’élément à la position indiquée dans une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_LAST = "Fixe le dernier élément dans une liste.";
Blockly.Msg.LISTS_SET_INDEX_TOOLTIP_SET_RANDOM = "Fixe un élément au hasard dans une liste.";
Blockly.Msg.LISTS_SORT_HELPURL = "https://github.com/google/blockly/wiki/Lists#sorting-a-list";
Blockly.Msg.LISTS_SORT_ORDER_ASCENDING = "croissant";
Blockly.Msg.LISTS_SORT_ORDER_DESCENDING = "décroissant";
Blockly.Msg.LISTS_SORT_TITLE = "trier %1 %2 %3";
Blockly.Msg.LISTS_SORT_TOOLTIP = "Trier une copie d’une liste.";
Blockly.Msg.LISTS_SORT_TYPE_IGNORECASE = "alphabétique, en ignorant la casse";
Blockly.Msg.LISTS_SORT_TYPE_NUMERIC = "numérique";
Blockly.Msg.LISTS_SORT_TYPE_TEXT = "alphabétique";
Blockly.Msg.LISTS_SPLIT_HELPURL = "https://github.com/google/blockly/wiki/Lists#splitting-strings-and-joining-lists";
Blockly.Msg.LISTS_SPLIT_LIST_FROM_TEXT = "créer une liste depuis le texte";
Blockly.Msg.LISTS_SPLIT_TEXT_FROM_LIST = "créer un texte depuis la liste";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_JOIN = "Réunir une liste de textes en un seul, en les séparant par un séparateur.";
Blockly.Msg.LISTS_SPLIT_TOOLTIP_SPLIT = "Couper un texte en une liste de textes, en coupant à chaque séparateur.";
Blockly.Msg.LISTS_SPLIT_WITH_DELIMITER = "avec le séparateur";
Blockly.Msg.LOGIC_BOOLEAN_FALSE = "faux";
Blockly.Msg.LOGIC_BOOLEAN_HELPURL = "https://github.com/google/blockly/wiki/Logic#values"; // untranslated
Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "Renvoie soit vrai soit faux.";
Blockly.Msg.LOGIC_BOOLEAN_TRUE = "vrai";
Blockly.Msg.LOGIC_COMPARE_HELPURL = "https://fr.wikipedia.org/wiki/Inegalite_(mathematiques)";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "Renvoyer vrai si les deux entrées sont égales.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "Renvoyer vrai si la première entrée est plus grande que la seconde.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "Renvoyer vrai si la première entrée est plus grande ou égale à la seconde.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "Renvoyer vrai si la première entrée est plus petite que la seconde.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "Renvoyer vrai si la première entrée est plus petite ou égale à la seconde.";
Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "Renvoyer vrai si les deux entrées sont différentes.";
Blockly.Msg.LOGIC_NEGATE_HELPURL = "https://github.com/google/blockly/wiki/Logic#not"; // untranslated
Blockly.Msg.LOGIC_NEGATE_TITLE = "pas %1";
Blockly.Msg.LOGIC_NEGATE_TOOLTIP = "Renvoie vrai si l’entrée est fausse. Renvoie faux si l’entrée est vraie.";
Blockly.Msg.LOGIC_NULL = "nul";
Blockly.Msg.LOGIC_NULL_HELPURL = "https://en.wikipedia.org/wiki/Nullable_type";
Blockly.Msg.LOGIC_NULL_TOOLTIP = "Renvoie nul.";
Blockly.Msg.LOGIC_OPERATION_AND = "et";
Blockly.Msg.LOGIC_OPERATION_HELPURL = "https://github.com/google/blockly/wiki/Logic#logical-operations"; // untranslated
Blockly.Msg.LOGIC_OPERATION_OR = "ou";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "Renvoyer vrai si les deux entrées sont vraies.";
Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "Renvoyer vrai si au moins une des entrées est vraie.";
Blockly.Msg.LOGIC_TERNARY_CONDITION = "test";
Blockly.Msg.LOGIC_TERNARY_HELPURL = "https://en.wikipedia.org/wiki/%3F:";
Blockly.Msg.LOGIC_TERNARY_IF_FALSE = "si faux";
Blockly.Msg.LOGIC_TERNARY_IF_TRUE = "si vrai";
Blockly.Msg.LOGIC_TERNARY_TOOLTIP = "Vérifier la condition dans 'test'. Si elle est vraie, renvoie la valeur 'si vrai' ; sinon renvoie la valeur 'si faux'.";
Blockly.Msg.MATH_ADDITION_SYMBOL = "+"; // untranslated
Blockly.Msg.MATH_ARITHMETIC_HELPURL = "https://fr.wikipedia.org/wiki/Arithmetique";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "Renvoie la somme des deux nombres.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "Renvoie le quotient des deux nombres.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MINUS = "Renvoie la différence des deux nombres.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "Renvoie le produit des deux nombres.";
Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_POWER = "Renvoie le premier nombre élevé à la puissance du second.";
Blockly.Msg.MATH_CHANGE_HELPURL = "https://en.wikipedia.org/wiki/Programming_idiom#Incrementing_a_counter";
Blockly.Msg.MATH_CHANGE_TITLE = "incrémenter %1 de %2";
Blockly.Msg.MATH_CHANGE_TOOLTIP = "Ajouter un nombre à la variable '%1'.";
Blockly.Msg.MATH_CONSTANT_HELPURL = "https://en.wikipedia.org/wiki/Mathematical_constant";
Blockly.Msg.MATH_CONSTANT_TOOLTIP = "Renvoie une des constantes courantes : π (3.141…), e (2.718…), φ (1.618…), sqrt(2) (1.414…), sqrt(½) (0.707…), ou ∞ (infini).";
Blockly.Msg.MATH_CONSTRAIN_HELPURL = "https://en.wikipedia.org/wiki/Clamping_%28graphics%29"; // untranslated
Blockly.Msg.MATH_CONSTRAIN_TITLE = "contraindre %1 entre %2 et %3";
Blockly.Msg.MATH_CONSTRAIN_TOOLTIP = "Contraindre un nombre à être entre les limites spécifiées (incluses).";
Blockly.Msg.MATH_DIVISION_SYMBOL = "÷"; // untranslated
Blockly.Msg.MATH_IS_DIVISIBLE_BY = "est divisible par";
Blockly.Msg.MATH_IS_EVEN = "est pair";
Blockly.Msg.MATH_IS_NEGATIVE = "est négatif";
Blockly.Msg.MATH_IS_ODD = "est impair";
Blockly.Msg.MATH_IS_POSITIVE = "est positif";
Blockly.Msg.MATH_IS_PRIME = "est premier";
Blockly.Msg.MATH_IS_TOOLTIP = "Vérifier si un nombre est pair, impair, premier, entier, positif, négatif, ou s’il est divisible par un certain nombre. Renvoie vrai ou faux.";
Blockly.Msg.MATH_IS_WHOLE = "est entier";
Blockly.Msg.MATH_MODULO_HELPURL = "https://en.wikipedia.org/wiki/Modulo_operation";
Blockly.Msg.MATH_MODULO_TITLE = "reste de %1 ÷ %2";
Blockly.Msg.MATH_MODULO_TOOLTIP = "Renvoyer le reste de la division euclidienne des deux nombres.";
Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "×"; // untranslated
Blockly.Msg.MATH_NUMBER_HELPURL = "https://fr.wikipedia.org/wiki/Nombre";
Blockly.Msg.MATH_NUMBER_TOOLTIP = "Un nombre.";
Blockly.Msg.MATH_ONLIST_HELPURL = ""; // untranslated
Blockly.Msg.MATH_ONLIST_OPERATOR_AVERAGE = "moyenne de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_MAX = "maximum de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_MEDIAN = "médiane de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_MIN = "minimum de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_MODE = "majoritaires de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_RANDOM = "élément aléatoire de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_STD_DEV = "écart-type de la liste";
Blockly.Msg.MATH_ONLIST_OPERATOR_SUM = "somme de la liste";
Blockly.Msg.MATH_ONLIST_TOOLTIP_AVERAGE = "Renvoyer la moyenne (arithmétique) des valeurs numériques dans la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MAX = "Renvoyer le plus grand nombre dans la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MEDIAN = "Renvoyer le nombre médian de la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MIN = "Renvoyer le plus petit nombre dans la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_MODE = "Renvoyer une liste des élément(s) le(s) plus courant(s) dans la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_RANDOM = "Renvoyer un élément dans la liste au hasard.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_STD_DEV = "Renvoyer l’écart-type de la liste.";
Blockly.Msg.MATH_ONLIST_TOOLTIP_SUM = "Renvoyer la somme de tous les nombres dans la liste.";
Blockly.Msg.MATH_POWER_SYMBOL = "^"; // untranslated
Blockly.Msg.MATH_RANDOM_FLOAT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_FLOAT_TITLE_RANDOM = "fraction aléatoire";
Blockly.Msg.MATH_RANDOM_FLOAT_TOOLTIP = "Renvoyer une fraction aléatoire entre 0.0 (inclus) et 1.0 (exclus).";
Blockly.Msg.MATH_RANDOM_INT_HELPURL = "https://en.wikipedia.org/wiki/Random_number_generation";
Blockly.Msg.MATH_RANDOM_INT_TITLE = "entier aléatoire entre %1 et %2";
Blockly.Msg.MATH_RANDOM_INT_TOOLTIP = "Renvoyer un entier aléatoire entre les deux limites spécifiées, incluses.";
Blockly.Msg.MATH_ROUND_HELPURL = "https://en.wikipedia.org/wiki/Rounding";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUND = "arrondir";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDDOWN = "arrondir par défaut";
Blockly.Msg.MATH_ROUND_OPERATOR_ROUNDUP = "arrondir par excès";
Blockly.Msg.MATH_ROUND_TOOLTIP = "Arrondir un nombre au-dessus ou au-dessous.";
Blockly.Msg.MATH_SINGLE_HELPURL = "https://fr.wikipedia.org/wiki/Racine_carree";
Blockly.Msg.MATH_SINGLE_OP_ABSOLUTE = "valeur absolue";
Blockly.Msg.MATH_SINGLE_OP_ROOT = "racine carrée";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ABS = "Renvoie la valeur absolue d’un nombre.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_EXP = "Renvoie e à la puissance d’un nombre.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LN = "Renvoie le logarithme naturel d’un nombre.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_LOG10 = "Renvoie le logarithme base 10 d’un nombre.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_NEG = "Renvoie l’opposé d’un nombre";
Blockly.Msg.MATH_SINGLE_TOOLTIP_POW10 = "Renvoie 10 à la puissance d’un nombre.";
Blockly.Msg.MATH_SINGLE_TOOLTIP_ROOT = "Renvoie la racine carrée d’un nombre.";
Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "-"; // untranslated
Blockly.Msg.MATH_TRIG_ACOS = "acos"; // untranslated
Blockly.Msg.MATH_TRIG_ASIN = "asin"; // untranslated
Blockly.Msg.MATH_TRIG_ATAN = "atan"; // untranslated
Blockly.Msg.MATH_TRIG_COS = "cos"; // untranslated
Blockly.Msg.MATH_TRIG_HELPURL = "https://en.wikipedia.org/wiki/Trigonometric_functions";
Blockly.Msg.MATH_TRIG_SIN = "sin"; // untranslated
Blockly.Msg.MATH_TRIG_TAN = "tan"; // untranslated
Blockly.Msg.MATH_TRIG_TOOLTIP_ACOS = "Renvoie l’arccosinus d’un nombre.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ASIN = "Renvoie l’arcsinus d’un nombre.";
Blockly.Msg.MATH_TRIG_TOOLTIP_ATAN = "Renvoie l’arctangente d’un nombre.";
Blockly.Msg.MATH_TRIG_TOOLTIP_COS = "Renvoie le cosinus d’un angle en degrés (pas en radians).";
Blockly.Msg.MATH_TRIG_TOOLTIP_SIN = "Renvoie le sinus d’un angle en degrés (pas en radians).";
Blockly.Msg.MATH_TRIG_TOOLTIP_TAN = "Renvoie la tangente d’un angle en degrés (pas en radians).";
Blockly.Msg.NEW_VARIABLE = "Nouvelle variable…";
Blockly.Msg.NEW_VARIABLE_TITLE = "Nouveau nom de la variable :";
Blockly.Msg.ORDINAL_NUMBER_SUFFIX = ""; // untranslated
Blockly.Msg.PROCEDURES_ALLOW_STATEMENTS = "autoriser les ordres";
Blockly.Msg.PROCEDURES_BEFORE_PARAMS = "avec :";
Blockly.Msg.PROCEDURES_CALLNORETURN_HELPURL = "http://fr.wikipedia.org/wiki/Proc%C3%A9dure_%28informatique%29";
Blockly.Msg.PROCEDURES_CALLNORETURN_TOOLTIP = "Exécuter la fonction '%1' définie par l’utilisateur.";
Blockly.Msg.PROCEDURES_CALLRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29";
Blockly.Msg.PROCEDURES_CALLRETURN_TOOLTIP = "Exécuter la fonction '%1' définie par l’utilisateur et utiliser son résultat.";
Blockly.Msg.PROCEDURES_CALL_BEFORE_PARAMS = "avec :";
Blockly.Msg.PROCEDURES_CREATE_DO = "Créer '%1'";
Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT = "Décrire cette fonction…";
Blockly.Msg.PROCEDURES_DEFNORETURN_DO = ""; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE = "faire quelque chose";
Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE = "pour";
Blockly.Msg.PROCEDURES_DEFNORETURN_TOOLTIP = "Crée une fonction sans sortie.";
Blockly.Msg.PROCEDURES_DEFRETURN_HELPURL = "https://en.wikipedia.org/wiki/Procedure_%28computer_science%29"; // untranslated
Blockly.Msg.PROCEDURES_DEFRETURN_RETURN = "retour";
Blockly.Msg.PROCEDURES_DEFRETURN_TOOLTIP = "Crée une fonction avec une sortie.";
Blockly.Msg.PROCEDURES_DEF_DUPLICATE_WARNING = "Attention : Cette fonction a des paramètres en double.";
Blockly.Msg.PROCEDURES_HIGHLIGHT_DEF = "Surligner la définition de la fonction";
Blockly.Msg.PROCEDURES_IFRETURN_HELPURL = "http://c2.com/cgi/wiki?GuardClause";
Blockly.Msg.PROCEDURES_IFRETURN_TOOLTIP = "Si une valeur est vraie, alors renvoyer une seconde valeur.";
Blockly.Msg.PROCEDURES_IFRETURN_WARNING = "Attention : Ce bloc pourrait n’être utilisé que dans une définition de fonction.";
Blockly.Msg.PROCEDURES_MUTATORARG_TITLE = "nom de l’entrée :";
Blockly.Msg.PROCEDURES_MUTATORARG_TOOLTIP = "Ajouter une entrée à la fonction.";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TITLE = "entrées";
Blockly.Msg.PROCEDURES_MUTATORCONTAINER_TOOLTIP = "Ajouter, supprimer, ou réarranger les entrées de cette fonction.";
Blockly.Msg.REDO = "Refaire";
Blockly.Msg.REMOVE_COMMENT = "Supprimer un commentaire";
Blockly.Msg.RENAME_VARIABLE = "Renommer la variable…";
Blockly.Msg.RENAME_VARIABLE_TITLE = "Renommer toutes les variables « %1 » en :";
Blockly.Msg.TEXT_APPEND_APPENDTEXT = "ajouter le texte";
Blockly.Msg.TEXT_APPEND_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_APPEND_TO = "à";
Blockly.Msg.TEXT_APPEND_TOOLTIP = "Ajouter du texte à la variable '%1'.";
Blockly.Msg.TEXT_CHANGECASE_HELPURL = "https://github.com/google/blockly/wiki/Text#adjusting-text-case"; // untranslated
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_LOWERCASE = "en minuscules";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_TITLECASE = "en Majuscule Au Début De Chaque Mot";
Blockly.Msg.TEXT_CHANGECASE_OPERATOR_UPPERCASE = "en MAJUSCULES";
Blockly.Msg.TEXT_CHANGECASE_TOOLTIP = "Renvoyer une copie du texte dans une autre casse.";
Blockly.Msg.TEXT_CHARAT_FIRST = "obtenir la première lettre";
Blockly.Msg.TEXT_CHARAT_FROM_END = "obtenir la lettre # depuis la fin";
Blockly.Msg.TEXT_CHARAT_FROM_START = "obtenir la lettre #";
Blockly.Msg.TEXT_CHARAT_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-text"; // untranslated
Blockly.Msg.TEXT_CHARAT_INPUT_INTEXT = "dans le texte";
Blockly.Msg.TEXT_CHARAT_LAST = "obtenir la dernière lettre";
Blockly.Msg.TEXT_CHARAT_RANDOM = "obtenir une lettre au hasard";
Blockly.Msg.TEXT_CHARAT_TAIL = ""; // untranslated
Blockly.Msg.TEXT_CHARAT_TOOLTIP = "Renvoie la lettre à la position indiquée.";
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TOOLTIP = "Ajouter un élément au texte.";
Blockly.Msg.TEXT_CREATE_JOIN_TITLE_JOIN = "joindre";
Blockly.Msg.TEXT_CREATE_JOIN_TOOLTIP = "Ajouter, supprimer, ou réordonner des sections pour reconfigurer ce bloc de texte.";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_END = "jusqu’à la lettre # depuis la fin";
Blockly.Msg.TEXT_GET_SUBSTRING_END_FROM_START = "jusqu’à la lettre #";
Blockly.Msg.TEXT_GET_SUBSTRING_END_LAST = "jusqu’à la dernière lettre";
Blockly.Msg.TEXT_GET_SUBSTRING_HELPURL = "https://github.com/google/blockly/wiki/Text#extracting-a-region-of-text"; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_INPUT_IN_TEXT = "dans le texte";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FIRST = "obtenir la sous-chaîne depuis la première lettre";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_END = "obtenir la sous-chaîne depuis la lettre # depuis la fin";
Blockly.Msg.TEXT_GET_SUBSTRING_START_FROM_START = "obtenir la sous-chaîne depuis la lettre #";
Blockly.Msg.TEXT_GET_SUBSTRING_TAIL = ""; // untranslated
Blockly.Msg.TEXT_GET_SUBSTRING_TOOLTIP = "Renvoie une partie indiquée du texte.";
Blockly.Msg.TEXT_INDEXOF_HELPURL = "https://github.com/google/blockly/wiki/Text#finding-text"; // untranslated
Blockly.Msg.TEXT_INDEXOF_INPUT_INTEXT = "dans le texte";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_FIRST = "trouver la première occurrence de la chaîne";
Blockly.Msg.TEXT_INDEXOF_OPERATOR_LAST = "trouver la dernière occurrence de la chaîne";
Blockly.Msg.TEXT_INDEXOF_TAIL = ""; // untranslated
Blockly.Msg.TEXT_INDEXOF_TOOLTIP = "Renvoie l’index de la première/dernière occurrence de la première chaîne dans la seconde. Renvoie %1 si la chaîne n’est pas trouvée.";
Blockly.Msg.TEXT_ISEMPTY_HELPURL = "https://github.com/google/blockly/wiki/Text#checking-for-empty-text"; // untranslated
Blockly.Msg.TEXT_ISEMPTY_TITLE = "%1 est vide";
Blockly.Msg.TEXT_ISEMPTY_TOOLTIP = "Renvoie vrai si le texte fourni est vide.";
Blockly.Msg.TEXT_JOIN_HELPURL = "https://github.com/google/blockly/wiki/Text#text-creation"; // untranslated
Blockly.Msg.TEXT_JOIN_TITLE_CREATEWITH = "créer un texte avec";
Blockly.Msg.TEXT_JOIN_TOOLTIP = "Créer un morceau de texte en agrégeant un nombre quelconque d’éléments.";
Blockly.Msg.TEXT_LENGTH_HELPURL = "https://github.com/google/blockly/wiki/Text#text-modification"; // untranslated
Blockly.Msg.TEXT_LENGTH_TITLE = "longueur de %1";
Blockly.Msg.TEXT_LENGTH_TOOLTIP = "Renvoie le nombre de lettres (espaces compris) dans le texte fourni.";
Blockly.Msg.TEXT_PRINT_HELPURL = "https://github.com/google/blockly/wiki/Text#printing-text"; // untranslated
Blockly.Msg.TEXT_PRINT_TITLE = "afficher %1";
Blockly.Msg.TEXT_PRINT_TOOLTIP = "Afficher le texte, le nombre ou une autre valeur spécifié.";
Blockly.Msg.TEXT_PROMPT_HELPURL = "https://github.com/google/blockly/wiki/Text#getting-input-from-the-user"; // untranslated
Blockly.Msg.TEXT_PROMPT_TOOLTIP_NUMBER = "Demander un nombre à l’utilisateur.";
Blockly.Msg.TEXT_PROMPT_TOOLTIP_TEXT = "Demander un texte à l’utilisateur.";
Blockly.Msg.TEXT_PROMPT_TYPE_NUMBER = "invite pour un nombre avec un message";
Blockly.Msg.TEXT_PROMPT_TYPE_TEXT = "invite pour un texte avec un message";
Blockly.Msg.TEXT_TEXT_HELPURL = "https://en.wikipedia.org/wiki/String_(computer_science)";
Blockly.Msg.TEXT_TEXT_TOOLTIP = "Une lettre, un mot ou une ligne de texte.";
Blockly.Msg.TEXT_TRIM_HELPURL = "https://github.com/google/blockly/wiki/Text#trimming-removing-spaces"; // untranslated
Blockly.Msg.TEXT_TRIM_OPERATOR_BOTH = "supprimer les espaces des deux côtés";
Blockly.Msg.TEXT_TRIM_OPERATOR_LEFT = "supprimer les espaces du côté gauche";
Blockly.Msg.TEXT_TRIM_OPERATOR_RIGHT = "supprimer les espaces du côté droit";
Blockly.Msg.TEXT_TRIM_TOOLTIP = "Renvoyer une copie du texte avec les espaces supprimés d’un bout ou des deux.";
Blockly.Msg.TODAY = "Aujourd'hui";
Blockly.Msg.UNDO = "Annuler";
Blockly.Msg.VARIABLES_DEFAULT_NAME = "élément";
Blockly.Msg.VARIABLES_GET_CREATE_SET = "Créer 'fixer %1'";
Blockly.Msg.VARIABLES_GET_HELPURL = "https://github.com/google/blockly/wiki/Variables#get"; // untranslated
Blockly.Msg.VARIABLES_GET_TOOLTIP = "Renvoie la valeur de cette variable.";
Blockly.Msg.VARIABLES_SET = "fixer %1 à %2";
Blockly.Msg.VARIABLES_SET_CREATE_GET = "Créer 'obtenir %1'";
Blockly.Msg.VARIABLES_SET_HELPURL = "https://github.com/google/blockly/wiki/Variables#set"; // untranslated
Blockly.Msg.VARIABLES_SET_TOOLTIP = "Fixe cette variable pour qu’elle soit égale à la valeur de l’entrée.";
Blockly.Msg.PROCEDURES_DEFRETURN_TITLE = Blockly.Msg.PROCEDURES_DEFNORETURN_TITLE;
Blockly.Msg.CONTROLS_IF_IF_TITLE_IF = Blockly.Msg.CONTROLS_IF_MSG_IF;
Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_MSG_THEN = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.CONTROLS_IF_ELSE_TITLE_ELSE = Blockly.Msg.CONTROLS_IF_MSG_ELSE;
Blockly.Msg.PROCEDURES_DEFRETURN_PROCEDURE = Blockly.Msg.PROCEDURES_DEFNORETURN_PROCEDURE;
Blockly.Msg.LISTS_GET_SUBLIST_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.LISTS_GET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.MATH_CHANGE_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.PROCEDURES_DEFRETURN_DO = Blockly.Msg.PROCEDURES_DEFNORETURN_DO;
Blockly.Msg.CONTROLS_IF_ELSEIF_TITLE_ELSEIF = Blockly.Msg.CONTROLS_IF_MSG_ELSEIF;
Blockly.Msg.LISTS_GET_INDEX_HELPURL = Blockly.Msg.LISTS_INDEX_OF_HELPURL;
Blockly.Msg.CONTROLS_FOREACH_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_SET_INDEX_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.CONTROLS_FOR_INPUT_DO = Blockly.Msg.CONTROLS_REPEAT_INPUT_DO;
Blockly.Msg.LISTS_CREATE_WITH_ITEM_TITLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_APPEND_VARIABLE = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.TEXT_CREATE_JOIN_ITEM_TITLE_ITEM = Blockly.Msg.VARIABLES_DEFAULT_NAME;
Blockly.Msg.LISTS_INDEX_OF_INPUT_IN_LIST = Blockly.Msg.LISTS_INLIST;
Blockly.Msg.PROCEDURES_DEFRETURN_COMMENT = Blockly.Msg.PROCEDURES_DEFNORETURN_COMMENT; | {'content_hash': 'd309263615ab0cc58a99fdee77bceac2', 'timestamp': '', 'source': 'github', 'line_count': 386, 'max_line_length': 255, 'avg_line_length': 79.41450777202073, 'alnum_prop': 0.7660337965681477, 'repo_name': 'TechplexEngineer/blockly', 'id': 'ededfe911a8a8c4527ac647a3d4c06bc9d9b21c6', 'size': '31211', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'msg/js/fr.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3993'}, {'name': 'JavaScript', 'bytes': '2975679'}, {'name': 'Python', 'bytes': '63334'}]} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HLTAssignment.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| {'content_hash': 'b284e7caeea3998454ea524958e37895', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 151, 'avg_line_length': 36.46666666666667, 'alnum_prop': 0.5648994515539305, 'repo_name': 'MichaelAquilina/Document-Classification', 'id': '7c0814ddc5ced483db4257de55cdbe3ae25123f4', 'size': '1096', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HLTAssignment/Properties/Settings.Designer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '166495'}]} |
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "mxfquark.h"
static const gchar *_quark_strings[] = {
"instance-uid",
"generation-uid",
"other-tags",
"tag",
"data",
"preface",
"last-modified-date",
"version",
"object-model-version",
"primary-package",
"identifications",
"content-storage",
"operational-pattern",
"essence-containers",
"dm-schemes",
"identification",
"this-generation-uid",
"company-name",
"product-name",
"product-version",
"version-string",
"product-uid",
"modification-date",
"toolkit-version",
"platform",
"packages",
"essence-container-data",
"linked-package",
"index-sid",
"body-sid",
"package-uid",
"name",
"package-creation-date",
"package-modified-date",
"tracks",
"material-package",
"source-package",
"descriptor",
"track-id",
"track-number",
"track-name",
"sequence",
"timeline-track",
"edit-rate",
"origin",
"event-track",
"event-edit-rate",
"event-origin",
"static-track",
"data-definition",
"duration",
"structural-components",
"timecode-component",
"start-timecode",
"rounded-timecode-base",
"drop-frame",
"source-clip",
"start-position",
"source-track-id",
"dm-source-clip",
"track-ids",
"dm-segment",
"event-start-position",
"event-comment",
"dm-framework",
"locators",
"file-descriptor",
"linked-track-id",
"sample-rate",
"container-duration",
"essence-container",
"codec",
"generic-picture-essence-descriptor",
"signal-standard",
"frame-layout",
"stored-width",
"stored-height",
"stored-f2-offset",
"sampled-width",
"sampled-height",
"sampled-x-offset",
"sampled-y-offset",
"display-height",
"display-width",
"display-x-offset",
"display-y-offset",
"display-f2-offset",
"aspect-ratio",
"active-format-descriptor",
"video-line-map-0",
"video-line-map-1",
"alpha-transparency",
"capture-gamma",
"image-alignment-offset",
"image-start-offset",
"image-end-offset",
"field-dominance",
"picture-essence-coding",
"cdci-picture-essence-descriptor",
"component-depth",
"horizontal-subsampling",
"vertical-subsampling",
"color-siting",
"reversed-byte-order",
"padding-bits",
"alpha-sample-depth",
"black-ref-level",
"white-ref-level",
"color-range",
"rgba-picture-essence-descriptor",
"component-max-ref",
"component-min-ref",
"alpha-max-ref",
"alpha-min-ref",
"scanning-direction",
"pixel-layout",
"generic-sound-essence-descriptor",
"audio-sampling-rate",
"locked",
"audio-ref-level",
"electro-spatial-formulation",
"channel-count",
"quantization-bits",
"dial-norm",
"sound-essence-compression",
"generic-data-essence-descriptor",
"data-essence-coding",
"multiple-descriptor",
"sub-descriptors",
"text-locator",
"locator-name",
"network-locator",
"url-string",
"wave-audio-essence-descriptor",
"block-align",
"sequence-offset",
"avg-bps",
"channel-assignment",
"peak-envelope-version",
"peak-envelope-format",
"points-per-peak-value",
"peak-envelope-block-size",
"peak-channels",
"peak-frames",
"peak-of-peaks-position",
"peak-envelope-timestamp",
"peak-envelope-data",
"aes3-audio-essence-descriptor",
"emphasis",
"block-start-offset",
"auxiliary-bits-mode",
"channel-status-mode",
"fixed-channel-status-data",
"user-data-mode",
"fixed-user-data",
"linked-timecode-track-id",
"stream-number",
"mpeg-video-descriptor",
"single-sequence",
"const-b-frames",
"coded-content-type",
"low-delay",
"closed-gop",
"identical-gop",
"max-gop",
"b-picture-count",
"bitrate",
"profile-and-level",
"filler",
};
GQuark _mxf_quark_table[MXF_QUARK_MAX];
void
mxf_quark_initialize (void)
{
gint i;
if (G_N_ELEMENTS (_quark_strings) != MXF_QUARK_MAX)
g_warning ("the quark table is not consistent! %d != %d",
(int) G_N_ELEMENTS (_quark_strings), MXF_QUARK_MAX);
for (i = 0; i < MXF_QUARK_MAX; i++) {
_mxf_quark_table[i] = g_quark_from_static_string (_quark_strings[i]);
}
}
| {'content_hash': 'f44764544f8ada7782d9d2c3d044d721', 'timestamp': '', 'source': 'github', 'line_count': 195, 'max_line_length': 73, 'avg_line_length': 20.83076923076923, 'alnum_prop': 0.6482028557360906, 'repo_name': 'google/aistreams', 'id': 'f086b3f93430af0da1889b46c9c5d0264454da04', 'size': '4898', 'binary': False, 'copies': '70', 'ref': 'refs/heads/master', 'path': 'third_party/gst-plugins-bad/gst/mxf/mxfquark.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '77741'}, {'name': 'C++', 'bytes': '626396'}, {'name': 'Python', 'bytes': '41809'}, {'name': 'Starlark', 'bytes': '56595'}]} |
<?php
namespace App\Export\FV\Import;
use App\Export\Mould\FVCampaignMould;
class CampaignExport extends FVImportExport
{
public function getType()
{
return 'campaign';
}
public function getMould()
{
return new FVCampaignMould;
}
} | {'content_hash': 'd873220b05fa80b35937615dc41dbd59', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 43, 'avg_line_length': 15.277777777777779, 'alnum_prop': 0.6618181818181819, 'repo_name': 'jocoonopa/lubri', 'id': 'd2282b21c1a54792251460c553b181c02f30f297', 'size': '275', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/Export/FV/Import/CampaignExport.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '412'}, {'name': 'CSS', 'bytes': '32689'}, {'name': 'HTML', 'bytes': '327107'}, {'name': 'JavaScript', 'bytes': '672106'}, {'name': 'PHP', 'bytes': '687582'}, {'name': 'PLpgSQL', 'bytes': '1580'}, {'name': 'PowerShell', 'bytes': '860'}, {'name': 'Shell', 'bytes': '35'}]} |
from numba import *
jitv = jit(void(), warnstyle='simple')
jitvi = jit(void(int_), warnstyle='simple')
jitvii = jit(void(int_, int_), warnstyle='simple')
jitii = jit(int_(int_), warnstyle='simple')
jitiii = jit(int_(int_, int_), warnstyle='simple')
def simple():
"""
>>> jitv(simple)
Traceback (most recent call last):
...
NumbaError: 17:10: local variable 'a' referenced before assignment
"""
print(a)
a = 0
def simple2(arg):
"""
>>> result = jitii(simple2)
Warning 27:11: local variable 'a' might be referenced before assignment
"""
if arg > 0:
a = 1
return a
def simple_pos(arg):
"""
>>> result = jitii(simple_pos)
"""
if arg > 0:
a = 1
else:
a = 0
return a
def ifelif(c1, c2):
"""
>>> result = jitiii(ifelif)
Warning 51:11: local variable 'a' might be referenced before assignment
"""
if c1 == 1:
if c2:
a = 1
else:
a = 2
elif c1 == 2:
a = 3
return a
def nowimpossible(a):
"""
>>> result = jitvi(nowimpossible)
Warning 61:14: local variable 'b' might be referenced before assignment
"""
if a:
b = 1
if a:
print(b)
def fromclosure():
"""
>> result = jitv(fromclosure)
"""
def bar():
print(a)
a = 1
return bar
# Should work ok in both py2 and py3
def list_comp(a):
return [i for i in a]
def set_comp(a):
return set(i for i in a)
#def dict_comp(a):
# return {i: j for i, j in a}
# args and kwargs
def generic_args_call(*args, **kwargs):
return args, kwargs
def cascaded(x):
print((a, b))
a = b = x
def from_import():
print(bar)
from foo import bar
def regular_import():
print(foo)
import foo
def raise_stat():
try:
raise exc(msg)
except:
pass
exc = ValueError
msg = 'dummy'
def defnode_decorator():
@decorator
def foo():
pass
def decorator():
pass
def defnode_default():
def foo(arg=default()):
pass
def default():
pass
def class_bases():
class foo(bar):
pass
class bar(object):
pass
def class_decorators():
@decorator
class foo(object):
pass
def decorator(cls):
return cls
def uninitialized_augmented_assignment():
"""
>>> func = jitv(uninitialized_augmented_assignment)
Traceback (most recent call last):
...
NumbaError: 139:4: local variable 'x' referenced before assignment
"""
x += 1
def uninitialized_augmented_assignment_loop():
"""
>>> func = jitv(uninitialized_augmented_assignment_loop)
Warning 148:8: local variable 'x' might be referenced before assignment
"""
for i in range(10):
x += 1
x = 0
if __name__ == "__main__":
import numba
numba.testing.testmod()
| {'content_hash': 'b9cfd3b049141a6c62c585fbc526ff97', 'timestamp': '', 'source': 'github', 'line_count': 154, 'max_line_length': 75, 'avg_line_length': 18.824675324675326, 'alnum_prop': 0.5584684373922042, 'repo_name': 'shiquanwang/numba', 'id': '972e3cd4a6bf5c94a6d98e77f0db1f53bbb73e5c', 'size': '2899', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'numba/control_flow/tests/test_w_uninitialized.py', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C', 'bytes': '62017'}, {'name': 'C++', 'bytes': '2247'}, {'name': 'Python', 'bytes': '1713467'}]} |
FROM balenalib/spacely-tx2-ubuntu:bionic-run
# remove several traces of debian python
RUN apt-get purge -y python.*
# http://bugs.python.org/issue19846
# > At the moment, setting "LANG=C" on a Linux system *fundamentally breaks Python 3*, and that's not OK.
ENV LANG C.UTF-8
# install python dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates \
netbase \
&& rm -rf /var/lib/apt/lists/*
# key 63C7CC90: public key "Simon McVittie <smcv@pseudorandom.co.uk>" imported
# key 3372DCFA: public key "Donald Stufft (dstufft) <donald@stufft.io>" imported
RUN gpg --keyserver keyring.debian.org --recv-keys 4DE8FF2A63C7CC90 \
&& gpg --keyserver keyserver.ubuntu.com --recv-key 6E3CBCE93372DCFA \
&& gpg --keyserver keyserver.ubuntu.com --recv-keys 0x52a43a1e4b77b059
ENV PYTHON_VERSION 3.10.2
# if this is called "PIP_VERSION", pip explodes with "ValueError: invalid truth value '<VERSION>'"
ENV PYTHON_PIP_VERSION 21.3.1
ENV SETUPTOOLS_VERSION 60.5.4
RUN set -x \
&& buildDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/python/v$PYTHON_VERSION/Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" \
&& echo "7deae9ac5659eec295be9a9e96b5846c5ba7cc39fe4768d174e1b3ec663b70e7 Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" | sha256sum -c - \
&& tar -xzf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" --strip-components=1 \
&& rm -rf "Python-$PYTHON_VERSION.linux-aarch64-libffi3.2.tar.gz" \
&& ldconfig \
&& if [ ! -e /usr/local/bin/pip3 ]; then : \
&& curl -SLO "https://raw.githubusercontent.com/pypa/get-pip/430ba37776ae2ad89f794c7a43b90dc23bac334c/get-pip.py" \
&& echo "19dae841a150c86e2a09d475b5eb0602861f2a5b7761ec268049a662dbd2bd0c get-pip.py" | sha256sum -c - \
&& python3 get-pip.py \
&& rm get-pip.py \
; fi \
&& pip3 install --no-cache-dir --upgrade --force-reinstall pip=="$PYTHON_PIP_VERSION" setuptools=="$SETUPTOOLS_VERSION" \
&& find /usr/local \
\( -type d -a -name test -o -name tests \) \
-o \( -type f -a -name '*.pyc' -o -name '*.pyo' \) \
-exec rm -rf '{}' + \
&& cd / \
&& rm -rf /usr/src/python ~/.cache
# make some useful symlinks that are expected to exist
RUN cd /usr/local/bin \
&& ln -sf pip3 pip \
&& { [ -e easy_install ] || ln -s easy_install-* easy_install; } \
&& ln -sf idle3 idle \
&& ln -sf pydoc3 pydoc \
&& ln -sf python3 python \
&& ln -sf python3-config python-config
# set PYTHONPATH to point to dist-packages
ENV PYTHONPATH /usr/lib/python3/dist-packages:$PYTHONPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@python.sh" \
&& echo "Running test-stack@python" \
&& chmod +x test-stack@python.sh \
&& bash test-stack@python.sh \
&& rm -rf test-stack@python.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v8 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nPython v3.10.2, Pip v21.3.1, Setuptools v60.5.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {'content_hash': '8379c2b77cd852adebe192215ef2c139', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 709, 'avg_line_length': 51.88461538461539, 'alnum_prop': 0.7079318013343218, 'repo_name': 'resin-io-library/base-images', 'id': 'da45c2b30d4a8c545f9dbd54ba54562ea7dde7c3', 'size': '4068', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/python/spacely-tx2/ubuntu/bionic/3.10.2/run/Dockerfile', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '71234697'}, {'name': 'JavaScript', 'bytes': '13096'}, {'name': 'Shell', 'bytes': '12051936'}, {'name': 'Smarty', 'bytes': '59789'}]} |
DECLARE_bool(enable_cublas_tensor_op_math);
namespace phi {
namespace funcs {
template <typename T>
struct CUBlas;
template <>
struct CUBlas<float> {
template <typename... ARGS>
static void GEMM(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_sgemm(args...));
}
template <typename... ARGS>
static void AXPY(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_saxpy(args...));
}
template <typename... ARGS>
static void SCAL(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_sscal(args...));
}
template <typename... ARGS>
static void VCOPY(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_scopy(args...));
}
template <typename... ARGS>
static void GEMV(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_sgemv(args...));
}
template <typename... ARGS>
static void GEMM_STRIDED_BATCH(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_sgemm_strided_batched(args...));
}
// HIP not supportted, refer to the doc here:
// https://github.com/ROCm-Developer-Tools/HIP/blob/roc-3.5.x/docs/markdown/CUBLAS_API_supported_by_HIP.md
template <typename... ARGS>
static void GEMM_EX(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasSgemmEx is not supported on HIP platform."));
}
template <typename... ARGS>
static void TRSM(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_strsm(args...));
}
template <typename... ARGS>
static void GETRF_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasSgetrfBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void GETRI_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasSgetriBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void MATINV_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasSmatinvBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void TRSM_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasStrsmBatched is not supported on HIP platform."));
}
};
template <>
struct CUBlas<double> {
template <typename... ARGS>
static void GEMM(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_dgemm(args...));
}
template <typename... ARGS>
static void AXPY(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_daxpy(args...));
}
template <typename... ARGS>
static void SCAL(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_dscal(args...));
}
template <typename... ARGS>
static void VCOPY(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_dcopy(args...));
}
template <typename... ARGS>
static void GEMV(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_dgemv(args...));
}
template <typename... ARGS>
static void GEMM_STRIDED_BATCH(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_dgemm_strided_batched(args...));
}
template <typename... ARGS>
static void GEMM_EX(ARGS... args) {
PADDLE_THROW(
phi::errors::Unimplemented("Currently there are not cublasDgemmEx."));
}
template <typename... ARGS>
static void TRSM(ARGS... args) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_dtrsm(args...));
}
template <typename... ARGS>
static void GETRF_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasDgetrfBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void GETRI_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasDgetriBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void MATINV_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasDmatinvBatched is not supported on HIP platform."));
}
template <typename... ARGS>
static void TRSM_BATCH(ARGS... args) {
PADDLE_THROW(phi::errors::Unimplemented(
"cublasDtrsmBatched is not supported on HIP platform."));
}
};
template <>
struct CUBlas<phi::dtype::float16> {
using float16 = phi::dtype::float16;
static void GEMM(rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const float16 *alpha,
const float16 *A,
int lda,
const float16 *B,
int ldb,
const float16 *beta,
float16 *C,
int ldc) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_hgemm(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_half *>(alpha),
reinterpret_cast<const rocblas_half *>(A),
lda,
reinterpret_cast<const rocblas_half *>(B),
ldb,
reinterpret_cast<const rocblas_half *>(beta),
reinterpret_cast<rocblas_half *>(C),
ldc));
}
static void GEMM_STRIDED_BATCH(rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const float16 *alpha,
const float16 *A,
int lda,
long long int strideA, // NOLINT
const float16 *B, // NOLINT
int ldb,
long long int strideB, // NOLINT
const float16 *beta,
float16 *C,
int ldc,
long long int strideC, // NOLINT
int batchCount) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_hgemm_strided_batched(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_half *>(alpha),
reinterpret_cast<const rocblas_half *>(A),
lda,
strideA,
reinterpret_cast<const rocblas_half *>(B),
ldb,
strideB,
reinterpret_cast<const rocblas_half *>(beta),
reinterpret_cast<rocblas_half *>(C),
ldc,
strideC,
batchCount));
}
// NOTES: GEMM_EX can use Tensor Core to accelerate matrix multiply.
// https://docs.nvidia.com/cuda/cublas/index.html#cublassetmathmode
template <typename... ARGS>
static void GEMM_EX(phi::GPUContext *dev_ctx,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const void *alpha,
const void *A,
rocblas_datatype Atype,
int lda,
const void *B,
rocblas_datatype Btype,
int ldb,
const void *beta,
void *C,
rocblas_datatype Ctype,
int ldc,
rocblas_datatype computeType) {
rocblas_gemm_algo algo = rocblas_gemm_algo_standard;
dev_ctx->TensorCoreCublasCallIfAvailable([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_gemm_ex(handle,
transa,
transb,
m,
n,
k,
alpha,
A,
Atype,
lda,
B,
Btype,
ldb,
beta,
C,
Ctype,
ldc,
C,
Ctype,
ldc,
computeType,
algo,
0,
0));
});
}
};
template <>
struct CUBlas<phi::dtype::complex<float>> {
static void GEMV(rocblas_handle handle,
rocblas_operation transa,
int m,
int n,
const phi::dtype::complex<float> *alpha,
const phi::dtype::complex<float> *A,
int lda,
const phi::dtype::complex<float> *B,
int ldb,
const phi::dtype::complex<float> *beta,
phi::dtype::complex<float> *C,
int ldc) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_cgemv(
handle,
transa,
m,
n,
reinterpret_cast<const rocblas_float_complex *>(alpha),
reinterpret_cast<const rocblas_float_complex *>(A),
lda,
reinterpret_cast<const rocblas_float_complex *>(B),
ldb,
reinterpret_cast<const rocblas_float_complex *>(beta),
reinterpret_cast<rocblas_float_complex *>(C),
ldc));
}
static void AXPY(rocblas_handle handle,
int n,
const phi::dtype::complex<float> *alpha,
const phi::dtype::complex<float> *X,
const int incX,
phi::dtype::complex<float> *Y,
const int incY) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_caxpy(
handle,
n,
reinterpret_cast<const rocblas_float_complex *>(alpha),
reinterpret_cast<const rocblas_float_complex *>(X),
incX,
reinterpret_cast<rocblas_float_complex *>(Y),
incY));
}
static void GEMM_STRIDED_BATCH(rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const phi::dtype::complex<float> *alpha,
const phi::dtype::complex<float> *A,
int lda,
long long int strideA, // NOLINT
const phi::dtype::complex<float> *B, // NOLINT
int ldb,
long long int strideB, // NOLINT
const phi::dtype::complex<float> *beta,
phi::dtype::complex<float> *C,
int ldc,
long long int strideC, // NOLINT
int batchCount) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_cgemm_strided_batched(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_float_complex *>(alpha),
reinterpret_cast<const rocblas_float_complex *>(A),
lda,
strideA,
reinterpret_cast<const rocblas_float_complex *>(B),
ldb,
strideB,
reinterpret_cast<const rocblas_float_complex *>(beta),
reinterpret_cast<rocblas_float_complex *>(C),
ldc,
strideC,
batchCount));
}
static void GEMM(rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const phi::dtype::complex<float> *alpha,
const phi::dtype::complex<float> *A,
int lda,
const phi::dtype::complex<float> *B,
int ldb,
const phi::dtype::complex<float> *beta,
phi::dtype::complex<float> *C,
int ldc) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_cgemm(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_float_complex *>(alpha),
reinterpret_cast<const rocblas_float_complex *>(A),
lda,
reinterpret_cast<const rocblas_float_complex *>(B),
ldb,
reinterpret_cast<const rocblas_float_complex *>(beta),
reinterpret_cast<rocblas_float_complex *>(C),
ldc));
}
// NOTES: GEMM_EX can use Tensor Core to accelerate matrix multiply.
// https://docs.nvidia.com/cuda/cublas/index.html#cublassetmathmode
template <typename... ARGS>
static void GEMM_EX(phi::GPUContext *dev_ctx,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const void *alpha,
const void *A,
rocblas_datatype Atype,
int lda,
const void *B,
rocblas_datatype Btype,
int ldb,
const void *beta,
void *C,
rocblas_datatype Ctype,
int ldc,
rocblas_datatype computeType) {
rocblas_gemm_algo algo = rocblas_gemm_algo_standard;
dev_ctx->TensorCoreCublasCallIfAvailable([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_gemm_ex(handle,
transa,
transb,
m,
n,
k,
alpha,
A,
Atype,
lda,
B,
Btype,
ldb,
beta,
C,
Ctype,
ldc,
C,
Ctype,
ldc,
computeType,
algo,
0,
0));
});
}
};
template <>
struct CUBlas<phi::dtype::complex<double>> {
static void GEMV(rocblas_handle handle,
rocblas_operation transa,
int m,
int n,
const phi::dtype::complex<double> *alpha,
const phi::dtype::complex<double> *A,
int lda,
const phi::dtype::complex<double> *B,
int ldb,
const phi::dtype::complex<double> *beta,
phi::dtype::complex<double> *C,
int ldc) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_zgemv(
handle,
transa,
m,
n,
reinterpret_cast<const rocblas_double_complex *>(alpha),
reinterpret_cast<const rocblas_double_complex *>(A),
lda,
reinterpret_cast<const rocblas_double_complex *>(B),
ldb,
reinterpret_cast<const rocblas_double_complex *>(beta),
reinterpret_cast<rocblas_double_complex *>(C),
ldc));
}
static void AXPY(rocblas_handle handle,
int n,
const phi::dtype::complex<double> *alpha,
const phi::dtype::complex<double> *X,
const int incX,
phi::dtype::complex<double> *Y,
const int incY) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_zaxpy(
handle,
n,
reinterpret_cast<const rocblas_double_complex *>(alpha),
reinterpret_cast<const rocblas_double_complex *>(X),
incX,
reinterpret_cast<rocblas_double_complex *>(Y),
incY));
}
static void GEMM_STRIDED_BATCH(
rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const phi::dtype::complex<double> *alpha,
const phi::dtype::complex<double> *A,
int lda,
long long int strideA, // NOLINT
const phi::dtype::complex<double> *B, // NOLINT
int ldb,
long long int strideB, // NOLINT
const phi::dtype::complex<double> *beta,
phi::dtype::complex<double> *C,
int ldc,
long long int strideC, // NOLINT
int batchCount) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_zgemm_strided_batched(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_double_complex *>(alpha),
reinterpret_cast<const rocblas_double_complex *>(A),
lda,
strideA,
reinterpret_cast<const rocblas_double_complex *>(B),
ldb,
strideB,
reinterpret_cast<const rocblas_double_complex *>(beta),
reinterpret_cast<rocblas_double_complex *>(C),
ldc,
strideC,
batchCount));
}
static void GEMM(rocblas_handle handle,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const phi::dtype::complex<double> *alpha,
const phi::dtype::complex<double> *A,
int lda,
const phi::dtype::complex<double> *B,
int ldb,
const phi::dtype::complex<double> *beta,
phi::dtype::complex<double> *C,
int ldc) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_zgemm(
handle,
transa,
transb,
m,
n,
k,
reinterpret_cast<const rocblas_double_complex *>(alpha),
reinterpret_cast<const rocblas_double_complex *>(A),
lda,
reinterpret_cast<const rocblas_double_complex *>(B),
ldb,
reinterpret_cast<const rocblas_double_complex *>(beta),
reinterpret_cast<rocblas_double_complex *>(C),
ldc));
}
// NOTES: GEMM_EX can use Tensor Core to accelerate matrix multiply.
// https://docs.nvidia.com/cuda/cublas/index.html#cublassetmathmode
template <typename... ARGS>
static void GEMM_EX(phi::GPUContext *dev_ctx,
rocblas_operation transa,
rocblas_operation transb,
int m,
int n,
int k,
const void *alpha,
const void *A,
rocblas_datatype Atype,
int lda,
const void *B,
rocblas_datatype Btype,
int ldb,
const void *beta,
void *C,
rocblas_datatype Ctype,
int ldc,
rocblas_datatype computeType) {
rocblas_gemm_algo algo = rocblas_gemm_algo_standard;
dev_ctx->TensorCoreCublasCallIfAvailable([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::rocblas_gemm_ex(handle,
transa,
transb,
m,
n,
k,
alpha,
A,
Atype,
lda,
B,
Btype,
ldb,
beta,
C,
Ctype,
ldc,
C,
Ctype,
ldc,
computeType,
algo,
0,
0));
});
}
};
template <>
template <typename T>
void Blas<phi::GPUContext>::GEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
T alpha,
const T *A,
const T *B,
T beta,
T *C) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GEMM(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
A,
lda,
&beta,
C,
N);
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::float16 alpha,
const phi::dtype::float16 *A,
const phi::dtype::float16 *B,
phi::dtype::float16 beta,
phi::dtype::float16 *C) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
// TODO(kexinzhao): add processing code for compute capability < 53 case
PADDLE_ENFORCE_GE(
context_.GetComputeCapability(),
53,
phi::errors::InvalidArgument(
"cublas fp16 gemm requires GPU compute capability >= 53,"
"but received %d",
context_.GetComputeCapability()));
float h_alpha = static_cast<float>(alpha);
float h_beta = static_cast<float>(beta);
auto &cuda_ctx = const_cast<phi::GPUContext &>(context_);
CUBlas<phi::dtype::float16>::GEMM_EX(&cuda_ctx,
cuTransB,
cuTransA,
N,
M,
K,
&h_alpha,
B,
rocblas_datatype_f16_r,
ldb,
A,
rocblas_datatype_f16_r,
lda,
&h_beta,
C,
rocblas_datatype_f16_r,
N,
rocblas_datatype_f32_r);
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::bfloat16 alpha,
const phi::dtype::bfloat16 *A,
const phi::dtype::bfloat16 *B,
phi::dtype::bfloat16 beta,
phi::dtype::bfloat16 *C) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
// TODO(zhiqiu): 80 has the same meaning for rocm and cuda?
PADDLE_ENFORCE_GE(
context_.GetComputeCapability(),
80,
phi::errors::InvalidArgument(
"rocblas fp16 gemm requires GPU compute capability >= 80,"
"but received %d",
context_.GetComputeCapability()));
float h_alpha = static_cast<float>(alpha);
float h_beta = static_cast<float>(beta);
rocblas_gemm_algo algo = rocblas_gemm_algo_standard;
context_.TensorCoreCublasCallIfAvailable([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_gemm_ex(handle,
cuTransB,
cuTransA,
N,
M,
K,
&h_alpha,
B,
rocblas_datatype_bf16_r,
ldb,
A,
rocblas_datatype_bf16_r,
lda,
&h_beta,
C,
rocblas_datatype_bf16_r,
N,
C,
rocblas_datatype_bf16_r,
N,
rocblas_datatype_f32_r,
algo,
0,
0));
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::complex<float> alpha,
const phi::dtype::complex<float> *A,
const phi::dtype::complex<float> *B,
phi::dtype::complex<float> beta,
phi::dtype::complex<float> *C) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
// TODO(kexinzhao): add processing code for compute capability < 53 case
PADDLE_ENFORCE_GE(
context_.GetComputeCapability(),
53,
phi::errors::InvalidArgument(
"cublas complex64 gemm requires GPU compute capability >= 53,"
"but received %d",
context_.GetComputeCapability()));
thrust::complex<float> c_alpha =
thrust::complex<float>(alpha.real, alpha.imag);
thrust::complex<float> c_beta = thrust::complex<float>(beta.real, beta.imag);
auto &cuda_ctx = const_cast<phi::GPUContext &>(context_);
CUBlas<phi::dtype::complex<float>>::GEMM_EX(&cuda_ctx,
cuTransB,
cuTransA,
N,
M,
K,
&c_alpha,
B,
rocblas_datatype_f32_c,
ldb,
A,
rocblas_datatype_f32_c,
lda,
&c_beta,
C,
rocblas_datatype_f32_c,
N,
rocblas_datatype_f32_c);
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::complex<double> alpha,
const phi::dtype::complex<double> *A,
const phi::dtype::complex<double> *B,
phi::dtype::complex<double> beta,
phi::dtype::complex<double> *C) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
// TODO(kexinzhao): add processing code for compute capability < 53 case
PADDLE_ENFORCE_GE(
context_.GetComputeCapability(),
53,
phi::errors::InvalidArgument(
"cublas complex128 gemm requires GPU compute capability >= 53,"
"but received %d",
context_.GetComputeCapability()));
thrust::complex<double> c_alpha =
thrust::complex<double>(alpha.real, alpha.imag);
thrust::complex<double> c_beta =
thrust::complex<double>(beta.real, beta.imag);
auto &cuda_ctx = const_cast<phi::GPUContext &>(context_);
CUBlas<phi::dtype::complex<double>>::GEMM_EX(&cuda_ctx,
cuTransB,
cuTransA,
N,
M,
K,
&c_alpha,
B,
rocblas_datatype_f64_c,
ldb,
A,
rocblas_datatype_f64_c,
lda,
&c_beta,
C,
rocblas_datatype_f64_c,
N,
rocblas_datatype_f64_c);
}
template <>
template <typename T>
void Blas<phi::GPUContext>::GEMM(bool transA,
bool transB,
int M,
int N,
int K,
T alpha,
const T *A,
int lda,
const T *B,
int ldb,
T beta,
T *C,
int ldc) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
rocblas_operation cuTransA =
transA ? rocblas_operation_transpose : rocblas_operation_none;
rocblas_operation cuTransB =
transB ? rocblas_operation_transpose : rocblas_operation_none;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GEMM(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
A,
lda,
&beta,
C,
ldc);
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMM(bool transA,
bool transB,
int M,
int N,
int K,
phi::dtype::float16 alpha,
const phi::dtype::float16 *A,
int lda,
const phi::dtype::float16 *B,
int ldb,
phi::dtype::float16 beta,
phi::dtype::float16 *C,
int ldc) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
rocblas_operation cuTransA =
transA ? rocblas_operation_transpose : rocblas_operation_none;
rocblas_operation cuTransB =
transB ? rocblas_operation_transpose : rocblas_operation_none;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<phi::dtype::float16>::GEMM(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
A,
lda,
&beta,
C,
ldc);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::AXPY(int n, T alpha, const T *x, T *y) const {
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::AXPY(handle, n, &alpha, x, 1, y, 1);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::SCAL(int n, const T alpha, T *x) const {
context_.CublasCall(
[&](rocblas_handle handle) { CUBlas<T>::SCAL(handle, n, &alpha, x, 1); });
}
template <>
template <typename T>
void Blas<phi::GPUContext>::VCOPY(int n, const T *x, T *y) const {
context_.CublasCall(
[&](rocblas_handle handle) { CUBlas<T>::VCOPY(handle, n, x, 1, y, 1); });
}
template <>
template <typename T>
void Blas<phi::GPUContext>::GEMV(bool trans_a,
int M,
int N,
T alpha,
const T *A,
const T *B,
T beta,
T *C) const {
rocblas_operation cuTransA =
!trans_a ? rocblas_operation_transpose : rocblas_operation_none;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GEMV(handle, cuTransA, N, M, &alpha, A, N, B, 1, &beta, C, 1);
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMV(bool trans_a,
int M,
int N,
phi::dtype::float16 alpha,
const phi::dtype::float16 *A,
const phi::dtype::float16 *B,
phi::dtype::float16 beta,
phi::dtype::float16 *C) const {
// Because cublas doesn't support half gemv, we use cublasHgemm to achieve it.
if (trans_a) {
this->template GEMM<phi::dtype::float16>(
CblasNoTrans, CblasNoTrans, 1, N, M, alpha, B, A, beta, C);
} else {
this->template GEMM<phi::dtype::float16>(
CblasNoTrans, CblasNoTrans, M, 1, N, alpha, A, B, beta, C);
}
}
template <>
template <>
inline void Blas<phi::GPUContext>::GEMV(bool trans_a,
int M,
int N,
phi::dtype::bfloat16 alpha,
const phi::dtype::bfloat16 *A,
const phi::dtype::bfloat16 *B,
phi::dtype::bfloat16 beta,
phi::dtype::bfloat16 *C) const {
// Because rocblas doesn't support bfloat16 gemv, we use gemmex to achieve it.
if (trans_a) {
this->template GEMM<phi::dtype::bfloat16>(
CblasNoTrans, CblasNoTrans, 1, N, M, alpha, B, A, beta, C);
} else {
this->template GEMM<phi::dtype::bfloat16>(
CblasNoTrans, CblasNoTrans, M, 1, N, alpha, A, B, beta, C);
}
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
T alpha,
const T *A,
const T *B,
T beta,
T *C,
int batchCount,
int64_t strideA,
int64_t strideB) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
int ldc = N;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
const int64_t strideC = M * N;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GEMM_STRIDED_BATCH(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
strideB,
A,
lda,
strideA,
&beta,
C,
ldc,
strideC,
batchCount);
});
}
// note(wangran16): unknown bug. parameters dislocation when calling
// GEMM_STRIDED_BATCH<float> and GEMM_STRIDED_BATCH<double>
template <>
template <>
inline void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
float alpha,
const float *A,
const float *B,
float beta,
float *C,
int batchCount,
int64_t strideA,
int64_t strideB) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
int ldc = N;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
const int64_t strideC = M * N;
context_.CublasCall([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_sgemm_strided_batched(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
strideB,
A,
lda,
strideA,
&beta,
C,
ldc,
strideC,
batchCount));
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
double alpha,
const double *A,
const double *B,
double beta,
double *C,
int batchCount,
int64_t strideA,
int64_t strideB) const {
// Note that cublas follows fortran order, so the order is different from
// the cblas convention.
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
int ldc = N;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
const int64_t strideC = M * N;
context_.CublasCall([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_dgemm_strided_batched(handle,
cuTransB,
cuTransA,
N,
M,
K,
&alpha,
B,
ldb,
strideB,
A,
lda,
strideA,
&beta,
C,
ldc,
strideC,
batchCount));
});
}
template <>
template <>
inline void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::bfloat16 alpha,
const phi::dtype::bfloat16 *A,
const phi::dtype::bfloat16 *B,
phi::dtype::bfloat16 beta,
phi::dtype::bfloat16 *C,
int batchCount,
int64_t strideA,
int64_t strideB) const {
int lda = (transA == CblasNoTrans) ? K : M;
int ldb = (transB == CblasNoTrans) ? N : K;
int ldc = N;
const int64_t strideC = M * N;
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_operation cuTransB = (transB == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
float h_alpha = static_cast<float>(alpha);
float h_beta = static_cast<float>(beta);
rocblas_gemm_algo algo = rocblas_gemm_algo_standard;
context_.TensorCoreCublasCallIfAvailable([&](rocblas_handle handle) {
PADDLE_ENFORCE_GPU_SUCCESS(
phi::dynload::rocblas_gemm_strided_batched_ex(handle,
cuTransB,
cuTransA,
N,
M,
K,
&h_alpha,
B,
rocblas_datatype_bf16_r,
ldb,
strideB,
A,
rocblas_datatype_bf16_r,
lda,
strideA,
&h_beta,
C,
rocblas_datatype_bf16_r,
ldc,
strideC,
C,
rocblas_datatype_bf16_r,
ldc,
strideC,
batchCount,
rocblas_datatype_f32_r,
algo,
0,
0));
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
T alpha,
const T **A,
const T **B,
T beta,
T **C,
int batchCount) const {
for (int k = 0; k < batchCount; ++k) {
this->template GEMM<T>(
transA, transB, M, N, K, alpha, A[k], B[k], beta, C[k]);
}
}
template <>
template <>
inline void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::float16 alpha,
const phi::dtype::float16 **A,
const phi::dtype::float16 **B,
phi::dtype::float16 beta,
phi::dtype::float16 **C,
int batchCount) const {
for (int k = 0; k < batchCount; ++k) {
this->template GEMM<phi::dtype::float16>(
transA, transB, M, N, K, alpha, A[k], B[k], beta, C[k]);
}
}
template <>
template <>
inline void Blas<phi::GPUContext>::BatchedGEMM(CBLAS_TRANSPOSE transA,
CBLAS_TRANSPOSE transB,
int M,
int N,
int K,
phi::dtype::bfloat16 alpha,
const phi::dtype::bfloat16 **A,
const phi::dtype::bfloat16 **B,
phi::dtype::bfloat16 beta,
phi::dtype::bfloat16 **C,
int batchCount) const {
for (int k = 0; k < batchCount; ++k) {
this->template GEMM<phi::dtype::bfloat16>(
transA, transB, M, N, K, alpha, A[k], B[k], beta, C[k]);
}
}
template <>
template <typename T>
void Blas<phi::GPUContext>::TRSM(CBLAS_SIDE side,
CBLAS_UPLO uplo,
CBLAS_TRANSPOSE transA,
CBLAS_DIAG diag,
int M,
int N,
T alpha,
const T *A,
int lda,
T *B,
int ldb) const {
// solve row major `op ( A ) X = α B` by taking it as `X' op ( A' ) = α B'`
// where ' stands for transpose
rocblas_side cuSide =
(side == CblasLeft) ? rocblas_side_right : rocblas_side_left;
rocblas_fill cuUplo =
(uplo == CblasLower) ? rocblas_fill_upper : rocblas_fill_lower;
// use CUBLAS_OP_C (conjugate transpose) for complex
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_diagonal cuDiag =
(diag == CblasUnit) ? rocblas_diagonal_unit : rocblas_diagonal_non_unit;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::TRSM(
handle, cuSide, cuUplo, cuTransA, cuDiag, N, M, &alpha, A, lda, B, ldb);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedGETRF(
int n, T **a, int *ipiv, int *info, int batch_size) const {
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GETRF_BATCH(handle, n, a, n, ipiv, info, batch_size);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedGETRI(int n,
const T **a,
const int *ipiv,
T **a_inv,
int *info,
int batch_size) const {
PADDLE_ENFORCE_NE(
a_inv,
a,
phi::errors::InvalidArgument(
"cuBLAS fuction 'cublas<S/D>getrfBatched' cannot be executed "
"in-place. The memory space of output matrix (address: %p) cannot "
"overlap memory space of input matrix (address: %p).",
a_inv,
a));
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GETRI_BATCH(handle, n, a, n, ipiv, a_inv, n, info, batch_size);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedMatInv(
int n, const T **a, T **a_inv, int *info, int batch_size) const {
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::MATINV_BATCH(handle, n, a, n, a_inv, n, info, batch_size);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedGETRS(CBLAS_TRANSPOSE trans,
int n,
int nrhs,
const T **a,
int lda,
int *ipiv,
T **b,
int ldb,
int *info,
int batch_size) const {
rocblas_operation cuTrans = (trans == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::GETRS_BATCH(
handle, cuTrans, n, nrhs, a, lda, ipiv, b, ldb, info, batch_size);
});
}
template <>
template <typename T>
void Blas<phi::GPUContext>::BatchedTRSM(CBLAS_SIDE side,
CBLAS_UPLO uplo,
CBLAS_TRANSPOSE transA,
CBLAS_DIAG diag,
int M,
int N,
T alpha,
const T **A,
int lda,
T **B,
int ldb,
int batch_size) const {
// solve row major `op ( A ) X = α B` by taking it as `X' op ( A' ) = α B'`
// where ' stands for transpose
rocblas_side cuSide =
(side == CblasLeft) ? rocblas_side_right : rocblas_side_left;
rocblas_fill cuUplo =
(uplo == CblasLower) ? rocblas_fill_upper : rocblas_fill_lower;
// use CUBLAS_OP_C (conjugate transpose) for complex
rocblas_operation cuTransA = (transA == CblasNoTrans)
? rocblas_operation_none
: rocblas_operation_transpose;
rocblas_diagonal cuDiag =
(diag == CblasUnit) ? rocblas_diagonal_unit : rocblas_diagonal_non_unit;
context_.CublasCall([&](rocblas_handle handle) {
CUBlas<T>::TRSM_BATCH(handle,
cuSide,
cuUplo,
cuTransA,
cuDiag,
N,
M,
&alpha,
A,
lda,
B,
ldb,
batch_size);
});
}
} // namespace funcs
} // namespace phi
| {'content_hash': 'c54363776f605c983616401d12250677', 'timestamp': '', 'source': 'github', 'line_count': 1452, 'max_line_length': 108, 'avg_line_length': 41.72314049586777, 'alnum_prop': 0.3808391931596844, 'repo_name': 'luotao1/Paddle', 'id': 'cbde4fdbc819bc58055116982299c9f0687c47fe', 'size': '61432', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'paddle/phi/kernels/funcs/blas/blas_impl.hip.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '58544'}, {'name': 'C', 'bytes': '210300'}, {'name': 'C++', 'bytes': '36771446'}, {'name': 'CMake', 'bytes': '903079'}, {'name': 'Cuda', 'bytes': '5200715'}, {'name': 'Dockerfile', 'bytes': '4361'}, {'name': 'Go', 'bytes': '49796'}, {'name': 'Java', 'bytes': '16630'}, {'name': 'Jinja', 'bytes': '23852'}, {'name': 'MLIR', 'bytes': '39982'}, {'name': 'Python', 'bytes': '36248258'}, {'name': 'R', 'bytes': '1332'}, {'name': 'Shell', 'bytes': '553175'}]} |
$ErrorActionPreference = 'Stop';
$packageArgs = @{
packageName = 'gimp'
fileType = 'exe'
softwareName = 'GIMP'
checksum = 'a2e52129a28feec1ee3f22f5aaf9bdecbb02d51af6da408ace0a2ac2e0365c8b'
checksum64 = 'a2e52129a28feec1ee3f22f5aaf9bdecbb02d51af6da408ace0a2ac2e0365c8b'
checksumType = 'sha256'
checksumType64 = 'sha256'
# The installer contains both 32-bit and 64-bit versions of GIMP, and will automatically use the appropriate one.
# Text quoted from <https://www.gimp.org/downloads/>, look below download buttons.
url = 'https://download.gimp.org/mirror/pub/gimp/v2.8/windows/gimp-2.8.22-setup.exe'
url64bit = 'https://download.gimp.org/mirror/pub/gimp/v2.8/windows/gimp-2.8.22-setup.exe'
silentArgs = '/VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SP-'
validExitCodes = @(0)
}
$version = '2.8.22'
$gimpRegistryPath = $(
'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\GIMP-2_is1'
)
if (Test-Path $gimpRegistryPath) {
$installedVersion = (
Get-ItemProperty -Path $gimpRegistryPath -Name 'DisplayVersion'
).DisplayVersion
}
if ($installedVersion -eq $version) {
Write-Output $(
"GIMP $installedVersion is already installed. " +
"Skipping download and installation."
)
} else {
Install-ChocolateyPackage @packageArgs
}
| {'content_hash': 'a6fe7d3be5c6197e555e563fc24ef816', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 115, 'avg_line_length': 34.02564102564103, 'alnum_prop': 0.7136397889977393, 'repo_name': 'octomike/chocolatey-coreteampackages', 'id': 'bd722ea6db338077a3f3c6cc20dfecc5f8d7e147', 'size': '1329', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'automatic/gimp/tools/chocolateyInstall.ps1', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AutoHotkey', 'bytes': '4068'}, {'name': 'AutoIt', 'bytes': '2948'}, {'name': 'Batchfile', 'bytes': '1155'}, {'name': 'JavaScript', 'bytes': '2517'}, {'name': 'PowerShell', 'bytes': '534978'}, {'name': 'Shell', 'bytes': '311'}, {'name': 'XSLT', 'bytes': '2253'}]} |
using LiveScoreUpdateSystem.Data.Models.FootballFixtures;
using LiveScoreUpdateSystem.Services.Common;
using LiveScoreUpdateSystem.Services.Common.Contracts;
using LiveScoreUpdateSystem.Services.Data.Contracts;
using LiveScoreUpdateSystem.Web.Areas.Admin.Controllers.Grids;
using LiveScoreUpdateSystem.Web.Areas.Admin.Models;
using Moq;
using NUnit.Framework;
using System;
using TestStack.FluentMVCTesting;
namespace LiveScoreUpdateSystem.Web.Tests.Areas.Admin.Grids.LeaguesGridControllerTests
{
[TestFixture]
public class EditLeague_Should
{
[Test]
public void CallCountryServiceUpdateMethodWithCOrrectMappedCountryDateModel_WhenPassedModelParamIsNotNull()
{
// arrange
var leagueService = new Mock<ILeagueService>();
var leagueViewModel = new GridLeagueViewModel() { Name = "someName" };
var mapService = new Mock<IMappingService>();
var leagueDataModel = new League() { Name = "someName" };
mapService.Setup(c => c.Map<League>(It.IsAny<Object>()))
.Returns(leagueDataModel);
MappingService.MappingProvider = mapService.Object;
var controller = new LeaguesGridController(leagueService.Object);
// act
controller.EditLeague(leagueViewModel);
// assert
leagueService.Verify(c => c.Update(leagueDataModel), Times.Once);
}
[Test]
public void ReturnJsonArrayWithTheEditedCountry_WhenPassedModelParamIsNotNull()
{
// arrange
var leagueService = new Mock<ILeagueService>();
var leagueViewModel = new GridLeagueViewModel() { Name = "someName" };
var mapService = new Mock<IMappingService>();
var leagueDataModel = new League() { Name = "someName" };
mapService.Setup(c => c.Map<League>(It.IsAny<Object>()))
.Returns(leagueDataModel);
MappingService.MappingProvider = mapService.Object;
var controller = new LeaguesGridController(leagueService.Object);
// act
controller.EditLeague(leagueViewModel);
// assert
controller.WithCallTo(c => c.EditLeague(leagueViewModel))
.ShouldReturnJson((data) => Assert.AreSame(data[0], leagueViewModel));
}
}
}
| {'content_hash': '64ffa90eb51da6b60459cae067d0c3ef', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 115, 'avg_line_length': 37.0, 'alnum_prop': 0.6587837837837838, 'repo_name': 'BorislavBorisov22/LiveScoreUpdateSystem', 'id': '51ed49bdcddf5c6ca6b56a05f1994314bad0140a', 'size': '2370', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LiveScoreUpdateSystem/LiveScoreUpdateSystem.Web.Tests/Areas/Admin/Controllers/Grids/LeaguesGridControllerTests/EditLeague_Should.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '116'}, {'name': 'C#', 'bytes': '404671'}, {'name': 'CSS', 'bytes': '189596'}, {'name': 'JavaScript', 'bytes': '152987'}]} |
'use strict';
import 'vs/css!./media/fileactions';
import { TPromise } from 'vs/base/common/winjs.base';
import nls = require('vs/nls');
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
import { sequence, ITask } from 'vs/base/common/async';
import paths = require('vs/base/common/paths');
import URI from 'vs/base/common/uri';
import errors = require('vs/base/common/errors');
import { toErrorMessage } from 'vs/base/common/errorMessage';
import strings = require('vs/base/common/strings');
import { EventType as CommonEventType } from 'vs/base/common/events';
import severity from 'vs/base/common/severity';
import diagnostics = require('vs/base/common/diagnostics');
import { Action, IAction } from 'vs/base/common/actions';
import { MessageType, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
import { ITree, IHighlightEvent } from 'vs/base/parts/tree/browser/tree';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { VIEWLET_ID } from 'vs/workbench/parts/files/common/files';
import labels = require('vs/base/common/labels');
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { IFileService, IFileStat } from 'vs/platform/files/common/files';
import { toResource, IEditorIdentifier, EditorInput } from 'vs/workbench/common/editor';
import { FileStat, NewStatPlaceholder } from 'vs/workbench/parts/files/common/explorerViewModel';
import { ExplorerView } from 'vs/workbench/parts/files/browser/views/explorerView';
import { ExplorerViewlet } from 'vs/workbench/parts/files/browser/explorerViewlet';
import { IActionProvider } from 'vs/base/parts/tree/browser/actionsRenderer';
import { IUntitledEditorService } from 'vs/workbench/services/untitled/common/untitledEditorService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { CollapseAction } from 'vs/workbench/browser/viewlet';
import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding';
import { IEditorGroupService } from 'vs/workbench/services/group/common/groupService';
import { IQuickOpenService, IFilePickOpenEntry } from 'vs/platform/quickOpen/common/quickOpen';
import { IHistoryService } from 'vs/workbench/services/history/common/history';
import { IViewletService } from 'vs/workbench/services/viewlet/browser/viewlet';
import { Position, IResourceInput, IEditorInput } from 'vs/platform/editor/common/editor';
import { IInstantiationService, IConstructorSignature2, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IMessageService, IMessageWithAction, IConfirmation, Severity, CancelAction } from 'vs/platform/message/common/message';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { Keybinding, KeyMod, KeyCode } from 'vs/base/common/keyCodes';
import { getCodeEditor } from 'vs/editor/common/services/codeEditorService';
import { IEditorViewState } from 'vs/editor/common/editorCommon';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { ITextModelResolverService } from 'vs/editor/common/services/resolverService';
export interface IEditableData {
action: IAction;
validator: IInputValidator;
}
export interface IFileViewletState {
actionProvider: IActionProvider;
getEditableData(stat: IFileStat): IEditableData;
setEditable(stat: IFileStat, editableData: IEditableData): void;
clearEditable(stat: IFileStat): void;
}
export class BaseFileAction extends Action {
private _element: FileStat;
constructor(
id: string,
label: string,
@IFileService private _fileService: IFileService,
@IMessageService private _messageService: IMessageService,
@ITextFileService private _textFileService: ITextFileService
) {
super(id, label);
this.enabled = false;
}
public get messageService() {
return this._messageService;
}
public get fileService() {
return this._fileService;
}
public get textFileService() {
return this._textFileService;
}
public get element() {
return this._element;
}
public set element(element: FileStat) {
this._element = element;
}
_isEnabled(): boolean {
return true;
}
_updateEnablement(): void {
this.enabled = !!(this._fileService && this._isEnabled());
}
protected onError(error: any): void {
this._messageService.show(Severity.Error, error);
}
protected onWarning(warning: any): void {
this._messageService.show(Severity.Warning, warning);
}
protected onErrorWithRetry(error: any, retry: () => TPromise<any>, extraAction?: Action): void {
const actions = [
new Action(this.id, nls.localize('retry', "Retry"), null, true, () => retry()),
CancelAction
];
if (extraAction) {
actions.unshift(extraAction);
}
const errorWithRetry: IMessageWithAction = {
actions,
message: toErrorMessage(error, false)
};
this._messageService.show(Severity.Error, errorWithRetry);
}
}
export class TriggerRenameFileAction extends BaseFileAction {
public static ID = 'workbench.files.action.triggerRename';
private tree: ITree;
private renameAction: BaseRenameAction;
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService,
@IInstantiationService instantiationService: IInstantiationService
) {
super(TriggerRenameFileAction.ID, nls.localize('rename', "Rename"), fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
this.renameAction = instantiationService.createInstance(RenameFileAction, element);
this._updateEnablement();
}
public validateFileName(parent: IFileStat, name: string): string {
return this.renameAction.validateFileName(this.element.parent, name);
}
public run(context?: any): TPromise<any> {
if (!context) {
return TPromise.wrapError('No context provided to BaseEnableFileRenameAction.');
}
const viewletState = <IFileViewletState>context.viewletState;
if (!viewletState) {
return TPromise.wrapError('Invalid viewlet state provided to BaseEnableFileRenameAction.');
}
const stat = <IFileStat>context.stat;
if (!stat) {
return TPromise.wrapError('Invalid stat provided to BaseEnableFileRenameAction.');
}
viewletState.setEditable(stat, {
action: this.renameAction,
validator: (value) => {
const message = this.validateFileName(this.element.parent, value);
if (!message) {
return null;
}
return {
content: message,
formatContent: true,
type: MessageType.ERROR
};
}
});
this.tree.refresh(stat, false).then(() => {
this.tree.setHighlight(stat);
const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
if (!e.highlight) {
viewletState.clearEditable(stat);
this.tree.refresh(stat).done(null, errors.onUnexpectedError);
unbind.dispose();
}
});
}).done(null, errors.onUnexpectedError);
}
}
export abstract class BaseRenameAction extends BaseFileAction {
constructor(
id: string,
label: string,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(id, label, fileService, messageService, textFileService);
this.element = element;
}
public run(context?: any): TPromise<any> {
if (!context) {
return TPromise.wrapError('No context provided to BaseRenameFileAction.');
}
let name = <string>context.value;
if (!name) {
return TPromise.wrapError('No new name provided to BaseRenameFileAction.');
}
// Automatically trim whitespaces and trailing dots to produce nice file names
name = getWellFormedFileName(name);
const existingName = getWellFormedFileName(this.element.name);
// Return early if name is invalid or didn't change
if (name === existingName || this.validateFileName(this.element.parent, name)) {
return TPromise.as(null);
}
// Call function and Emit Event through viewer
const promise = this.runAction(name).then(null, (error: any) => {
this.onError(error);
});
return promise;
}
public validateFileName(parent: IFileStat, name: string): string {
let source = this.element.name;
let target = name;
if (!isLinux) { // allow rename of same file also when case differs (e.g. Game.js => game.js)
source = source.toLowerCase();
target = target.toLowerCase();
}
if (getWellFormedFileName(source) === getWellFormedFileName(target)) {
return null;
}
return validateFileName(parent, name, false);
}
public abstract runAction(newName: string): TPromise<any>;
}
class RenameFileAction extends BaseRenameAction {
public static ID = 'workbench.files.action.renameFile';
constructor(
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService,
@ITextModelResolverService private textModelResolverService: ITextModelResolverService,
@IBackupFileService private backupFileService: IBackupFileService
) {
super(RenameFileAction.ID, nls.localize('rename', "Rename"), element, fileService, messageService, textFileService);
this._updateEnablement();
}
public runAction(newName: string): TPromise<any> {
// 1. check for dirty files that are being moved and backup to new target
const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, this.element.resource.fsPath));
const dirtyRenamed: URI[] = [];
return TPromise.join(dirty.map(d => {
const targetPath = paths.join(this.element.parent.resource.fsPath, newName);
let renamed: URI;
// If the dirty file itself got moved, just reparent it to the target folder
if (this.element.resource.fsPath === d.fsPath) {
renamed = URI.file(targetPath);
}
// Otherwise, a parent of the dirty resource got moved, so we have to reparent more complicated. Example:
else {
renamed = URI.file(paths.join(targetPath, d.fsPath.substr(this.element.resource.fsPath.length + 1)));
}
dirtyRenamed.push(renamed);
const model = this.textFileService.models.get(d);
return this.backupFileService.backupResource(renamed, model.getValue(), model.getVersionId());
}))
// 2. soft revert all dirty since we have backed up their contents
.then(() => this.textFileService.revertAll(dirty, { soft: true /* do not attempt to load content from disk */ }))
// 3.) run the rename operation
.then(() => this.fileService.rename(this.element.resource, newName).then(null, (error: Error) => {
return TPromise.join(dirtyRenamed.map(d => this.backupFileService.discardResourceBackup(d))).then(() => {
this.onErrorWithRetry(error, () => this.runAction(newName));
});
}))
// 4.) resolve those that were dirty to load their previous dirty contents from disk
.then(() => {
return TPromise.join(dirtyRenamed.map(t => this.textModelResolverService.createModelReference(t)));
});
}
}
/* Base New File/Folder Action */
export class BaseNewAction extends BaseFileAction {
private presetFolder: FileStat;
private tree: ITree;
private isFile: boolean;
private renameAction: BaseRenameAction;
constructor(
id: string,
label: string,
tree: ITree,
isFile: boolean,
editableAction: BaseRenameAction,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(id, label, fileService, messageService, textFileService);
if (element) {
this.presetFolder = element.isDirectory ? element : element.parent;
}
this.tree = tree;
this.isFile = isFile;
this.renameAction = editableAction;
}
public run(context?: any): TPromise<any> {
if (!context) {
return TPromise.wrapError('No context provided to BaseNewAction.');
}
const viewletState = <IFileViewletState>context.viewletState;
if (!viewletState) {
return TPromise.wrapError('Invalid viewlet state provided to BaseNewAction.');
}
let folder: FileStat = this.presetFolder;
if (!folder) {
const focus = <FileStat>this.tree.getFocus();
if (focus) {
folder = focus.isDirectory ? focus : focus.parent;
} else {
folder = this.tree.getInput();
}
}
if (!folder) {
return TPromise.wrapError('Invalid parent folder to create.');
}
return this.tree.reveal(folder, 0.5).then(() => {
return this.tree.expand(folder).then(() => {
const stat = NewStatPlaceholder.addNewStatPlaceholder(folder, !this.isFile);
this.renameAction.element = stat;
viewletState.setEditable(stat, {
action: this.renameAction,
validator: (value) => {
const message = this.renameAction.validateFileName(folder, value);
if (!message) {
return null;
}
return {
content: message,
formatContent: true,
type: MessageType.ERROR
};
}
});
return this.tree.refresh(folder).then(() => {
return this.tree.expand(folder).then(() => {
return this.tree.reveal(stat, 0.5).then(() => {
this.tree.setHighlight(stat);
const unbind = this.tree.addListener2(CommonEventType.HIGHLIGHT, (e: IHighlightEvent) => {
if (!e.highlight) {
stat.destroy();
this.tree.refresh(folder).done(null, errors.onUnexpectedError);
unbind.dispose();
}
});
});
});
});
});
});
}
}
/* New File */
export class NewFileAction extends BaseNewAction {
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService,
@IInstantiationService instantiationService: IInstantiationService
) {
super('workbench.action.files.newFile', nls.localize('newFile', "New File"), tree, true, instantiationService.createInstance(CreateFileAction, element), null, fileService, messageService, textFileService);
this.class = 'explorer-action new-file';
this._updateEnablement();
}
}
/* New Folder */
export class NewFolderAction extends BaseNewAction {
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService,
@IInstantiationService instantiationService: IInstantiationService
) {
super('workbench.action.files.newFolder', nls.localize('newFolder', "New Folder"), tree, false, instantiationService.createInstance(CreateFolderAction, element), null, fileService, messageService, textFileService);
this.class = 'explorer-action new-folder';
this._updateEnablement();
}
}
export abstract class BaseGlobalNewAction extends Action {
private toDispose: Action;
constructor(
id: string,
label: string,
@IViewletService private viewletService: IViewletService,
@IInstantiationService private instantiationService: IInstantiationService,
@IMessageService private messageService: IMessageService
) {
super(id, label);
}
public run(): TPromise<any> {
return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet) => {
return TPromise.timeout(100).then(() => { // use a timeout to prevent the explorer from revealing the active file
viewlet.focus();
const explorer = <ExplorerViewlet>viewlet;
const explorerView = explorer.getExplorerView();
// Not having a folder opened
if (!explorerView) {
return this.messageService.show(Severity.Info, nls.localize('openFolderFirst', "Open a folder first to create files or folders within."));
}
if (!explorerView.isExpanded()) {
explorerView.expand();
}
const action = this.toDispose = this.instantiationService.createInstance(this.getAction(), explorerView.getViewer(), null);
return explorer.getActionRunner().run(action);
});
});
}
protected abstract getAction(): IConstructorSignature2<ITree, IFileStat, Action>;
public dispose(): void {
super.dispose();
if (this.toDispose) {
this.toDispose.dispose();
this.toDispose = null;
}
}
}
/* Create new file from anywhere: Open untitled */
export class GlobalNewUntitledFileAction extends Action {
public static ID = 'workbench.action.files.newUntitledFile';
public static LABEL = nls.localize('newUntitledFile', "New Untitled File");
constructor(
id: string,
label: string,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService
) {
super(id, label);
}
public run(): TPromise<any> {
const input = this.untitledEditorService.createOrGet();
return this.editorService.openEditor(input, { pinned: true }); // untitled are always pinned
}
}
/* Create new file from anywhere */
export class GlobalNewFileAction extends BaseGlobalNewAction {
public static ID = 'workbench.action.files.newFile';
public static LABEL = nls.localize('newFile', "New File");
protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
return NewFileAction;
}
}
/* Create new folder from anywhere */
export class GlobalNewFolderAction extends BaseGlobalNewAction {
public static ID = 'workbench.action.files.newFolder';
public static LABEL = nls.localize('newFolder', "New Folder");
protected getAction(): IConstructorSignature2<ITree, IFileStat, Action> {
return NewFolderAction;
}
}
/* Create New File/Folder (only used internally by explorerViewer) */
export abstract class BaseCreateAction extends BaseRenameAction {
public validateFileName(parent: IFileStat, name: string): string {
if (this.element instanceof NewStatPlaceholder) {
return validateFileName(parent, name, false);
}
return super.validateFileName(parent, name);
}
}
/* Create New File (only used internally by explorerViewer) */
export class CreateFileAction extends BaseCreateAction {
public static ID = 'workbench.files.action.createFileFromExplorer';
public static LABEL = nls.localize('createNewFile', "New File");
constructor(
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(CreateFileAction.ID, CreateFileAction.LABEL, element, fileService, messageService, textFileService);
this._updateEnablement();
}
public runAction(fileName: string): TPromise<any> {
return this.fileService.createFile(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
this.onErrorWithRetry(error, () => this.runAction(fileName));
});
}
}
/* Create New Folder (only used internally by explorerViewer) */
export class CreateFolderAction extends BaseCreateAction {
public static ID = 'workbench.files.action.createFolderFromExplorer';
public static LABEL = nls.localize('createNewFolder', "New Folder");
constructor(
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(CreateFolderAction.ID, CreateFolderAction.LABEL, null, fileService, messageService, textFileService);
this._updateEnablement();
}
public runAction(fileName: string): TPromise<any> {
return this.fileService.createFolder(URI.file(paths.join(this.element.parent.resource.fsPath, fileName))).then(null, (error) => {
this.onErrorWithRetry(error, () => this.runAction(fileName));
});
}
}
export class BaseDeleteFileAction extends BaseFileAction {
private tree: ITree;
private useTrash: boolean;
private skipConfirm: boolean;
constructor(
id: string,
label: string,
tree: ITree,
element: FileStat,
useTrash: boolean,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(id, label, fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
this.useTrash = useTrash && !paths.isUNC(element.resource.fsPath); // on UNC shares there is no trash
this._updateEnablement();
}
public run(context?: any): TPromise<any> {
// Remove highlight
if (this.tree) {
this.tree.clearHighlight();
}
// Read context
if (context && context.event) {
const bypassTrash = (isMacintosh && context.event.altKey) || (!isMacintosh && context.event.shiftKey);
if (bypassTrash) {
this.useTrash = false;
}
}
let primaryButton: string;
if (this.useTrash) {
primaryButton = isWindows ? nls.localize('deleteButtonLabelRecycleBin', "&&Move to Recycle Bin") : nls.localize({ key: 'deleteButtonLabelTrash', comment: ['&& denotes a mnemonic'] }, "&&Move to Trash");
} else {
primaryButton = nls.localize({ key: 'deleteButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Delete");
}
// Handle dirty
let revertPromise: TPromise<any> = TPromise.as(null);
const dirty = this.textFileService.getDirty().filter(d => paths.isEqualOrParent(d.fsPath, this.element.resource.fsPath));
if (dirty.length) {
let message: string;
if (this.element.isDirectory) {
if (dirty.length === 1) {
message = nls.localize('dirtyMessageFolderOneDelete', "You are deleting a folder with unsaved changes in 1 file. Do you want to continue?");
} else {
message = nls.localize('dirtyMessageFolderDelete', "You are deleting a folder with unsaved changes in {0} files. Do you want to continue?", dirty.length);
}
} else {
message = nls.localize('dirtyMessageFileDelete', "You are deleting a file with unsaved changes. Do you want to continue?");
}
const res = this.messageService.confirm({
message,
type: 'warning',
detail: nls.localize('dirtyWarning', "Your changes will be lost if you don't save them."),
primaryButton
});
if (!res) {
return TPromise.as(null);
}
this.skipConfirm = true; // since we already asked for confirmation
revertPromise = this.textFileService.revertAll(dirty);
}
// Check if file is dirty in editor and save it to avoid data loss
return revertPromise.then(() => {
// Ask for Confirm
if (!this.skipConfirm) {
let confirm: IConfirmation;
if (this.useTrash) {
confirm = {
message: this.element.isDirectory ? nls.localize('confirmMoveTrashMessageFolder', "Are you sure you want to delete '{0}' and its contents?", this.element.name) : nls.localize('confirmMoveTrashMessageFile', "Are you sure you want to delete '{0}'?", this.element.name),
detail: isWindows ? nls.localize('undoBin', "You can restore from the recycle bin.") : nls.localize('undoTrash', "You can restore from the trash."),
primaryButton
};
} else {
confirm = {
message: this.element.isDirectory ? nls.localize('confirmDeleteMessageFolder', "Are you sure you want to permanently delete '{0}' and its contents?", this.element.name) : nls.localize('confirmDeleteMessageFile', "Are you sure you want to permanently delete '{0}'?", this.element.name),
detail: nls.localize('irreversible', "This action is irreversible!"),
primaryButton
};
}
if (!this.messageService.confirm(confirm)) {
return TPromise.as(null);
}
}
// Call function
const servicePromise = this.fileService.del(this.element.resource, this.useTrash).then(() => {
if (this.element.parent) {
this.tree.setFocus(this.element.parent); // move focus to parent
}
}, (error: any) => {
// Allow to retry
let extraAction: Action;
if (this.useTrash) {
extraAction = new Action('permanentDelete', nls.localize('permDelete', "Delete Permanently"), null, true, () => { this.useTrash = false; this.skipConfirm = true; return this.run(); });
}
this.onErrorWithRetry(error, () => this.run(), extraAction);
// Focus back to tree
this.tree.DOMFocus();
});
return servicePromise;
});
}
}
/* Move File/Folder to trash */
export class MoveFileToTrashAction extends BaseDeleteFileAction {
public static ID = 'workbench.files.action.moveFileToTrash';
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(MoveFileToTrashAction.ID, nls.localize('delete', "Delete"), tree, element, true, fileService, messageService, textFileService);
}
}
/* Import File */
export class ImportFileAction extends BaseFileAction {
public static ID = 'workbench.files.action.importFile';
private tree: ITree;
constructor(
tree: ITree,
element: FileStat,
clazz: string,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(ImportFileAction.ID, nls.localize('importFiles', "Import Files"), fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
if (clazz) {
this.class = clazz;
}
this._updateEnablement();
}
public getViewer(): ITree {
return this.tree;
}
public run(context?: any): TPromise<any> {
const importPromise = TPromise.as(null).then(() => {
const input = context.input;
if (input.files && input.files.length > 0) {
// Find parent for import
let targetElement: FileStat;
if (this.element) {
targetElement = this.element;
} else {
targetElement = this.tree.getFocus() || this.tree.getInput();
}
if (!targetElement.isDirectory) {
targetElement = targetElement.parent;
}
// Create real files array
const filesArray: File[] = [];
for (let i = 0; i < input.files.length; i++) {
const file = input.files[i];
filesArray.push(file);
}
// Resolve target to check for name collisions and ask user
return this.fileService.resolveFile(targetElement.resource).then((targetStat: IFileStat) => {
// Check for name collisions
const targetNames: { [name: string]: IFileStat } = {};
targetStat.children.forEach((child) => {
targetNames[isLinux ? child.name : child.name.toLowerCase()] = child;
});
let overwrite = true;
if (filesArray.some((file) => {
return !!targetNames[isLinux ? file.name : file.name.toLowerCase()];
})) {
const confirm: IConfirmation = {
message: nls.localize('confirmOverwrite', "A file or folder with the same name already exists in the destination folder. Do you want to replace it?"),
detail: nls.localize('irreversible', "This action is irreversible!"),
primaryButton: nls.localize({ key: 'replaceButtonLabel', comment: ['&& denotes a mnemonic'] }, "&&Replace")
};
overwrite = this.messageService.confirm(confirm);
}
if (!overwrite) {
return;
}
// Run import in sequence
const importPromisesFactory: ITask<TPromise<void>>[] = [];
filesArray.forEach(file => {
importPromisesFactory.push(() => {
const sourceFile = URI.file(file.path);
const targetFile = URI.file(paths.join(targetElement.resource.fsPath, paths.basename(file.path)));
// if the target exists and is dirty, make sure to revert it. otherwise the dirty contents
// of the target file would replace the contents of the imported file. since we already
// confirmed the overwrite before, this is OK.
let revertPromise = TPromise.as(null);
if (this.textFileService.isDirty(targetFile)) {
revertPromise = this.textFileService.revertAll([targetFile], { soft: true });
}
return revertPromise.then(() => {
return this.fileService.importFile(sourceFile, targetElement.resource).then(null, (error: any) => {
this.messageService.show(Severity.Error, error);
});
});
});
});
return sequence(importPromisesFactory);
});
}
});
return importPromise.then(() => {
this.tree.clearHighlight();
}, (error: any) => {
this.onError(error);
this.tree.clearHighlight();
});
}
}
// Copy File/Folder
let fileToCopy: FileStat;
export class CopyFileAction extends BaseFileAction {
public static ID = 'workbench.files.action.copyFile';
private tree: ITree;
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super(CopyFileAction.ID, nls.localize('copyFile', "Copy"), fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
this._updateEnablement();
}
public run(): TPromise<any> {
// Remember as file/folder to copy
fileToCopy = this.element;
// Remove highlight
if (this.tree) {
this.tree.clearHighlight();
}
this.tree.DOMFocus();
return TPromise.as(null);
}
}
// Paste File/Folder
export class PasteFileAction extends BaseFileAction {
public static ID = 'workbench.files.action.pasteFile';
private tree: ITree;
constructor(
tree: ITree,
element: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService,
@IInstantiationService private instantiationService: IInstantiationService
) {
super(PasteFileAction.ID, nls.localize('pasteFile', "Paste"), fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
this._updateEnablement();
}
_isEnabled(): boolean {
// Need at least a file to copy
if (!fileToCopy) {
return false;
}
// Check if file was deleted or moved meanwhile
const root: FileStat = this.tree.getInput();
const exists = root.find(fileToCopy.resource);
if (!exists) {
fileToCopy = null;
return false;
}
// Check if target is ancestor of pasted folder
if (this.element.resource.toString() !== fileToCopy.resource.toString() && paths.isEqualOrParent(this.element.resource.fsPath, fileToCopy.resource.fsPath)) {
return false;
}
return true;
}
public run(): TPromise<any> {
// Find target
let target: FileStat;
if (this.element.resource.toString() === fileToCopy.resource.toString()) {
target = this.element.parent;
} else {
target = this.element.isDirectory ? this.element : this.element.parent;
}
// Reuse duplicate action
const pasteAction = this.instantiationService.createInstance(DuplicateFileAction, this.tree, fileToCopy, target);
return pasteAction.run().then(() => {
this.tree.DOMFocus();
});
}
}
// Duplicate File/Folder
export class DuplicateFileAction extends BaseFileAction {
private tree: ITree;
private target: IFileStat;
constructor(
tree: ITree,
element: FileStat,
target: FileStat,
@IFileService fileService: IFileService,
@IMessageService messageService: IMessageService,
@ITextFileService textFileService: ITextFileService
) {
super('workbench.files.action.duplicateFile', nls.localize('duplicateFile', "Duplicate"), fileService, messageService, textFileService);
this.tree = tree;
this.element = element;
this.target = (target && target.isDirectory) ? target : element.parent;
this._updateEnablement();
}
public run(): TPromise<any> {
// Remove highlight
if (this.tree) {
this.tree.clearHighlight();
}
// Copy File
const result = this.fileService.copyFile(this.element.resource, this.findTarget()).then(null, (error: any) => {
this.onError(error);
});
return result;
}
public onError(error: any): void {
this.messageService.show(Severity.Error, error);
}
private findTarget(): URI {
const root: FileStat = this.tree.getInput();
let name = this.element.name;
let candidate = URI.file(paths.join(this.target.resource.fsPath, name));
while (true) {
if (!root.find(candidate)) {
break;
}
name = this.toCopyName(name, this.element.isDirectory);
candidate = URI.file(paths.join(this.target.resource.fsPath, name));
}
return candidate;
}
private toCopyName(name: string, isFolder: boolean): string {
// file.1.txt=>file.2.txt
if (!isFolder && name.match(/(\d+)(\..*)$/)) {
return name.replace(/(\d+)(\..*)$/, (match, g1?, g2?) => { return (parseInt(g1) + 1) + g2; });
}
// file.txt=>file.1.txt
const lastIndexOfDot = name.lastIndexOf('.');
if (!isFolder && lastIndexOfDot >= 0) {
return strings.format('{0}.1{1}', name.substr(0, lastIndexOfDot), name.substr(lastIndexOfDot));
}
// folder.1=>folder.2
if (isFolder && name.match(/(\d+)$/)) {
return name.replace(/(\d+)$/, (match: string, ...groups: any[]) => { return String(parseInt(groups[0]) + 1); });
}
// file/folder=>file.1/folder.1
return strings.format('{0}.1', name);
}
}
// Open to the side
export class OpenToSideAction extends Action {
public static ID = 'workbench.files.action.openToSide';
public static LABEL = nls.localize('openToSide', "Open to the Side");
private tree: ITree;
private resource: URI;
private preserveFocus: boolean;
constructor(
tree: ITree,
resource: URI,
preserveFocus: boolean,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
super(OpenToSideAction.ID, OpenToSideAction.LABEL);
this.tree = tree;
this.preserveFocus = preserveFocus;
this.resource = resource;
this.updateEnablement();
}
private updateEnablement(): void {
const activeEditor = this.editorService.getActiveEditor();
this.enabled = (!activeEditor || activeEditor.position !== Position.THREE);
}
public run(): TPromise<any> {
// Remove highlight
this.tree.clearHighlight();
// Set side input
return this.editorService.openEditor({
resource: this.resource,
options: {
preserveFocus: this.preserveFocus
}
}, true);
}
}
let globalResourceToCompare: URI;
export class SelectResourceForCompareAction extends Action {
private resource: URI;
private tree: ITree;
constructor(resource: URI, tree: ITree) {
super('workbench.files.action.selectForCompare', nls.localize('compareSource', "Select for Compare"));
this.tree = tree;
this.resource = resource;
this.enabled = true;
}
public run(): TPromise<any> {
// Remember as source file to compare
globalResourceToCompare = this.resource;
// Remove highlight
if (this.tree) {
this.tree.clearHighlight();
this.tree.DOMFocus();
}
return TPromise.as(null);
}
}
// Global Compare with
export class GlobalCompareResourcesAction extends Action {
public static ID = 'workbench.files.action.compareFileWith';
public static LABEL = nls.localize('globalCompareFile', "Compare Active File With...");
constructor(
id: string,
label: string,
@IQuickOpenService private quickOpenService: IQuickOpenService,
@IInstantiationService private instantiationService: IInstantiationService,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IHistoryService private historyService: IHistoryService,
@IWorkspaceContextService private contextService: IWorkspaceContextService,
@IMessageService private messageService: IMessageService
) {
super(id, label);
}
public run(): TPromise<any> {
const activeResource = toResource(this.editorService.getActiveEditorInput(), { filter: ['file', 'untitled'] });
if (activeResource) {
// Keep as resource to compare
globalResourceToCompare = activeResource;
// Pick another entry from history
interface IHistoryPickEntry extends IFilePickOpenEntry {
input: IEditorInput | IResourceInput;
}
const history = this.historyService.getHistory();
const picks: IHistoryPickEntry[] = history.map(input => {
let resource: URI;
let label: string;
let description: string;
if (input instanceof EditorInput) {
resource = toResource(input, { filter: ['file', 'untitled'] });
} else {
resource = (input as IResourceInput).resource;
}
if (!resource) {
return void 0; // only support to compare with files and untitled
}
label = paths.basename(resource.fsPath);
description = resource.scheme === 'file' ? labels.getPathLabel(paths.dirname(resource.fsPath), this.contextService) : void 0;
return <IHistoryPickEntry>{ input, resource, label, description };
}).filter(p => !!p);
return this.quickOpenService.pick(picks, { placeHolder: nls.localize('pickHistory', "Select a previously opened file to compare with"), autoFocus: { autoFocusFirstEntry: true }, matchOnDescription: true }).then(pick => {
if (pick) {
const compareAction = this.instantiationService.createInstance(CompareResourcesAction, pick.resource, null);
if (compareAction._isEnabled()) {
compareAction.run().done(() => compareAction.dispose());
} else {
this.messageService.show(Severity.Info, nls.localize('unableToFileToCompare', "The selected file can not be compared with '{0}'.", paths.basename(globalResourceToCompare.fsPath)));
}
}
});
} else {
this.messageService.show(Severity.Info, nls.localize('openFileToCompare', "Open a file first to compare it with another file."));
}
return TPromise.as(true);
}
}
// Compare with Resource
export class CompareResourcesAction extends Action {
private tree: ITree;
private resource: URI;
constructor(
resource: URI,
tree: ITree,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService
) {
super('workbench.files.action.compareFiles', CompareResourcesAction.computeLabel());
this.tree = tree;
this.resource = resource;
}
private static computeLabel(): string {
if (globalResourceToCompare) {
return nls.localize('compareWith', "Compare with '{0}'", paths.basename(globalResourceToCompare.fsPath));
}
return nls.localize('compareFiles', "Compare Files");
}
public getLabel(): string {
return CompareResourcesAction.computeLabel();
}
_isEnabled(): boolean {
// Need at least a resource to compare
if (!globalResourceToCompare) {
return false;
}
// Check if file was deleted or moved meanwhile (explorer only)
if (this.tree) {
const root: FileStat = this.tree.getInput();
if (root instanceof FileStat) {
const exists = root.find(globalResourceToCompare);
if (!exists) {
globalResourceToCompare = null;
return false;
}
}
}
// Check if target is identical to source
if (this.resource.toString() === globalResourceToCompare.toString()) {
return false;
}
return true;
}
public run(): TPromise<any> {
// Remove highlight
if (this.tree) {
this.tree.clearHighlight();
}
return this.editorService.openEditor({
leftResource: globalResourceToCompare,
rightResource: this.resource
});
}
}
// Refresh Explorer Viewer
export class RefreshViewExplorerAction extends Action {
constructor(explorerView: ExplorerView, clazz: string) {
super('workbench.files.action.refreshFilesExplorer', nls.localize('refresh', "Refresh"), clazz, true, (context: any) => explorerView.refresh());
}
}
export abstract class BaseActionWithErrorReporting extends Action {
constructor(
id: string,
label: string,
private messageService: IMessageService
) {
super(id, label);
}
public run(context?: any): TPromise<boolean> {
return this.doRun(context).then(() => true, (error) => {
this.messageService.show(Severity.Error, toErrorMessage(error, false));
});
}
protected abstract doRun(context?: any): TPromise<boolean>;
}
export abstract class BaseSaveFileAction extends BaseActionWithErrorReporting {
private resource: URI;
constructor(
id: string,
label: string,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
@IMessageService messageService: IMessageService
) {
super(id, label, messageService);
this.enabled = true;
}
public abstract isSaveAs(): boolean;
public setResource(resource: URI): void {
this.resource = resource;
}
protected doRun(context: any): TPromise<boolean> {
let source: URI;
if (this.resource) {
source = this.resource;
} else {
source = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: ['file', 'untitled'] });
}
if (source) {
// Save As (or Save untitled with associated path)
if (this.isSaveAs() || source.scheme === 'untitled') {
let encodingOfSource: string;
if (source.scheme === 'untitled') {
encodingOfSource = this.untitledEditorService.get(source).getEncoding();
} else if (source.scheme === 'file') {
const textModel = this.textFileService.models.get(source);
encodingOfSource = textModel && textModel.getEncoding(); // text model can be null e.g. if this is a binary file!
}
let viewStateOfSource: IEditorViewState;
const activeEditor = this.editorService.getActiveEditor();
const editor = getCodeEditor(activeEditor);
if (editor) {
const activeResource = toResource(activeEditor.input, { supportSideBySide: true, filter: ['file', 'untitled'] });
if (activeResource && activeResource.toString() === source.toString()) {
viewStateOfSource = editor.saveViewState();
}
}
// Special case: an untitled file with associated path gets saved directly unless "saveAs" is true
let savePromise: TPromise<URI>;
if (!this.isSaveAs() && source.scheme === 'untitled' && this.untitledEditorService.hasAssociatedFilePath(source)) {
savePromise = this.textFileService.save(source).then((result) => {
if (result) {
return URI.file(source.fsPath);
}
return null;
});
}
// Otherwise, really "Save As..."
else {
savePromise = this.textFileService.saveAs(source);
}
return savePromise.then((target) => {
if (!target || target.toString() === source.toString()) {
return; // save canceled or same resource used
}
const replaceWith: IResourceInput = {
resource: target,
encoding: encodingOfSource,
options: {
pinned: true,
viewState: viewStateOfSource
}
};
return this.editorService.replaceEditors([{
toReplace: { resource: source },
replaceWith
}]).then(() => true);
});
}
// Just save
return this.textFileService.save(source, { force: true /* force a change to the file to trigger external watchers if any */ });
}
return TPromise.as(false);
}
}
export class SaveFileAction extends BaseSaveFileAction {
public static ID = 'workbench.action.files.save';
public static LABEL = nls.localize('save', "Save");
public isSaveAs(): boolean {
return false;
}
}
export class SaveFileAsAction extends BaseSaveFileAction {
public static ID = 'workbench.action.files.saveAs';
public static LABEL = nls.localize('saveAs', "Save As...");
public isSaveAs(): boolean {
return true;
}
}
export abstract class BaseSaveAllAction extends BaseActionWithErrorReporting {
private toDispose: IDisposable[];
private lastIsDirty: boolean;
constructor(
id: string,
label: string,
@IWorkbenchEditorService protected editorService: IWorkbenchEditorService,
@IEditorGroupService private editorGroupService: IEditorGroupService,
@ITextFileService private textFileService: ITextFileService,
@IUntitledEditorService private untitledEditorService: IUntitledEditorService,
@IMessageService messageService: IMessageService
) {
super(id, label, messageService);
this.toDispose = [];
this.lastIsDirty = this.textFileService.isDirty();
this.enabled = this.lastIsDirty;
this.registerListeners();
}
protected abstract getSaveAllArguments(context?: any): any;
protected abstract includeUntitled(): boolean;
private registerListeners(): void {
// listen to files being changed locally
this.toDispose.push(this.textFileService.models.onModelsDirty(e => this.updateEnablement(true)));
this.toDispose.push(this.textFileService.models.onModelsSaved(e => this.updateEnablement(false)));
this.toDispose.push(this.textFileService.models.onModelsReverted(e => this.updateEnablement(false)));
this.toDispose.push(this.textFileService.models.onModelsSaveError(e => this.updateEnablement(true)));
if (this.includeUntitled()) {
this.toDispose.push(this.untitledEditorService.onDidChangeDirty(resource => this.updateEnablement(this.untitledEditorService.isDirty(resource))));
}
}
private updateEnablement(isDirty: boolean): void {
if (this.lastIsDirty !== isDirty) {
this.enabled = this.textFileService.isDirty();
this.lastIsDirty = this.enabled;
}
}
protected doRun(context: any): TPromise<boolean> {
const stacks = this.editorGroupService.getStacksModel();
// Store some properties per untitled file to restore later after save is completed
const mapUntitledToProperties: { [resource: string]: { encoding: string; indexInGroups: number[]; activeInGroups: boolean[] } } = Object.create(null);
this.textFileService.getDirty()
.filter(r => r.scheme === 'untitled') // All untitled resources
.map(r => this.untitledEditorService.get(r)) // Mapped to their inputs
.filter(input => !!input) // If possible :)
.forEach(input => {
mapUntitledToProperties[input.getResource().toString()] = {
encoding: input.getEncoding(),
indexInGroups: stacks.groups.map(g => g.indexOf(input)),
activeInGroups: stacks.groups.map(g => g.isActive(input))
};
});
// Save all
return this.textFileService.saveAll(this.getSaveAllArguments(context)).then(results => {
// Reopen saved untitled editors
const untitledToReopen: { input: IResourceInput, position: Position }[] = [];
results.results.forEach(result => {
if (!result.success || result.source.scheme !== 'untitled') {
return;
}
const untitledProps = mapUntitledToProperties[result.source.toString()];
if (!untitledProps) {
return;
}
// For each position where the untitled file was opened
untitledProps.indexInGroups.forEach((indexInGroup, index) => {
if (indexInGroup >= 0) {
untitledToReopen.push({
input: {
resource: result.target,
encoding: untitledProps.encoding,
options: {
pinned: true,
index: indexInGroup,
preserveFocus: true,
inactive: !untitledProps.activeInGroups[index]
}
},
position: index
});
}
});
});
if (untitledToReopen.length) {
return this.editorService.openEditors(untitledToReopen).then(() => true);
}
});
}
public dispose(): void {
this.toDispose = dispose(this.toDispose);
super.dispose();
}
}
export class SaveAllAction extends BaseSaveAllAction {
public static ID = 'workbench.action.files.saveAll';
public static LABEL = nls.localize('saveAll', "Save All");
public get class(): string {
return 'explorer-action save-all';
}
protected getSaveAllArguments(): boolean {
return this.includeUntitled();
}
protected includeUntitled(): boolean {
return true;
}
}
export class SaveAllInGroupAction extends BaseSaveAllAction {
public static ID = 'workbench.files.action.saveAllInGroup';
public static LABEL = nls.localize('saveAllInGroup', "Save All in Group");
public get class(): string {
return 'explorer-action save-all';
}
protected getSaveAllArguments(editorIdentifier: IEditorIdentifier): any {
if (!editorIdentifier) {
return this.includeUntitled();
}
const editorGroup = editorIdentifier.group;
const resourcesToSave: URI[] = [];
editorGroup.getEditors().forEach(editor => {
const resource = toResource(editor, { supportSideBySide: true, filter: ['file', 'untitled'] });
if (resource) {
resourcesToSave.push(resource);
}
});
return resourcesToSave;
}
protected includeUntitled(): boolean {
return true;
}
}
export class SaveFilesAction extends BaseSaveAllAction {
public static ID = 'workbench.action.files.saveFiles';
public static LABEL = nls.localize('saveFiles', "Save Dirty Files");
protected getSaveAllArguments(): boolean {
return this.includeUntitled();
}
protected includeUntitled(): boolean {
return false;
}
}
export class RevertFileAction extends Action {
public static ID = 'workbench.action.files.revert';
public static LABEL = nls.localize('revert', "Revert File");
private resource: URI;
constructor(
id: string,
label: string,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@ITextFileService private textFileService: ITextFileService
) {
super(id, label);
this.enabled = true;
}
public setResource(resource: URI): void {
this.resource = resource;
}
public run(): TPromise<any> {
let resource: URI;
if (this.resource) {
resource = this.resource;
} else {
resource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
}
if (resource && resource.scheme !== 'untitled') {
return this.textFileService.revert(resource, true /* force */);
}
return TPromise.as(true);
}
}
export class FocusOpenEditorsView extends Action {
public static ID = 'workbench.files.action.focusOpenEditorsView';
public static LABEL = nls.localize({ key: 'focusOpenEditors', comment: ['Open is an adjective'] }, "Focus on Open Editors View");
constructor(
id: string,
label: string,
@IViewletService private viewletService: IViewletService
) {
super(id, label);
}
public run(): TPromise<any> {
return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
const openEditorsView = viewlet.getOpenEditorsView();
if (openEditorsView) {
openEditorsView.expand();
openEditorsView.getViewer().DOMFocus();
}
});
}
}
export class FocusFilesExplorer extends Action {
public static ID = 'workbench.files.action.focusFilesExplorer';
public static LABEL = nls.localize('focusFilesExplorer', "Focus on Files Explorer");
constructor(
id: string,
label: string,
@IViewletService private viewletService: IViewletService
) {
super(id, label);
}
public run(): TPromise<any> {
return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
const view = viewlet.getExplorerView();
if (view) {
view.expand();
view.getViewer().DOMFocus();
}
});
}
}
export const revealInExplorerCommand = (accessor: ServicesAccessor, resource: URI) => {
const viewletService = accessor.get(IViewletService);
const contextService = accessor.get(IWorkspaceContextService);
viewletService.openViewlet(VIEWLET_ID, false).then((viewlet: ExplorerViewlet) => {
const isInsideWorkspace = contextService.isInsideWorkspace(resource);
if (isInsideWorkspace) {
const explorerView = viewlet.getExplorerView();
if (explorerView) {
explorerView.expand();
explorerView.select(resource, true);
}
} else {
const openEditorsView = viewlet.getOpenEditorsView();
if (openEditorsView) {
openEditorsView.expand();
}
}
});
};
export class ShowActiveFileInExplorer extends Action {
public static ID = 'workbench.files.action.showActiveFileInExplorer';
public static LABEL = nls.localize('showInExplorer', "Reveal Active File in Side Bar");
constructor(
id: string,
label: string,
@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
@IInstantiationService private instantiationService: IInstantiationService,
@IMessageService private messageService: IMessageService
) {
super(id, label);
}
public run(): TPromise<any> {
const fileResource = toResource(this.editorService.getActiveEditorInput(), { supportSideBySide: true, filter: 'file' });
if (fileResource) {
this.instantiationService.invokeFunction.apply(this.instantiationService, [revealInExplorerCommand, fileResource]);
} else {
this.messageService.show(severity.Info, nls.localize('openFileToShow', "Open a file first to show it in the explorer"));
}
return TPromise.as(true);
}
}
export class CollapseExplorerView extends Action {
public static ID = 'workbench.files.action.collapseExplorerFolders';
public static LABEL = nls.localize('collapseExplorerFolders', "Collapse Folders in Explorer");
constructor(
id: string,
label: string,
@IViewletService private viewletService: IViewletService
) {
super(id, label);
}
public run(): TPromise<any> {
return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
const explorerView = viewlet.getExplorerView();
if (explorerView) {
const viewer = explorerView.getViewer();
if (viewer) {
const action = new CollapseAction(viewer, true, null);
action.run().done();
action.dispose();
}
}
});
}
}
export class RefreshExplorerView extends Action {
public static ID = 'workbench.files.action.refreshFilesExplorer';
public static LABEL = nls.localize('refreshExplorer', "Refresh Explorer");
constructor(
id: string,
label: string,
@IViewletService private viewletService: IViewletService
) {
super(id, label);
}
public run(): TPromise<any> {
return this.viewletService.openViewlet(VIEWLET_ID, true).then((viewlet: ExplorerViewlet) => {
const explorerView = viewlet.getExplorerView();
if (explorerView) {
explorerView.refresh();
}
});
}
}
export function keybindingForAction(id: string, keybindingService: IKeybindingService): Keybinding {
switch (id) {
case GlobalNewUntitledFileAction.ID:
return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_N);
case TriggerRenameFileAction.ID:
return new Keybinding(isMacintosh ? KeyCode.Enter : KeyCode.F2);
case SaveFileAction.ID:
return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_S);
case MoveFileToTrashAction.ID:
return new Keybinding(isMacintosh ? KeyMod.CtrlCmd | KeyCode.Backspace : KeyCode.Delete);
case CopyFileAction.ID:
return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_C);
case PasteFileAction.ID:
return new Keybinding(KeyMod.CtrlCmd | KeyCode.KEY_V);
case OpenToSideAction.ID:
if (isMacintosh) {
return new Keybinding(KeyMod.WinCtrl | KeyCode.Enter);
} else {
return new Keybinding(KeyMod.CtrlCmd | KeyCode.Enter);
}
}
if (keybindingService) {
const keys = keybindingService.lookupKeybindings(id);
if (keys.length > 0) {
return keys[0]; // only take the first one
}
}
return null;
}
export function validateFileName(parent: IFileStat, name: string, allowOverwriting: boolean = false): string {
// Produce a well formed file name
name = getWellFormedFileName(name);
// Name not provided
if (!name || name.length === 0 || /^\s+$/.test(name)) {
return nls.localize('emptyFileNameError', "A file or folder name must be provided.");
}
// Do not allow to overwrite existing file
if (!allowOverwriting) {
if (parent.children && parent.children.some((c) => {
if (isLinux) {
return c.name === name;
}
return c.name.toLowerCase() === name.toLowerCase();
})) {
return nls.localize('fileNameExistsError', "A file or folder **{0}** already exists at this location. Please choose a different name.", name);
}
}
// Invalid File name
if (!paths.isValidBasename(name)) {
return nls.localize('invalidFileNameError', "The name **{0}** is not valid as a file or folder name. Please choose a different name.", name);
}
// Max length restriction (on Windows)
if (isWindows) {
const fullPathLength = name.length + parent.resource.fsPath.length + 1 /* path segment */;
if (fullPathLength > 255) {
return nls.localize('filePathTooLongError', "The name **{0}** results in a path that is too long. Please choose a shorter name.", name);
}
}
return null;
}
export function getWellFormedFileName(filename: string): string {
if (!filename) {
return filename;
}
// Trim whitespaces
filename = strings.trim(strings.trim(filename, ' '), '\t');
// Remove trailing dots
filename = strings.rtrim(filename, '.');
return filename;
}
// Diagnostics support
let diag: (...args: any[]) => void;
if (!diag) {
diag = diagnostics.register('FileActionsDiagnostics', function (...args: any[]) {
console.log(args[1] + ' - ' + args[0] + ' (time: ' + args[2].getTime() + ' [' + args[2].toUTCString() + '])');
});
}
| {'content_hash': '57898a2e787603b0ba45fd5596c69a89', 'timestamp': '', 'source': 'github', 'line_count': 1852, 'max_line_length': 291, 'avg_line_length': 30.41252699784017, 'alnum_prop': 0.7127867338967403, 'repo_name': 'zyml/vscode', 'id': 'a1458c0fbb869287a61e4bcdc1710b47e491ccb0', 'size': '56675', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/vs/workbench/parts/files/browser/fileActions.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '4294'}, {'name': 'C', 'bytes': '818'}, {'name': 'C#', 'bytes': '1152'}, {'name': 'C++', 'bytes': '1000'}, {'name': 'CSS', 'bytes': '487189'}, {'name': 'Clojure', 'bytes': '1206'}, {'name': 'CoffeeScript', 'bytes': '590'}, {'name': 'F#', 'bytes': '634'}, {'name': 'GLSL', 'bytes': '330'}, {'name': 'Go', 'bytes': '613'}, {'name': 'Groovy', 'bytes': '3928'}, {'name': 'HTML', 'bytes': '32838'}, {'name': 'Inno Setup', 'bytes': '106295'}, {'name': 'Java', 'bytes': '576'}, {'name': 'JavaScript', 'bytes': '3026177'}, {'name': 'Lua', 'bytes': '252'}, {'name': 'Makefile', 'bytes': '553'}, {'name': 'Objective-C', 'bytes': '1387'}, {'name': 'PHP', 'bytes': '802'}, {'name': 'Perl', 'bytes': '857'}, {'name': 'Perl6', 'bytes': '1065'}, {'name': 'PowerShell', 'bytes': '1432'}, {'name': 'Python', 'bytes': '2119'}, {'name': 'R', 'bytes': '362'}, {'name': 'Ruby', 'bytes': '1703'}, {'name': 'Rust', 'bytes': '532'}, {'name': 'Shell', 'bytes': '10086'}, {'name': 'Swift', 'bytes': '220'}, {'name': 'TypeScript', 'bytes': '11528533'}, {'name': 'Visual Basic', 'bytes': '893'}]} |
require 'ffaker/address'
module FFaker
module AddressGR
include FFaker::Address
extend ModuleUtils
extend self
STREET_PREFIX = %w( Οδός Πάροδος )
STREET_NUMBER = %w( # ## ### )
STATE = REGION
def zip_code
FFaker.numerify '#####'
end
def region
fetch_sample(STATE)
end
def city
fetch_sample(CITY)
end
def street_name
fetch_sample(STREET)
end
def street_nbr
FFaker.numerify(fetch_sample(STREET_NUMBER))
end
def street_address
"#{fetch_sample(STREET_PREFIX)} #{street_name}, #{street_nbr}"
end
end
end
| {'content_hash': '8135abbd400e01b70291227dd772123c', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 68, 'avg_line_length': 16.31578947368421, 'alnum_prop': 0.603225806451613, 'repo_name': 'teeparham/ffaker', 'id': 'd83a5407eef83f6ea6e2dae87921e7204689fc63', 'size': '650', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/ffaker/address_gr.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '378211'}, {'name': 'Shell', 'bytes': '60'}]} |
<!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_55) on Sun Oct 26 05:56:34 EDT 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.apache.solr.update (Solr 4.10.2 API)</title>
<meta name="date" content="2014-10-26">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar"><a href="../../../../org/apache/solr/update/package-summary.html" target="classFrame">org.apache.solr.update</a></h1>
<div class="indexContainer">
<h2 title="Interfaces">Interfaces</h2>
<ul title="Interfaces">
<li><a href="SolrCmdDistributor.AbortCheck.html" title="interface in org.apache.solr.update" target="classFrame"><i>SolrCmdDistributor.AbortCheck</i></a></li>
<li><a href="SolrCoreState.IndexWriterCloser.html" title="interface in org.apache.solr.update" target="classFrame"><i>SolrCoreState.IndexWriterCloser</i></a></li>
</ul>
<h2 title="Classes">Classes</h2>
<ul title="Classes">
<li><a href="AddUpdateCommand.html" title="class in org.apache.solr.update" target="classFrame">AddUpdateCommand</a></li>
<li><a href="CommitTracker.html" title="class in org.apache.solr.update" target="classFrame">CommitTracker</a></li>
<li><a href="CommitUpdateCommand.html" title="class in org.apache.solr.update" target="classFrame">CommitUpdateCommand</a></li>
<li><a href="DefaultSolrCoreState.html" title="class in org.apache.solr.update" target="classFrame">DefaultSolrCoreState</a></li>
<li><a href="DeleteUpdateCommand.html" title="class in org.apache.solr.update" target="classFrame">DeleteUpdateCommand</a></li>
<li><a href="DirectUpdateHandler2.html" title="class in org.apache.solr.update" target="classFrame">DirectUpdateHandler2</a></li>
<li><a href="DocumentBuilder.html" title="class in org.apache.solr.update" target="classFrame">DocumentBuilder</a></li>
<li><a href="HdfsTransactionLog.html" title="class in org.apache.solr.update" target="classFrame">HdfsTransactionLog</a></li>
<li><a href="HdfsUpdateLog.html" title="class in org.apache.solr.update" target="classFrame">HdfsUpdateLog</a></li>
<li><a href="LoggingInfoStream.html" title="class in org.apache.solr.update" target="classFrame">LoggingInfoStream</a></li>
<li><a href="MemOutputStream.html" title="class in org.apache.solr.update" target="classFrame">MemOutputStream</a></li>
<li><a href="MergeIndexesCommand.html" title="class in org.apache.solr.update" target="classFrame">MergeIndexesCommand</a></li>
<li><a href="PeerSync.html" title="class in org.apache.solr.update" target="classFrame">PeerSync</a></li>
<li><a href="RollbackUpdateCommand.html" title="class in org.apache.solr.update" target="classFrame">RollbackUpdateCommand</a></li>
<li><a href="SolrCmdDistributor.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor</a></li>
<li><a href="SolrCmdDistributor.Error.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.Error</a></li>
<li><a href="SolrCmdDistributor.Node.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.Node</a></li>
<li><a href="SolrCmdDistributor.Req.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.Req</a></li>
<li><a href="SolrCmdDistributor.Response.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.Response</a></li>
<li><a href="SolrCmdDistributor.RetryNode.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.RetryNode</a></li>
<li><a href="SolrCmdDistributor.StdNode.html" title="class in org.apache.solr.update" target="classFrame">SolrCmdDistributor.StdNode</a></li>
<li><a href="SolrCoreState.html" title="class in org.apache.solr.update" target="classFrame">SolrCoreState</a></li>
<li><a href="SolrIndexConfig.html" title="class in org.apache.solr.update" target="classFrame">SolrIndexConfig</a></li>
<li><a href="SolrIndexSplitter.html" title="class in org.apache.solr.update" target="classFrame">SolrIndexSplitter</a></li>
<li><a href="SolrIndexWriter.html" title="class in org.apache.solr.update" target="classFrame">SolrIndexWriter</a></li>
<li><a href="SplitIndexCommand.html" title="class in org.apache.solr.update" target="classFrame">SplitIndexCommand</a></li>
<li><a href="StreamingSolrServers.html" title="class in org.apache.solr.update" target="classFrame">StreamingSolrServers</a></li>
<li><a href="TransactionLog.html" title="class in org.apache.solr.update" target="classFrame">TransactionLog</a></li>
<li><a href="UpdateCommand.html" title="class in org.apache.solr.update" target="classFrame">UpdateCommand</a></li>
<li><a href="UpdateHandler.html" title="class in org.apache.solr.update" target="classFrame">UpdateHandler</a></li>
<li><a href="UpdateLog.html" title="class in org.apache.solr.update" target="classFrame">UpdateLog</a></li>
<li><a href="UpdateLog.LogPtr.html" title="class in org.apache.solr.update" target="classFrame">UpdateLog.LogPtr</a></li>
<li><a href="UpdateLog.RecoveryInfo.html" title="class in org.apache.solr.update" target="classFrame">UpdateLog.RecoveryInfo</a></li>
<li><a href="UpdateShardHandler.html" title="class in org.apache.solr.update" target="classFrame">UpdateShardHandler</a></li>
<li><a href="VersionBucket.html" title="class in org.apache.solr.update" target="classFrame">VersionBucket</a></li>
<li><a href="VersionInfo.html" title="class in org.apache.solr.update" target="classFrame">VersionInfo</a></li>
</ul>
<h2 title="Enums">Enums</h2>
<ul title="Enums">
<li><a href="UpdateLog.State.html" title="enum in org.apache.solr.update" target="classFrame">UpdateLog.State</a></li>
<li><a href="UpdateLog.SyncLevel.html" title="enum in org.apache.solr.update" target="classFrame">UpdateLog.SyncLevel</a></li>
</ul>
</div>
</body>
</html>
| {'content_hash': '10a5fa8c2d20c7439ea32ed0dcc3a1d4', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 162, 'avg_line_length': 91.13846153846154, 'alnum_prop': 0.7488183659689399, 'repo_name': 'eissac/solr4sentiment', 'id': '92b289c7dc578da330432a0d3caa619245d1b01c', 'size': '5924', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/solr-core/org/apache/solr/update/package-frame.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '125503'}, {'name': 'Groff', 'bytes': '4194391'}, {'name': 'HTML', 'bytes': '84659'}, {'name': 'JavaScript', 'bytes': '1019096'}, {'name': 'Shell', 'bytes': '78948'}, {'name': 'XSLT', 'bytes': '124615'}]} |
class RootCategory
include Mongoid::Document
embeds_many :categories
end
| {'content_hash': 'ed22a6638e9521f7b80b4141d9942f86', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 27, 'avg_line_length': 19.25, 'alnum_prop': 0.8051948051948052, 'repo_name': 'massayoshi/mongoid', 'id': 'fa8dc37703a07e85bbea767107fd01d7a15a9ab9', 'size': '126', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/support/models/root_category.rb', 'mode': '33188', 'license': 'mit', 'language': []} |
import functools
from tornado.escape import url_escape
from tornado.httpclient import AsyncHTTPClient
from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, LogTrapTestCase
from tornado.util import b
from tornado.web import Application, RequestHandler, asynchronous
from tornado import gen
class GenTest(AsyncTestCase):
def run_gen(self, f):
f()
self.wait()
def delay_callback(self, iterations, callback, arg):
"""Runs callback(arg) after a number of IOLoop iterations."""
if iterations == 0:
callback(arg)
else:
self.io_loop.add_callback(functools.partial(
self.delay_callback, iterations - 1, callback, arg))
def test_no_yield(self):
@gen.engine
def f():
self.stop()
self.run_gen(f)
def test_inline_cb(self):
@gen.engine
def f():
(yield gen.Callback("k1"))()
res = yield gen.Wait("k1")
assert res is None
self.stop()
self.run_gen(f)
def test_ioloop_cb(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.stop()
self.run_gen(f)
def test_exception_phase1(self):
@gen.engine
def f():
1/0
self.assertRaises(ZeroDivisionError, self.run_gen, f)
def test_exception_phase2(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
1/0
self.assertRaises(ZeroDivisionError, self.run_gen, f)
def test_exception_in_task_phase1(self):
def fail_task(callback):
1/0
@gen.engine
def f():
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.stop()
self.run_gen(f)
def test_exception_in_task_phase2(self):
# This is the case that requires the use of stack_context in gen.engine
def fail_task(callback):
self.io_loop.add_callback(lambda: 1/0)
@gen.engine
def f():
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.stop()
self.run_gen(f)
def test_with_arg(self):
@gen.engine
def f():
(yield gen.Callback("k1"))(42)
res = yield gen.Wait("k1")
self.assertEqual(42, res)
self.stop()
self.run_gen(f)
def test_key_reuse(self):
@gen.engine
def f():
yield gen.Callback("k1")
yield gen.Callback("k1")
self.stop()
self.assertRaises(gen.KeyReuseError, self.run_gen, f)
def test_key_mismatch(self):
@gen.engine
def f():
yield gen.Callback("k1")
yield gen.Wait("k2")
self.stop()
self.assertRaises(gen.UnknownKeyError, self.run_gen, f)
def test_leaked_callback(self):
@gen.engine
def f():
yield gen.Callback("k1")
self.stop()
self.assertRaises(gen.LeakedCallbackError, self.run_gen, f)
def test_parallel_callback(self):
@gen.engine
def f():
for k in range(3):
self.io_loop.add_callback((yield gen.Callback(k)))
yield gen.Wait(1)
self.io_loop.add_callback((yield gen.Callback(3)))
yield gen.Wait(0)
yield gen.Wait(3)
yield gen.Wait(2)
self.stop()
self.run_gen(f)
def test_bogus_yield(self):
@gen.engine
def f():
yield 42
self.assertRaises(gen.BadYieldError, self.run_gen, f)
def test_reuse(self):
@gen.engine
def f():
self.io_loop.add_callback((yield gen.Callback(0)))
yield gen.Wait(0)
self.stop()
self.run_gen(f)
self.run_gen(f)
def test_task(self):
@gen.engine
def f():
yield gen.Task(self.io_loop.add_callback)
self.stop()
self.run_gen(f)
def test_wait_all(self):
@gen.engine
def f():
(yield gen.Callback("k1"))("v1")
(yield gen.Callback("k2"))("v2")
results = yield gen.WaitAll(["k1", "k2"])
self.assertEqual(results, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_exception_in_yield(self):
@gen.engine
def f():
try:
yield gen.Wait("k1")
raise "did not get expected exception"
except gen.UnknownKeyError:
pass
self.stop()
self.run_gen(f)
def test_resume_after_exception_in_yield(self):
@gen.engine
def f():
try:
yield gen.Wait("k1")
raise "did not get expected exception"
except gen.UnknownKeyError:
pass
(yield gen.Callback("k2"))("v2")
self.assertEqual((yield gen.Wait("k2")), "v2")
self.stop()
self.run_gen(f)
def test_orphaned_callback(self):
@gen.engine
def f():
self.orphaned_callback = yield gen.Callback(1)
try:
self.run_gen(f)
raise "did not get expected exception"
except gen.LeakedCallbackError:
pass
self.orphaned_callback()
def test_multi(self):
@gen.engine
def f():
(yield gen.Callback("k1"))("v1")
(yield gen.Callback("k2"))("v2")
results = yield [gen.Wait("k1"), gen.Wait("k2")]
self.assertEqual(results, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_multi_delayed(self):
@gen.engine
def f():
# callbacks run at different times
responses = yield [
gen.Task(self.delay_callback, 3, arg="v1"),
gen.Task(self.delay_callback, 1, arg="v2"),
]
self.assertEqual(responses, ["v1", "v2"])
self.stop()
self.run_gen(f)
def test_arguments(self):
@gen.engine
def f():
(yield gen.Callback("noargs"))()
self.assertEqual((yield gen.Wait("noargs")), None)
(yield gen.Callback("1arg"))(42)
self.assertEqual((yield gen.Wait("1arg")), 42)
(yield gen.Callback("kwargs"))(value=42)
result = yield gen.Wait("kwargs")
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((), dict(value=42)), result)
self.assertEqual(dict(value=42), result.kwargs)
(yield gen.Callback("2args"))(42, 43)
result = yield gen.Wait("2args")
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((42, 43), {}), result)
self.assertEqual((42, 43), result.args)
def task_func(callback):
callback(None, error="foo")
result = yield gen.Task(task_func)
self.assertTrue(isinstance(result, gen.Arguments))
self.assertEqual(((None,), dict(error="foo")), result)
self.stop()
self.run_gen(f)
class GenSequenceHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
self.io_loop = self.request.connection.stream.io_loop
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.write("1")
self.io_loop.add_callback((yield gen.Callback("k2")))
yield gen.Wait("k2")
self.write("2")
# reuse an old key
self.io_loop.add_callback((yield gen.Callback("k1")))
yield gen.Wait("k1")
self.finish("3")
class GenTaskHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
io_loop = self.request.connection.stream.io_loop
client = AsyncHTTPClient(io_loop=io_loop)
response = yield gen.Task(client.fetch, self.get_argument('url'))
response.rethrow()
self.finish(b("got response: ") + response.body)
class GenExceptionHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
# This test depends on the order of the two decorators.
io_loop = self.request.connection.stream.io_loop
yield gen.Task(io_loop.add_callback)
raise Exception("oops")
class GenYieldExceptionHandler(RequestHandler):
@asynchronous
@gen.engine
def get(self):
io_loop = self.request.connection.stream.io_loop
# Test the interaction of the two stack_contexts.
def fail_task(callback):
io_loop.add_callback(lambda: 1/0)
try:
yield gen.Task(fail_task)
raise Exception("did not get expected exception")
except ZeroDivisionError:
self.finish('ok')
class GenWebTest(AsyncHTTPTestCase, LogTrapTestCase):
def get_app(self):
return Application([
('/sequence', GenSequenceHandler),
('/task', GenTaskHandler),
('/exception', GenExceptionHandler),
('/yield_exception', GenYieldExceptionHandler),
])
def test_sequence_handler(self):
response = self.fetch('/sequence')
self.assertEqual(response.body, b("123"))
def test_task_handler(self):
response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence')))
self.assertEqual(response.body, b("got response: 123"))
def test_exception_handler(self):
# Make sure we get an error and not a timeout
response = self.fetch('/exception')
self.assertEqual(500, response.code)
def test_yield_exception_handler(self):
response = self.fetch('/yield_exception')
self.assertEqual(response.body, b('ok'))
| {'content_hash': '34a10db62443e9c172b66309c2548a25', 'timestamp': '', 'source': 'github', 'line_count': 324, 'max_line_length': 85, 'avg_line_length': 31.305555555555557, 'alnum_prop': 0.5482598836636103, 'repo_name': 'e1ven/Waymoot', 'id': '935b409482cff079458d87a5f3f64555e3f5ef10', 'size': '10143', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'libs/tornado-2.2/tornado/test/gen_test.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3085'}, {'name': 'JavaScript', 'bytes': '54051'}, {'name': 'Python', 'bytes': '2704538'}, {'name': 'Shell', 'bytes': '168'}]} |
package hu.akarnokd.reactive.comparison.rx1;
import java.util.Arrays;
import java.util.concurrent.*;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import hu.akarnokd.reactive.comparison.consumers.PerfRxAsyncSubscriber;
import rx.schedulers.Schedulers;
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 5)
@Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(value = 1)
@State(Scope.Thread)
public class AsyncPerf {
@Param({"1", "10", "100", "1000", "10000", "100000", "1000000" })
public int count;
rx.Observable<Integer> asyncRxObservable;
rx.Observable<Integer> pipelineRxObservable;
ExecutorService exec = Executors.newSingleThreadExecutor();
ExecutorService exec2 = Executors.newSingleThreadExecutor();
@Setup
public void setup() {
Integer[] array = new Integer[count];
Arrays.fill(array, 777);
rx.Observable<Integer> arrayRx = rx.Observable.from(array);
asyncRxObservable = arrayRx.observeOn(Schedulers.from(exec));
pipelineRxObservable = arrayRx.subscribeOn(Schedulers.from(exec2)).observeOn(Schedulers.from(exec));
}
@TearDown
public void teardown() {
exec.shutdown();
exec2.shutdown();
}
final void run(rx.Observable<?> p, Blackhole bh) {
PerfRxAsyncSubscriber s = new PerfRxAsyncSubscriber(bh);
p.subscribe(s);
s.await(count);
}
@Benchmark
public void asyncRxObservable(Blackhole bh) {
run(asyncRxObservable, bh);
}
@Benchmark
public void pipelineRxObservable(Blackhole bh) {
run(pipelineRxObservable, bh);
}
}
| {'content_hash': '26a83ae8b24a9a27fea57f94fad6c816', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 108, 'avg_line_length': 26.609375, 'alnum_prop': 0.6923076923076923, 'repo_name': 'akarnokd/akarnokd-misc', 'id': 'ac9daa37d6361ba86276d79a94f08fa359b40786', 'size': '1703', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/jmh/java/hu/akarnokd/reactive/comparison/rx1/AsyncPerf.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2171'}, {'name': 'HTML', 'bytes': '2942'}, {'name': 'Java', 'bytes': '1604867'}]} |
<DIV NAME="detail" ID="detail" xmlns="http://www.w3.org/TR/REC-html40"><H3><A NAME='detail_IsEndOfFile'></A>TestComplete DDDriverFileCommands::<BIG>IsEndOfFile</BIG>
</H3> <TABLE><TR>
<TD class="borderStyle"><SPAN CLASS='Support' TITLE='SAFS TID Commands'>TID</SPAN></TD>
<TD class="borderStyle"><SPAN CLASS='Support' TITLE='SAFS Driver Commands'>SDC</SPAN></TD>
</TR></TABLE>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
If the specified file is at the end of file, a 'variable' gets true assigned, otherwise it gets false
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
<BR/>
<DIV NAME="list" ID="other">
<p><B>Fields: </B><SMALL>[ ]=Optional with Default Value</SMALL></p>
<code class="safs">
<OL start="3" ><LI>
<B>FileNumber</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
The file number for the file to be closed.
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
<LI>
<B>Variable</B>
<BR/>
<DIV NAME="list" ID="short_desc"><short_desc xmlns="">
Variable to assign true or false
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI></OL ></code>
<br/>
<p><B>Examples:</B></p>
<code class="safs"><UL>
<LI>
<B><usage xmlns="">
C, IsEndOfFile, 8, variable
</usage></B>
<BR/><DIV NAME="list" ID="short_desc"><short_desc xmlns="">
if the file with file number 8 is at the end of file, 'variable' gets true assigned, otherwise it gets false
</short_desc></DIV>
<BR/>
<DIV NAME="list" ID="detail_desc"/>
</LI>
</UL>
</code>
<br/>
<A href="SAFSReferenceKey.htm" alt="Reference Legend or Key">
<SMALL><B>[How To Read This Reference]</B></SMALL>
</A>
<HR/>
</DIV>
</DIV>
| {'content_hash': '46fdb94e7f9db7e86032b436d75324ca', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 165, 'avg_line_length': 32.527272727272724, 'alnum_prop': 0.6031302403577418, 'repo_name': 'kid551/safsdev.test.github.io', 'id': '0cc5e3a2ad1e13496e2c775de4fdcf32e0806dde', 'size': '1789', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'keyref/TestCompleteDDDriverFileCommandsIsEndOfFile.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '27646'}, {'name': 'HTML', 'bytes': '27805169'}, {'name': 'JavaScript', 'bytes': '2769'}]} |
//using System;
//using System.ComponentModel;
//using System.Drawing;
//using System.Drawing.Design;
//using System.Windows.Forms;
//namespace CSharpGL
//{
// // TODO: how to deal with keyboard/mouse events? Where put events?
// /// <summary>
// /// OpenGL Canvas on Windows platform.
// /// </summary>
// [Editor(typeof(PropertyGridEditor), typeof(UITypeEditor))]
// public interface IWinGLCanvas : IGLCanvas
// {
// /// <summary>
// ///
// /// </summary>
// RenderTrigger RenderTrigger { get; set; }
// /// <summary>
// ///
// /// </summary>
// int TimerTriggerInterval { get; set; }
// }
//} | {'content_hash': '3ec25e6a8cb5f248676d86797fe43e07', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 72, 'avg_line_length': 24.285714285714285, 'alnum_prop': 0.5647058823529412, 'repo_name': 'bitzhuwei/CSharpGL', 'id': '8ab488661ad8051120a2cd83cc68120f71e33429', 'size': '682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CSharpGL.Windows/WinGLCanvas/IWinGLCanvas.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '43'}, {'name': 'C', 'bytes': '228855'}, {'name': 'C#', 'bytes': '4399753'}, {'name': 'C++', 'bytes': '17417'}, {'name': 'GLSL', 'bytes': '3191'}, {'name': 'Smalltalk', 'bytes': '118027'}]} |
<?php
/**
* Install routine
*
*@since 1.0
*@access private
*@ignore
*/
function eventorganiser_install(){
global $wpdb, $eventorganiser_db_version;
eventorganiser_wpdb_fix();
$charset_collate = '';
if ( ! empty($wpdb->charset) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty($wpdb->collate) )
$charset_collate .= " COLLATE $wpdb->collate";
//Events table
$sql_events_table = "CREATE TABLE " .$wpdb->eo_events. " (
event_id bigint(20) NOT NULL AUTO_INCREMENT,
post_id bigint(20) NOT NULL,
StartDate DATE NOT NULL,
EndDate DATE NOT NULL,
StartTime TIME NOT NULL,
FinishTime TIME NOT NULL,
event_occurrence bigint(20) NOT NULL,
PRIMARY KEY (event_id),
KEY StartDate (StartDate),
KEY EndDate (EndDate)
)".$charset_collate;
//Venue meta table
$sql_venuemeta_table ="CREATE TABLE {$wpdb->prefix}eo_venuemeta (
meta_id bigint(20) unsigned NOT NULL auto_increment,
eo_venue_id bigint(20) unsigned NOT NULL default '0',
meta_key varchar(255) default NULL,
meta_value longtext,
PRIMARY KEY (meta_id),
KEY eo_venue_id (eo_venue_id),
KEY meta_key (meta_key)
) $charset_collate; ";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql_events_table);
dbDelta($sql_venuemeta_table);
//Add options and capabilities
$eventorganiser_options = array (
'supports' => array('title','editor','author','thumbnail','excerpt','custom-fields','comments'),
'event_redirect' => 'events',
'dateformat'=>'dd-mm',
'prettyurl'=> 1,
'templates'=> 1,
'addtomenu'=> 0,
'excludefromsearch'=>0,
'showpast'=> 0,
'group_events'=>'',
'url_venue'=>'events/event',
'url_venue'=> 'events/venues',
'url_cat' => 'events/category',
'url_tag' => 'events/tag',
'navtitle' => __('Events','eventorganiser'),
'eventtag' => 1,
'feed' => 1,
'runningisnotpast' => 0,
'deleteexpired' => 0
);
add_option('eventorganiser_options',$eventorganiser_options);
/* Add existing notices */
$notices = array('autofillvenue17','changedtemplate17');
add_option('eventorganiser_admin_notices',$notices);
//Add roles to administrator
global $wp_roles;
$all_roles = $wp_roles->roles;
$eventorganiser_roles = array(
'edit_events' => __( 'Edit Events', 'eventorganiser' ),
'publish_events' => __( 'Publish Events', 'eventorganiser' ),
'delete_events' => __( 'Delete Events', 'eventorganiser' ),
'edit_others_events' => __( 'Edit Others\' Events', 'eventorganiser' ),
'delete_others_events' => __( 'Delete Other\'s Events', 'eventorganiser' ),
'read_private_events' => __( 'Read Private Events', 'eventorganiser' ),
'manage_venues' => __( 'Manage Venues', 'eventorganiser' ),
'manage_event_categories' => __( 'Manage Event Categories & Tags', 'eventorganiser' ),
);
foreach ($all_roles as $role_name => $display_name):
$role = $wp_roles->get_role($role_name);
if($role->has_cap('manage_options')){
foreach($eventorganiser_roles as $eo_role=>$eo_role_display):
$role->add_cap($eo_role);
endforeach;
}
endforeach; //End foreach $all_roles
//Manually register CPT and CTs ready for flushing
eventorganiser_create_event_taxonomies();
eventorganiser_cpt_register();
//Flush rewrite rules only on activation, and after CPT/CTs has been registered.
flush_rewrite_rules();
}
/**
* Deactivate routine
*
* Clears cron jobs and flushes rewrite rules
*
*@since 1.5
*@access private
*@ignore
*/
function eventorganiser_deactivate(){
eventorganiser_clear_cron_jobs();
flush_rewrite_rules();
}
/**
* Upgrade routine. Hooked onto admin_init
*
*@since 1.1
*@access private
*@ignore
*/
function eventorganiser_upgradecheck(){
global $eventorganiser_db_version, $wpdb;
global $EO_Errors;
$installed_ver = get_option('eventorganiser_version');
if( empty($installed_ver) ){
//This is a fresh install. Add current database version
add_option('eventorganiser_version', $eventorganiser_db_version);
//But a bug in 1.5 means that it could be that they first installed in 1.5 (as no db version was added)
//So set to 1.5. Fresh installs will have to go through the 1.6 (and above) update, but this is ok.
$installed_ver = '1.5';
}
//If this is an old version, perform some updates.
if ( !empty($installed_ver ) && $installed_ver != $eventorganiser_db_version ):
if($installed_ver <'1.3'){
wp_die('You cannot upgrade to this version from 1.3 or before. Please upgrade to 1.5.7 first.');
}
if($installed_ver <'1.4'){
eventorganiser_140_update();
}
if($installed_ver <'1.5'){
eventorganiser_150_update();
}
if( $installed_ver < '1.6' ){
//Remove columns:
$columns = $wpdb->get_col("DESC {$wpdb->eo_events}", 0);
$remove_columns = array('Venue','event_schedule','event_schedule_meta', 'event_frequency','reoccurrence_start', 'reoccurrence_end' );
$delete_columns = array_intersect($remove_columns, $columns);
if( !empty($delete_columns) )
$sql = $wpdb->query("ALTER TABLE {$wpdb->eo_events} DROP COLUMN ".implode(', DROP COLUMN ',$delete_columns).';');
eventorganiser_install();
}
if( $installed_ver < '1.6.2' ){
$options = get_option('eventorganiser_options');
if( !empty($options['eventtag']) ){
$options['supports'][] = 'eventtag';
update_option('eventorganiser_options', $options);
}
}
if( $installed_ver < '1.7.1' ){
//Forgot to remove event_allday in 1.6 upgrade. This causes problems no Windows servers.
$columns = $wpdb->get_col("DESC {$wpdb->eo_events}", 0);
$remove_columns = array('event_allday');
if( !empty($delete_columns) )
$sql = $wpdb->query("ALTER TABLE {$wpdb->eo_events} DROP COLUMN ".implode(', DROP COLUMN ',$delete_columns).';');
flush_rewrite_rules();
}
update_option('eventorganiser_version', $eventorganiser_db_version);
//Run upgrade checks
add_action('admin_notices', 'eventorganiser_db_checks',0);
endif;
}
add_action('admin_init', 'eventorganiser_upgradecheck');
/**
* Upgrade routine for 1.5
*
*@since 1.5
*@access private
*@ignore
*/
function eventorganiser_150_update(){
global $wpdb;
$et =$wpdb->eo_events;
$events = $wpdb->get_results("SELECT*, min({$et}.StartDate) as StartDate, min({$et}.EndDate) as EndDate FROM $wpdb->eo_events GROUP BY {$et}.post_id ORDER BY {$et}.StartDate");
if( $events ):
foreach( $events as $event ):
$post_id = (int) $event->post_id;
$event_data = array(
'schedule' => $event->event_schedule,
'all_day' => $event->event_allday,
'schedule_meta' => ('weekly' == $event->event_schedule ? maybe_unserialize($event->event_schedule_meta) : $event->event_schedule_meta),
'frequency' => $event->event_frequency,
'exclude'=>array(),
'include'=>array(),
);
$start = new DateTime($event->StartDate.' '.$event->StartTime, eo_get_blog_timezone());
$end = new DateTime($event->EndDate.' '.$event->FinishTime, eo_get_blog_timezone());
$schedule_last = new DateTime($event->reoccurrence_end.' '.$event->StartTime, eo_get_blog_timezone());
$seconds = round(abs($start->format('U') - $end->format('U')));
$days = floor($seconds/86400);// 86400 = 60*60*24 seconds in a normal day
$sec_diff = $seconds - $days*86400;
$duration_str = '+'.$days.'days '.$sec_diff.' seconds';
$event_data['duration_str'] =$duration_str;
$schedule_last_end = clone $schedule_last;
$schedule_last_end->modify($duration_str);
update_post_meta( $post_id,'_eventorganiser_event_schedule', $event_data);
update_post_meta( $post_id,'_eventorganiser_schedule_start_start', $start->format('Y-m-d H:i:s')); //Schedule start
update_post_meta( $post_id,'_eventorganiser_schedule_start_finish', $end->format('Y-m-d H:i:s')); //Schedule start
update_post_meta( $post_id,'_eventorganiser_schedule_last_start', $schedule_last->format('Y-m-d H:i:s'));//Schedule last
update_post_meta( $post_id,'_eventorganiser_schedule_last_finish', $schedule_last_end->format('Y-m-d H:i:s'));//Schedule last
endforeach;
endif;
}
/**
* Upgrade routine for 1.4
*
*@since 1.4
*@access private
*@ignore
*/
function eventorganiser_140_update(){
//Migrates from Venue table to venue meta table
//Run install to create new table:
eventorganiser_install();
global $wpdb;
$eventorganiser_venue_table = $wpdb->prefix."eo_venues";
$venues = eo_get_the_venues();
$venue_metavalues = $wpdb->get_results(" SELECT venue_slug, venue_address, venue_postal, venue_country, venue_lng, venue_lat, venue_description FROM $eventorganiser_venue_table");
$fields = array('venue_address'=>'_address','venue_postal'=>'_postcode','venue_country'=>'_country','venue_lng'=>'_lng','venue_lat'=>'_lat','venue_description'=>'_description');
foreach( $venue_metavalues as $venue ){
$term = get_term_by('slug',$venue->venue_slug,'event-venue');
if( empty($term) || is_wp_error($term) )
continue;
foreach ($fields as $column_name => $meta_key){
if( ! empty($venue->$column_name) ){
update_metadata('eo_venue',$term->term_id,$meta_key,$venue->$column_name);
}
}
}
}
/**
* Uninstall routine
*
*@since 1.0
*@access private
*@ignore
*/
function eventorganiser_uninstall(){
global $wpdb,$eventorganiser_roles, $wp_roles,$wp_taxonomies;
eventorganiser_clear_cron_jobs();
eventorganiser_create_event_taxonomies();
//Remove custom taxonomies and terms.
$taxs = array('event-category','event-venue','event-tag');
$terms = get_terms($taxs, 'hide_empty=0' );
if( $terms ){
foreach ($terms as $term) {
$term_id = (int)$term->term_id;
wp_delete_term($term_id ,$term->taxonomy);
}
}
//Remove all posts of CPT Event
//?? $wpdb->query("DELETE FROM $wpdb->posts WHERE post_type = 'event'");
//Delete options
delete_option('eventorganiser_options');
delete_option('eventorganiser_admin_notices');
delete_option('eventorganiser_version');
delete_option('eo_notice');
delete_option('widget_eo_calendar_widget');
delete_option('widget_eo_list_widget');
//Remove Event Organiser capabilities
$all_roles = $wp_roles->roles;
foreach ($all_roles as $role_name => $display_name):
$role = $wp_roles->get_role($role_name);
foreach($eventorganiser_roles as $eo_role=>$eo_role_display):
$role->remove_cap($eo_role);
endforeach;
endforeach;
eventorganiser_clear_cron_jobs();
//Drop tables
$wpdb->query("DROP TABLE IF EXISTS $wpdb->eo_events");
$eventorganiser_venue_table = $wpdb->prefix."eo_venues";
$wpdb->query("DROP TABLE IF EXISTS $eventorganiser_venue_table");
$wpdb->query("DROP TABLE IF EXISTS $wpdb->eo_venuemeta");
//Remove user-meta-data:
$meta_keys = array('metaboxhidden_event','closedpostboxes_event','wp_event_page_venues_per_page','manageedit-eventcolumnshidden');
$sql =$wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE ");
foreach($meta_keys as $key):
$sql .= $wpdb->prepare("meta_key = %s OR ",$key);
endforeach;
$sql.=" 1=0 "; //Deal with final 'OR', must be something false!
$re =$wpdb->get_results( $sql);
flush_rewrite_rules();
}
?>
| {'content_hash': '9be394d2fb416c3c71bc802bf03d0741', 'timestamp': '', 'source': 'github', 'line_count': 337, 'max_line_length': 180, 'avg_line_length': 32.637982195845694, 'alnum_prop': 0.6648786253295754, 'repo_name': 'peter-watters/WebPortfolio', 'id': 'bf07dd8dee3dc40f6227689ade71ab35cf1dc665', 'size': '10999', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fitnessperformacesystems/wp-content/plugins/event-organiser/includes/event-organiser-install.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '4489'}, {'name': 'ActionScript', 'bytes': '529910'}, {'name': 'CSS', 'bytes': '5681789'}, {'name': 'CoffeeScript', 'bytes': '48851'}, {'name': 'Java', 'bytes': '24402'}, {'name': 'JavaScript', 'bytes': '15741063'}, {'name': 'PHP', 'bytes': '36775095'}, {'name': 'Shell', 'bytes': '53068'}, {'name': 'XSLT', 'bytes': '5803'}]} |
class AddUserIdToEntries < ActiveRecord::Migration
def change
add_column :entries, :user_id, :integer
end
end
| {'content_hash': 'f01efcce316359e98b735e41de03fa94', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 50, 'avg_line_length': 23.6, 'alnum_prop': 0.7457627118644068, 'repo_name': 'benniemosher/scriptorium', 'id': '20cde8419c922c3da4903de7264c048726940fc1', 'size': '118', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'db/migrate/20141014141137_add_user_id_to_entries.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19097'}, {'name': 'JavaScript', 'bytes': '748'}, {'name': 'Ruby', 'bytes': '43856'}, {'name': 'Shell', 'bytes': '777'}]} |
//
// ZLAVideoImageView.h
// ZLApp
//
// Created by MacTsin on 16/4/11.
// Copyright © 2016年 MacTsin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZLAVideoImageView : UIImageView
- (void)addTarget:(id)target action:(SEL)action;
/** loadingLabel */
@property (nonatomic, weak) UILabel *loadingLabel;
@end
| {'content_hash': 'b78cb05a84f8fdffb17db31f50060392', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 51, 'avg_line_length': 19.176470588235293, 'alnum_prop': 0.7024539877300614, 'repo_name': 'TsinHzl/ZLApp', 'id': 'af48a4a12bb19f17cf751e2a67bba450f78d3483', 'size': '329', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ZLApp/Classes/Video(视频)/View/ZLAVideoImageView.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '55057'}, {'name': 'Objective-C', 'bytes': '148610'}, {'name': 'Ruby', 'bytes': '192'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<recipeml version="0.5">
<recipe>
<head>
<title>Almond Fruit Balls</title>
<categories>
<cat>Almonds</cat>
<cat>Desserts</cat></categories>
<yield>24</yield></head>
<ingredients>
<ing>
<amt>
<qty>1</qty>
<unit>cup</unit></amt>
<item>Whole natural almonds; toasted *</item></ing>
<ing>
<amt>
<qty>6</qty>
<unit>ounces</unit></amt>
<item>Mixed dried fruit bits</item></ing>
<ing>
<amt>
<qty>1 1/2</qty>
<unit>teaspoons</unit></amt>
<item>Honey</item></ing>
<ing>
<amt>
<qty>1/2</qty>
<unit>teaspoons</unit></amt>
<item>Cinnamon</item></ing>
<ing>
<amt>
<qty>1/4</qty>
<unit>teaspoons</unit></amt>
<item>Nutmeg</item></ing>
<ing>
<amt>
<qty>1 1/2</qty>
<unit>tablespoons</unit></amt>
<item>Orange-flavored liqueur</item></ing></ingredients>
<directions>
<step> Place almonds in bowl of food processor fitted with steel blade; process
until finely chopped. Add fruit, honey, cinnamon and nutmeg. Pulse on and
off a few times, then process to make a rough paste. Add liqueur and
process to make a firm, sticky paste. (Add more liqueur, a few drops at a
time, if needed to make a slightly moist dough.) Shape into 1-inch balls,
rolling between palms of hands. Pack loosely in airtight container with
waxed paper between layers. Serve as confections or as dessert with coffee
or tea. These make a nice gift, packed in an attractive tin or box. Recipe
can be doubled.
Servings: 24 balls
* To toast almonds, spread in an ungreased baking pan. Place in 350 degree
oven and bake 5 to 10 minutes or until almonds are light brown; stir once
or twice to assure even browning. Note that almonds will continue to brown
slightly after removing from oven.
See http://www.almondsarein.com/ >Hanneman/Buster/MasterCook 1998/Ap
Recipe by: Almond Board of California
Posted to MC-Recipe Digest by KitPATh <phannema@wizard.ucr.edu> on Apr 08,
1998
</step></directions></recipe></recipeml>
| {'content_hash': 'b081e8aa97dbb0658e635fb1519bbc92', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 86, 'avg_line_length': 34.56716417910448, 'alnum_prop': 0.6044905008635578, 'repo_name': 'coogle/coogle-recipes', 'id': 'de5d49e3e3b0aa3c3a836c3154f816da46cab8fc', 'size': '2316', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'extras/recipes/Almond_Fruit_Balls.xml', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Blade', 'bytes': '70365'}, {'name': 'CSS', 'bytes': '2508'}, {'name': 'HTML', 'bytes': '1294'}, {'name': 'JavaScript', 'bytes': '1133'}, {'name': 'PHP', 'bytes': '130922'}, {'name': 'Puppet', 'bytes': '23814'}, {'name': 'SCSS', 'bytes': '1015'}, {'name': 'Shell', 'bytes': '3538'}, {'name': 'Vue', 'bytes': '559'}]} |
class PerWattIncentive < Incentive
def derate?
derate
end
def value_for(profile_or_quote)
if applicable_to(profile_or_quote)
value = watts_for(profile_or_quote) * rate
if maximum_amount.blank? && maximum_percentage.blank?
value
else
unless maximum_amount.blank?
maximum = maximum_amount
else
maximum = maximum_percentage * profile_or_quote.total_price
end
[ value, maximum ].min
end
else
0.0
end
end
end | {'content_hash': 'c195794640a81054034c1a7896b13d14', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 69, 'avg_line_length': 21.28, 'alnum_prop': 0.5921052631578947, 'repo_name': 'jdhollis/renewzle', 'id': '4d42b33423670a12350f60ea00dd62d2079fa064', 'size': '532', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/models/per_watt_incentive.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '22312'}, {'name': 'Ruby', 'bytes': '641869'}]} |
module Admin
class CouponsController < Admin::ApplicationController
# To customize the behavior of this controller,
# simply overwrite any of the RESTful actions. For example:
#
# def index
# super
# @resources = Coupon.all.paginate(10, params[:page])
# end
# Define a custom finder by overriding the `find_resource` method:
# def find_resource(param)
# Coupon.find_by!(slug: param)
# end
# See https://administrate-docs.herokuapp.com/customizing_controller_actions
# for more information
end
end
| {'content_hash': '6d8bde2d3b1409d7945c72ffa08e1e6d', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 80, 'avg_line_length': 29.526315789473685, 'alnum_prop': 0.6809269162210339, 'repo_name': 'Discounty/Discounty', 'id': '05b1f60afa1bffd10d670c28767a44cad6448e45', 'size': '561', 'binary': False, 'copies': '1', 'ref': 'refs/heads/development', 'path': 'app/controllers/admin/coupons_controller.rb', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '65977'}, {'name': 'HTML', 'bytes': '29353'}, {'name': 'JavaScript', 'bytes': '64343'}, {'name': 'Ruby', 'bytes': '163482'}]} |
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
/**
* CommentsRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class CommentsRepository extends EntityRepository
{
}
| {'content_hash': '0431788ca6f28406f61a69b205421194', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 68, 'avg_line_length': 17.4, 'alnum_prop': 0.7662835249042146, 'repo_name': 'mizualps/blog', 'id': 'c5a4d314a0fc5f0e6a12f909055bfdfdb14779df', 'size': '261', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/AppBundle/Repository/CommentsRepository.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '3606'}, {'name': 'HTML', 'bytes': '5568'}, {'name': 'PHP', 'bytes': '77943'}]} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>DestinyActivityLoadoutRequirementSet | The Traveler</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">The Traveler</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="destinyactivityloadoutrequirementset.html">DestinyActivityLoadoutRequirementSet</a>
</li>
</ul>
<h1>Interface DestinyActivityLoadoutRequirementSet</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">DestinyActivityLoadoutRequirementSet</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="destinyactivityloadoutrequirementset.html#requirements" class="tsd-kind-icon">requirements</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="requirements" class="tsd-anchor"></a>
<h3>requirements</h3>
<div class="tsd-signature tsd-kind-icon">requirements<span class="tsd-signature-symbol">:</span> <a href="destinyactivityloadoutrequirement.html" class="tsd-signature-type">DestinyActivityLoadoutRequirement</a><span class="tsd-signature-symbol">[]</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/alexanderwe/the-traveler/blob/bfd7db0/src/type-definitions/destiny2/interfaces.ts#L2547">type-definitions/destiny2/interfaces.ts:2547</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>The set of requirements that will be applied on the activity if this requirement
set is active.</p>
</div>
</div>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-is-external">
<a href="destinyactivityloadoutrequirementset.html" class="tsd-kind-icon">Destiny<wbr>Activity<wbr>Loadout<wbr>Requirement<wbr>Set</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="destinyactivityloadoutrequirementset.html#requirements" class="tsd-kind-icon">requirements</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer>
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {'content_hash': '2b9112c83b075c350333dc092e6a8eb0', 'timestamp': '', 'source': 'github', 'line_count': 200, 'max_line_length': 265, 'avg_line_length': 49.2, 'alnum_prop': 0.6659552845528456, 'repo_name': 'alexanderwe/the-traveler', 'id': '211cfebc3c77c70a275c0054f9f3b58ba44dd2e9', 'size': '9840', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/interfaces/destinyactivityloadoutrequirementset.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '298'}, {'name': 'TypeScript', 'bytes': '690965'}]} |
package org.apache.spark.sql.hive
import java.nio.ByteBuffer
import scala.collection.JavaConverters._
import scala.collection.mutable.ArrayBuffer
import org.apache.hadoop.hive.ql.exec._
import org.apache.hadoop.hive.ql.udf.{UDFType => HiveUDFType}
import org.apache.hadoop.hive.ql.udf.generic._
import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator.AggregationBuffer
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF._
import org.apache.hadoop.hive.ql.udf.generic.GenericUDFUtils.ConversionHelper
import org.apache.hadoop.hive.serde2.objectinspector.{ConstantObjectInspector, ObjectInspector, ObjectInspectorFactory}
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory.ObjectInspectorOptions
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.expressions.aggregate._
import org.apache.spark.sql.catalyst.expressions.codegen.CodegenFallback
import org.apache.spark.sql.hive.HiveShim._
import org.apache.spark.sql.types._
private[hive] case class HiveSimpleUDF(
name: String, funcWrapper: HiveFunctionWrapper, children: Seq[Expression])
extends Expression with HiveInspectors with CodegenFallback with Logging {
override def deterministic: Boolean = isUDFDeterministic
override def nullable: Boolean = true
@transient
lazy val function = funcWrapper.createFunction[UDF]()
@transient
private lazy val method =
function.getResolver.getEvalMethod(children.map(_.dataType.toTypeInfo).asJava)
@transient
private lazy val arguments = children.map(toInspector).toArray
@transient
private lazy val isUDFDeterministic = {
val udfType = function.getClass.getAnnotation(classOf[HiveUDFType])
udfType != null && udfType.deterministic() && !udfType.stateful()
}
override def foldable: Boolean = isUDFDeterministic && children.forall(_.foldable)
// Create parameter converters
@transient
private lazy val conversionHelper = new ConversionHelper(method, arguments)
override lazy val dataType = javaTypeToDataType(method.getGenericReturnType)
@transient
private lazy val wrappers = children.map(x => wrapperFor(toInspector(x), x.dataType)).toArray
@transient
lazy val unwrapper = unwrapperFor(ObjectInspectorFactory.getReflectionObjectInspector(
method.getGenericReturnType, ObjectInspectorOptions.JAVA))
@transient
private lazy val cached: Array[AnyRef] = new Array[AnyRef](children.length)
@transient
private lazy val inputDataTypes: Array[DataType] = children.map(_.dataType).toArray
// TODO: Finish input output types.
override def eval(input: InternalRow): Any = {
val inputs = wrap(children.map(_.eval(input)), wrappers, cached, inputDataTypes)
val ret = FunctionRegistry.invoke(
method,
function,
conversionHelper.convertIfNecessary(inputs : _*): _*)
unwrapper(ret)
}
override def toString: String = {
s"$nodeName#${funcWrapper.functionClassName}(${children.mkString(",")})"
}
override def prettyName: String = name
override def sql: String = s"$name(${children.map(_.sql).mkString(", ")})"
}
// Adapter from Catalyst ExpressionResult to Hive DeferredObject
private[hive] class DeferredObjectAdapter(oi: ObjectInspector, dataType: DataType)
extends DeferredObject with HiveInspectors {
private val wrapper = wrapperFor(oi, dataType)
private var func: () => Any = _
def set(func: () => Any): Unit = {
this.func = func
}
override def prepare(i: Int): Unit = {}
override def get(): AnyRef = wrapper(func()).asInstanceOf[AnyRef]
}
private[hive] case class HiveGenericUDF(
name: String, funcWrapper: HiveFunctionWrapper, children: Seq[Expression])
extends Expression with HiveInspectors with CodegenFallback with Logging {
override def nullable: Boolean = true
override def deterministic: Boolean = isUDFDeterministic
override def foldable: Boolean =
isUDFDeterministic && returnInspector.isInstanceOf[ConstantObjectInspector]
@transient
lazy val function = funcWrapper.createFunction[GenericUDF]()
@transient
private lazy val argumentInspectors = children.map(toInspector)
@transient
private lazy val returnInspector = {
function.initializeAndFoldConstants(argumentInspectors.toArray)
}
@transient
private lazy val unwrapper = unwrapperFor(returnInspector)
@transient
private lazy val isUDFDeterministic = {
val udfType = function.getClass.getAnnotation(classOf[HiveUDFType])
udfType != null && udfType.deterministic() && !udfType.stateful()
}
@transient
private lazy val deferredObjects = argumentInspectors.zip(children).map { case (inspect, child) =>
new DeferredObjectAdapter(inspect, child.dataType)
}.toArray[DeferredObject]
override lazy val dataType: DataType = inspectorToDataType(returnInspector)
override def eval(input: InternalRow): Any = {
returnInspector // Make sure initialized.
var i = 0
val length = children.length
while (i < length) {
val idx = i
deferredObjects(i).asInstanceOf[DeferredObjectAdapter]
.set(() => children(idx).eval(input))
i += 1
}
unwrapper(function.evaluate(deferredObjects))
}
override def prettyName: String = name
override def toString: String = {
s"$nodeName#${funcWrapper.functionClassName}(${children.mkString(",")})"
}
}
/**
* Converts a Hive Generic User Defined Table Generating Function (UDTF) to a
* `Generator`. Note that the semantics of Generators do not allow
* Generators to maintain state in between input rows. Thus UDTFs that rely on partitioning
* dependent operations like calls to `close()` before producing output will not operate the same as
* in Hive. However, in practice this should not affect compatibility for most sane UDTFs
* (e.g. explode or GenericUDTFParseUrlTuple).
*
* Operators that require maintaining state in between input rows should instead be implemented as
* user defined aggregations, which have clean semantics even in a partitioned execution.
*/
private[hive] case class HiveGenericUDTF(
name: String,
funcWrapper: HiveFunctionWrapper,
children: Seq[Expression])
extends Generator with HiveInspectors with CodegenFallback {
@transient
protected lazy val function: GenericUDTF = {
val fun: GenericUDTF = funcWrapper.createFunction()
fun.setCollector(collector)
fun
}
@transient
protected lazy val inputInspectors = children.map(toInspector)
@transient
protected lazy val outputInspector = function.initialize(inputInspectors.toArray)
@transient
protected lazy val udtInput = new Array[AnyRef](children.length)
@transient
protected lazy val collector = new UDTFCollector
override lazy val elementSchema = StructType(outputInspector.getAllStructFieldRefs.asScala.map {
field => StructField(field.getFieldName, inspectorToDataType(field.getFieldObjectInspector),
nullable = true)
})
@transient
private lazy val inputDataTypes: Array[DataType] = children.map(_.dataType).toArray
@transient
private lazy val wrappers = children.map(x => wrapperFor(toInspector(x), x.dataType)).toArray
@transient
private lazy val unwrapper = unwrapperFor(outputInspector)
override def eval(input: InternalRow): TraversableOnce[InternalRow] = {
outputInspector // Make sure initialized.
val inputProjection = new InterpretedProjection(children)
function.process(wrap(inputProjection(input), wrappers, udtInput, inputDataTypes))
collector.collectRows()
}
protected class UDTFCollector extends Collector {
var collected = new ArrayBuffer[InternalRow]
override def collect(input: java.lang.Object) {
// We need to clone the input here because implementations of
// GenericUDTF reuse the same object. Luckily they are always an array, so
// it is easy to clone.
collected += unwrapper(input).asInstanceOf[InternalRow]
}
def collectRows(): Seq[InternalRow] = {
val toCollect = collected
collected = new ArrayBuffer[InternalRow]
toCollect
}
}
override def terminate(): TraversableOnce[InternalRow] = {
outputInspector // Make sure initialized.
function.close()
collector.collectRows()
}
override def toString: String = {
s"$nodeName#${funcWrapper.functionClassName}(${children.mkString(",")})"
}
override def prettyName: String = name
}
/**
* While being evaluated by Spark SQL, the aggregation state of a Hive UDAF may be in the following
* three formats:
*
* 1. An instance of some concrete `GenericUDAFEvaluator.AggregationBuffer` class
*
* This is the native Hive representation of an aggregation state. Hive `GenericUDAFEvaluator`
* methods like `iterate()`, `merge()`, `terminatePartial()`, and `terminate()` use this format.
* We call these methods to evaluate Hive UDAFs.
*
* 2. A Java object that can be inspected using the `ObjectInspector` returned by the
* `GenericUDAFEvaluator.init()` method.
*
* Hive uses this format to produce a serializable aggregation state so that it can shuffle
* partial aggregation results. Whenever we need to convert a Hive `AggregationBuffer` instance
* into a Spark SQL value, we have to convert it to this format first and then do the conversion
* with the help of `ObjectInspector`s.
*
* 3. A Spark SQL value
*
* We use this format for serializing Hive UDAF aggregation states on Spark side. To be more
* specific, we convert `AggregationBuffer`s into equivalent Spark SQL values, write them into
* `UnsafeRow`s, and then retrieve the byte array behind those `UnsafeRow`s as serialization
* results.
*
* We may use the following methods to convert the aggregation state back and forth:
*
* - `wrap()`/`wrapperFor()`: from 3 to 1
* - `unwrap()`/`unwrapperFor()`: from 1 to 3
* - `GenericUDAFEvaluator.terminatePartial()`: from 2 to 3
*/
private[hive] case class HiveUDAFFunction(
name: String,
funcWrapper: HiveFunctionWrapper,
children: Seq[Expression],
isUDAFBridgeRequired: Boolean = false,
mutableAggBufferOffset: Int = 0,
inputAggBufferOffset: Int = 0)
extends TypedImperativeAggregate[GenericUDAFEvaluator.AggregationBuffer] with HiveInspectors {
override def withNewMutableAggBufferOffset(newMutableAggBufferOffset: Int): ImperativeAggregate =
copy(mutableAggBufferOffset = newMutableAggBufferOffset)
override def withNewInputAggBufferOffset(newInputAggBufferOffset: Int): ImperativeAggregate =
copy(inputAggBufferOffset = newInputAggBufferOffset)
// Hive `ObjectInspector`s for all child expressions (input parameters of the function).
@transient
private lazy val inputInspectors = children.map(toInspector).toArray
// Spark SQL data types of input parameters.
@transient
private lazy val inputDataTypes: Array[DataType] = children.map(_.dataType).toArray
private def newEvaluator(): GenericUDAFEvaluator = {
val resolver = if (isUDAFBridgeRequired) {
new GenericUDAFBridge(funcWrapper.createFunction[UDAF]())
} else {
funcWrapper.createFunction[AbstractGenericUDAFResolver]()
}
val parameterInfo = new SimpleGenericUDAFParameterInfo(inputInspectors, false, false)
resolver.getEvaluator(parameterInfo)
}
// The UDAF evaluator used to consume raw input rows and produce partial aggregation results.
@transient
private lazy val partial1ModeEvaluator = newEvaluator()
// Hive `ObjectInspector` used to inspect partial aggregation results.
@transient
private val partialResultInspector = partial1ModeEvaluator.init(
GenericUDAFEvaluator.Mode.PARTIAL1,
inputInspectors
)
// The UDAF evaluator used to merge partial aggregation results.
@transient
private lazy val partial2ModeEvaluator = {
val evaluator = newEvaluator()
evaluator.init(GenericUDAFEvaluator.Mode.PARTIAL2, Array(partialResultInspector))
evaluator
}
// Spark SQL data type of partial aggregation results
@transient
private lazy val partialResultDataType = inspectorToDataType(partialResultInspector)
// The UDAF evaluator used to compute the final result from a partial aggregation result objects.
@transient
private lazy val finalModeEvaluator = newEvaluator()
// Hive `ObjectInspector` used to inspect the final aggregation result object.
@transient
private val returnInspector = finalModeEvaluator.init(
GenericUDAFEvaluator.Mode.FINAL,
Array(partialResultInspector)
)
// Wrapper functions used to wrap Spark SQL input arguments into Hive specific format.
@transient
private lazy val inputWrappers = children.map(x => wrapperFor(toInspector(x), x.dataType)).toArray
// Unwrapper function used to unwrap final aggregation result objects returned by Hive UDAFs into
// Spark SQL specific format.
@transient
private lazy val resultUnwrapper = unwrapperFor(returnInspector)
@transient
private lazy val cached: Array[AnyRef] = new Array[AnyRef](children.length)
@transient
private lazy val aggBufferSerDe: AggregationBufferSerDe = new AggregationBufferSerDe
override def nullable: Boolean = true
override lazy val dataType: DataType = inspectorToDataType(returnInspector)
override def prettyName: String = name
override def sql(isDistinct: Boolean): String = {
val distinct = if (isDistinct) "DISTINCT " else " "
s"$name($distinct${children.map(_.sql).mkString(", ")})"
}
override def createAggregationBuffer(): AggregationBuffer =
partial1ModeEvaluator.getNewAggregationBuffer
@transient
private lazy val inputProjection = UnsafeProjection.create(children)
override def update(buffer: AggregationBuffer, input: InternalRow): AggregationBuffer = {
partial1ModeEvaluator.iterate(
buffer, wrap(inputProjection(input), inputWrappers, cached, inputDataTypes))
buffer
}
override def merge(buffer: AggregationBuffer, input: AggregationBuffer): AggregationBuffer = {
// The 2nd argument of the Hive `GenericUDAFEvaluator.merge()` method is an input aggregation
// buffer in the 3rd format mentioned in the ScalaDoc of this class. Originally, Hive converts
// this `AggregationBuffer`s into this format before shuffling partial aggregation results, and
// calls `GenericUDAFEvaluator.terminatePartial()` to do the conversion.
partial2ModeEvaluator.merge(buffer, partial1ModeEvaluator.terminatePartial(input))
buffer
}
override def eval(buffer: AggregationBuffer): Any = {
resultUnwrapper(finalModeEvaluator.terminate(buffer))
}
override def serialize(buffer: AggregationBuffer): Array[Byte] = {
// Serializes an `AggregationBuffer` that holds partial aggregation results so that we can
// shuffle it for global aggregation later.
aggBufferSerDe.serialize(buffer)
}
override def deserialize(bytes: Array[Byte]): AggregationBuffer = {
// Deserializes an `AggregationBuffer` from the shuffled partial aggregation phase to prepare
// for global aggregation by merging multiple partial aggregation results within a single group.
aggBufferSerDe.deserialize(bytes)
}
// Helper class used to de/serialize Hive UDAF `AggregationBuffer` objects
private class AggregationBufferSerDe {
private val partialResultUnwrapper = unwrapperFor(partialResultInspector)
private val partialResultWrapper = wrapperFor(partialResultInspector, partialResultDataType)
private val projection = UnsafeProjection.create(Array(partialResultDataType))
private val mutableRow = new GenericInternalRow(1)
def serialize(buffer: AggregationBuffer): Array[Byte] = {
// `GenericUDAFEvaluator.terminatePartial()` converts an `AggregationBuffer` into an object
// that can be inspected by the `ObjectInspector` returned by `GenericUDAFEvaluator.init()`.
// Then we can unwrap it to a Spark SQL value.
mutableRow.update(0, partialResultUnwrapper(partial1ModeEvaluator.terminatePartial(buffer)))
val unsafeRow = projection(mutableRow)
val bytes = ByteBuffer.allocate(unsafeRow.getSizeInBytes)
unsafeRow.writeTo(bytes)
bytes.array()
}
def deserialize(bytes: Array[Byte]): AggregationBuffer = {
// `GenericUDAFEvaluator` doesn't provide any method that is capable to convert an object
// returned by `GenericUDAFEvaluator.terminatePartial()` back to an `AggregationBuffer`. The
// workaround here is creating an initial `AggregationBuffer` first and then merge the
// deserialized object into the buffer.
val buffer = partial2ModeEvaluator.getNewAggregationBuffer
val unsafeRow = new UnsafeRow(1)
unsafeRow.pointTo(bytes, bytes.length)
val partialResult = unsafeRow.get(0, partialResultDataType)
partial2ModeEvaluator.merge(buffer, partialResultWrapper(partialResult))
buffer
}
}
}
| {'content_hash': 'ff424b419011bd609503b4eb7caa08c0', 'timestamp': '', 'source': 'github', 'line_count': 449, 'max_line_length': 119, 'avg_line_length': 37.70824053452116, 'alnum_prop': 0.7540015356446754, 'repo_name': 'JerryLead/spark', 'id': '51c814cf32a8148ecedfaa1ec85f974487bb4d90', 'size': '17731', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'sql/hive/src/main/scala/org/apache/spark/sql/hive/hiveUDFs.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '32578'}, {'name': 'Batchfile', 'bytes': '24296'}, {'name': 'C', 'bytes': '1493'}, {'name': 'CSS', 'bytes': '23957'}, {'name': 'HTML', 'bytes': '9811'}, {'name': 'Java', 'bytes': '2837508'}, {'name': 'JavaScript', 'bytes': '140380'}, {'name': 'Makefile', 'bytes': '7774'}, {'name': 'PLpgSQL', 'bytes': '3031'}, {'name': 'PowerShell', 'bytes': '3751'}, {'name': 'Python', 'bytes': '2171117'}, {'name': 'R', 'bytes': '991497'}, {'name': 'Roff', 'bytes': '14302'}, {'name': 'SQLPL', 'bytes': '6233'}, {'name': 'Scala', 'bytes': '22309527'}, {'name': 'Shell', 'bytes': '155176'}, {'name': 'Thrift', 'bytes': '33605'}]} |
{% with author=action.primary_instance %}
<div class="extra text">
<h3 class="ui header">
<a href="{{ author.get_absolute_url }}">{{ author }}</a>
</h3>
</div>
{% endwith %}
| {'content_hash': 'a861bebd1062f986ab44f1a8974a5703', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 64, 'avg_line_length': 27.142857142857142, 'alnum_prop': 0.5631578947368421, 'repo_name': 'dellsystem/bookmarker', 'id': '67d61563ff55006e47d9af06a4c2612e73f4ad9d', 'size': '190', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/templates/actions/author.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2057'}, {'name': 'HTML', 'bytes': '142166'}, {'name': 'JavaScript', 'bytes': '8485'}, {'name': 'Python', 'bytes': '165926'}]} |
<HTML><HEAD>
<TITLE>Review for Sweet Hereafter, The (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0120255">Sweet Hereafter, The (1997)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Frankie+Paiva">Frankie Paiva</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>The Sweet Hereafter (R) ****
Starring Ian Holm, Sarah Polley
Directed by Atom Egoyan
A Review by Frankie Paiva</PRE>
<P>Has there ever been a film so spectacular and so wonderful that you have ever
been afraid to write a review for it? A picture show with a story so
fantastically woven into a great motion picture experience? If the slightest
word could set off someone or do disrespect to the film? This is exactly the
way I feel about The Sweet Hereafter which has just joined my Top 5 favorite
films of all time.</P>
<P>Mitchell Stephens (Holm) is a lawyer who has gone to a snowy town where
fourteen kids have died in a bus crash. He suggests that something was wrong
with the bus, and wants to file a claims suit for the damages experienced by
the families. He interviews various parents and victims of the crash including
Nicole (Polley) who has been confined to a wheelchair. </P>
<P>But Mitchell soons finds these problems connecting to what's happening in his
life with his troubled daughter. He learns certain lessons here that can help
him towards bettering the life of his family. He also has to deal with people
who are living in the past and cannot move on.</P>
<P>But it's not just the great screenplay (which was Oscar nominated) and the
great characters that appear that make this film what it is. It's the way the
film is shot. For some scenes, Egoyan fills the screen with people's mouth
quivering as they talk to one another, and rather then letting the film start
with the bus crash and have all of the conversations follow it, the film tells
the story is a weird sort of way, flashing back between after the accident,
before the accident, and the present day. </P>
<P>The film has robbed of all of the two Oscars it got nominated for. Where was
the Best Picture nomination? Where were the Supporting Actress and Best Actor
nods? Who cares about Titanic? I cried much more often in this than I did in
that. You need to see this film now! This instant! Go! Go to Blockbuster and
see The Sweet Hereafter which gets **** stars.</P>
<P>The Young-Uns: Brief frontal female nudity and some breasts are present as well
as some mild language. Good Age: 14 & Up</P>
<P>A Review by Frankie Paiva
The 12 Year-Old Movie Reviewer
E-Mail me at <A HREF="mailto:SwpStke@aol.com">SwpStke@aol.com</A>
Visit my website at: <A HREF="http://expage.com/page/teenagemoviecritic">http://expage.com/page/teenagemoviecritic</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {'content_hash': '5d010f3af5207c67950a6240de504c7c', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 208, 'avg_line_length': 63.12068965517241, 'alnum_prop': 0.7533460803059273, 'repo_name': 'xianjunzhengbackup/code', 'id': '8c2054e6c22082fa42fd1104260c464060fa3dfd', 'size': '3661', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'data science/machine_learning_for_the_web/chapter_4/movie/20257.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'BitBake', 'bytes': '113'}, {'name': 'BlitzBasic', 'bytes': '256'}, {'name': 'CSS', 'bytes': '49827'}, {'name': 'HTML', 'bytes': '157006325'}, {'name': 'JavaScript', 'bytes': '14029'}, {'name': 'Jupyter Notebook', 'bytes': '4875399'}, {'name': 'Mako', 'bytes': '2060'}, {'name': 'Perl', 'bytes': '716'}, {'name': 'Python', 'bytes': '874414'}, {'name': 'R', 'bytes': '454'}, {'name': 'Shell', 'bytes': '3984'}]} |
package com.sun.jini.test.spec.activation.util;
import java.lang.IllegalArgumentException;
import java.lang.reflect.InvocationHandler;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.rmi.Remote;
import com.sun.jini.test.spec.activation.util.ExceptionThrowingInterface;
/**
* An implementation of the {@link ExceptionThrowingInterface}
* class.
*/
public class ExceptionThrowingProxy implements ExceptionThrowingInterface {
private Logger logger;
private Throwable testedException;
public ExceptionThrowingProxy(Logger logger) {
logger.log(Level.FINEST, "OK");
this.logger = logger;
}
public void exceptionForThrow(Throwable testedException) {
logger.log(Level.FINEST, "testedException="
+ testedException.toString());
this.testedException = testedException;
};
public void throwsException() throws Throwable {
logger.log(Level.FINEST, "testedException="
+ testedException.toString());
throw testedException;
};
}
| {'content_hash': '5277e11c76129f1da60fe3027955c571', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 75, 'avg_line_length': 30.37142857142857, 'alnum_prop': 0.7196613358419567, 'repo_name': 'trasukg/river-qa-2.2', 'id': '175f8eeae936801126fa5db5d85588ced7ea20ff', 'size': '1869', 'binary': False, 'copies': '2', 'ref': 'refs/heads/2.2', 'path': 'qa/src/com/sun/jini/test/spec/activation/util/ExceptionThrowingProxy.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2047'}, {'name': 'Groovy', 'bytes': '17991'}, {'name': 'Java', 'bytes': '21668373'}, {'name': 'Shell', 'bytes': '117675'}]} |
class AddUsePacksToCampaign < ActiveRecord::Migration[5.2]
def change
add_column :campaigns, :use_packs, :boolean
end
end
| {'content_hash': 'a14aa408817723d863e42e8e0b9e55ea', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 58, 'avg_line_length': 26.0, 'alnum_prop': 0.7461538461538462, 'repo_name': 'scottag99/myhomelibrary', 'id': '9b34f52aea5fd6ab554e4defe570c86e2324a36f', 'size': '130', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'db/migrate/20201217212730_add_use_packs_to_campaign.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '969'}, {'name': 'CoffeeScript', 'bytes': '1266'}, {'name': 'HTML', 'bytes': '198535'}, {'name': 'JavaScript', 'bytes': '63342'}, {'name': 'Ruby', 'bytes': '242149'}, {'name': 'SCSS', 'bytes': '28024'}]} |
import abc
import six
from oslo_messaging._drivers.zmq_driver import zmq_names
@six.add_metaclass(abc.ABCMeta)
class Response(object):
def __init__(self, message_id=None, reply_id=None, message_version=None):
if self.msg_type not in zmq_names.RESPONSE_TYPES:
raise RuntimeError("Unknown response type!")
self._message_id = message_id
self._reply_id = reply_id
self._message_version = message_version
@abc.abstractproperty
def msg_type(self):
"""ZMQ response type"""
@property
def message_id(self):
return self._message_id
@property
def reply_id(self):
return self._reply_id
@property
def message_version(self):
return self._message_version
def to_dict(self):
return {zmq_names.FIELD_MSG_ID: self._message_id,
zmq_names.FIELD_REPLY_ID: self._reply_id,
zmq_names.FIELD_MSG_VERSION: self._message_version}
def __str__(self):
return str(self.to_dict())
class Ack(Response):
msg_type = zmq_names.ACK_TYPE
class Reply(Response):
msg_type = zmq_names.REPLY_TYPE
def __init__(self, message_id=None, reply_id=None, message_version=None,
reply_body=None, failure=None):
super(Reply, self).__init__(message_id, reply_id, message_version)
self._reply_body = reply_body
self._failure = failure
@property
def reply_body(self):
return self._reply_body
@property
def failure(self):
return self._failure
def to_dict(self):
dict_ = super(Reply, self).to_dict()
dict_.update({zmq_names.FIELD_REPLY_BODY: self._reply_body,
zmq_names.FIELD_FAILURE: self._failure})
return dict_
| {'content_hash': 'a564393ffc573434bfb7df1cc11f22e8', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 77, 'avg_line_length': 25.098591549295776, 'alnum_prop': 0.6133557800224467, 'repo_name': 'ozamiatin/oslo.messaging', 'id': '140feed460b1e495c99ca59f06160dc897e046f8', 'size': '2397', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'oslo_messaging/_drivers/zmq_driver/client/zmq_response.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '1221796'}, {'name': 'Shell', 'bytes': '8290'}]} |
module UseCases
module Argument
class GetQuestionArgument < ArgumentUseCase
def call
raise "Please provide at least one user" if request.user_ids.empty?
Response.new(argument: build_argument(request.question_id, request.user_ids))
end
private
def build_argument(question_id, user_ids)
argument_builder(question_id, user_ids).conclusion_level_argument
end
end
end
end
| {'content_hash': 'f5f7ff73ac454a47e11b1862d93086c0', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 85, 'avg_line_length': 24.27777777777778, 'alnum_prop': 0.6864988558352403, 'repo_name': 'jcbashdown/graph', 'id': 'b8da9c0db25454acdb260a237bcc91dc235cb1f6', 'size': '437', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/graph/use_cases/argument/get_question_argument.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '25776'}]} |
package net.safedata.spring.intro.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SuccessfulAuthHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
}
}
| {'content_hash': 'adca0e7d6971c24970f3da26dfc63f1f', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 128, 'avg_line_length': 37.0, 'alnum_prop': 0.8362480127186009, 'repo_name': 'bogdansolga/spring-intro', 'id': 'd8b8ce85ae59991f50334c6bdb5db9e0556efedb', 'size': '629', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-intro-s12/spring-intro-s12-complete/src/main/java/net/safedata/spring/intro/security/SuccessfulAuthHandler.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1407'}, {'name': 'HTML', 'bytes': '38080'}, {'name': 'Java', 'bytes': '128904'}, {'name': 'JavaScript', 'bytes': '30501'}, {'name': 'PLpgSQL', 'bytes': '14777'}]} |
package com.twu.biblioteca;
public class Book extends Item {
private String author;
private String yearPublished;
public Book(String title, String author, String yearPublished) {
super(title);
this.author = author;
this.yearPublished = yearPublished;
}
public String getAuthor() {
return author;
}
public String getYearPublished() {
return yearPublished;
}
}
| {'content_hash': 'e59c1c4b65687b734201d815e315d9c7', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 68, 'avg_line_length': 18.291666666666668, 'alnum_prop': 0.642369020501139, 'repo_name': 'dneale/twu-biblioteca-dneale', 'id': 'acdc8f30a99147700a70f91570e824df58e06756', 'size': '439', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/twu/biblioteca/Book.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '20228'}]} |
//*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *
package com.familytime.model.entity;
import org.hibernate.validator.constraints.NotBlank;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Class for reflect table Role from persistence layout.
*
* @version 1.0
*/
@SuppressWarnings( "serial" )
@Entity
@Table(
name = "role"
)
public class Role implements Serializable {
/// *** Properties *** ///
@Id
@GeneratedValue
@Column( name = "id" )
protected Long id;
@NotBlank
@Column(name = "authority", unique = true)
protected String authority;
/**
* Default constructor.
*/
public Role() {
}
/**
* Constructor.
*
* @param authority Role type
*/
public Role(String authority) {
this.authority = authority;
}
//- SECTION :: GET -//
/**
* Get ID of the authority.
*
* @return Long ID of family
*/
public Long getId() {
return id;
}
/**
* Get authority.
*
* @return String Authority
*/
public String getAuthority() {
return authority;
}
//- SECTION :: SET -//
/**
* Set ID of the family.
*
* @param id Id of the family
*/
public void setId(Long id) {
this.id = id;
}
/**
* Set authority.
*
* @param authority Authority type
*/
public void setAuthority(String authority) {
this.authority = authority;
}
}
| {'content_hash': 'f8bff4c8db6f72658a09df368811158a', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 67, 'avg_line_length': 18.307692307692307, 'alnum_prop': 0.5492196878751501, 'repo_name': 'Valentine1996/FamilyTime', 'id': '282395142b8db24645fcdf883ec00a91612d0a43', 'size': '2099', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/familytime/model/entity/Role.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '210'}, {'name': 'Java', 'bytes': '237942'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>RC CAR: Data Fields</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">RC CAR
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li><a href="classes.html"><span>Data Structure Index</span></a></li>
<li><a href="inherits.html"><span>Class Hierarchy</span></a></li>
<li class="current"><a href="functions.html"><span>Data Fields</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li class="current"><a href="functions.html"><span>All</span></a></li>
<li><a href="functions_func.html"><span>Functions</span></a></li>
<li><a href="functions_vars.html"><span>Variables</span></a></li>
<li><a href="functions_rela.html"><span>Related Functions</span></a></li>
</ul>
</div>
<div id="navrow4" class="tabs3">
<ul class="tablist">
<li><a href="functions.html#index__"><span>_</span></a></li>
<li><a href="functions_a.html#index_a"><span>a</span></a></li>
<li><a href="functions_b.html#index_b"><span>b</span></a></li>
<li><a href="functions_c.html#index_c"><span>c</span></a></li>
<li><a href="functions_d.html#index_d"><span>d</span></a></li>
<li><a href="functions_e.html#index_e"><span>e</span></a></li>
<li><a href="functions_f.html#index_f"><span>f</span></a></li>
<li><a href="functions_g.html#index_g"><span>g</span></a></li>
<li><a href="functions_h.html#index_h"><span>h</span></a></li>
<li><a href="functions_i.html#index_i"><span>i</span></a></li>
<li><a href="functions_l.html#index_l"><span>l</span></a></li>
<li><a href="functions_m.html#index_m"><span>m</span></a></li>
<li><a href="functions_n.html#index_n"><span>n</span></a></li>
<li><a href="functions_o.html#index_o"><span>o</span></a></li>
<li><a href="functions_p.html#index_p"><span>p</span></a></li>
<li><a href="functions_r.html#index_r"><span>r</span></a></li>
<li><a href="functions_s.html#index_s"><span>s</span></a></li>
<li><a href="functions_t.html#index_t"><span>t</span></a></li>
<li><a href="functions_u.html#index_u"><span>u</span></a></li>
<li class="current"><a href="functions_v.html#index_v"><span>v</span></a></li>
<li><a href="functions_w.html#index_w"><span>w</span></a></li>
</ul>
</div>
</div><!-- top -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="contents">
<div class="textblock">Here is a list of all struct and union fields with links to the structures/unions they belong to:</div>
<h3><a class="anchor" id="index_v"></a>- v -</h3><ul>
<li>versionH
: <a class="el" href="struct_h_i_d_desc_descriptor.html#a25c3b37fcec9c0b6cd0b3aaa62c904f0">HIDDescDescriptor</a>
</li>
<li>versionL
: <a class="el" href="struct_h_i_d_desc_descriptor.html#abbe47c1ab026892a2d5ed0c8690f63c4">HIDDescDescriptor</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.10
</small></address>
</body>
</html>
| {'content_hash': '61de686f308785bc54d1386ca895edb5', 'timestamp': '', 'source': 'github', 'line_count': 136, 'max_line_length': 154, 'avg_line_length': 44.713235294117645, 'alnum_prop': 0.6248972208518336, 'repo_name': 'trex2000/Arobs-Academy', 'id': 'dbdd8be855a552881e63c72388979f7289e2f930', 'size': '6081', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Doxygen Generated/html/functions_v.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1354'}, {'name': 'C', 'bytes': '120493'}, {'name': 'C++', 'bytes': '179585'}, {'name': 'CSS', 'bytes': '62338'}, {'name': 'HTML', 'bytes': '10212564'}, {'name': 'JavaScript', 'bytes': '372178'}, {'name': 'Lua', 'bytes': '9671'}, {'name': 'Makefile', 'bytes': '1016'}, {'name': 'TeX', 'bytes': '1828367'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>regexp: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1 / regexp - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
regexp
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-15 18:57:04 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-15 18:57:04 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
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.7.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "https://github.com/coq-contribs/regexp"
license: "LGPL"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/RegExp"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword: regular expressions"
"keyword: Kleene algebra"
"category: Computer Science/Formal Languages Theory and Automata"
]
authors: [ "Takashi Miyamoto <tmiya@bu.iij4u.or.jp> [http://study-func-prog.blogspot.com/]" ]
bug-reports: "https://github.com/coq-contribs/regexp/issues"
dev-repo: "git+https://github.com/coq-contribs/regexp.git"
synopsis: "Regular Expression"
description: """
The Library RegExp is a Coq library for regular expression. The implementation is based on the Janusz Brzozowski's algorithm ("Derivatives of Regular Expressions", Journal of the ACM 1964).
The RegExp library satisfies the axioms of Kleene Algebra. The proofs are shown in the library."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/regexp/archive/v8.6.0.tar.gz"
checksum: "md5=1504590c0ff7dfc943a2ebf97e2c1975"
}
</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-regexp.8.6.0 coq.8.7.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1).
The following dependencies couldn't be met:
- coq-regexp -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-regexp.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': 'f36af563f1c1c6122a99156a5e2f169b', 'timestamp': '', 'source': 'github', 'line_count': 168, 'max_line_length': 203, 'avg_line_length': 41.98809523809524, 'alnum_prop': 0.5452225687553162, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '33d7dc5d25f4bc8d5919757bd6aaabb7571554dc', 'size': '7079', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1/regexp/8.6.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
<!--
Description: item link relative to document URI
Expect: not bozo and entries[0]['link'] == 'http://127.0.0.1:8097/relative/uri'
-->
<rss version="2.0">
<channel>
<item>
<link>/relative/uri</link>
</item>
</channel>
</rss> | {'content_hash': 'ef00f2c437ae6a8a517e72a0406bfc22', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 84, 'avg_line_length': 21.0, 'alnum_prop': 0.645021645021645, 'repo_name': 'simplepie/simplepie-ng', 'id': '3df40d056f6453cfca2f09cab10b68ec3534900c', 'size': '231', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tests/Integration/feeds/wellformed/base/http_item_link_base_docuri.xml', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '22404'}, {'name': 'Makefile', 'bytes': '8026'}, {'name': 'PHP', 'bytes': '505427'}, {'name': 'Python', 'bytes': '10399'}, {'name': 'Roff', 'bytes': '2170'}, {'name': 'Shell', 'bytes': '271'}, {'name': 'XSLT', 'bytes': '734'}]} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
Ber. dt. bot. Ges. 35: (1917)
#### Original name
Lachnaster gracilis Höhn.
### Remarks
null | {'content_hash': '0614e91b62970bc1de52bfe81010f0ef', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 29, 'avg_line_length': 11.923076923076923, 'alnum_prop': 0.6774193548387096, 'repo_name': 'mdoering/backbone', 'id': '272c9308e4c15791d1f4d165a090a273f342fbf3', 'size': '206', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Fungi/Ascomycota/Leotiomycetes/Helotiales/Hyaloscyphaceae/Lachnum/Lachnaster gracilis/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
package cli
import (
"fmt"
"github.com/brightbox/gobrightbox"
"gopkg.in/alecthomas/kingpin.v2"
"strings"
)
type serverGroupsCommand struct {
*CLIApp
Id string
Dst string
IdList []string
Name *string
Description *string
}
func (l *serverGroupsCommand) list(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
groups, err := l.Client.ServerGroups()
if err != nil {
return err
}
w := tabWriter()
defer w.Flush()
listRec(w, "ID", "SERVER_COUNT", "FWPOLICY", "NAME")
for _, s := range groups {
listRec(
w, s.Id, len(s.Servers), s.FirewallPolicy.Id, s.Name)
}
return nil
}
func (l *serverGroupsCommand) show(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
w := tabWriterRight()
defer w.Flush()
g, err := l.Client.ServerGroup(l.Id)
if err != nil {
l.Fatalf(err.Error())
}
drawShow(w, []interface{}{
"id", g.Id,
"name", g.Name,
"default", g.Default,
"servers", collectById(g.Servers),
"firewall_policy", g.FirewallPolicy.Id,
"description", g.Description,
})
return nil
}
func (l *serverGroupsCommand) create(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
newGroup := brightbox.ServerGroupOptions{
Name: l.Name,
Description: l.Description,
}
group, err := l.Client.CreateServerGroup(&newGroup)
if err != nil {
return err
}
w := tabWriter()
defer w.Flush()
listRec(w, "ID", "SERVER_COUNT", "FWPOLICY", "NAME")
listRec(
w, group.Id, len(group.Servers), group.FirewallPolicy.Id, group.Name)
return nil
}
func (l *serverGroupsCommand) update(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
updateGroup := brightbox.ServerGroupOptions{
Id: l.Id,
Name: l.Name,
Description: l.Description,
}
group, err := l.Client.UpdateServerGroup(&updateGroup)
if err != nil {
return err
}
w := tabWriter()
defer w.Flush()
listRec(w, "ID", "SERVER_COUNT", "FWPOLICY", "NAME")
listRec(
w, group.Id, len(group.Servers), group.FirewallPolicy.Id, group.Name)
return nil
}
func (l *serverGroupsCommand) destroy(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
returnError := false
for _, id := range l.IdList {
fmt.Printf("Destroying server group %s\n", id)
err := l.Client.DestroyServerGroup(id)
if err != nil {
l.Errorf("%s: %s", err.Error(), id)
returnError = true
}
}
if returnError {
return errGeneric
}
return nil
}
func (l *serverGroupsCommand) add(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
fmt.Printf("Adding servers %s to server group %s\n", strings.Join(l.IdList, ", "), l.Id)
_, err = l.Client.AddServersToServerGroup(l.Id, l.IdList)
if err != nil {
return err
}
return nil
}
func (l *serverGroupsCommand) remove(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
fmt.Printf("Removing servers %s to server group %s\n", strings.Join(l.IdList, ", "), l.Id)
_, err = l.Client.RemoveServersFromServerGroup(l.Id, l.IdList)
if err != nil {
return err
}
return nil
}
func (l *serverGroupsCommand) move(pc *kingpin.ParseContext) error {
err := l.Configure()
if err != nil {
return err
}
fmt.Printf("Moving servers %s from server group %s to server group %s\n", strings.Join(l.IdList, ", "), l.Dst, l.Id)
_, err = l.Client.MoveServersToServerGroup(l.Id, l.Dst, l.IdList)
if err != nil {
return err
}
return nil
}
func configureServerGroupsCommand(app *CLIApp) {
cmd := serverGroupsCommand{CLIApp: app}
groups := app.Command("groups", "manage server groups")
groups.Command("list", "list server groups").
Default().Action(cmd.list)
show := groups.Command("show", "View details of a server group").
Action(cmd.show)
show.Arg("identifier", "id of server group to show").
StringVar(&cmd.Id)
create := groups.Command("create", "Create a new server group").
Action(cmd.create)
create.Flag("name", "Name to give the new server group").
Short('n').SetValue(&pStringValue{&cmd.Name})
create.Flag("description", "Description to give the new server group").
Short('d').SetValue(&pStringValue{&cmd.Description})
update := groups.Command("update", "Update a new server group").
Action(cmd.update)
update.Arg("identifier", "id of server group to update").
Required().StringVar(&cmd.Id)
update.Flag("name", "Set a new name for the server group").
Short('n').SetValue(&pStringValue{&cmd.Name})
update.Flag("description", "Set a new description for the server group").
Short('d').SetValue(&pStringValue{&cmd.Description})
destroy := groups.Command("destroy", "Destroy a server group").
Action(cmd.destroy)
destroy.Arg("identifier", "Identifier of server groupto destroy").
Required().StringsVar(&cmd.IdList)
add := groups.Command("add_servers", "Add servers to a server group").
Action(cmd.add)
add.Arg("group_identifier", "Identifier of group to add the servers to").
Required().StringVar(&cmd.Id)
add.Arg("server_identifiers", "Identifiers of servers to add to the group").
Required().StringsVar(&cmd.IdList)
rem := groups.Command("remove_servers", "Remove servers from a server group").
Action(cmd.remove)
rem.Arg("group_identifier", "Identifier of group to remove the servers from").
Required().StringVar(&cmd.Id)
rem.Arg("server_identifiers", "Identifiers of servers to remove from the group").
Required().StringsVar(&cmd.IdList)
mv := groups.Command("move_servers", "Move servers between server groups").
Action(cmd.move)
mv.Arg("src_group_identifier", "Identifier of group to move the servers from").
Required().StringVar(&cmd.Id)
mv.Arg("dst_group_identifier", "Identifier of group to move the servers to").
Required().StringVar(&cmd.Dst)
mv.Arg("server_identifiers", "Identifiers of servers to move").
Required().StringsVar(&cmd.IdList)
}
| {'content_hash': 'f536a06f14b77ba9d6caf451bdfda060', 'timestamp': '', 'source': 'github', 'line_count': 220, 'max_line_length': 117, 'avg_line_length': 27.09090909090909, 'alnum_prop': 0.6788590604026845, 'repo_name': 'brightbox/gobrightbox-cli', 'id': 'b9ec8d4fc4251c10af640d399dd5b58a8ba8240a', 'size': '5960', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cli/server_groups.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '64724'}, {'name': 'Shell', 'bytes': '332'}]} |
package org.apache.sshd.client.auth.password;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.sshd.util.test.JUnitTestSupport;
import org.apache.sshd.util.test.NoIoTestCase;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runners.MethodSorters;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category({ NoIoTestCase.class })
public class PasswordIdentityProviderTest extends JUnitTestSupport {
public PasswordIdentityProviderTest() {
super();
}
@Test
public void testMultiProvider() throws IOException, GeneralSecurityException {
String[][] values = {
{ getClass().getSimpleName(), getCurrentTestName() },
{ new Date(System.currentTimeMillis()).toString() },
{ getClass().getPackage().getName() }
};
List<String> expected = new ArrayList<>();
Collection<PasswordIdentityProvider> providers = new LinkedList<>();
for (String[] va : values) {
Collection<String> passwords = Arrays.asList(va);
expected.addAll(passwords);
PasswordIdentityProvider p = PasswordIdentityProvider.wrapPasswords(passwords);
assertProviderContents("Wrapped", p, passwords);
providers.add(p);
}
PasswordIdentityProvider p = PasswordIdentityProvider.multiProvider(null, providers);
assertProviderContents("Multi", p, expected);
}
private static void assertProviderContents(String message, PasswordIdentityProvider p, Iterable<String> expected)
throws IOException, GeneralSecurityException {
assertNotNull(message + ": no provider", p);
assertEquals(message, expected, p.loadPasswords(null));
}
}
| {'content_hash': '4d74607626cd1fbf9181a9f65beaad00', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 117, 'avg_line_length': 35.793103448275865, 'alnum_prop': 0.7023121387283237, 'repo_name': 'apache/mina-sshd', 'id': '679f515bb56a64dceffed6ddd74134a07b3952ba', 'size': '2877', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sshd-common/src/test/java/org/apache/sshd/client/auth/password/PasswordIdentityProviderTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '15035'}, {'name': 'HTML', 'bytes': '6129'}, {'name': 'Java', 'bytes': '8143189'}, {'name': 'Python', 'bytes': '11690'}, {'name': 'Shell', 'bytes': '36747'}]} |
package com.produban.openbus.trident;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import backtype.storm.tuple.Values;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import storm.trident.tuple.TridentTuple;
public class ParseProxy extends BaseFunction {
private static final Logger log = LoggerFactory.getLogger(ParseProxy.class);
public static final char SEPARADOR='\001'; //caracter SOH
public static Pattern pattern = Pattern.compile("(?<cabecera>(.{15}) (.*) ([^:]*)): \\s+((?<eventTimeStamp>(.{19})) (?<timeTaken>(\\d+)) (?<clientIP>(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3})) (?<User>(.*?)) (?<Group>(.*?)) (?<Exception>(.*?)) (?<filterResult>(\\S+)) (?<category>\"?([^\"]*)\"?) (?<referer>(\\S+))\\s+(?<responseCode>(\\d+)) (?<action>(\\S+)) (?<method>(\\S+)) (?<contentType>(\\S+)) (?<protocol>(\\S+)) (?<requestDomain>(\\S+)) (?<requestPort>(\\d+)) (?<requestPath>(\\S+)) (?<requestQuery>(.*?)) (?<requestURIExtension>(\\S+)) (?<userAgent>\"?([^\"]*)\"?) (?<serverIP>(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3})) (?<scBytes>(\\d+)) (?<csBytes>(\\d+)) (?<virusID>(\\S+)) (\\S+) (\\S+) (?<destinationIP>(\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}))?(.*))");
@Override
public void execute(TridentTuple tupla, TridentCollector colector) {
Matcher matcher = pattern.matcher(tupla.getString(0));
String resultado;
if (matcher.find()) {
//colector.emit(new Values(resultado));
colector.emit(new Values(matcher.group("eventTimeStamp"),
matcher.group("timeTaken"),
matcher.group("clientIP"),
matcher.group("User"),
matcher.group("Group"),
matcher.group("Exception"),
matcher.group("filterResult"),
matcher.group("category"),
matcher.group("referer"),
matcher.group("responseCode"),
matcher.group("action"),
matcher.group("method"),
matcher.group("contentType"),
matcher.group("protocol"),
matcher.group("requestDomain"),
matcher.group("requestPort"),
matcher.group("requestPath"),
matcher.group("requestQuery"),
matcher.group("requestURIExtension"),
matcher.group("userAgent"),
matcher.group("serverIP"),
matcher.group("scBytes"),
matcher.group("csBytes"),
matcher.group("virusID"),
matcher.group("destinationIP")));
}
}
}
| {'content_hash': 'cae0261b2a3ed497fb912e30a2f9843d', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 757, 'avg_line_length': 41.827586206896555, 'alnum_prop': 0.6302555647155812, 'repo_name': 'Produban/openbus', 'id': '455a7a406d35d85602b678570d6805da8d6266f2', 'size': '2426', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'onlineTopology/src/main/java/com/produban/openbus/trident/ParseProxy.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '67960'}, {'name': 'CSS', 'bytes': '48637'}, {'name': 'Java', 'bytes': '686010'}, {'name': 'JavaScript', 'bytes': '6860'}, {'name': 'PigLatin', 'bytes': '960'}, {'name': 'Shell', 'bytes': '3310'}]} |
package org.elasticsearch.common.xcontent;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.core.CheckedFunction;
import org.elasticsearch.xcontent.NamedXContentRegistry;
import org.elasticsearch.xcontent.XContentLocation;
import org.elasticsearch.xcontent.XContentParser;
import org.elasticsearch.xcontent.XContentParser.Token;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Consumer;
/**
* A set of static methods to get {@link Token} from {@link XContentParser}
* while checking for their types and throw {@link ParsingException} if needed.
*/
public final class XContentParserUtils {
private XContentParserUtils() {}
/**
* Makes sure that current token is of type {@link Token#FIELD_NAME} and the field name is equal to the provided one
* @throws ParsingException if the token is not of type {@link Token#FIELD_NAME} or is not equal to the given field name
*/
public static void ensureFieldName(XContentParser parser, Token token, String fieldName) throws IOException {
ensureExpectedToken(Token.FIELD_NAME, token, parser);
String currentName = parser.currentName();
if (currentName.equals(fieldName) == false) {
String message = "Failed to parse object: expecting field with name [%s] but found [%s]";
throw new ParsingException(parser.getTokenLocation(), String.format(Locale.ROOT, message, fieldName, currentName));
}
}
/**
* @throws ParsingException with a "unknown field found" reason
*/
public static void throwUnknownField(String field, XContentLocation location) {
String message = "Failed to parse object: unknown field [%s] found";
throw new ParsingException(location, String.format(Locale.ROOT, message, field));
}
/**
* @throws ParsingException with a "unknown token found" reason
*/
public static void throwUnknownToken(Token token, XContentLocation location) {
String message = "Failed to parse object: unexpected token [%s] found";
throw new ParsingException(location, String.format(Locale.ROOT, message, token));
}
/**
* Makes sure that provided token is of the expected type
*
* @throws ParsingException if the token is not equal to the expected type
*/
public static void ensureExpectedToken(Token expected, Token actual, XContentParser parser) {
if (actual != expected) {
throw parsingException(parser, expected, actual);
}
}
private static ParsingException parsingException(XContentParser parser, Token expected, Token actual) {
return new ParsingException(
parser.getTokenLocation(),
String.format(Locale.ROOT, "Failed to parse object: expecting token of type [%s] but found [%s]", expected, actual)
);
}
/**
* Parse the current token depending on its token type. The following token types will be
* parsed by the corresponding parser methods:
* <ul>
* <li>{@link Token#VALUE_STRING}: {@link XContentParser#text()}</li>
* <li>{@link Token#VALUE_NUMBER}: {@link XContentParser#numberValue()} ()}</li>
* <li>{@link Token#VALUE_BOOLEAN}: {@link XContentParser#booleanValue()} ()}</li>
* <li>{@link Token#VALUE_EMBEDDED_OBJECT}: {@link XContentParser#binaryValue()} ()}</li>
* <li>{@link Token#VALUE_NULL}: returns null</li>
* <li>{@link Token#START_OBJECT}: {@link XContentParser#mapOrdered()} ()}</li>
* <li>{@link Token#START_ARRAY}: {@link XContentParser#listOrderedMap()} ()}</li>
* </ul>
*
* @throws ParsingException if the token is none of the allowed values
*/
public static Object parseFieldsValue(XContentParser parser) throws IOException {
Token token = parser.currentToken();
Object value = null;
if (token == Token.VALUE_STRING) {
// binary values will be parsed back and returned as base64 strings when reading from json and yaml
value = parser.text();
} else if (token == Token.VALUE_NUMBER) {
value = parser.numberValue();
} else if (token == Token.VALUE_BOOLEAN) {
value = parser.booleanValue();
} else if (token == Token.VALUE_EMBEDDED_OBJECT) {
// binary values will be parsed back and returned as BytesArray when reading from cbor and smile
value = new BytesArray(parser.binaryValue());
} else if (token == Token.VALUE_NULL) {
value = null;
} else if (token == Token.START_OBJECT) {
value = parser.mapOrdered();
} else if (token == Token.START_ARRAY) {
value = parser.listOrderedMap();
} else {
throwUnknownToken(token, parser.getTokenLocation());
}
return value;
}
/**
* This method expects that the current field name is the concatenation of a type, a delimiter and a name
* (ex: terms#foo where "terms" refers to the type of a registered {@link NamedXContentRegistry.Entry},
* "#" is the delimiter and "foo" the name of the object to parse).
*
* It also expected that following this field name is either an Object or an array xContent structure and
* the cursor points to the start token of this structure.
*
* The method splits the field's name to extract the type and name and then parses the object
* using the {@link XContentParser#namedObject(Class, String, Object)} method.
*
* @param parser the current {@link XContentParser}
* @param delimiter the delimiter to use to splits the field's name
* @param objectClass the object class of the object to parse
* @param consumer something to consume the parsed object
* @param <T> the type of the object to parse
* @throws IOException if anything went wrong during parsing or if the type or name cannot be derived
* from the field's name
* @throws ParsingException if the parser isn't positioned on either START_OBJECT or START_ARRAY at the beginning
*/
public static <T> void parseTypedKeysObject(XContentParser parser, String delimiter, Class<T> objectClass, Consumer<T> consumer)
throws IOException {
if (parser.currentToken() != Token.START_OBJECT && parser.currentToken() != Token.START_ARRAY) {
throwUnknownToken(parser.currentToken(), parser.getTokenLocation());
}
String currentFieldName = parser.currentName();
if (Strings.hasLength(currentFieldName)) {
int position = currentFieldName.indexOf(delimiter);
if (position > 0) {
String type = currentFieldName.substring(0, position);
String name = currentFieldName.substring(position + 1);
consumer.accept(parser.namedObject(objectClass, type, name));
return;
}
// if we didn't find a delimiter we ignore the object or array for forward compatibility instead of throwing an error
parser.skipChildren();
} else {
throw new ParsingException(parser.getTokenLocation(), "Failed to parse object: empty key");
}
}
/**
* Parses a list of a given type from the given {@code parser}. Assumes that the parser is currently positioned on a
* {@link Token#START_ARRAY} token and will fail if it is not. The returned list may or may not be mutable.
*
* @param parser x-content parser
* @param valueParser parser for expected list value type
* @return list parsed from parser
*/
public static <T> List<T> parseList(XContentParser parser, CheckedFunction<XContentParser, T, IOException> valueParser)
throws IOException {
XContentParserUtils.ensureExpectedToken(Token.START_ARRAY, parser.currentToken(), parser);
if (parser.nextToken() == Token.END_ARRAY) {
return List.of();
}
final ArrayList<T> list = new ArrayList<>();
do {
list.add(valueParser.apply(parser));
} while (parser.nextToken() != Token.END_ARRAY);
return list;
}
}
| {'content_hash': '00546da07aff757df52146773a041962', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 132, 'avg_line_length': 47.5, 'alnum_prop': 0.6627990430622009, 'repo_name': 'GlenRSmith/elasticsearch', 'id': '900a159b65eb3ddb33608c093217f8255743c28c', 'size': '8713', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'server/src/main/java/org/elasticsearch/common/xcontent/XContentParserUtils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '11082'}, {'name': 'Batchfile', 'bytes': '11057'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '337461'}, {'name': 'HTML', 'bytes': '2186'}, {'name': 'Java', 'bytes': '43224931'}, {'name': 'Perl', 'bytes': '11756'}, {'name': 'Python', 'bytes': '19852'}, {'name': 'Shell', 'bytes': '99571'}]} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Open_Tera_Launcher.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| {'content_hash': 'c69ef05c31c893c3d0cecb31b00d4abc', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 151, 'avg_line_length': 41.26923076923077, 'alnum_prop': 0.5824790307548928, 'repo_name': 'jamiepg1/open-tera-launcher', 'id': 'cf1a11acd5534b4c0f1f2826de725533da326a8e', 'size': '1075', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Open Tera Launcher/Properties/Settings.Designer.cs', 'mode': '33188', 'license': 'mit', 'language': []} |
package greenapi.core.model.software.os;
import java.io.Serializable;
import java.util.Map;
import static java.util.Objects.requireNonNull;
import greenapi.core.model.data.Frequency;
import greenapi.core.model.data.IOStats;
import greenapi.core.model.data.Temperature;
import greenapi.core.model.resources.logic.Processes;
import greenapi.core.model.resources.net.NetworkInterface;
import greenapi.core.model.resources.net.NetworkInterfaces;
import greenapi.core.model.software.os.commands.Command;
import greenapi.core.model.software.os.commands.CpuScalingAvailableFrequencies;
import greenapi.core.model.software.os.commands.Who;
public abstract class OperatingSystem implements Serializable, Comparable<OperatingSystem>
{
/**
* Serial code version <code>serialVersionUID</code>.
*/
private static final long serialVersionUID = -63543969636463188L;
/**
* OS's name.
*/
private final String name;
/**
* Create an instance of this class.
*
* @param osName
* The OS's name.
*/
public OperatingSystem(String osName)
{
this.name = requireNonNull(osName);
}
/**
* Returns O.S's name.
*
* @return The O.S's name.
*/
public String name()
{
return name;
}
/**
* Returns the command to get the I/O states of a machine. This method does not execute the command.
*
* @return the command to get the I/O states of a machine.
*/
public abstract Command<IOStats> iostats();
/**
* Returns the command to get the CPU frequencies. This method does not execute the command.
*
* @return Returns the command to get the CPU frequencies.
*/
public abstract CpuScalingAvailableFrequencies cpuAvailableFrequencies();
/**
* Returns the actually CPU frequency.
*
* @return The actually CPU frequency.
*/
public abstract Frequency currentCpuFrequency();
/**
* Returns the CPUs' temperature.
*
* @return A {@link Map} with the temperature of each CPU. The key is id CPU's id.
*/
public abstract Map<String, Temperature> cpuTemperature();
/**
* Returns the description of a given network interface.
*
* @param id
* The id of the network interface.
* @return The description of a given network interface.
*/
public abstract NetworkInterface networkInterfaceDescription(String id);
/**
* Returns the available network interfaces.
*
* @return The available network interfaces.
*/
public abstract NetworkInterfaces networkInterfaces();
/**
* Returns the processes of this O.S.
*
* @return The processes of this O.S.
*/
public abstract Processes processes();
/**
* Returns the name of the active user.
*
* @return the name of the active user.
*/
public abstract Who who();
@Override
public int compareTo(OperatingSystem other)
{
return this.name.compareTo(other.name());
}
}
| {'content_hash': '2428cc88a87a7892afa0e8c4bf485e42', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 104, 'avg_line_length': 26.53448275862069, 'alnum_prop': 0.6575698505523067, 'repo_name': 'alessandroleite/greenapi', 'id': '5c51741aa5ecc6e0382d42c98e2709e0086d6af0', 'size': '4194', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/greenapi/core/model/software/os/OperatingSystem.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '424194'}]} |
<?php
namespace ZipkinTests\Unit\Reporters;
use PHPUnit_Framework_TestCase;
use Zipkin\Reporter;
use Zipkin\Reporters\Noop;
final class NoopTest extends PHPUnit_Framework_TestCase
{
public function testCreateNoopReporterSuccess()
{
$noopReporter = new Noop();
$this->assertInstanceOf(Reporter::class, $noopReporter);
}
}
| {'content_hash': '30774c536ae5d2b3e50c03969e400e82', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 64, 'avg_line_length': 22.0, 'alnum_prop': 0.7329545454545454, 'repo_name': 'jcchavezs/zipkin-php', 'id': 'e76a9198e0eb3096033fb330add306c2f0c623e0', 'size': '352', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/Unit/Reporters/NoopTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '141570'}]} |
package VMOMI::HostNatServiceConfig;
use parent 'VMOMI::DynamicData';
use strict;
use warnings;
our @class_ancestors = (
'DynamicData',
);
our @class_members = (
['changeOperation', undef, 0, 1],
['key', undef, 0, ],
['spec', 'HostNatServiceSpec', 0, ],
);
sub get_class_ancestors {
return @class_ancestors;
}
sub get_class_members {
my $class = shift;
my @super_members = $class->SUPER::get_class_members();
return (@super_members, @class_members);
}
1;
| {'content_hash': '0a1b7be0e7b2ef9af44b79aaaa33141b', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 59, 'avg_line_length': 18.333333333333332, 'alnum_prop': 0.6343434343434343, 'repo_name': 'stumpr/p5-vmomi', 'id': 'ce9fef689b80c3c222f27b471b66276f2ec7e5aa', 'size': '495', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/VMOMI/HostNatServiceConfig.pm', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Perl', 'bytes': '2084415'}]} |
<p>An email has been sent with password reset instructions</p> | {'content_hash': 'c1ee51f8e20d672fe2319a64a526a5bd', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 62, 'avg_line_length': 62.0, 'alnum_prop': 0.7903225806451613, 'repo_name': 'Sarah-Alsinan/muypicky', 'id': '914805a768b94830ffcd33d3cb35b0f9086b8ecb', 'size': '62', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/templates/registration/password_reset_done.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '47175'}, {'name': 'HTML', 'bytes': '145740'}, {'name': 'JavaScript', 'bytes': '115482'}, {'name': 'Python', 'bytes': '7684881'}, {'name': 'Shell', 'bytes': '3754'}]} |
package com.fissionworks.restalm.constants.field;
/**
* System fields that comprise Release objects in ALM; The ENUM is equal to the
* default label for fields that are displayed in the UI.
*
* @since 1.0.0
*/
public enum ReleaseField implements FieldName {
/**
* The description field for relating defects to their detected in release;
* field name is {@code description} with alias
* {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_DESCRIPTION("description", "defect-to-detected-release-mirror"),
/**
* The end date field for relating defects to their detected in release;
* field name is {@code end-date} with alias
* {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_END_DATE("end-date", "defect-to-detected-release-mirror"),
/**
* The ID field for relating defects to their detected in release; field
* name is {@code id} with alias {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_ID("id", "defect-to-detected-release-mirror"),
/**
* The name field for relating defects to their detected in release; field
* name is {@code name} with alias
* {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_NAME("name", "defect-to-detected-release-mirror"),
/**
* The parent id field for relating defects to their detected in release;
* field name is {@code parent-id} with alias
* {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_PARENT_ID("parent-id", "defect-to-detected-release-mirror"),
/**
* The start date field for relating defects to their detected in release;
* field name is {@code start-date} with alias
* {@code defect-to-detected-release-mirror}.
*
* @since 1.0.0
*/
DEFECT_DETECTED_RELEASE_START_DATE("start-date", "defect-to-detected-release-mirror"),
/**
* The description field; field name is {@code description} with alias
* {@code release}.
*
* @since 1.0.0
*/
DESCRIPTION("description", "release"),
/**
* The end date field; field name is {@code end-date} with alias
* {@code release}.
*
* @since 1.0.0
*/
END_DATE("end-date", "release"),
/**
* The ID field; field name is {@code id} with alias {@code release}.
*
* @since 1.0.0
*/
ID("id", "release"),
/**
* The name field; field name is {@code name} with alias {@code release}.
*
* @since 1.0.0
*/
NAME("name", "release"),
/**
* The parent id field; field name is {@code parent-id} with alias
* {@code release}.
*
* @since 1.0.0
*/
PARENT_ID("parent-id", "release"),
/**
* The start date field; field name is {@code start-date} with alias
* {@code release}.
*
* @since 1.0.0
*/
START_DATE("start-date", "release");
private final String alias;
private final String name;
private ReleaseField(final String theName, final String theAlias) {
this.name = theName;
this.alias = theAlias;
}
@Override
public String getName() {
return name;
}
@Override
public String getQualifiedName() {
return String.format("%s.%s", alias, name);
}
}
| {'content_hash': '7f2bcbec155a5083fc7272f9b24d26c4', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 89, 'avg_line_length': 24.5968992248062, 'alnum_prop': 0.6615190671289001, 'repo_name': 'stevensimmons/restalm', 'id': 'e70b7916e40aa26c297a3b1e095f8dac021d40ef', 'size': '3173', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/fissionworks/restalm/constants/field/ReleaseField.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '895873'}]} |
@implementation HCIsInstanceOf
- (BOOL)matches:(nullable id)item
{
return [item isKindOfClass:self.theClass];
}
- (NSString *)expectation
{
return @"an instance of ";
}
@end
id HC_instanceOf(Class expectedClass)
{
return [[HCIsInstanceOf alloc] initWithClass:expectedClass];
}
| {'content_hash': '31ffb6d7b32ab248301724fc97910d0e', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 64, 'avg_line_length': 15.473684210526315, 'alnum_prop': 0.717687074829932, 'repo_name': 'hamcrest/OCHamcrest', 'id': 'd63015fc526834cb14dd3767828342326a7e895c', 'size': '511', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'Source/Library/Object/HCIsInstanceOf.m', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Objective-C', 'bytes': '386344'}, {'name': 'Ruby', 'bytes': '2064'}, {'name': 'Shell', 'bytes': '3699'}, {'name': 'Swift', 'bytes': '1005'}]} |
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css','../assets/dashboard.css']
})
export class AppComponent {
title = 'app works!';
}
| {'content_hash': '2463e1ad9e6c53ac569a699d092f3ee4', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 62, 'avg_line_length': 24.0, 'alnum_prop': 0.6625, 'repo_name': 'ramanujamrs/angular-bootstrap-starter', 'id': '6b2d5c49db0f1ada442f4e4fb2bccf27c35cb762', 'size': '240', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/app.component.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2673'}, {'name': 'HTML', 'bytes': '4495'}, {'name': 'JavaScript', 'bytes': '1996'}, {'name': 'TypeScript', 'bytes': '9700'}]} |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddMeasurementsStationIdForeign extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('measurements', function (Blueprint $table) {
$table->foreign('station_id')
->references('id')
->on('stations')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('measurements', function (Blueprint $table) {
$table->dropForeign('measurements_station_id_foreign');
});
}
}
| {'content_hash': '4d01dff425e7798cf2b2f24b239764bd', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 67, 'avg_line_length': 22.176470588235293, 'alnum_prop': 0.5477453580901857, 'repo_name': 'Jarinus/2.1-unwdmi-web', 'id': 'e22532a4efd041a063052cc96bf0831fa8da1607', 'size': '754', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'database/migrations/2015_11_05_104511_add_measurements_station_id_foreign.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '412'}, {'name': 'CSS', 'bytes': '2509'}, {'name': 'JavaScript', 'bytes': '9487'}, {'name': 'PHP', 'bytes': '179338'}]} |
#include "driverBase.h"
int DriverBase::openDeviceFile(const char* name)
{
int file = open(name, O_RDWR);
if (file < 0) {
qDebug() << "Device file open failed.";
return -1;
}
return file;
}
bool DriverBase::setSlaveAddress(int file, unsigned char address)
{
if (ioctl(file, I2C_SLAVE, address) < 0) {
qDebug() << "ioctl failed.";
return false;
}
return true;
}
bool DriverBase::i2cWrite(int file, char buffer[], int buffer_length)
{
if (write(file, buffer, buffer_length) != buffer_length) {
close(file);
qDebug() << "Write failed.";
return false;
}
// qDebug() << "Write successfull.";
return true;
}
bool DriverBase::i2cRead(int file, char buffer[], int howManyBytesToRead)
{
if (read(file, buffer, howManyBytesToRead) != howManyBytesToRead) {
close(file);
qDebug() << "Read failed.";
return false;
}
// qDebug() << "Read successfull.";
return true;
}
bool DriverBase::writeBytes(unsigned char address, char bytes[], int length)
{
// try to open the device
int file = openDeviceFile("/dev/i2c-1");
if (file != -1) {
// set slave address
if (setSlaveAddress(file, address)) {
// try to perform the actual write
if (i2cWrite(file, bytes, length)) {
close(file);
return true;
}
}
}
close(file);
return false;
}
QByteArray DriverBase::readBytes(unsigned char address, int howManyBytesToRead)
{
QByteArray result;
char buffer[256];
if (howManyBytesToRead > 255)
{
qDebug() << "Reading too many bytes.";
return QByteArray();
}
// try to open the device
int file = openDeviceFile("/dev/i2c-1");
if (file != -1) {
// set slave address
if (setSlaveAddress(file, address)) {
// read from the register
if(i2cRead(file, buffer, howManyBytesToRead)) {
// convert to QByteArray
close(file);
for(int i = 0; i < howManyBytesToRead; ++i) {
result.append(buffer[i]);
}
return result;
}
}
}
// return empty QList in case of failure
return result;
}
QByteArray DriverBase::writeThenRead(unsigned char address,
char registerToRead,
int howManyBytesToRead) {
QByteArray result;
char reg[1];
reg[0] = registerToRead;
if (writeBytes(address, reg, 1)) {
result = readBytes(address, howManyBytesToRead);
}
return result;
}
| {'content_hash': '331703ba7a48042a28674fcabd1f6624', 'timestamp': '', 'source': 'github', 'line_count': 111, 'max_line_length': 79, 'avg_line_length': 24.27927927927928, 'alnum_prop': 0.5525046382189239, 'repo_name': 'kimmoli/tohiri', 'id': 'f7f8ebdc119077f56f5c8aeaafc1808416b0b68e', 'size': '3786', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/src/driverBase.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '20594'}]} |
package pl.chormon.ultimateclans.commands;
import pl.chormon.ultimateclans.Role;
import pl.chormon.ultimateclans.commands.req.ReqHasClan;
import pl.chormon.ultimateclans.commands.req.ReqRoleAtLeast;
/**
*
* @author Chormon
*/
public class CmdBoardRemove extends UCCommand {
public CmdBoardRemove() {
this.addAlias("usun");
this.addReq(new ReqHasClan());
this.addReq(new ReqRoleAtLeast(Role.MODERATOR));
}
@Override
public void perform() {
}
}
| {'content_hash': '14593e4c8406d14a14991b322326eb1e', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 60, 'avg_line_length': 19.615384615384617, 'alnum_prop': 0.6843137254901961, 'repo_name': 'Chormon/UltimateClans', 'id': '3065ab6ca24a0f1a5f7613b6d998155a7de98078', 'size': '1640', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/pl/chormon/ultimateclans/commands/CmdBoardRemove.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '88646'}]} |
package org.ofbiz.accounting.thirdparty.clearcommerce;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.transform.TransformerException;
import org.ofbiz.accounting.payment.PaymentGatewayServices;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.HttpClient;
import org.ofbiz.base.util.HttpClientException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilNumber;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* ClearCommerce Payment Services (CCE 5.4)
*/
public class CCPaymentServices {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private static int decimals = UtilNumber.getBigDecimalScale("invoice.decimals");
private static RoundingMode rounding = UtilNumber.getRoundingMode("invoice.rounding");
public final static String resource = "AccountingUiLabels";
private final static int maxSevComp = 4;
public static Map<String, Object> ccAuth(DispatchContext dctx, Map<String, Object> context) {
String ccAction = (String) context.get("ccAction");
Delegator delegator = dctx.getDelegator();
if (ccAction == null) {
ccAction = "PreAuth";
}
Document authRequestDoc = buildPrimaryTxRequest(context, ccAction, (BigDecimal) context.get("processAmount"),
(String) context.get("orderId"));
Document authResponseDoc = null;
try {
authResponseDoc = sendRequest(authRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(authResponseDoc) > maxSevComp) { // 5 and higher, process error from HSBC
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("authResult", Boolean.FALSE);
result.put("processAmount", BigDecimal.ZERO);
result.put("authRefNum", getReferenceNum(authResponseDoc));
List<String> messages = getMessageList(authResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processAuthResponse(authResponseDoc);
}
public static Map<String, Object> ccCredit(DispatchContext dctx, Map<String, Object> context) {
String action = "Credit";
Delegator delegator = dctx.getDelegator();
if (context.get("pbOrder") != null) {
action = "Auth"; // required for periodic billing....
}
Document creditRequestDoc = buildPrimaryTxRequest(context, action, (BigDecimal) context.get("creditAmount"),
(String) context.get("referenceCode"));
Document creditResponseDoc = null;
try {
creditResponseDoc = sendRequest(creditRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(creditResponseDoc) > maxSevComp) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("creditResult", Boolean.FALSE);
result.put("creditAmount", BigDecimal.ZERO);
result.put("creditRefNum", getReferenceNum(creditResponseDoc));
List<String> messages = getMessageList(creditResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processCreditResponse(creditResponseDoc);
}
public static Map<String, Object> ccCapture(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingPaymentTransactionAuthorizationNotFoundCannotCapture", locale));
}
Document captureRequestDoc = buildSecondaryTxRequest(context, authTransaction.getString("referenceNum"),
"PostAuth", (BigDecimal) context.get("captureAmount"), delegator);
Document captureResponseDoc = null;
try {
captureResponseDoc = sendRequest(captureRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(captureResponseDoc) > maxSevComp) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("captureResult", Boolean.FALSE);
result.put("captureAmount", BigDecimal.ZERO);
result.put("captureRefNum", getReferenceNum(captureResponseDoc));
List<String> messages = getMessageList(captureResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processCaptureResponse(captureResponseDoc);
}
public static Map<String, Object> ccRelease(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingPaymentTransactionAuthorizationNotFoundCannotRelease", locale));
}
Document releaseRequestDoc = buildSecondaryTxRequest(context, authTransaction.getString("referenceNum"), "Void",
null, delegator);
Document releaseResponseDoc = null;
try {
releaseResponseDoc = sendRequest(releaseRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(releaseResponseDoc) > maxSevComp) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("releaseResult", Boolean.FALSE);
result.put("releaseAmount", BigDecimal.ZERO);
result.put("releaseRefNum", getReferenceNum(releaseResponseDoc));
List<String> messages = getMessageList(releaseResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processReleaseResponse(releaseResponseDoc);
}
public static Map<String, Object> ccReleaseNoop(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingPaymentTransactionAuthorizationNotFoundCannotRelease", locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("releaseResult", Boolean.TRUE);
result.put("releaseCode", authTransaction.getString("gatewayCode"));
result.put("releaseAmount", authTransaction.getBigDecimal("amount"));
result.put("releaseRefNum", authTransaction.getString("referenceNum"));
result.put("releaseFlag", authTransaction.getString("gatewayFlag"));
result.put("releaseMessage", "Approved.");
return result;
}
public static Map<String, Object> ccRefund(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingPaymentTransactionAuthorizationNotFoundCannotRefund", locale));
}
// Although refunds are applied to captured transactions, using the auth reference number is ok here
// Related auth and capture transactions will always have the same reference number
Document refundRequestDoc = buildSecondaryTxRequest(context, authTransaction.getString("referenceNum"),
"Credit", (BigDecimal) context.get("refundAmount"), delegator);
Document refundResponseDoc = null;
try {
refundResponseDoc = sendRequest(refundRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(refundResponseDoc) > maxSevComp) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("refundResult", Boolean.FALSE);
result.put("refundAmount", BigDecimal.ZERO);
result.put("refundRefNum", getReferenceNum(refundResponseDoc));
List<String> messages = getMessageList(refundResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processRefundResponse(refundResponseDoc);
}
public static Map<String, Object> ccReAuth(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference);
if (authTransaction == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingPaymentTransactionAuthorizationNotFoundCannotReauth", locale));
}
Document reauthRequestDoc = buildSecondaryTxRequest(context, authTransaction.getString("referenceNum"),
"RePreAuth", (BigDecimal) context.get("reauthAmount"), delegator);
Document reauthResponseDoc = null;
try {
reauthResponseDoc = sendRequest(reauthRequestDoc, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
if (getMessageListMaxSev(reauthResponseDoc) > maxSevComp) {
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("reauthResult", Boolean.FALSE);
result.put("reauthAmount", BigDecimal.ZERO);
result.put("reauthRefNum", getReferenceNum(reauthResponseDoc));
List<String> messages = getMessageList(reauthResponseDoc);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
return processReAuthResponse(reauthResponseDoc);
}
public static Map<String, Object> ccReport(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
// configuration file
String paymentConfig = (String) context.get("paymentConfig");
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
// orderId
String orderId = (String) context.get("orderId");
if (UtilValidate.isEmpty(orderId)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"AccountingClearCommerceCannotExecuteReport", locale));
}
// EngineDocList
Document requestDocument = UtilXml.makeEmptyXmlDocument("EngineDocList");
Element engineDocListElement = requestDocument.getDocumentElement();
UtilXml.addChildElementValue(engineDocListElement, "DocVersion", "1.0", requestDocument);
// EngineDocList.EngineDoc
Element engineDocElement = UtilXml.addChildElement(engineDocListElement, "EngineDoc", requestDocument);
UtilXml.addChildElementValue(engineDocElement, "ContentType", "ReportDoc", requestDocument);
String sourceId = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.sourceId", delegator);
if (UtilValidate.isNotEmpty(sourceId)) {
UtilXml.addChildElementValue(engineDocElement, "SourceId", sourceId, requestDocument);
}
String groupId = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.groupId", delegator);
if (UtilValidate.isNotEmpty(groupId)) {
UtilXml.addChildElementValue(engineDocElement, "GroupId", groupId, requestDocument);
} else {
UtilXml.addChildElementValue(engineDocElement, "GroupId", orderId, requestDocument);
}
// EngineDocList.EngineDoc.User
Element userElement = UtilXml.addChildElement(engineDocElement, "User", requestDocument);
UtilXml.addChildElementValue(userElement, "Name",
EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.username", "", delegator), requestDocument);
UtilXml.addChildElementValue(userElement, "Password",
EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.password", "", delegator), requestDocument);
UtilXml.addChildElementValue(userElement, "Alias",
EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.alias", "", delegator), requestDocument);
String effectiveAlias = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.effectiveAlias", delegator);
if (UtilValidate.isNotEmpty(effectiveAlias)) {
UtilXml.addChildElementValue(userElement, "EffectiveAlias", effectiveAlias, requestDocument);
}
// EngineDocList.EngineDoc.Instructions
Element instructionsElement = UtilXml.addChildElement(engineDocElement, "Instructions", requestDocument);
Element routingListDocElement = UtilXml.addChildElement(instructionsElement, "RoutingList", requestDocument);
Element routingDocElement = UtilXml.addChildElement(routingListDocElement, "Routing", requestDocument);
UtilXml.addChildElementValue(routingDocElement, "name", "CcxReports", requestDocument);
// EngineDocList.EngineDoc.ReportDoc
Element reportDocElement = UtilXml.addChildElement(engineDocElement, "ReportDoc", requestDocument);
Element compList = UtilXml.addChildElement(reportDocElement, "CompList", requestDocument);
Element comp = UtilXml.addChildElement(compList, "Comp", requestDocument);
UtilXml.addChildElementValue(comp, "Name", "CcxReports", requestDocument);
// EngineDocList.EngineDoc.ReportDoc.ReportActionList
Element actionList = UtilXml.addChildElement(comp, "ReportActionList", requestDocument);
Element action = UtilXml.addChildElement(actionList, "ReportAction", requestDocument);
UtilXml.addChildElementValue(action, "ReportName", "CCE_OrderDetail", requestDocument);
Element start = UtilXml.addChildElementValue(action, "Start", "1", requestDocument);
start.setAttribute("DataType", "S32");
Element count = UtilXml.addChildElementValue(action, "Count", "10", requestDocument);
count.setAttribute("DataType", "S32");
// EngineDocList.EngineDoc.ReportDoc.ReportActionList.ReportAction.ValueList
Element valueList = UtilXml.addChildElement(action, "ValueList", requestDocument);
Element value = UtilXml.addChildElement(valueList, "Value", requestDocument);
String clientIdConfig = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.clientId", delegator);
if (UtilValidate.isNotEmpty(clientIdConfig)) {
Element clientId = UtilXml.addChildElementValue(value, "ClientId", clientIdConfig, requestDocument);
clientId.setAttribute("DataType", "S32");
}
UtilXml.addChildElementValue(value, "OrderId", orderId, requestDocument);
Debug.set(Debug.VERBOSE, true);
// Document reportResponseDoc = null;
try {
sendRequest(requestDocument, (String) context.get("paymentConfig"), delegator);
} catch (ClearCommerceException cce) {
return ServiceUtil.returnError(cce.getMessage());
}
Debug.set(Debug.VERBOSE, true);
Map<String, Object> result = ServiceUtil.returnSuccess();
return result;
}
private static Map<String, Object> processAuthResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("authResult", Boolean.TRUE);
result.put("authCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String authAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("processAmount", new BigDecimal(authAmountStr).movePointLeft(2));
} else {
result.put("authResult", Boolean.FALSE);
result.put("processAmount", BigDecimal.ZERO);
}
result.put("authRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("authFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("authMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
// AVS
String avsCode = UtilXml.childElementValue(procResponseElement, "AvsDisplay");
if (UtilValidate.isNotEmpty(avsCode)) {
result.put("avsCode", avsCode);
}
// Fraud score
Element fraudInfoElement = UtilXml.firstChildElement(orderFormElement, "FraudInfo");
if (fraudInfoElement != null) {
result.put("scoreCode", UtilXml.childElementValue(fraudInfoElement, "TotalScore"));
}
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static Map<String, Object> processCreditResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("creditResult", Boolean.TRUE);
result.put("creditCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String creditAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("creditAmount", new BigDecimal(creditAmountStr).movePointLeft(2));
} else {
result.put("creditResult", Boolean.FALSE);
result.put("creditAmount", BigDecimal.ZERO);
}
result.put("creditRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("creditFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("creditMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static Map<String, Object> processCaptureResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("captureResult", Boolean.TRUE);
result.put("captureCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String captureAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("captureAmount", new BigDecimal(captureAmountStr).movePointLeft(2));
} else {
result.put("captureResult", Boolean.FALSE);
result.put("captureAmount", BigDecimal.ZERO);
}
result.put("captureRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("captureFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("captureMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static Map<String, Object> processReleaseResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("releaseResult", Boolean.TRUE);
result.put("releaseCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String releaseAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("releaseAmount", new BigDecimal(releaseAmountStr).movePointLeft(2));
} else {
result.put("releaseResult", Boolean.FALSE);
result.put("releaseAmount", BigDecimal.ZERO);
}
result.put("releaseRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("releaseFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("releaseMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static Map<String, Object> processRefundResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("refundResult", Boolean.TRUE);
result.put("refundCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String refundAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("refundAmount", new BigDecimal(refundAmountStr).movePointLeft(2));
} else {
result.put("refundResult", Boolean.FALSE);
result.put("refundAmount", BigDecimal.ZERO);
}
result.put("refundRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("refundFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("refundMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static Map<String, Object> processReAuthResponse(Document responseDocument) {
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
Element transactionElement = UtilXml.firstChildElement(orderFormElement, "Transaction");
Element procResponseElement = UtilXml.firstChildElement(transactionElement, "CardProcResp");
Map<String, Object> result = ServiceUtil.returnSuccess();
String errorCode = UtilXml.childElementValue(procResponseElement, "CcErrCode");
if ("1".equals(errorCode)) {
result.put("reauthResult", Boolean.TRUE);
result.put("reauthCode", UtilXml.childElementValue(transactionElement, "AuthCode"));
Element currentTotalsElement = UtilXml.firstChildElement(transactionElement, "CurrentTotals");
Element totalsElement = UtilXml.firstChildElement(currentTotalsElement, "Totals");
String reauthAmountStr = UtilXml.childElementValue(totalsElement, "Total");
result.put("reauthAmount", new BigDecimal(reauthAmountStr).movePointLeft(2));
} else {
result.put("reauthResult", Boolean.FALSE);
result.put("reauthAmount", BigDecimal.ZERO);
}
result.put("reauthRefNum", UtilXml.childElementValue(orderFormElement, "Id"));
result.put("reauthFlag", UtilXml.childElementValue(procResponseElement, "Status"));
result.put("reauthMessage", UtilXml.childElementValue(procResponseElement, "CcReturnMsg"));
List<String> messages = getMessageList(responseDocument);
if (UtilValidate.isNotEmpty(messages)) {
result.put("internalRespMsgs", messages);
}
return result;
}
private static List<String> getMessageList(Document responseDocument) {
List<String> messageList = new ArrayList<>();
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element messageListElement = UtilXml.firstChildElement(engineDocElement, "MessageList");
List<? extends Element> messageElementList = UtilXml.childElementList(messageListElement, "Message");
if (UtilValidate.isNotEmpty(messageElementList)) {
for (Element messageElement : messageElementList) {
int severity = 0;
try {
severity = Integer.parseInt(UtilXml.childElementValue(messageElement, "Sev"));
} catch (NumberFormatException nfe) {
Debug.logError("Error parsing message severity: " + nfe.getMessage(), module);
severity = 9;
}
String message = "[" + UtilXml.childElementValue(messageElement, "Audience") + "] " + UtilXml
.childElementValue(messageElement, "Text") + " (" + severity + ")";
messageList.add(message);
}
}
return messageList;
}
private static int getMessageListMaxSev(Document responseDocument) {
int maxSev = 0;
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
Element messageListElement = UtilXml.firstChildElement(engineDocElement, "MessageList");
String maxSevStr = UtilXml.childElementValue(messageListElement, "MaxSev");
if (UtilValidate.isNotEmpty(maxSevStr)) {
try {
maxSev = Integer.parseInt(maxSevStr);
} catch (NumberFormatException nfe) {
Debug.logError("Error parsing MaxSev: " + nfe.getMessage(), module);
maxSev = 9;
}
}
return maxSev;
}
private static String getReferenceNum(Document responseDocument) {
String referenceNum = null;
Element engineDocElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(), "EngineDoc");
if (engineDocElement != null) {
Element orderFormElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
if (orderFormElement != null) {
referenceNum = UtilXml.childElementValue(orderFormElement, "Id");
}
}
return referenceNum;
}
private static Document buildPrimaryTxRequest(Map<String, Object> context, String type, BigDecimal amount, String refNum) {
String paymentConfig = (String) context.get("paymentConfig");
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
// payment mech
GenericValue creditCard = (GenericValue) context.get("creditCard");
Delegator delegator = creditCard.getDelegator();
Document requestDocument = createRequestDocument(paymentConfig, delegator);
Element engineDocElement = UtilXml.firstChildElement(requestDocument.getDocumentElement(), "EngineDoc");
Element orderFormDocElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
// add the reference number as a comment
UtilXml.addChildElementValue(orderFormDocElement, "Comments", refNum, requestDocument);
Element consumerElement = UtilXml.addChildElement(orderFormDocElement, "Consumer", requestDocument);
// email address
GenericValue billToEmail = (GenericValue) context.get("billToEmail");
if (billToEmail != null) {
UtilXml.addChildElementValue(consumerElement, "Email", billToEmail.getString("infoString"), requestDocument);
}
boolean enableCVM = EntityUtilProperties.propertyValueEqualsIgnoreCase(paymentConfig, "payment.clearcommerce.enableCVM", "Y", delegator);
String cardSecurityCode = enableCVM ? (String) context.get("cardSecurityCode") : null;
// Default to locale code 840 (United States)
String localCode = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.localeCode", "840", delegator);
appendPaymentMechNode(consumerElement, creditCard, cardSecurityCode, localCode);
// billing address
GenericValue billingAddress = (GenericValue) context.get("billingAddress");
if (billingAddress != null) {
Element billToElement = UtilXml.addChildElement(consumerElement, "BillTo", requestDocument);
Element billToLocationElement = UtilXml.addChildElement(billToElement, "Location", requestDocument);
appendAddressNode(billToLocationElement, billingAddress);
}
// shipping address
GenericValue shippingAddress = (GenericValue) context.get("shippingAddress");
if (shippingAddress != null) {
Element shipToElement = UtilXml.addChildElement(consumerElement, "ShipTo", requestDocument);
Element shipToLocationElement = UtilXml.addChildElement(shipToElement, "Location", requestDocument);
appendAddressNode(shipToLocationElement, shippingAddress);
}
// Default to currency code 840 (USD)
String currencyCode = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.currencyCode", "840", delegator);
// transaction
appendTransactionNode(orderFormDocElement, type, amount, currencyCode);
// TODO: determine if adding OrderItemList is worthwhile - JFE 2004.02.14
Map<String, Object> pbOrder = UtilGenerics.checkMap(context.get("pbOrder"));
if (pbOrder != null) {
if (Debug.verboseOn()) {
Debug.logVerbose("pbOrder Map not empty:" + pbOrder.toString(), module);
}
Element pbOrderElement = UtilXml.addChildElement(orderFormDocElement, "PbOrder", requestDocument); // periodic billing order
UtilXml.addChildElementValue(pbOrderElement, "OrderFrequencyCycle", (String) pbOrder.get(
"OrderFrequencyCycle"), requestDocument);
Element interval = UtilXml.addChildElementValue(pbOrderElement, "OrderFrequencyInterval", (String) pbOrder
.get("OrderFrequencyInterval"), requestDocument);
interval.setAttribute("DataType", "S32");
Element total = UtilXml.addChildElementValue(pbOrderElement, "TotalNumberPayments", (String) pbOrder.get(
"TotalNumberPayments"), requestDocument);
total.setAttribute("DataType", "S32");
} else if (context.get("OrderFrequencyCycle") != null && context.get("OrderFrequencyInterval") != null
&& context.get("TotalNumberPayments") != null) {
Element pbOrderElement = UtilXml.addChildElement(orderFormDocElement, "PbOrder", requestDocument); // periodic billing order
UtilXml.addChildElementValue(pbOrderElement, "OrderFrequencyCycle", (String) context.get(
"OrderFrequencyCycle"), requestDocument);
Element interval = UtilXml.addChildElementValue(pbOrderElement, "OrderFrequencyInterval", (String) context
.get("OrderFrequencyInterval"), requestDocument);
interval.setAttribute("DataType", "S32");
Element total = UtilXml.addChildElementValue(pbOrderElement, "TotalNumberPayments", (String) context.get(
"TotalNumberPayments"), requestDocument);
total.setAttribute("DataType", "S32");
}
return requestDocument;
}
private static Document buildSecondaryTxRequest(Map<String, Object> context, String id, String type, BigDecimal amount, Delegator delegator) {
String paymentConfig = (String) context.get("paymentConfig");
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
Document requestDocument = createRequestDocument(paymentConfig, delegator);
Element engineDocElement = UtilXml.firstChildElement(requestDocument.getDocumentElement(), "EngineDoc");
Element orderFormDocElement = UtilXml.firstChildElement(engineDocElement, "OrderFormDoc");
UtilXml.addChildElementValue(orderFormDocElement, "Id", id, requestDocument);
// Default to currency code 840 (USD)
String currencyCode = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.currencyCode", "840", delegator);
appendTransactionNode(orderFormDocElement, type, amount, currencyCode);
return requestDocument;
}
private static void appendPaymentMechNode(Element element, GenericValue creditCard, String cardSecurityCode, String localeCode) {
final int securityCodeLength = 4;
Document document = element.getOwnerDocument();
Element paymentMechElement = UtilXml.addChildElement(element, "PaymentMech", document);
Element creditCardElement = UtilXml.addChildElement(paymentMechElement, "CreditCard", document);
UtilXml.addChildElementValue(creditCardElement, "Number", creditCard.getString("cardNumber"), document);
String expDate = creditCard.getString("expireDate");
Element expiresElement = UtilXml.addChildElementValue(creditCardElement, "Expires", expDate.substring(0, 3)
+ expDate.substring(5), document);
expiresElement.setAttribute("DataType", "ExpirationDate");
expiresElement.setAttribute("Locale", localeCode);
if (UtilValidate.isNotEmpty(cardSecurityCode)) {
// Cvv2Val must be exactly securityCodeLength characters
if (cardSecurityCode.length() < securityCodeLength) {
// space padding on right side of cardSecurityCode
cardSecurityCode = String.format("%-" + securityCodeLength + "s", cardSecurityCode);
} else if (cardSecurityCode.length() > securityCodeLength) {
cardSecurityCode = cardSecurityCode.substring(0, securityCodeLength);
}
UtilXml.addChildElementValue(creditCardElement, "Cvv2Val", cardSecurityCode, document);
UtilXml.addChildElementValue(creditCardElement, "Cvv2Indicator", "1", document);
}
}
private static void appendAddressNode(Element element, GenericValue address) {
Document document = element.getOwnerDocument();
Element addressElement = UtilXml.addChildElement(element, "Address", document);
UtilXml.addChildElementValue(addressElement, "Name", address.getString("toName"), document);
UtilXml.addChildElementValue(addressElement, "Street1", address.getString("address1"), document);
UtilXml.addChildElementValue(addressElement, "Street2", address.getString("address2"), document);
UtilXml.addChildElementValue(addressElement, "City", address.getString("city"), document);
UtilXml.addChildElementValue(addressElement, "StateProv", address.getString("stateProvinceGeoId"), document);
UtilXml.addChildElementValue(addressElement, "PostalCode", address.getString("postalCode"), document);
String countryGeoId = address.getString("countryGeoId");
if (UtilValidate.isNotEmpty(countryGeoId)) {
try {
GenericValue countryGeo = address.getRelatedOne("CountryGeo", true);
UtilXml.addChildElementValue(addressElement, "Country", countryGeo.getString("geoSecCode"), document);
} catch (GenericEntityException gee) {
Debug.logInfo(gee, "Error finding related Geo for countryGeoId: " + countryGeoId, module);
}
}
}
private static void appendTransactionNode(Element element, String type, BigDecimal amount, String currencyCode) {
Document document = element.getOwnerDocument();
Element transactionElement = UtilXml.addChildElement(element, "Transaction", document);
UtilXml.addChildElementValue(transactionElement, "Type", type, document);
// Some transactions will not have an amount (release, reAuth)
if (amount != null) {
Element currentTotalsElement = UtilXml.addChildElement(transactionElement, "CurrentTotals", document);
Element totalsElement = UtilXml.addChildElement(currentTotalsElement, "Totals", document);
// DecimalFormat("#") is used here in case the total is something like 9.9999999...
// in that case, we want to send 999, not 999.9999999...
String totalString = amount.setScale(decimals, rounding).movePointRight(2).toPlainString();
Element totalElement = UtilXml.addChildElementValue(totalsElement, "Total", totalString, document);
totalElement.setAttribute("DataType", "Money");
totalElement.setAttribute("Currency", currencyCode);
}
}
private static Document createRequestDocument(String paymentConfig, Delegator delegator) {
// EngineDocList
Document requestDocument = UtilXml.makeEmptyXmlDocument("EngineDocList");
Element engineDocListElement = requestDocument.getDocumentElement();
UtilXml.addChildElementValue(engineDocListElement, "DocVersion", "1.0", requestDocument);
// EngineDocList.EngineDoc
Element engineDocElement = UtilXml.addChildElement(engineDocListElement, "EngineDoc", requestDocument);
UtilXml.addChildElementValue(engineDocElement, "ContentType", "OrderFormDoc", requestDocument);
String sourceId = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.sourceId", delegator);
if (UtilValidate.isNotEmpty(sourceId)) {
UtilXml.addChildElementValue(engineDocElement, "SourceId", sourceId, requestDocument);
}
String groupId = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.groupId", delegator);
if (UtilValidate.isNotEmpty(groupId)) {
UtilXml.addChildElementValue(engineDocElement, "GroupId", groupId, requestDocument);
}
// EngineDocList.EngineDoc.User
Element userElement = UtilXml.addChildElement(engineDocElement, "User", requestDocument);
UtilXml.addChildElementValue(userElement, "Name", EntityUtilProperties.getPropertyValue(paymentConfig,
"payment.clearcommerce.username", "", delegator), requestDocument);
UtilXml.addChildElementValue(userElement, "Password", EntityUtilProperties.getPropertyValue(paymentConfig,
"payment.clearcommerce.password", "", delegator), requestDocument);
UtilXml.addChildElementValue(userElement, "Alias", EntityUtilProperties.getPropertyValue(paymentConfig,
"payment.clearcommerce.alias", "", delegator), requestDocument);
String effectiveAlias = EntityUtilProperties.getPropertyValue(paymentConfig,
"payment.clearcommerce.effectiveAlias", delegator);
if (UtilValidate.isNotEmpty(effectiveAlias)) {
UtilXml.addChildElementValue(userElement, "EffectiveAlias", effectiveAlias, requestDocument);
}
// EngineDocList.EngineDoc.Instructions
Element instructionsElement = UtilXml.addChildElement(engineDocElement, "Instructions", requestDocument);
String pipeline = "PaymentNoFraud";
if (EntityUtilProperties.propertyValueEqualsIgnoreCase(paymentConfig, "payment.clearcommerce.enableFraudShield", "Y", delegator)) {
pipeline = "Payment";
}
UtilXml.addChildElementValue(instructionsElement, "Pipeline", pipeline, requestDocument);
// EngineDocList.EngineDoc.OrderFormDoc
Element orderFormDocElement = UtilXml.addChildElement(engineDocElement, "OrderFormDoc", requestDocument);
// default to "P" for Production Mode
String mode = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.processMode", "P", delegator);
UtilXml.addChildElementValue(orderFormDocElement, "Mode", mode, requestDocument);
return requestDocument;
}
private static Document sendRequest(Document requestDocument, String paymentConfig, Delegator delegator) throws ClearCommerceException {
if (UtilValidate.isEmpty(paymentConfig)) {
paymentConfig = "payment.properties";
}
String serverURL = EntityUtilProperties.getPropertyValue(paymentConfig, "payment.clearcommerce.serverURL", delegator);
if (UtilValidate.isEmpty(serverURL)) {
throw new ClearCommerceException("Missing server URL; check your ClearCommerce configuration");
}
if (Debug.verboseOn()) {
Debug.logVerbose("ClearCommerce server URL: " + serverURL, module);
}
OutputStream os = new ByteArrayOutputStream();
try {
UtilXml.writeXmlDocument(requestDocument, os, "UTF-8", true, false, 0);
} catch (TransformerException e) {
throw new ClearCommerceException("Error serializing requestDocument: " + e.getMessage());
}
String xmlString = os.toString();
if (Debug.verboseOn()) {
Debug.logVerbose("ClearCommerce XML request string: " + xmlString, module);
}
HttpClient http = new HttpClient(serverURL);
http.setParameter("CLRCMRC_XML", xmlString);
String response = null;
try {
response = http.post();
} catch (HttpClientException hce) {
Debug.logInfo(hce, module);
throw new ClearCommerceException("ClearCommerce connection problem", hce);
}
Document responseDocument = null;
try {
responseDocument = UtilXml.readXmlDocument(response, false);
} catch (Exception e) {
throw new ClearCommerceException("Error reading response Document from a String: " + e.getMessage());
}
if (Debug.verboseOn()) {
Debug.logVerbose("Result severity from clearCommerce:" + getMessageListMaxSev(responseDocument), module);
}
if (Debug.verboseOn() && getMessageListMaxSev(responseDocument) > maxSevComp) {
Debug.logVerbose("Returned messages:" + getMessageList(responseDocument), module);
}
return responseDocument;
}
}
@SuppressWarnings("serial")
class ClearCommerceException extends GeneralException {
ClearCommerceException() {
super();
}
ClearCommerceException(String msg) {
super(msg);
}
ClearCommerceException(Throwable t) {
super(t);
}
ClearCommerceException(String msg, Throwable t) {
super(msg, t);
}
}
| {'content_hash': 'e5ec99590c9fb94b39e4db1b47457ea0', 'timestamp': '', 'source': 'github', 'line_count': 946, 'max_line_length': 146, 'avg_line_length': 51.321353065539114, 'alnum_prop': 0.6920906282183317, 'repo_name': 'ilscipio/scipio-erp', 'id': '6cee62d02d2e4e877e5e8352167376cac9261a0c', 'size': '49511', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'applications/accounting/src/org/ofbiz/accounting/thirdparty/clearcommerce/CCPaymentServices.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '15540'}, {'name': 'CSS', 'bytes': '533213'}, {'name': 'FreeMarker', 'bytes': '6482124'}, {'name': 'Groovy', 'bytes': '2254105'}, {'name': 'HTML', 'bytes': '4409922'}, {'name': 'Java', 'bytes': '23079876'}, {'name': 'JavaScript', 'bytes': '1106310'}, {'name': 'Ruby', 'bytes': '2377'}, {'name': 'SCSS', 'bytes': '514759'}, {'name': 'Shell', 'bytes': '66335'}, {'name': 'XSLT', 'bytes': '1712'}]} |
@interface B2DRayCastOutputTest : SenTestCase
@end
| {'content_hash': 'ec9eaa71b5a8444ef0b2b201cd187d0c', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 45, 'avg_line_length': 17.333333333333332, 'alnum_prop': 0.8269230769230769, 'repo_name': 'CurveBeryl/Joybox-Box2D', 'id': '1bfb0dc88b6e14be354421c4d039a803efc9bcf0', 'size': '235', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Box2DTests/Collision/B2DRayCastOutputTest.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '6006'}, {'name': 'C++', 'bytes': '515750'}, {'name': 'Objective-C', 'bytes': '204433'}]} |
RAIDFactoryManager::RAIDFactoryManager(FactoryImplementationBase *parent) : FactoryManager(parent){
add(new RAIDProcessStub(this));
add(new RAIDDiskStub(this));
add(new RAIDForkStub(this));
}
// This is a static method defined in FactoryManager that the user must
// define (or compilation errors will result)
// This is how the simulation kernel gets a handle to the user factory
// that needs to be instantiated.
FactoryManager*
FactoryManager::createUserFactory(){
return ((FactoryManager *)new RAIDFactoryManager(NULL));
}
| {'content_hash': '85fce7ef18e106e631bc15d31a32c902', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 99, 'avg_line_length': 36.06666666666667, 'alnum_prop': 0.7726432532347505, 'repo_name': 'wilseypa/warped-models', 'id': 'c0c14b045c939a0e4a830a3e5772ca51f91614e6', 'size': '738', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/raid/factory/src/RAIDFactoryManager.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '381481'}, {'name': 'Python', 'bytes': '14336'}, {'name': 'Shell', 'bytes': '38725'}]} |
module AppDirect
class AuthenticationError < AppDirectError
end
end | {'content_hash': 'a9fb85eb6f23d3d2b90adfe8dabdce39', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 44, 'avg_line_length': 17.75, 'alnum_prop': 0.8309859154929577, 'repo_name': 'aditya01933/appdirect', 'id': '8e3728e710edeeddaf6badd1a4d23d1efd19283b', 'size': '71', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'lib/appdirect/errors/authentication_error.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '12349'}]} |
<?xml version="1.0" encoding="utf-8"?>
<net.coding.program.common.widget.LoginAutoCompleteEdit xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:background="@null"
android:hint="邮箱"
android:id="@+id/editName"
android:inputType="textEmailAddress"
android:layout_height="@dimen/edit_height"
android:layout_marginLeft="@dimen/padding_15"
android:layout_marginRight="@dimen/padding_15"
android:layout_width="match_parent"
android:maxLines="1"
android:singleLine="true"
android:textCursorDrawable="@null"
android:textSize="18sp"
custom:emailOnly="true" />
| {'content_hash': '8affd4a674ff519726a6b8f5fba6e8bb', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 114, 'avg_line_length': 42.4375, 'alnum_prop': 0.7187039764359352, 'repo_name': 'lonfen1108/Coding-Android-master', 'id': '65981a71fb3f28ea1eb7568dbde77eeba7e22170', 'size': '683', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/login_baselayout_email_auto_complete.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '2292527'}]} |
package divconq.tasks.work;
import divconq.lang.op.OperationResult;
import divconq.work.IQueueAlerter;
import divconq.xml.XElement;
// TODO this is an out dated system, move to use Hub Events instead
public class QueueAlerter implements IQueueAlerter {
@Override
public void init(OperationResult or, XElement config) {
}
@Override
public void sendAlert(long code, Object... params) {
// if could not start task
if (code == 179) {
// maybe filter some
}
//Email.sendOperatorAlert(code, params);
}
}
| {'content_hash': 'a1fa5ed0201df6eb0269acce714972ee', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 68, 'avg_line_length': 23.73913043478261, 'alnum_prop': 0.7014652014652014, 'repo_name': 'gspandy/divconq', 'id': '8c92805b5ab18b65de43523eadaa921d5ca43ed7', 'size': '951', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'divconq.tasks/src/main/java/divconq/tasks/work/QueueAlerter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '400513'}, {'name': 'Groovy', 'bytes': '1834'}, {'name': 'HTML', 'bytes': '3416'}, {'name': 'Java', 'bytes': '4893514'}, {'name': 'JavaScript', 'bytes': '2212695'}, {'name': 'M', 'bytes': '141646'}]} |
namespace arrow {
struct GContext;
namespace ir {
struct Node {
Node(ptr<ast::Node> source) : source(source) {
}
virtual ~Node() noexcept;
/// Source (in file) of the item
ptr<ast::Node> source;
};
} // namespace ir
} // namespace arrow
#endif // ARROW_IR_NODE_H
| {'content_hash': '277fe4c51549862fde28d52618571478', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 48, 'avg_line_length': 14.15, 'alnum_prop': 0.6325088339222615, 'repo_name': 'arrow-lang/arrow', 'id': '73a8395a44830bc16c594a5add0d6487f6212ff3', 'size': '535', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'include/arrow/ir/node.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '43397'}, {'name': 'C++', 'bytes': '420860'}, {'name': 'Python', 'bytes': '10336'}, {'name': 'Shell', 'bytes': '112'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pi-calc: Not compatible</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.2 / pi-calc - 8.9.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
pi-calc
<small>
8.9.0
<span class="label label-info">Not compatible</span>
</small>
</h1>
<p><em><script>document.write(moment("2021-04-14 05:24:55 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-04-14 05:24:55 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.1 Official release 4.11.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "Hugo.Herbelin@inria.fr"
homepage: "http://www.dimi.uniud.it/~scagnett/pi-calculus.html"
license: "Unknown"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/PiCalc"]
depends: [
"ocaml"
"coq" {>= "8.9" & < "8.10~"}
]
tags: [
"keyword: process algebras"
"keyword: pi-calculus"
"keyword: concurrency"
"keyword: higher-order syntax"
"category: Computer Science/Concurrent Systems and Protocols/Theory of concurrent systems"
"date: 1998-07"
]
authors: [
"Ivan Scagnetto <scagnett@dimi.uniud.it>"
]
bug-reports: "https://github.com/coq-contribs/pi-calc/issues"
dev-repo: "git+https://github.com/coq-contribs/pi-calc.git"
synopsis: "Pi-calculus in Coq"
description: """
This is a HOAS-based encoding of the pi-calculus (as originally
conceived by Milner, Parrow and Walker in "A Calculus of Mobile
Processes" Parts I-II, Information and Computation n. 100)
together with the formal verification of a large part of the
metatheory of Strong Late Bisimilarity."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/pi-calc/archive/v8.9.0.tar.gz"
checksum: "md5=d0882753de8b62ef0fe18fb05acc9f66"
}
</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-pi-calc.8.9.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-pi-calc -> coq < 8.10~ -> ocaml < 4.10
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-pi-calc.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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': '7d58f18d1a9929a4efe11e01dacc7d0b', 'timestamp': '', 'source': 'github', 'line_count': 174, 'max_line_length': 157, 'avg_line_length': 40.44252873563219, 'alnum_prop': 0.5481028847520251, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'ca6fa022dafeb87483704059290eb37c9149a9d8', 'size': '7039', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.11.1-2.0.7/released/8.11.2/pi-calc/8.9.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |
'use strict';
var mongoose = require('mongoose');
var RouteAssembler = require('puretech-foundation').Express.RouteAssembler;
function configureRoutes (app, config) {
var routes = new RouteAssembler(app, config);
//
// USERS
//
var users = new (require('../app/controllers/users'))(app, config);
routes.add({ 'method': 'POST', 'uri': '/users', 'controllerMethod': users.create.bind(users) });
routes.add({ 'method': 'GET', 'uri': '/users', 'controllerMethod': users.list.bind(users) });
routes.add({ 'method': 'POST', 'uri': '/users/request-password-reset', 'controllerMethod': users.requestPasswordReset.bind(users) });
routes.add({ 'method': 'POST', 'uri': '/users/execute-password-reset', 'controllerMethod': users.executePasswordReset.bind(users) });
routes.add({ 'method': 'GET', 'uri': '/users/me', 'controllerMethod': users.getMyProfile.bind(users) });
routes.add({ 'method': 'GET', 'uri': '/users/:userId', 'controllerMethod': users.get.bind(users) });
routes.add({ 'method': 'PUT', 'uri': '/users/:userId', 'controllerMethod': users.update.bind(users) });
routes.add({ 'method': 'DELETE', 'uri': '/users/:userId', 'controllerMethod': users.delete.bind(users) });
routes.add({ 'method': 'POST', 'uri': '/users/:userId/verify', 'controllerMethod': users.verifyEmailKey.bind(users) });
routes.add({ 'method': 'GET', 'uri': '/users/:userId/friends', 'controllerMethod': users.listFriends.bind(users) });
routes.add({ 'method': 'POST', 'uri': '/users/:userId/friends', 'controllerMethod': users.addFriend.bind(users) });
routes.add({ 'method': 'DELETE', 'uri': '/users/:userId/friends/:friendId', 'controllerMethod': users.removeFriend.bind(users) });
//
// SESSIONS
//
var sessions = new (require('../app/controllers/sessions'))(app, config);
routes.add({ 'method': 'POST', 'uri': '/sessions', 'controllerMethod': sessions.create.bind(sessions) });
routes.add({ 'method': 'GET', 'uri': '/sessions', 'controllerMethod': sessions.get.bind(sessions) });
routes.add({ 'method': 'DELETE', 'uri': '/sessions', 'controllerMethod': sessions.delete.bind(sessions) });
var settings = new (require('../app/controllers/settings'))(app, config);
routes.add({ 'method': 'GET', 'uri': '/settings', 'controllerMethod': settings.get.bind(settings) });
routes.add({ 'method': 'PUT', 'uri': '/settings', 'controllerMethod': settings.update.bind(settings) });
//
// PULSES
//
var pulses = new (require('../app/controllers/pulses'))(app, config);
var pulseInteractions = new (require('../app/controllers/interactions'))(mongoose.model('Pulses'), app, config);
routes.add({ 'method': 'GET', 'uri': '/pulses', 'controllerMethod': pulses.list.bind(pulses) });
routes.add({ 'method': 'POST', 'uri': '/pulses', 'controllerMethod': pulses.create.bind(pulses) });
routes.add({ 'method': 'GET', 'uri': '/pulses/:pulseId', 'controllerMethod': pulses.get.bind(pulses) });
routes.add({ 'method': 'PUT', 'uri': '/pulses/:pulseId', 'controllerMethod': pulses.update.bind(pulses) });
routes.add({ 'method': 'DELETE', 'uri': '/pulses/:pulseId', 'controllerMethod': pulses.delete.bind(pulses) });
// Simply tell interactions where to find a /pulses/:objectId, and it adds the
// interaction service endpoints and handler methods to it:
pulseInteractions.mount(routes, '/pulses/:objectId');
//
// SIDEBAR PULSES
//
var sidebarPulses = new (require('../app/controllers/sidebar-pulses'))(app, config);
var sidebarPulseInteractions = new (require('../app/controllers/interactions'))(mongoose.model('SidebarPulses'), app, config);
routes.add({ 'method': 'GET', 'uri': '/sidebar-pulses', 'controllerMethod': sidebarPulses.list.bind(sidebarPulses) });
routes.add({ 'method': 'POST', 'uri': '/sidebar-pulses', 'controllerMethod': sidebarPulses.create.bind(sidebarPulses) });
routes.add({ 'method': 'GET', 'uri': '/sidebar-pulses/:pulseId', 'controllerMethod': sidebarPulses.get.bind(sidebarPulses) });
routes.add({ 'method': 'PUT', 'uri': '/sidebar-pulses/:pulseId', 'controllerMethod': sidebarPulses.update.bind(sidebarPulses) });
routes.add({ 'method': 'DELETE', 'uri': '/sidebar-pulses/:pulseId', 'controllerMethod': sidebarPulses.delete.bind(sidebarPulses) });
// Simply tell interactions where to find a sidebar-pulse/:objectId, and it
// adds the interaction service endpoints and handler methods to it:
sidebarPulseInteractions.mount(routes, '/sidebar-pulses/:objectId');
var congresspeople = new (require('../app/controllers/congresspeople'))(app, config);
routes.add({ 'method': 'GET', 'uri': '/congresspeople', 'controllerMethod': congresspeople.list.bind(congresspeople) });
routes.add({ 'method': 'GET', 'uri': '/congresspeople/:name', 'controllerMethod': congresspeople.get.bind(congresspeople) });
routes.add({ 'method': 'POST', 'uri': '/congresspeople/:name/comment', 'controllerMethod': congresspeople.comment.bind(congresspeople) });
routes.add({ 'method': 'POST', 'uri': '/congresspeople/:name/video', 'controllerMethod': congresspeople.addVideo.bind(congresspeople) });
//
// VIDEOS
//
// var videos = new (require('../app/controllers/videos'))(app, config);
// routes.add({ 'method': 'POST', 'uri': '/videos', 'controllerMethod': videos.create.bind(videos) });
// routes.add({ 'method': 'GET', 'uri': '/videos', 'controllerMethod': videos.list.bind(videos) });
// routes.add({ 'method': 'GET', 'uri': '/videos/:videoId', 'controllerMethod': videos.get.bind(videos) });
// routes.add({ 'method': 'PUT', 'uri': '/videos/:videoId', 'controllerMethod': videos.update.bind(videos) });
// routes.add({ 'method': 'DELETE', 'uri': '/videos/:videoId', 'controllerMethod': videos.delete.bind(videos) });
}
module.exports = exports = configureRoutes;
| {'content_hash': '6ab071896268445524844953f41b65fe', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 141, 'avg_line_length': 55.60377358490566, 'alnum_prop': 0.663386494740414, 'repo_name': 'blakelapierre/wiyc', 'id': 'cfdd2f31e0faf8649887fab9305d8999e27abf1d', 'size': '7113', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'api/config/routes.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14985'}, {'name': 'JavaScript', 'bytes': '173234'}, {'name': 'Shell', 'bytes': '2926'}]} |
package com.devexmile.tunetz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A placeholder fragment containing a simple view.
*/
public class RadioActivityFragment extends Fragment {
private String mRadioStr;
public RadioActivityFragment() {
setHasOptionsMenu(true);
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_radio, container, false);
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
mRadioStr = intent.getStringExtra(Intent.EXTRA_TEXT);
rootView.findViewById(R.id.radiolayout);
//.setText(mRadioStr);
}
return inflater.inflate(R.layout.fragment_radio, container, false);
}
}
| {'content_hash': '489dc698cf83e9f41c4730fd9b199846', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 84, 'avg_line_length': 30.974358974358974, 'alnum_prop': 0.6862582781456954, 'repo_name': 'devexmile/tunetz', 'id': 'a8e11f4635096ea3b63c91650bd4db256b96f433', 'size': '1208', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/java/com/devexmile/tunetz/RadioActivityFragment.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '307963'}]} |
namespace XBox360ControllerManager
{
/// <summary>
/// Represents the state of the gamepad when <see cref="XBox360.GetGamepad"/> is called
/// </summary>
public enum XBox360GamepadState : ushort
{
/// <summary>
/// Gamepad is currently connected
/// </summary>
Connected = 0x0000,
/// <summary>
/// Gamepad is not currently connected
/// </summary>
NotConnected = 0x048F
}
}
| {'content_hash': 'd48583a955889eabd7d8fd473990daba', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 91, 'avg_line_length': 25.833333333333332, 'alnum_prop': 0.5720430107526882, 'repo_name': 'mina-asham/XBox360ControllerManager', 'id': 'd2794bb6c4bc34a37d50419616793c2bb516135c', 'size': '467', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'XBox360ControllerManager/XBox360GamepadState.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '13921'}]} |
#include <epub/private/epub_parse_opf.h>
int _epub_parse_opf(epub * book, xmlNode * root) {
if(!book || !root) {
return EINVAL;
}
root = _epub_opf_find_metadata(root);
if(!root) {
return EPUB_BROKEN_OPF;
}
xmlHashTable * lookup = _epub_build_opf_lookup_table();
if(!lookup) {
return EPUB_ERROR;
}
xmlNode * el;
for(el = root->children; el; el = el->next) {
_epub_opf_set_field * s = xmlHashLookup(lookup, el->name);
if(s) {
if(!s(book, el)) {
return EPUB_BROKEN_OPF;
}
}
}
xmlHashFree(lookup, NULL);
return EPUB_OK;
}
xmlNode * _epub_opf_find_metadata(xmlNode * root) {
if(!root) {
return NULL;
}
unsigned char * package = (unsigned char * ) "package";
unsigned char * metadata = (unsigned char * ) "metadata";
unsigned char * dc_metadata = (unsigned char * ) "dc-metadata";
if(!xmlStrEqual(root->name, package)) {
return NULL;
}
xmlNode * child, * inner; /* dc-metadata killed my inner child */
for(child = root->children; child; child = child->next) {
if(xmlStrEqual(child->name, metadata)) {
for(inner = child->children; inner; inner = inner->next) {
if(xmlStrEqual(inner->name, dc_metadata)) {
return inner;
}
}
return child;
}
}
return NULL;
}
static xmlChar * rights = (unsigned char *) "rights";
static xmlChar * identifier = (unsigned char *) "identifier";
static xmlChar * creator = (unsigned char *) "creator";
static xmlChar * title = (unsigned char *) "title";
static xmlChar * date = (unsigned char *) "date";
xmlHashTable * _epub_build_opf_lookup_table(void) {
xmlHashTable * lookup = xmlHashCreate(20);
if(!lookup) {
return NULL;
}
if(xmlHashAddEntry(lookup, rights, _epub_opf_set_rights) == -1) {
xmlHashFree(lookup, NULL);
return NULL;
}
if(xmlHashAddEntry(lookup, identifier, _epub_opf_set_identifier) == -1) {
xmlHashFree(lookup, NULL);
return NULL;
}
if(xmlHashAddEntry(lookup, creator, _epub_opf_set_creator) == -1) {
xmlHashFree(lookup, NULL);
return NULL;
}
if(xmlHashAddEntry(lookup, title, _epub_opf_set_title) == -1) {
xmlHashFree(lookup, NULL);
return NULL;
}
if(xmlHashAddEntry(lookup, date, _epub_opf_set_date) == -1) {
xmlHashFree(lookup, NULL);
return NULL;
}
return lookup;
}
int _epub_opf_set_rights(epub * book, xmlNode * el) {
xmlChar * rights_xml = xmlNodeGetContent(el->children);
epub_rights * rights, * new_rights;
for(rights = book->rights; rights; rights = rights->next) {
if(!rights->next) {
break;
}
}
new_rights = malloc(sizeof(epub_rights));
if(!new_rights) {
xmlFree(rights_xml);
return ENOMEM;
}
new_rights->next = NULL;
new_rights->rights = strndup(
(const char *) rights_xml,
(size_t) xmlStrlen(rights_xml)
);
xmlFree(rights_xml);
if(rights && rights->rights) {
rights->next = new_rights;
} else {
book->rights = new_rights;
}
return EPUB_OK;
}
int _epub_opf_set_identifier(epub * book, xmlNode * el) {
xmlChar * identifier_xml = xmlNodeGetContent(el->children);
epub_identifier * identifier, * new_identifier;
for(identifier = book->identifiers; identifier; identifier = identifier->next) {
if(!identifier->next) {
break;
}
}
new_identifier = malloc(sizeof(epub_identifier));
if(!new_identifier) {
xmlFree(identifier_xml);
return ENOMEM;
}
new_identifier->next = NULL;
new_identifier->identifier = strndup(
(const char *) identifier_xml,
(size_t) xmlStrlen(identifier_xml)
);
xmlFree(identifier_xml);
if(identifier && identifier->identifier) {
identifier->next = new_identifier;
} else {
book->identifiers = new_identifier;
}
return EPUB_OK;
}
int _epub_opf_set_creator(epub * book, xmlNode * el) {
xmlChar * creator_xml = xmlNodeGetContent(el->children);
epub_creator * creator, * new_creator;
/* find the end of the list */
for(creator = book->creators; creator; creator = creator->next) {
if(!creator->next) {
break;
}
}
new_creator = malloc(sizeof(epub_creator));
if(!new_creator) {
xmlFree(creator_xml);
return ENOMEM;
}
new_creator->next = NULL;
new_creator->creator = strndup(
(const char *) creator_xml,
(size_t)xmlStrlen(creator_xml)
);
xmlFree(creator_xml);
if(creator && creator->creator) {
creator->next = new_creator;
} else {
book->creators = new_creator;
}
return EPUB_OK;
}
int _epub_opf_set_title(epub * book, xmlNode * el) {
xmlChar * titles_xml = xmlNodeGetContent(el->children);
epub_title * titles, * new_titles;
for(titles = book->titles; titles; titles = titles->next) {
if(!titles->next) {
break;
}
}
new_titles = malloc(sizeof(epub_title));
if(!new_titles) {
xmlFree(titles_xml);
return ENOMEM;
}
new_titles->next = NULL;
new_titles->title = strndup(
(const char *) titles_xml,
(size_t) xmlStrlen(titles_xml)
);
xmlFree(titles_xml);
if(titles && titles->title) {
titles->next = new_titles;
} else {
book->titles = new_titles;
}
return EPUB_OK;
}
int _epub_opf_set_date(epub * book, xmlNode * el) {
xmlChar * publication = (unsigned char * ) "publication";
xmlChar * event = (unsigned char *) "event";
unsigned char * prop = xmlGetProp(el, event);
if(xmlStrEqual(prop, publication)) {
xmlChar * date = xmlNodeGetContent(el->children);
char * remaining = strptime(
(char * ) date,
"%Y-%m-%d",
book->publication_date
);
xmlFree(date);
if(!remaining) {
xmlFree(prop);
return EPUB_BROKEN_OPF;
}
}
xmlFree(prop);
return EPUB_OK;
}
| {'content_hash': 'f600e4117b8acb9f7d4a8718605060c3', 'timestamp': '', 'source': 'github', 'line_count': 213, 'max_line_length': 82, 'avg_line_length': 26.835680751173708, 'alnum_prop': 0.6210636808957313, 'repo_name': 'apeiron/books', 'id': 'c825dc99a306a5a5fef2ecd4622d55a088514064', 'size': '5716', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/epub_parse_opf.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '27214'}, {'name': 'CMake', 'bytes': '1618'}, {'name': 'Shell', 'bytes': '39'}]} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_15.html">Class Test_AbaRouteValidator_15</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_34459_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15.html?line=46103#src-46103" >testAbaNumberCheck_34459_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:44:20
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_34459_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=4219#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | {'content_hash': 'be635b4dd2e84e082d87a12e35953c4c', 'timestamp': '', 'source': 'github', 'line_count': 209, 'max_line_length': 296, 'avg_line_length': 43.92344497607655, 'alnum_prop': 0.5096949891067538, 'repo_name': 'dcarda/aba.route.validator', 'id': '07128631152b6c0e58507d247f9f91b5a4ab5739', 'size': '9180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_15_testAbaNumberCheck_34459_good_397.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '18715254'}]} |
{% extends "base.html" %}
{% load pages_tags mezzanine_tags crispy_forms_tags %}
{% block main %}
<h1>PERSON</h1>
<div class='row'>
<form enctype="multipart/form-data" method="post" action="">
<fieldset class="model">
{{ form.management_form }}
{{ form.non_form_errors }}
{% fields_for form %}
</fieldset>
<ul class="nav nav-tabs">
<li class="active"><a href="#location_form" data-toggle="tab">Addresses</a></li>
<li><a href="#phone_form" data-toggle="tab">Phone</a></li>
<li><a href="#email_form" data-toggle="tab">email</a></li>
<li><a href="#names_form" data-toggle="tab">alternate Names</a></li>
<li><a href="#identifiers_form" data-toggle="tab">Identifiers</a></li>
{# <li><a href="#orgs_form" data-toggle="tab">Organizations</a></li> #}
</ul>
<div class="tab-content">
<div class="tab-pane active" id="location_form">
<div class="panel panel-primary" >
{{ location_form.management_form }}
{{ location_form.non_form_errors }}
{% comment %} {% crispy location_form %} {% endcomment %}
{% for lf in location_form %}
<div class="panel-heading">Address</div>
{% fields_for lf %}
{% endfor %}
</div>
</div>
<div class="tab-pane " id="phone_form">
<div class="panel panel-primary" >
{{ phone_form.management_form }}
{{ phone_form.non_form_errors }}
{% for lf in phone_form %}
<div class="panel-heading">Phone</div>
{% fields_for lf %}
{% endfor %}
</div>
</div>
<div class="tab-pane " id="email_form">
<div class="panel panel-primary" >
{{ email_form.management_form }}
{{ email_form.non_form_errors }}
{% for lf in email_form %}
<div class="panel-heading">Email</div>
{% fields_for lf %}
{% endfor %}
</div>
</div>
<div class="tab-pane " id="names_form">
<div class="panel panel-primary" >
{{ name_form.management_form }}
{{ name_form.non_form_errors }}
{% for lf in name_form %}
<div class="panel-heading">Name</div>
{% fields_for lf %}
{% endfor %}
</div></div>
<div class="tab-pane " id="identifiers_form">
<div class="panel panel-primary" >
{{ identifier_form.management_form }}
{{ identifier_form.non_form_errors }}
{% for lf in identifier_form %}
<div class="panel-heading">Identifier</div>
{% fields_for lf %}
{% endfor %}
</div></div>
{% comment %}
<div class="tab-pane " id="orgs_form">
<div class="panel panel-primary" >
<div class="panel-heading">orgs</div>
{{ orgs_form.management_form }}
{{ orgs_form.non_form_errors }}
{% for lf in orgs_form %}
{% fields_for lf %}
{% endfor %}
</div></div>
{% endcomment %}
</div>
<input class="btn btn-warning btn-lg" type="submit" value="Save Edits" action=""/>
</form>
</div>
{% endblock %} | {'content_hash': 'db537aee60477a0fa4c7a2576a35a36f', 'timestamp': '', 'source': 'github', 'line_count': 120, 'max_line_length': 100, 'avg_line_length': 29.5, 'alnum_prop': 0.4666666666666667, 'repo_name': 'hydroshare/hydroshare_temp', 'id': 'b0fe4f7dfa9904d511d6701b15078992d1fd0508', 'size': '3540', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hs_party/templates/pages/person/person_edit.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '173515'}, {'name': 'C++', 'bytes': '4136'}, {'name': 'CSS', 'bytes': '228598'}, {'name': 'CoffeeScript', 'bytes': '34267'}, {'name': 'JavaScript', 'bytes': '736373'}, {'name': 'Python', 'bytes': '1870088'}, {'name': 'Shell', 'bytes': '5335'}, {'name': 'XSLT', 'bytes': '790987'}]} |
require 'spec_helper'
require 'vk/api/groups/methods/get'
RSpec.describe Vk::API::Groups::Methods::Get do
subject(:model) { described_class }
it { is_expected.to be < Dry::Struct }
it { is_expected.to be < Vk::Schema::Method }
describe 'attributes' do
subject(:attributes) { model.instance_methods(false) }
it { is_expected.to include :user_id }
it { is_expected.to include :extended }
it { is_expected.to include :filter }
it { is_expected.to include :fields }
it { is_expected.to include :offset }
it { is_expected.to include :count }
end
end
| {'content_hash': '53136bdebce2cd2e6ee4b453b244c92b', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 58, 'avg_line_length': 30.842105263157894, 'alnum_prop': 0.6706484641638225, 'repo_name': 'alsemyonov/vk', 'id': '1407d97bbc9fbc7c7ce7065179f1b009422cad25', 'size': '616', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/vk/api/groups/methods/get_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '2302334'}, {'name': 'Shell', 'bytes': '389'}]} |
.class Lcom/android/systemui/keyguard/KeyguardViewMediator$3;
.super Ljava/lang/Object;
.source "KeyguardViewMediator.java"
# interfaces
.implements Lcom/android/keyguard/ViewMediatorCallback;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/systemui/keyguard/KeyguardViewMediator;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# direct methods
.method constructor <init>(Lcom/android/systemui/keyguard/KeyguardViewMediator;)V
.locals 0
.prologue
.line 642
iput-object p1, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public isInputRestricted()Z
.locals 1
.prologue
.line 703
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-virtual {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->isInputRestricted()Z
move-result v0
return v0
.end method
.method public keyguardDone(Z)V
.locals 2
.param p1, "authenticated" # Z
.prologue
.line 649
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mKeyguardDonePending:Z
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2000(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Z
move-result v0
if-nez v0, :cond_0
.line 650
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
const/4 v1, 0x1
invoke-virtual {v0, p1, v1}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->keyguardDone(ZZ)V
.line 652
:cond_0
return-void
.end method
.method public keyguardDoneDrawing()V
.locals 2
.prologue
.line 655
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mHandler:Landroid/os/Handler;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2100(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Landroid/os/Handler;
move-result-object v0
const/16 v1, 0xa
invoke-virtual {v0, v1}, Landroid/os/Handler;->sendEmptyMessage(I)Z
.line 656
return-void
.end method
.method public keyguardDonePending()V
.locals 4
.prologue
const/4 v1, 0x1
.line 670
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# setter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mKeyguardDonePending:Z
invoke-static {v0, v1}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2002(Lcom/android/systemui/keyguard/KeyguardViewMediator;Z)Z
.line 671
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# setter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mHideAnimationRun:Z
invoke-static {v0, v1}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2202(Lcom/android/systemui/keyguard/KeyguardViewMediator;Z)Z
.line 672
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mStatusBarKeyguardViewManager:Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$1800(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
move-result-object v0
const/4 v1, 0x0
invoke-virtual {v0, v1}, Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;->startPreHideAnimation(Ljava/lang/Runnable;)V
.line 673
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mHandler:Landroid/os/Handler;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2100(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Landroid/os/Handler;
move-result-object v0
const/16 v1, 0x14
const-wide/16 v2, 0xbb8
invoke-virtual {v0, v1, v2, v3}, Landroid/os/Handler;->sendEmptyMessageDelayed(IJ)Z
.line 675
return-void
.end method
.method public keyguardGone()V
.locals 1
.prologue
.line 683
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mKeyguardDisplayManager:Lcom/android/keyguard/KeyguardDisplayManager;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2300(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Lcom/android/keyguard/KeyguardDisplayManager;
move-result-object v0
invoke-virtual {v0}, Lcom/android/keyguard/KeyguardDisplayManager;->hide()V
.line 684
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# invokes: Lcom/android/systemui/keyguard/KeyguardViewMediator;->wakeUpAndStartActivityAfterKeyguardExit()V
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2400(Lcom/android/systemui/keyguard/KeyguardViewMediator;)V
.line 685
return-void
.end method
.method public onUserActivityTimeoutChanged()V
.locals 1
.prologue
.line 665
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mStatusBarKeyguardViewManager:Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$1800(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
move-result-object v0
invoke-virtual {v0}, Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;->updateUserActivityTimeout()V
.line 666
return-void
.end method
.method public playTrustedSound()V
.locals 1
.prologue
.line 698
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# invokes: Lcom/android/systemui/keyguard/KeyguardViewMediator;->playTrustedSound()V
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2500(Lcom/android/systemui/keyguard/KeyguardViewMediator;)V
.line 699
return-void
.end method
.method public readyForKeyguardDone()V
.locals 2
.prologue
const/4 v1, 0x1
.line 689
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mKeyguardDonePending:Z
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$2000(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Z
move-result v0
if-eqz v0, :cond_0
.line 692
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-virtual {v0, v1, v1}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->keyguardDone(ZZ)V
.line 694
:cond_0
return-void
.end method
.method public resetStateLocked()V
.locals 1
.prologue
.line 708
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# invokes: Lcom/android/systemui/keyguard/KeyguardViewMediator;->resetStateLocked()V
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$000(Lcom/android/systemui/keyguard/KeyguardViewMediator;)V
.line 709
return-void
.end method
.method public setNeedsInput(Z)V
.locals 1
.param p1, "needsInput" # Z
.prologue
.line 660
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
# getter for: Lcom/android/systemui/keyguard/KeyguardViewMediator;->mStatusBarKeyguardViewManager:Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
invoke-static {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->access$1800(Lcom/android/systemui/keyguard/KeyguardViewMediator;)Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;
move-result-object v0
invoke-virtual {v0, p1}, Lcom/android/systemui/statusbar/phone/StatusBarKeyguardViewManager;->setNeedsInput(Z)V
.line 661
return-void
.end method
.method public userActivity()V
.locals 1
.prologue
.line 645
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-virtual {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->userActivity()V
.line 646
return-void
.end method
# hxs modify begin
.method public isOccluded()Z
.locals 1
.prologue
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-virtual {v0}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->isOccluded()Z
move-result v0
return v0
.end method
.method public setFingerprintFlag(Z)V
.locals 1
.param p1, "flag" # Z
.prologue
iget-object v0, p0, Lcom/android/systemui/keyguard/KeyguardViewMediator$3;->this$0:Lcom/android/systemui/keyguard/KeyguardViewMediator;
invoke-virtual {v0, p1}, Lcom/android/systemui/keyguard/KeyguardViewMediator;->setFingerprintFlag(Z)V
return-void
.end method
# hxs modify end | {'content_hash': '7c9635a5a9e048f571e9157207bd08a2', 'timestamp': '', 'source': 'github', 'line_count': 301, 'max_line_length': 210, 'avg_line_length': 35.76744186046512, 'alnum_prop': 0.770202489318224, 'repo_name': 'hexiaoshuai/Flyme_device_ZTE_A1', 'id': '6c2ea825f8acdf578717623fdd6c9bbdc91b9a13', 'size': '10766', 'binary': False, 'copies': '1', 'ref': 'refs/heads/C880AV1.0.0B06', 'path': 'SystemUI/smali/com/android/systemui/keyguard/KeyguardViewMediator$3.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '1500'}, {'name': 'HTML', 'bytes': '10195'}, {'name': 'Makefile', 'bytes': '11258'}, {'name': 'Python', 'bytes': '924'}, {'name': 'Shell', 'bytes': '2734'}, {'name': 'Smali', 'bytes': '234274633'}]} |
<div>
<p>
Workspace selector defines which files will be checked out.
</p>
<p>
Job build parameters can be referenced as <code>${PARAMETER_NAME}</code>. These will be substituted at build time.
</p>
</div>
| {'content_hash': 'd469f7b16951dbc1ad07b5c8afffd06c', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 118, 'avg_line_length': 27.75, 'alnum_prop': 0.6711711711711712, 'repo_name': 'jenkinsci/plasticscm-plugin', 'id': '1e305f3a4760ef9bc6a90eba28914f62232e153a', 'size': '222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/webapp/selector.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Groovy', 'bytes': '284'}, {'name': 'HTML', 'bytes': '7102'}, {'name': 'Java', 'bytes': '168654'}]} |
package com.intellij.testIntegration.createTest;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.CodeInsightUtil;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.util.classMembers.MemberInfo;
import com.intellij.testIntegration.TestFramework;
import com.intellij.testIntegration.TestIntegrationUtils;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class JavaTestGenerator implements TestGenerator {
public JavaTestGenerator() {
}
public PsiElement generateTest(final Project project, final CreateTestDialog d) {
return PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable<PsiElement>() {
public PsiElement compute() {
return ApplicationManager.getApplication().runWriteAction(new Computable<PsiElement>() {
public PsiElement compute() {
try {
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();
PsiClass targetClass = JavaDirectoryService.getInstance().createClass(d.getTargetDirectory(), d.getClassName());
addSuperClass(targetClass, project, d.getSuperClassName());
Editor editor = CodeInsightUtil.positionCursor(project, targetClass.getContainingFile(), targetClass.getLBrace());
addTestMethods(editor,
targetClass,
d.getSelectedTestFrameworkDescriptor(),
d.getSelectedMethods(),
d.shouldGeneratedBefore(),
d.shouldGeneratedAfter());
return targetClass;
}
catch (IncorrectOperationException e) {
showErrorLater(project, d.getClassName());
return null;
}
}
});
}
});
}
private static void addSuperClass(PsiClass targetClass, Project project, String superClassName) throws IncorrectOperationException {
if (superClassName == null) return;
PsiElementFactory ef = JavaPsiFacade.getInstance(project).getElementFactory();
PsiJavaCodeReferenceElement superClassRef;
PsiClass superClass = findClass(project, superClassName);
if (superClass != null) {
superClassRef = ef.createClassReferenceElement(superClass);
}
else {
superClassRef = ef.createFQClassNameReferenceElement(superClassName, GlobalSearchScope.allScope(project));
}
targetClass.getExtendsList().add(superClassRef);
}
@Nullable
private static PsiClass findClass(Project project, String fqName) {
GlobalSearchScope scope = GlobalSearchScope.allScope(project);
return JavaPsiFacade.getInstance(project).findClass(fqName, scope);
}
private static void addTestMethods(Editor editor,
PsiClass targetClass,
TestFramework descriptor,
Collection<MemberInfo> methods,
boolean generateBefore,
boolean generateAfter) throws IncorrectOperationException {
final Set<String> existingNames = new HashSet<String>();
if (generateBefore) {
generateMethod(TestIntegrationUtils.MethodKind.SET_UP, descriptor, targetClass, editor, null, existingNames);
}
if (generateAfter) {
generateMethod(TestIntegrationUtils.MethodKind.TEAR_DOWN, descriptor, targetClass, editor, null, existingNames);
}
for (MemberInfo m : methods) {
generateMethod(TestIntegrationUtils.MethodKind.TEST, descriptor, targetClass, editor, m.getMember().getName(), existingNames);
}
}
private static void showErrorLater(final Project project, final String targetClassName) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
public void run() {
Messages.showErrorDialog(project,
CodeInsightBundle.message("intention.error.cannot.create.class.message", targetClassName),
CodeInsightBundle.message("intention.error.cannot.create.class.title"));
}
});
}
private static void generateMethod(TestIntegrationUtils.MethodKind methodKind,
TestFramework descriptor,
PsiClass targetClass,
Editor editor,
@Nullable String name, Set<String> existingNames) {
PsiMethod method = (PsiMethod)targetClass.add(TestIntegrationUtils.createDummyMethod(targetClass));
PsiDocumentManager.getInstance(targetClass.getProject()).doPostponedOperationsAndUnblockDocument(editor.getDocument());
TestIntegrationUtils.runTestMethodTemplate(methodKind, descriptor, editor, targetClass, method, name, true, existingNames);
}
@Override
public String toString() {
return CodeInsightBundle.message("intention.create.test.dialog.java");
}
} | {'content_hash': '8218249003d7d0988da5006db17e9d04', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 134, 'avg_line_length': 44.983739837398375, 'alnum_prop': 0.688957166094343, 'repo_name': 'IllusionRom-deprecated/android_platform_tools_idea', 'id': 'a23c6cadfe64e2e3d4d8bfbb38fc9768c2b3db0a', 'size': '6133', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'java/java-impl/src/com/intellij/testIntegration/createTest/JavaTestGenerator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '177802'}, {'name': 'C#', 'bytes': '390'}, {'name': 'C++', 'bytes': '78894'}, {'name': 'CSS', 'bytes': '102018'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '1906667'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '128322265'}, {'name': 'JavaScript', 'bytes': '123045'}, {'name': 'Objective-C', 'bytes': '22558'}, {'name': 'Perl', 'bytes': '6549'}, {'name': 'Python', 'bytes': '17760420'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Shell', 'bytes': '76554'}, {'name': 'TeX', 'bytes': '60798'}, {'name': 'XSLT', 'bytes': '113531'}]} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>coinduction: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.5.3 / coinduction - 1.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
coinduction
<small>
1.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-01 06:03:43 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-01 06:03:43 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.3 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
# opam file:
opam-version: "2.0"
maintainer: "damien.pous@ens-lyon.fr"
homepage: "https://github.com/damien-pous/coinduction"
dev-repo: "git+https://github.com/damien-pous/coinduction.git"
bug-reports: "https://github.com/damien-pous/coinduction/issues"
license: "LGPL-3.0-or-later"
synopsis: "A library and plugin for doing proofs by (enhanced) coinduction"
description: """
Coinductive predicates are greatest fixpoints of monotone functions.
The `companion' makes it possible to enhance the associated coinduction scheme.
This library provides a formalisation on enhancements based on the companion, as well as tactics in making it straightforward to perform proofs by enhanced coinduction.
"""
build: [
[make "-j%{jobs}%" ]
]
install: [make "install"]
depends: [
"ocaml"
"coq" {>= "8.13" & < "8.15~"}
"coq-aac-tactics"
]
tags: [
"keyword:coinduction"
"keyword:up to techniques"
"keyword:companion"
"keyword:bisimilarity"
"keyword:streams"
"keyword:CCS"
"logpath:Coinduction"
]
authors: [
"Damien Pous"
]
url {
src:
"https://github.com/damien-pous/coinduction/archive/v1.0.tar.gz"
checksum: "sha512=47d3a3dc7a2bbbd361131344b08133160353df3997a5df9bae4e6f91ee128b6d9212308ffd7709e9a0379abb4314e569353dba55062c61e0196bce0a4258e1c0"
}
</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-coinduction.1.0 coq.8.5.3</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.5.3).
The following dependencies couldn't be met:
- coq-coinduction -> coq >= 8.13 -> ocaml >= 4.05.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coinduction.1.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {'content_hash': '0e62ae6a29303c2094c61835dbfaa11c', 'timestamp': '', 'source': 'github', 'line_count': 178, 'max_line_length': 168, 'avg_line_length': 40.57865168539326, 'alnum_prop': 0.5554478748442475, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'cdb5bf4ce53daed20e496328e1de2af5f8120ebe', 'size': '7248', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.04.2-2.0.5/released/8.5.3/coinduction/1.0.html', 'mode': '33188', 'license': 'mit', 'language': []} |