code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/**
* at test
* @authors yanjixiong
* @date 2016-10-11 11:02:10
*/
const should = require('should')
const at = require('../../common/at')
describe('test/common/at.test.js', function() {
describe('fetchUsers()', function() {
it('should return a names array', function(done) {
const names = at.fetchUsers('@foo @bar')
names.should.be.Array
done()
})
})
describe('linkUsers()', function() {
it('should return text contains `/u/` path ', function(done) {
const result = at.linkUsers('@foo @bar')
result.should.containEql('/u/')
done()
})
})
})
|
luoyjx/gaoqi-blog
|
test/common/at.test.js
|
JavaScript
|
mit
| 610
|
/* RequiredLibraries: pcre */
/* RequiredWindowsLibraries: libpcre */
#include "module.h"
#include <pcre.h>
class PCRERegex : public Regex
{
pcre *regex;
public:
PCRERegex(const Anope::string &expr) : Regex(expr)
{
const char *error;
int erroffset;
this->regex = pcre_compile(expr.c_str(), PCRE_CASELESS, &error, &erroffset, NULL);
if (!this->regex)
throw RegexException("Error in regex " + expr + " at offset " + stringify(erroffset) + ": " + error);
}
~PCRERegex()
{
pcre_free(this->regex);
}
bool Matches(const Anope::string &str)
{
return pcre_exec(this->regex, NULL, str.c_str(), str.length(), 0, 0, NULL, 0) > -1;
}
};
class PCRERegexProvider : public RegexProvider
{
public:
PCRERegexProvider(Module *creator) : RegexProvider(creator, "regex/pcre") { }
Regex *Compile(const Anope::string &expression) anope_override
{
return new PCRERegex(expression);
}
};
class ModuleRegexPCRE : public Module
{
PCRERegexProvider pcre_regex_provider;
public:
ModuleRegexPCRE(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, EXTRA | VENDOR),
pcre_regex_provider(this)
{
this->SetPermanent(true);
}
};
MODULE_INIT(ModuleRegexPCRE)
|
nmaggioni/SnapIRC
|
anope-src/modules/extra/m_regex_pcre.cpp
|
C++
|
mit
| 1,212
|
<?php
class m141005_205510_auth_PpxtPersonXType extends CDbMigration
{
public function up()
{
$this->execute("
INSERT INTO `AuthItem` (`name`, `type`, `description`, `bizrule`, `data`) VALUES('D2person.PpxtPersonXType.*','0','D2person.PpxtPersonXType',NULL,'N;');
INSERT INTO `AuthItem` (`name`, `type`, `description`, `bizrule`, `data`) VALUES('D2person.PpxtPersonXType.Create','0','D2person.PpxtPersonXType module create',NULL,'N;');
INSERT INTO `AuthItem` (`name`, `type`, `description`, `bizrule`, `data`) VALUES('D2person.PpxtPersonXType.View','0','D2person.PpxtPersonXType module view',NULL,'N;');
INSERT INTO `AuthItem` (`name`, `type`, `description`, `bizrule`, `data`) VALUES('D2person.PpxtPersonXType.Update','0','D2person.PpxtPersonXType module update',NULL,'N;');
INSERT INTO `AuthItem` (`name`, `type`, `description`, `bizrule`, `data`) VALUES('D2person.PpxtPersonXType.Delete','0','D2person.PpxtPersonXType module delete',NULL,'N;');
INSERT INTO `AuthItemChild` (`parent`, `child`) VALUES ('D2person.PprsPersonUpdate', 'D2person.PpxtPersonXType.Update');
INSERT INTO `AuthItemChild` (`parent`, `child`) VALUES ('D2person.PprsPersonUpdate', 'D2person.PpxtPersonXType.Create');
INSERT INTO `AuthItemChild` (`parent`, `child`) VALUES ('D2person.PprsPersonUpdate', 'D2person.PpxtPersonXType.Delete');
INSERT INTO `AuthItemChild` (`parent`, `child`) VALUES ('D2person.PprsPersonUpdate', 'D2person.PpxtPersonXType.*');
INSERT INTO `AuthItemChild` (`parent`, `child`) VALUES ('D2person.PprsPersonView', 'D2person.PpxtPersonXType.View');
");
}
public function down()
{
$this->execute("
DELETE FROM `AuthItemChild` WHERE `child` like 'D2person.PpxtPersonXType.%';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXType.*';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXType.edit';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXType.fullcontrol';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXType.readonly';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXTypeEdit';
DELETE FROM `AuthItem` WHERE `name` = 'D2person.PpxtPersonXTypeView';
");
}
public function safeUp()
{
$this->up();
}
public function safeDown()
{
$this->down();
}
}
|
DBRisinajumi/d2person
|
migrations/m141005_205510_auth_PpxtPersonXType.php
|
PHP
|
mit
| 2,526
|
Parameters
----------
Parameters entity encapsulates all parameters required for grid. Default implementation receives parameters
from Request object.
#### Class Description
* **Datagrid / ParametersInterface** - basic interface for Parameters entity;
* **Datagrid / RequestParameters** - Parameters interface implementation, gets data from Request object.
#### Configuration
```
parameters:
oro_grid.datagrid.parameters.class: Oro\Bundle\GridBundle\Datagrid\RequestParameters
```
|
umpirsky/platform
|
src/Oro/Bundle/GridBundle/Resources/doc/reference/backend/parameters.md
|
Markdown
|
mit
| 490
|
package Amazon::S3::Bucket;
use strict;
use warnings;
use Carp;
use File::stat;
use base qw(Class::Accessor::Fast);
__PACKAGE__->mk_accessors(qw(bucket creation_date account));
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
croak "no bucket" unless $self->bucket;
croak "no account" unless $self->account;
return $self;
}
sub _uri {
my ($self, $key) = @_;
return ($key)
? $self->bucket . "/" . $self->account->_urlencode($key)
: $self->bucket . "/";
}
# returns bool
sub add_key {
my ($self, $key, $value, $conf) = @_;
croak 'must specify key' unless $key && length $key;
if ($conf->{acl_short}) {
$self->account->_validate_acl_short($conf->{acl_short});
$conf->{'x-amz-acl'} = $conf->{acl_short};
delete $conf->{acl_short};
}
if (ref($value) eq 'SCALAR') {
$conf->{'Content-Length'} ||= -s $$value;
$value = _content_sub($$value);
} else {
$conf->{'Content-Length'} ||= length $value;
}
# If we're pushing to a bucket that's under DNS flux, we might get a 307
# Since LWP doesn't support actually waiting for a 100 Continue response,
# we'll just send a HEAD first to see what's going on
if (ref($value)) {
return
$self->account->_send_request_expect_nothing_probed('PUT',
$self->_uri($key), $conf, $value);
} else {
return
$self->account->_send_request_expect_nothing('PUT', $self->_uri($key),
$conf, $value);
}
}
sub add_key_filename {
my ($self, $key, $value, $conf) = @_;
return $self->add_key($key, \$value, $conf);
}
sub head_key {
my ($self, $key) = @_;
return $self->get_key($key, "HEAD");
}
sub get_key {
my ($self, $key, $method, $filename) = @_;
$method ||= "GET";
$filename = $$filename if ref $filename;
my $acct = $self->account;
my $request = $acct->_make_request($method, $self->_uri($key), {});
my $response = $acct->_do_http($request, $filename);
if ($response->code == 404) {
return undef;
}
$acct->_croak_if_response_error($response);
my $etag = $response->header('ETag');
if ($etag) {
$etag =~ s/^"//;
$etag =~ s/"$//;
}
my $return = {
content_length => $response->content_length || 0,
content_type => $response->content_type,
etag => $etag,
value => $response->content,
};
foreach my $header ($response->headers->header_field_names) {
next unless $header =~ /x-amz-meta-/i;
$return->{lc $header} = $response->header($header);
}
return $return;
}
sub get_key_filename {
my ($self, $key, $method, $filename) = @_;
return $self->get_key($key, $method, \$filename);
}
# returns bool
sub delete_key {
my ($self, $key) = @_;
croak 'must specify key' unless $key && length $key;
return
$self->account->_send_request_expect_nothing('DELETE', $self->_uri($key),
{});
}
sub delete_bucket {
my $self = shift;
croak "Unexpected arguments" if @_;
return $self->account->delete_bucket($self);
}
sub list {
my $self = shift;
my $conf = shift || {};
$conf->{bucket} = $self->bucket;
return $self->account->list_bucket($conf);
}
sub list_all {
my $self = shift;
my $conf = shift || {};
$conf->{bucket} = $self->bucket;
return $self->account->list_bucket_all($conf);
}
sub get_acl {
my ($self, $key) = @_;
my $acct = $self->account;
my $request = $acct->_make_request('GET', $self->_uri($key) . '?acl', {});
my $response = $acct->_do_http($request);
if ($response->code == 404) {
return undef;
}
$acct->_croak_if_response_error($response);
return $response->content;
}
sub set_acl {
my ($self, $conf) = @_;
$conf ||= {};
unless ($conf->{acl_xml} || $conf->{acl_short}) {
croak "need either acl_xml or acl_short";
}
if ($conf->{acl_xml} && $conf->{acl_short}) {
croak "cannot provide both acl_xml and acl_short";
}
my $path = $self->_uri($conf->{key}) . '?acl';
my $hash_ref =
($conf->{acl_short})
? {'x-amz-acl' => $conf->{acl_short}}
: {};
my $xml = $conf->{acl_xml} || '';
return
$self->account->_send_request_expect_nothing('PUT', $path, $hash_ref,
$xml);
}
sub get_location_constraint {
my ($self) = @_;
my $xpc =
$self->account->_send_request('GET', $self->bucket . '/?location');
return undef unless $xpc && !$self->account->_remember_errors($xpc);
my $lc = $xpc->{content};
if (defined $lc && $lc eq '') {
$lc = undef;
}
return $lc;
}
# proxy up the err requests
sub err { $_[0]->account->err }
sub errstr { $_[0]->account->errstr }
sub _content_sub {
my $filename = shift;
my $stat = stat($filename);
my $remaining = $stat->size;
my $blksize = $stat->blksize || 4096;
croak "$filename not a readable file with fixed size"
unless -r $filename
and $remaining;
open DATA, "< $filename" or croak "Could not open $filename: $!";
return sub {
my $buffer;
# warn "read remaining $remaining";
unless (my $read = read(DATA, $buffer, $blksize)) {
# warn "read $read buffer $buffer remaining $remaining";
croak
"Error while reading upload content $filename ($remaining remaining) $!"
if $! and $remaining;
# otherwise, we found EOF
close DATA
or croak "close of upload content $filename failed: $!";
$buffer ||=
''; # LWP expects an emptry string on finish, read returns 0
}
$remaining -= length($buffer);
return $buffer;
};
}
1;
__END__
=head1 NAME
Amazon::S3::Bucket - A container class for a S3 bucket and its contents.
=head1 SYNOPSIS
use Amazon::S3;
# creates bucket object (no "bucket exists" check)
my $bucket = $s3->bucket("foo");
# create resource with meta data (attributes)
my $keyname = 'testing.txt';
my $value = 'T';
$bucket->add_key(
$keyname, $value,
{ content_type => 'text/plain',
'x-amz-meta-colour' => 'orange',
}
);
# list keys in the bucket
$response = $bucket->list
or die $s3->err . ": " . $s3->errstr;
print $response->{bucket}."\n";
for my $key (@{ $response->{keys} }) {
print "\t".$key->{key}."\n";
}
# check if resource exists.
print "$keyname exists\n" if $bucket->head_key($keyname);
# delete key from bucket
$bucket->delete_key($keyname);
=head1 METHODS
=head2 new
Instaniates a new bucket object.
Requires a hash containing two arguments:
=over
=item bucket
The name (identifier) of the bucket.
=item account
The L<S3::Amazon> object (representing the S3 account) this
bucket is associated with.
=back
NOTE: This method does not check if a bucket actually
exists. It simply instaniates the bucket.
Typically a developer will not call this method directly,
but work through the interface in L<S3::Amazon> that will
handle their creation.
=head2 add_key
Takes three positional parameters:
=over
=item key
A string identifier for the resource in this bucket
=item value
A SCALAR string representing the contents of the resource.
=item configuration
A HASHREF of configuration data for this key. The configuration
is generally the HTTP headers you want to pass the S3
service. The client library will add all necessary headers.
Adding them to the configuration hash will override what the
library would send and add headers that are not typically
required for S3 interactions.
In addition to additional and overriden HTTP headers, this
HASHREF can have a C<acl_short> key to set the permissions
(access) of the resource without a seperate call via
C<add_acl> or in the form of an XML document. See the
documentation in C<add_acl> for the values and usage.
=back
Returns a boolean indicating its success. Check C<err> and
C<errstr> for error message if this operation fails.
=head2 add_key_filename
The method works like C<add_key> except the value is assumed
to be a filename on the local file system. The file will
be streamed rather then loaded into memory in one big chunk.
=head2 head_key $key_name
Returns a configuration HASH of the given key. If a key does
not exist in the bucket C<undef> will be returned.
=head2 get_key $key_name, [$method]
Takes a key and an optional HTTP method and fetches it from
S3. The default HTTP method is GET.
The method returns C<undef> if the key does not exist in the
bucket and throws an exception (dies) on server errors.
On success, the method returns a HASHREF containing:
=over
=item content_type
=item etag
=item value
=item @meta
=back
=head2 get_key_filename $key_name, $method, $filename
This method works like C<get_key>, but takes an added
filename that the S3 resource will be written to.
=head2 delete_key $key_name
Permanently removes C<$key_name> from the bucket. Returns a
boolean value indicating the operations success.
=head2 delete_bucket
Permanently removes the bucket from the server. A bucket
cannot be removed if it contains any keys (contents).
This is an alias for C<$s3->delete_bucket($bucket)>.
=head2 list
List all keys in this bucket.
See L<Amazon::S3/list_bucket> for documentation of this
method.
=head2 list_all
List all keys in this bucket without having to worry about
'marker'. This may make multiple requests to S3 under the
hood.
See L<Amazon::S3/list_bucket_all> for documentation of this
method.
=head2 get_acl
Retrieves the Access Control List (ACL) for the bucket or
resource as an XML document.
=over
=item key
The key of the stored resource to fetch. This parameter is
optional. By default the method returns the ACL for the
bucket itself.
=back
=head2 set_acl $conf
Retrieves the Access Control List (ACL) for the bucket or
resource. Requires a HASHREF argument with one of the following keys:
=over
=item acl_xml
An XML string which contains access control information
which matches Amazon's published schema.
=item acl_short
Alternative shorthand notation for common types of ACLs that
can be used in place of a ACL XML document.
According to the Amazon S3 API documentation the following recognized acl_short
types are defined as follows:
=over
=item private
Owner gets FULL_CONTROL. No one else has any access rights.
This is the default.
=item public-read
Owner gets FULL_CONTROL and the anonymous principal is
granted READ access. If this policy is used on an object, it
can be read from a browser with no authentication.
=item public-read-write
Owner gets FULL_CONTROL, the anonymous principal is granted
READ and WRITE access. This is a useful policy to apply to a
bucket, if you intend for any anonymous user to PUT objects
into the bucket.
=item authenticated-read
Owner gets FULL_CONTROL, and any principal authenticated as
a registered Amazon S3 user is granted READ access.
=back
=item key
The key name to apply the permissions. If the key is not
provided the bucket ACL will be set.
=back
Returns a boolean indicating the operations success.
=head2 get_location_constraint
Returns the location constraint data on a bucket.
For more information on location constraints, refer to the
Amazon S3 Developer Guide.
=head2 err
The S3 error code for the last error the account encountered.
=head2 errstr
A human readable error string for the last error the account encountered.
=head1 SEE ALSO
L<Amazon::S3>
=head1 AUTHOR & COPYRIGHT
Please see the L<Amazon::S3> manpage for author, copyright, and
license information.
|
sharkhack/AmazonS3
|
PERL/Amazon/S3/Bucket.pm
|
Perl
|
mit
| 11,958
|
global.add = function(){
return 20;
}
|
BenHuiHui/React-Native-OSX
|
Experimental/packager/osx/osx-webpack/osx-webpack/test.js
|
JavaScript
|
mit
| 41
|
#ifndef SFUI_APPWINDOW_H
#define SFUI_APPWINDOW_H
////////////////////////////////////////////////////////////
//
// MIT License
//
// Copyright(c) 2017 Kurt Slagle - kurt_slagle@yahoo.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// The origin of this software must not be misrepresented; you must not claim
// that you wrote the original software.If you use this software in a product,
// an acknowledgment of the software used is required.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Internal Headers
////////////////////////////////////////////////////////////
#include <SFUI/Include/Common.h>
#include <SFUI/Include/Application/Concurrent.h>
#include <SFUI/Include/UI/UI.h>
#include <SFUI/Include/UI/Theme.h>
////////////////////////////////////////////////////////////
// Dependency Headers
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Standard Library Headers
////////////////////////////////////////////////////////////
namespace sfui
{
class AppWindow;
class AppWindowHandle
{
public:
AppWindowHandle(AppWindow *win);
~AppWindowHandle();
void Open();
void Close();
void Hide();
void Show();
private:
AppWindow *m_Handle = nullptr;
};
class AppWindow
{
public:
AppWindow(Vec2i Size, const std::string &Title, sf::Uint32 style);
virtual ~AppWindow();
friend class AppMainWindow;
virtual void Launch();
bool IsOpen();
bool IsModal();
bool IsDone();
virtual void Close();
virtual void Hide();
virtual void Show();
virtual void AddWidget(Widget::shared_ptr widget);
protected:
virtual void PostLaunch();
virtual void MainLoop();
virtual void Update();
virtual void Render();
virtual void QueryQueues();
Vec2i m_WindowSize = { 0, 0 };
std::string m_WindowTitle = "Popup";
sf::Uint32 m_WindowStyle = sf::Style::Default;
std::atomic<bool> m_IsModal = false;
std::atomic<bool> m_IsVisible = false;
std::atomic<bool> m_MarkForClose = false;
std::atomic<bool> m_MarkForCleanup = false;
std::atomic<bool> m_MarkForHide = false;
std::thread m_Thread;
concurrency::concurrent_queue<Widget::shared_ptr> m_widgetQueue;
std::shared_ptr<sf::RenderWindow> m_Window;
std::shared_ptr<WidgetWindow> m_Widgets;
};
}
#endif // SFUI_APPWINDOW_H
|
JayhawkZombie/SFUI
|
SFUI/Include/Application/AppWindow.h
|
C
|
mit
| 3,524
|
</main><!-- End content -->
<footer id="footer">
<div class="container">
<div class="row">
<div class="col">
<div class="copyright">© Blog, 2017</div>
</div>
</div>
</div>
</footer>
</div><!-- End wrapper -->
<div class="modal fade" id="deleteArticle" tabindex="-1" role="dialog" aria-labelledby="deleteArticle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Delete article?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="">Delete article</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="deleteArticleSuccess" tabindex="-1" role="dialog" aria-labelledby="deleteArticleSuccess" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">The article deleted</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
<script type="text/javascript" src="/admin/view/js/common.js?ver=0.00"></script>
</body>
</html>
|
palval/blog
|
admin/view/footer.php
|
PHP
|
mit
| 2,778
|
'use strict';
/*
1. Переместите 0 в конец массива, остальные числа должны остаться
неизменными
.сoncat();
example:
[1,false,2,0,3,null,0,4,0,25] => [1, false, 2, 3, null, 4, 25, 0, 0, 0]
[ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ] => ["a","b",null,"c","d",1,false,1,3,[],1,9,{},9,0,0,0,0,0,0,0,0,0,0]
[ 0, 1, null, 2, false, 1, 0 ] => [1,null,2,false,1,0,0]
*/
let arr1 = [1, false, 2, 0, 3, null, 0, 4, 0, 25];
arr1 = [ 'a', 0, 0, 'b', null, 'c', 'd', 0, 1, false, 0, 1, 0, 3, [], 0, 1, 9, 0, 0, {}, 0, 0, 9 ];
function moveZeroToEnd(arr){
let lookingFor = 0;
let zeroArray = [];
for (let i = 0; i < arr.length;){
if (arr[i] === lookingFor){
arr.splice(i, 1);
zeroArray.push(lookingFor);
continue;
}
i++;
}
return arr.concat(zeroArray);
}
console.log(moveZeroToEnd(arr1));
/*
2. Верните сумму двух найменьших чисел в массиве
[10,20,30,1,31,11,10] => 11
[-1,0,25] => -1
[-4,-10,25,10] => -14
[0,200,10,25,15] => 10
*/
function orderNumbers(a, b){// WTF????
return a - b;
}
function minimalNumber(arr){
let a = arr.sort(orderNumbers);//Вот эту МАГИЮ Я РЕАЛЬНО НЕ ВКУРИЛ КАК ЭТО РАБОТЕТ???
return a.shift() + a.shift();
}
console.log(minimalNumber([10,20,30,1,31,11,10]));
/*
3. Напишите функцию которая меняет местами имя и фамилию
nameShuffler('john McClane'); => "McClane john"
nameShuffler('Arnold Schwarzenegger'); => "Schwarzenegger Arnold"
nameShuffler('James Bond'); => "Bond James"
*/
function nameShuffler(name){
return name.split(' ').reverse().join(' ');
}
console.log(nameShuffler('john McClane'));
console.log(nameShuffler('Arnold Schwarzenegger'));
console.log(nameShuffler('James Bond'));
/*
// !
4. Напишите функцию которая принимает массив с именами и возвращает массив
в котором каждая буква становится заглавной
capMe(['jo', 'nelson', 'jurie']) // returns ['Jo', 'Nelson', 'Jurie']
capMe(['KARLY', 'DANIEL', 'KELSEY']) // returns ['Karly', 'Daniel', 'Kelsey']
*/
function capMe(arr){
for (var i = 0; i < arr.length; i++){
arr[i] = arr[i][0].toUpperCase() + arr[i].slice(1).toLowerCase();
}
return arr;
}
console.log(capMe(['KARLY', 'DANIEL', 'KELSEY']));
console.log(capMe(['jo', 'nelson', 'jurie']));
//@SUPER
/*
1. Найдите число отсутствующее в заданной последовательности
example:
[1,3,5,9] => 7
[0,8,16,32] => 24
[4, 6, 8, 10] => 2 // число сначала
[0,16,24,32] => 8
*/
function steps(arr){
let maxStep = 0;
let index = 0;
if (arr[0] !== 0){
arr.unshift(0); // для коректного поиска с 0;
}
for (let i = 0; i + 1 < arr.length; i++){
if (maxStep < (arr[i + 1] - arr[i])){
maxStep = (arr[i + 1] - arr[i]);
index = i;
}
}
return arr[index] + maxStep/2;
}
function random(arr) {
console.log(arr);
console.log('Пропущеное число: ' + steps(arr));
}
random([1, 3, 5, 9]);
random([0, 8, 16, 32]);
random([4, 6, 8, 10]);
random([0, 16, 24, 32]);
/*
2. Напишите функция которая преобразовывает/открывает скобки всех
вложенных внутри массивов
Необходимо реализовать рекурсивный фызов функции.
Функция должна открывать любое количество внутренних массивов
example:
[[1,2],[3,[4]],5, 10] => [1,2,3,4,5,10]
[25,10,[10,[15]]] => [25,10,10,15]
*/
function openBraces(arr, arrNoBraces = []) {
for (let i = 0; i < arr.length; i++){
if (Array.isArray(arr[i])){
openBraces(arr[i], arrNoBraces);
}
else{
arrNoBraces.push(arr[i]);
}
}
return arrNoBraces;
}
console.log(openBraces ([[1,2],[3,[4]],5, 10]));
console.log(openBraces ([25,10,[10,[15]]]));
|
OkYesAnap/JSEasyCodeHomeWorks
|
Lesson5/src/main.js
|
JavaScript
|
mit
| 4,108
|
<?php
namespace Rmc\Car\PostBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('RmcCarPostBundle:Default:index.html.twig');
}
}
|
jignesh-russmediatech/rmcdemo
|
src/Rmc/Car/PostBundle/Controller/DefaultController.php
|
PHP
|
mit
| 275
|
package lykrast.eirinislegacy.common.block;
import java.util.List;
import java.util.Random;
import com.google.common.collect.ImmutableSet;
import lykrast.eirinislegacy.common.init.ModItems;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockPetramiteDecoration extends BlockVariant {
public static final PropertyEnum VARIANT = PropertyEnum.create("variant", VariantsPetramiteDecoration.class);
public BlockPetramiteDecoration(float hardness, float resistance, int harvestLevel) {
super(Material.ROCK, SoundType.STONE, hardness, resistance, "pickaxe", harvestLevel, true);
setDefaultState(blockState.getBaseState().withProperty(VARIANT, VariantsPetramiteDecoration.POLISHED));
}
@Override
public Enum[] getVariants() {
return VariantsPetramiteDecoration.values();
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list) {
for (Enum v : getVariants())
list.add(new ItemStack(this, 1, getMetaFromState(blockState.getBaseState().withProperty(VARIANT, v))));
}
@Override
public BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[]{VARIANT});
}
@Override
public int getMetaFromState(IBlockState state) {
return ((VariantsPetramiteDecoration) state.getValue(VARIANT)).ordinal();
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty(VARIANT, getVariants()[meta]);
}
@Override
@SideOnly(Side.CLIENT)
public void initModel() {
for (Enum v : getVariants())
ModelLoader.setCustomModelResourceLocation(Item.getItemFromBlock(this), getMetaFromState(blockState.getBaseState().withProperty(VARIANT, v)),
new ModelResourceLocation(getRegistryName() + "_" + v, "inventory"));
}
public enum VariantsPetramiteDecoration implements IStringSerializable {
POLISHED, TILES_BIG, TILES_SMALL, BRICKS_BIG, BRICKS_SMALL, BRICKS_LONG, ROAD, PAVEMENT, CARVED, EXTRUDED;
@Override
public String getName()
{
return name().toLowerCase();
}
@Override
public String toString()
{
return getName();
}
}
}
|
Lykrast/EirinisLegacy
|
src/main/java/lykrast/eirinislegacy/common/block/BlockPetramiteDecoration.java
|
Java
|
mit
| 3,012
|
/*
** File: utf_cfe_psp_eeprom.c
** $Id: utf_cfe_psp_eeprom.c 1.5 2012/01/13 12:51:57GMT-05:00 acudmore Exp $
**
** Copyright (c) 2004-2012, United States government as represented by the
** administrator of the National Aeronautics Space Administration.
** All rights reserved. This software(cFE) was created at NASA's Goddard
** Space Flight Center pursuant to government contracts.
**
** This is governed by the NASA Open Source Agreement and may be used,
** distributed and modified only pursuant to the terms of that agreement.
**
**
** Purpose: This module defines the UTF versions of the cFE platform support package
** EEPROM functions.
**
** References:
**
** Assumptions and Notes:
**
** $Date: 2012/01/13 12:51:57GMT-05:00 $
** $Revision: 1.5 $
** $Log: utf_cfe_psp_eeprom.c $
** Revision 1.5 2012/01/13 12:51:57GMT-05:00 acudmore
** Changed license text to reflect open source
** Revision 1.4 2010/11/29 08:45:13EST jmdagost
** Enhanced support for CFE_PSP_EepromWriteEnable and CFE_PSP_EepromWriteDisable
** Revision 1.3 2010/10/25 15:06:35EDT jmdagost
** Corrected bad apostrophe in prologue.
** Revision 1.2 2010/10/04 14:57:11EDT jmdagost
** Cleaned up copyright symbol.
** Revision 1.1 2009/10/20 13:25:31EDT wmoleski
** Initial revision
** Member added to project c:/MKSDATA/MKS-REPOSITORY/MKS-CFE-PROJECT/tools/utf/src/project.pj
*/
/*
** Include Files
*/
#include "common_types.h"
#include "osapi.h"
/*
** Types and prototypes for this module
*/
#include "utf_types.h"
#include "utf_cfe_psp.h"
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
/* Function Hook Stuff */
typedef struct
{
int32 (*CFE_PSP_EepromWrite8)(uint32, uint8);
int32 (*CFE_PSP_EepromWrite16)(int32, uint16);
int32 (*CFE_PSP_EepromWrite32)(int32, uint32);
int32 (*CFE_PSP_EepromWriteEnable)(uint32);
int32 (*CFE_PSP_EepromWriteDisable)(uint32);
} UTF_PSP_HookTable_t;
UTF_PSP_HookTable_t UTF_PSP_HookTable = {
NULL,
NULL,
NULL,
NULL,
NULL
};
extern int32 cfe_psp_return_value[NUM_OF_CFE_PSP_PROCS];
/******************************************************************************
** Function: UTF_PSP_set_function_hook()
**
** Purpose:
** Install a user defined hook function for a CFE_PSP function call.
*/
void UTF_PSP_set_function_hook(int Index, void *FunPtr)
{
if (Index == CFE_PSP_EEPROMWRITE8_HOOK) { UTF_PSP_HookTable.CFE_PSP_EepromWrite8 = FunPtr; }
else if (Index == CFE_PSP_EEPROMWRITE16_HOOK) { UTF_PSP_HookTable.CFE_PSP_EepromWrite16 = FunPtr; }
else if (Index == CFE_PSP_EEPROMWRITE32_HOOK) { UTF_PSP_HookTable.CFE_PSP_EepromWrite32 = FunPtr; }
else if (Index == CFE_PSP_EEPROMWRITEENA_HOOK) { UTF_PSP_HookTable.CFE_PSP_EepromWriteEnable = FunPtr; }
else if (Index == CFE_PSP_EEPROMWRITEDIS_HOOK) { UTF_PSP_HookTable.CFE_PSP_EepromWriteDisable = FunPtr; }
else { UTF_error("Invalid PSP Hook Index In Set Hook Call %d", Index); }
}
/*******************************************************************************
Memory Access API
*******************************************************************************/
int32 CFE_PSP_EepromWrite8(uint32 Address, uint8 Data)
{
boolean Status;
/* Handle the Function Hook */
if (UTF_PSP_HookTable.CFE_PSP_EepromWrite8)
return(UTF_PSP_HookTable.CFE_PSP_EepromWrite8(Address,Data));
Status = UTF_write_sim_address(Address, 1, &Data);
if(Status == FALSE)
return(CFE_PSP_ERROR);
return(CFE_PSP_SUCCESS);
}
int32 CFE_PSP_EepromWrite16(uint32 Address, uint16 Data)
{
int32 Status;
/* Handle the Function Hook */
if (UTF_PSP_HookTable.CFE_PSP_EepromWrite16)
return(UTF_PSP_HookTable.CFE_PSP_EepromWrite16(Address,Data));
/* Check that the address is on a 16 bit boundary; the flight code
will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
if ((Address % 2) != 0)
{ /* Address is not on 16 bit boundary */
UTF_put_text("Address Not On 16 Bit Boundary: 0x%08x\n", Address);
return (CFE_PSP_ERROR);
}
else
{ /* Address is on 16 bit boundary */
Status = UTF_write_sim_address(Address, 2, &Data);
if(Status == FALSE)
return(CFE_PSP_ERROR);
else
return(CFE_PSP_SUCCESS);
}
}
int32 CFE_PSP_EepromWrite32(uint32 Address, uint32 Data)
{
int32 Status;
/* Handle the Function Hook */
if (UTF_PSP_HookTable.CFE_PSP_EepromWrite32)
return(UTF_PSP_HookTable.CFE_PSP_EepromWrite32(Address,Data));
/* Check that the address is on a 32 bit boundary; the flight code
will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
if ((Address % 4) != 0)
{ /* Address is not on 32 bit boundary */
UTF_put_text("Address Not On 32 Bit Boundary: 0x%08x\n", Address);
return (CFE_PSP_ERROR);
}
else
{ /* Address is on 32 bit boundary */
Status = UTF_write_sim_address(Address, 4, &Data);
if(Status == FALSE)
return(CFE_PSP_ERROR);
else
return(CFE_PSP_SUCCESS);
}
}
int32 CFE_PSP_EepromWriteEnable(uint32 Bank)
{
/* Handle the Function Hook */
if (UTF_PSP_HookTable.CFE_PSP_EepromWriteEnable)
return(UTF_PSP_HookTable.CFE_PSP_EepromWriteEnable(Bank));
/* Handle Preset Return Code */
if (cfe_psp_return_value[CFE_PSP_EEPROMWRITEENA_PROC] != UTF_CFE_USE_DEFAULT_RETURN_CODE)
{
return cfe_psp_return_value[CFE_PSP_EEPROMWRITEENA_PROC];
}
return(CFE_PSP_SUCCESS);
}
int32 CFE_PSP_EepromWriteDisable(uint32 Bank)
{
/* Handle the Function Hook */
if (UTF_PSP_HookTable.CFE_PSP_EepromWriteDisable)
return(UTF_PSP_HookTable.CFE_PSP_EepromWriteDisable(Bank));
/* Handle Preset Return Code */
if (cfe_psp_return_value[CFE_PSP_EEPROMWRITEDIS_PROC] != UTF_CFE_USE_DEFAULT_RETURN_CODE)
{
return cfe_psp_return_value[CFE_PSP_EEPROMWRITEDIS_PROC];
}
return(CFE_PSP_SUCCESS);
}
int32 CFE_PSP_EepromPowerUp(uint32 Bank)
{
return(CFE_PSP_SUCCESS);
}
int32 CFE_PSP_EepromPowerDown(uint32 Bank)
{
return(CFE_PSP_SUCCESS);
}
|
CACTUS-Mission/TRAPSat
|
TRAPSat_cFS/cfs/cfe/tools/utf/src/utf_cfe_psp_eeprom.c
|
C
|
mit
| 6,224
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 1997, 2012 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
#ifndef _DB_CXX_H_
#define _DB_CXX_H_
//
// C++ assumptions:
//
// To ensure portability to many platforms, both new and old, we make
// few assumptions about the C++ compiler and library. For example,
// we do not expect STL, templates or namespaces to be available. The
// "newest" C++ feature used is exceptions, which are used liberally
// to transmit error information. Even the use of exceptions can be
// disabled at runtime, to do so, use the DB_CXX_NO_EXCEPTIONS flags
// with the DbEnv or Db constructor.
//
// C++ naming conventions:
//
// - All top level class names start with Db.
// - All class members start with lower case letter.
// - All private data members are suffixed with underscore.
// - Use underscores to divide names into multiple words.
// - Simple data accessors are named with get_ or set_ prefix.
// - All method names are taken from names of functions in the C
// layer of db (usually by dropping a prefix like "db_").
// These methods have the same argument types and order,
// other than dropping the explicit arg that acts as "this".
//
// As a rule, each DbFoo object has exactly one underlying DB_FOO struct
// (defined in db.h) associated with it. In some cases, we inherit directly
// from the DB_FOO structure to make this relationship explicit. Often,
// the underlying C layer allocates and deallocates these structures, so
// there is no easy way to add any data to the DbFoo class. When you see
// a comment about whether data is permitted to be added, this is what
// is going on. Of course, if we need to add data to such C++ classes
// in the future, we will arrange to have an indirect pointer to the
// DB_FOO struct (as some of the classes already have).
//
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// Forward declarations
//
#include <stdarg.h>
#ifdef HAVE_CXX_STDHEADERS
#include <iostream>
#include <exception>
#define __DB_STD(x) std::x
#else
#include <iostream.h>
#include <exception.h>
#define __DB_STD(x) x
#endif
#include "db.h"
class Db; // forward
class Dbc; // forward
class DbChannel; // forward
class DbEnv; // forward
class DbHeapRecordId; // forward
class DbInfo; // forward
class DbLock; // forward
class DbLogc; // forward
class DbLsn; // forward
class DbMpoolFile; // forward
class DbPreplist; // forward
class DbSequence; // forward
class DbSite; // forward
class Dbt; // forward
class DbTxn; // forward
class DbMultipleIterator; // forward
class DbMultipleKeyDataIterator; // forward
class DbMultipleRecnoDataIterator; // forward
class DbMultipleDataIterator; // forward
class DbException; // forward
class DbDeadlockException; // forward
class DbLockNotGrantedException; // forward
class DbMemoryException; // forward
class DbRepHandleDeadException; // forward
class DbRunRecoveryException; // forward
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// Turn off inappropriate compiler warnings
//
#ifdef _MSC_VER
// These are level 4 warnings that are explicitly disabled.
// With Visual C++, by default you do not see above level 3 unless
// you use /W4. But we like to compile with the highest level
// warnings to catch other errors.
//
// 4201: nameless struct/union
// triggered by standard include file <winnt.h>
//
// 4514: unreferenced inline function has been removed
// certain include files in MSVC define methods that are not called
//
#pragma warning(push)
#pragma warning(disable: 4201 4514)
#endif
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// Mechanisms for declaring classes
//
//
// Every class defined in this file has an _exported next to the class name.
// This is needed for WinTel machines so that the class methods can
// be exported or imported in a DLL as appropriate. Users of the DLL
// use the define DB_USE_DLL. When the DLL is built, DB_CREATE_DLL
// must be defined.
//
#if defined(_MSC_VER)
# if defined(DB_CREATE_DLL)
# define _exported __declspec(dllexport) // creator of dll
# elif defined(DB_USE_DLL)
# define _exported __declspec(dllimport) // user of dll
# else
# define _exported // static lib creator or user
# endif
#else /* _MSC_VER */
# define _exported
#endif /* _MSC_VER */
// Some interfaces can be customized by allowing users to define
// callback functions. For performance and logistical reasons, some
// callback functions must be declared in extern "C" blocks. For others,
// we allow you to declare the callbacks in C++ or C (or an extern "C"
// block) as you wish. See the set methods for the callbacks for
// the choices.
//
extern "C" {
typedef void * (*db_malloc_fcn_type)
(size_t);
typedef void * (*db_realloc_fcn_type)
(void *, size_t);
typedef void (*db_free_fcn_type)
(void *);
typedef int (*bt_compare_fcn_type) /*C++ version available*/
(DB *, const DBT *, const DBT *);
typedef size_t (*bt_prefix_fcn_type) /*C++ version available*/
(DB *, const DBT *, const DBT *);
typedef int (*dup_compare_fcn_type) /*C++ version available*/
(DB *, const DBT *, const DBT *);
typedef int (*h_compare_fcn_type) /*C++ version available*/
(DB *, const DBT *, const DBT *);
typedef u_int32_t (*h_hash_fcn_type) /*C++ version available*/
(DB *, const void *, u_int32_t);
typedef int (*pgin_fcn_type)
(DB_ENV *dbenv, db_pgno_t pgno, void *pgaddr, DBT *pgcookie);
typedef int (*pgout_fcn_type)
(DB_ENV *dbenv, db_pgno_t pgno, void *pgaddr, DBT *pgcookie);
}
//
// Represents a database table = a set of keys with associated values.
//
class _exported Db
{
friend class DbEnv;
public:
Db(DbEnv*, u_int32_t); // Create a Db object.
virtual ~Db(); // Calls close() if the user hasn't.
// These methods exactly match those in the C interface.
//
virtual int associate(DbTxn *txn, Db *secondary, int (*callback)
(Db *, const Dbt *, const Dbt *, Dbt *), u_int32_t flags);
virtual int associate_foreign(Db *foreign, int (*callback)
(Db *, const Dbt *, Dbt *, const Dbt *, int *), u_int32_t flags);
virtual int close(u_int32_t flags);
virtual int compact(DbTxn *txnid, Dbt *start,
Dbt *stop, DB_COMPACT *c_data, u_int32_t flags, Dbt *end);
virtual int cursor(DbTxn *txnid, Dbc **cursorp, u_int32_t flags);
virtual int del(DbTxn *txnid, Dbt *key, u_int32_t flags);
virtual void err(int, const char *, ...);
virtual void errx(const char *, ...);
virtual int exists(DbTxn *txnid, Dbt *key, u_int32_t flags);
virtual int fd(int *fdp);
virtual int get(DbTxn *txnid, Dbt *key, Dbt *data, u_int32_t flags);
virtual int get_alloc(
db_malloc_fcn_type *, db_realloc_fcn_type *, db_free_fcn_type *);
virtual int get_append_recno(int (**)(Db *, Dbt *, db_recno_t));
virtual int get_bt_compare(int (**)(Db *, const Dbt *, const Dbt *));
virtual int get_bt_compress(
int (**)(
Db *, const Dbt *, const Dbt *, const Dbt *, const Dbt *, Dbt *),
int (**)(Db *, const Dbt *, const Dbt *, Dbt *, Dbt *, Dbt *));
virtual int get_bt_minkey(u_int32_t *);
virtual int get_bt_prefix(size_t (**)(Db *, const Dbt *, const Dbt *));
virtual int get_byteswapped(int *);
virtual int get_cachesize(u_int32_t *, u_int32_t *, int *);
virtual int get_create_dir(const char **);
virtual int get_dbname(const char **, const char **);
virtual int get_dup_compare(int (**)(Db *, const Dbt *, const Dbt *));
virtual int get_encrypt_flags(u_int32_t *);
virtual void get_errcall(
void (**)(const DbEnv *, const char *, const char *));
virtual void get_errfile(FILE **);
virtual void get_errpfx(const char **);
virtual int get_feedback(void (**)(Db *, int, int));
virtual int get_flags(u_int32_t *);
virtual int get_heapsize(u_int32_t *, u_int32_t *);
virtual int get_heap_regionsize(u_int32_t *);
virtual int get_h_compare(int (**)(Db *, const Dbt *, const Dbt *));
virtual int get_h_ffactor(u_int32_t *);
virtual int get_h_hash(u_int32_t (**)(Db *, const void *, u_int32_t));
virtual int get_h_nelem(u_int32_t *);
virtual int get_lk_exclusive(bool *, bool *);
virtual int get_lorder(int *);
virtual void get_msgcall(void (**)(const DbEnv *, const char *));
virtual void get_msgfile(FILE **);
virtual int get_multiple();
virtual int get_open_flags(u_int32_t *);
virtual int get_pagesize(u_int32_t *);
virtual int get_partition_callback(
u_int32_t *, u_int32_t (**)(Db *, Dbt *key));
virtual int get_partition_dirs(const char ***);
virtual int get_partition_keys(u_int32_t *, Dbt **);
virtual int get_priority(DB_CACHE_PRIORITY *);
virtual int get_q_extentsize(u_int32_t *);
virtual int get_re_delim(int *);
virtual int get_re_len(u_int32_t *);
virtual int get_re_pad(int *);
virtual int get_re_source(const char **);
virtual int get_transactional();
virtual int get_type(DBTYPE *);
virtual int join(Dbc **curslist, Dbc **dbcp, u_int32_t flags);
virtual int key_range(DbTxn *, Dbt *, DB_KEY_RANGE *, u_int32_t);
virtual int open(DbTxn *txnid,
const char *, const char *subname, DBTYPE, u_int32_t, int);
virtual int pget(DbTxn *txnid,
Dbt *key, Dbt *pkey, Dbt *data, u_int32_t flags);
virtual int put(DbTxn *, Dbt *, Dbt *, u_int32_t);
virtual int remove(const char *, const char *, u_int32_t);
virtual int rename(const char *, const char *, const char *, u_int32_t);
virtual int set_alloc(
db_malloc_fcn_type, db_realloc_fcn_type, db_free_fcn_type);
virtual void set_app_private(void *);
virtual int set_append_recno(int (*)(Db *, Dbt *, db_recno_t));
virtual int set_bt_compare(bt_compare_fcn_type); /*deprecated*/
virtual int set_bt_compare(int (*)(Db *, const Dbt *, const Dbt *));
virtual int set_bt_compress(
int (*)
(Db *, const Dbt *, const Dbt *, const Dbt *, const Dbt *, Dbt *),
int (*)(Db *, const Dbt *, const Dbt *, Dbt *, Dbt *, Dbt *));
virtual int set_bt_minkey(u_int32_t);
virtual int set_bt_prefix(bt_prefix_fcn_type); /*deprecated*/
virtual int set_bt_prefix(size_t (*)(Db *, const Dbt *, const Dbt *));
virtual int set_cachesize(u_int32_t, u_int32_t, int);
virtual int set_create_dir(const char *);
virtual int set_dup_compare(dup_compare_fcn_type); /*deprecated*/
virtual int set_dup_compare(int (*)(Db *, const Dbt *, const Dbt *));
virtual int set_encrypt(const char *, u_int32_t);
virtual void set_errcall(
void (*)(const DbEnv *, const char *, const char *));
virtual void set_errfile(FILE *);
virtual void set_errpfx(const char *);
virtual int set_feedback(void (*)(Db *, int, int));
virtual int set_flags(u_int32_t);
virtual int set_heapsize(u_int32_t, u_int32_t);
virtual int set_heap_regionsize(u_int32_t);
virtual int set_h_compare(h_compare_fcn_type); /*deprecated*/
virtual int set_h_compare(int (*)(Db *, const Dbt *, const Dbt *));
virtual int set_h_ffactor(u_int32_t);
virtual int set_h_hash(h_hash_fcn_type); /*deprecated*/
virtual int set_h_hash(u_int32_t (*)(Db *, const void *, u_int32_t));
virtual int set_h_nelem(u_int32_t);
virtual int set_lk_exclusive(bool);
virtual int set_lorder(int);
virtual void set_msgcall(void (*)(const DbEnv *, const char *));
virtual void set_msgfile(FILE *);
virtual int set_pagesize(u_int32_t);
virtual int set_paniccall(void (*)(DbEnv *, int));
virtual int set_partition(
u_int32_t, Dbt *, u_int32_t (*)(Db *, Dbt *));
virtual int set_partition_dirs(const char **);
virtual int set_priority(DB_CACHE_PRIORITY);
virtual int set_q_extentsize(u_int32_t);
virtual int set_re_delim(int);
virtual int set_re_len(u_int32_t);
virtual int set_re_pad(int);
virtual int set_re_source(const char *);
virtual int sort_multiple(Dbt *, Dbt *, u_int32_t);
virtual int stat(DbTxn *, void *sp, u_int32_t flags);
virtual int stat_print(u_int32_t flags);
virtual int sync(u_int32_t flags);
virtual int truncate(DbTxn *, u_int32_t *, u_int32_t);
virtual int upgrade(const char *name, u_int32_t flags);
virtual int verify(
const char *, const char *, __DB_STD(ostream) *, u_int32_t);
// These additional methods are not in the C interface, and
// are only available for C++.
//
virtual void *get_app_private() const;
virtual __DB_STD(ostream) *get_error_stream();
virtual void set_error_stream(__DB_STD(ostream) *);
virtual __DB_STD(ostream) *get_message_stream();
virtual void set_message_stream(__DB_STD(ostream) *);
virtual DbEnv *get_env();
virtual DbMpoolFile *get_mpf();
virtual ENV *get_ENV()
{
return imp_->env;
}
virtual DB *get_DB()
{
return imp_;
}
virtual const DB *get_const_DB() const
{
return imp_;
}
static Db* get_Db(DB *db)
{
return (Db *)db->api_internal;
}
static const Db* get_const_Db(const DB *db)
{
return (const Db *)db->api_internal;
}
u_int32_t get_create_flags() const
{
return construct_flags_;
}
private:
// no copying
Db(const Db &);
Db &operator = (const Db &);
void cleanup();
int initialize();
int error_policy();
// instance data
DB *imp_;
DbEnv *dbenv_;
DbMpoolFile *mpf_;
int construct_error_;
u_int32_t flags_;
u_int32_t construct_flags_;
static int alt_close(DB *, u_int32_t);
public:
// These are public only because they need to be called
// via C callback functions. They should never be used by
// external users of this class.
//
int (*append_recno_callback_)(Db *, Dbt *, db_recno_t);
int (*associate_callback_)(Db *, const Dbt *, const Dbt *, Dbt *);
int (*associate_foreign_callback_)
(Db *, const Dbt *, Dbt *, const Dbt *, int *);
int (*bt_compare_callback_)(Db *, const Dbt *, const Dbt *);
int (*bt_compress_callback_)(
Db *, const Dbt *, const Dbt *, const Dbt *, const Dbt *, Dbt *);
int (*bt_decompress_callback_)(
Db *, const Dbt *, const Dbt *, Dbt *, Dbt *, Dbt *);
size_t (*bt_prefix_callback_)(Db *, const Dbt *, const Dbt *);
u_int32_t (*db_partition_callback_)(Db *, Dbt *);
int (*dup_compare_callback_)(Db *, const Dbt *, const Dbt *);
void (*feedback_callback_)(Db *, int, int);
int (*h_compare_callback_)(Db *, const Dbt *, const Dbt *);
u_int32_t (*h_hash_callback_)(Db *, const void *, u_int32_t);
};
//
// Cursor
//
class _exported Dbc : protected DBC
{
friend class Db;
public:
int close();
int cmp(Dbc *other_csr, int *result, u_int32_t flags);
int count(db_recno_t *countp, u_int32_t flags);
int del(u_int32_t flags);
int dup(Dbc** cursorp, u_int32_t flags);
int get(Dbt* key, Dbt *data, u_int32_t flags);
int get_priority(DB_CACHE_PRIORITY *priorityp);
int pget(Dbt* key, Dbt* pkey, Dbt *data, u_int32_t flags);
int put(Dbt* key, Dbt *data, u_int32_t flags);
int set_priority(DB_CACHE_PRIORITY priority);
private:
// No data is permitted in this class (see comment at top)
// Note: use Db::cursor() to get pointers to a Dbc,
// and call Dbc::close() rather than delete to release them.
//
Dbc();
~Dbc();
// no copying
Dbc(const Dbc &);
Dbc &operator = (const Dbc &);
};
//
// A channel in replication group
//
class _exported DbChannel
{
friend class DbEnv;
public:
int close();
int send_msg(Dbt *msg, u_int32_t nmsg, u_int32_t flags);
int send_request(Dbt *request, u_int32_t nrequest, Dbt *response,
db_timeout_t timeout, u_int32_t flags);
int set_timeout(db_timeout_t timeout);
virtual DB_CHANNEL *get_DB_CHANNEL()
{
return imp_;
}
virtual const DB_CHANNEL *get_const_DB_CHANNEL() const
{
return imp_;
}
private:
DbChannel();
virtual ~DbChannel();
// no copying
DbChannel(const DbChannel &);
DbChannel &operator = (const DbChannel &);
DB_CHANNEL *imp_;
DbEnv *dbenv_;
};
//
// Berkeley DB environment class. Provides functions for opening databases.
// User of this library can use this class as a starting point for
// developing a DB application - derive their application class from
// this one, add application control logic.
//
// Note that if you use the default constructor, you must explicitly
// call appinit() before any other db activity (e.g. opening files)
//
class _exported DbEnv
{
friend class Db;
friend class DbLock;
friend class DbMpoolFile;
public:
// After using this constructor, you can set any needed
// parameters for the environment using the set_* methods.
// Then call open() to finish initializing the environment
// and attaching it to underlying files.
//
DbEnv(u_int32_t flags);
virtual ~DbEnv();
// These methods match those in the C interface.
//
virtual int add_data_dir(const char *);
virtual int backup(const char *target, u_int32_t flags);
virtual int cdsgroup_begin(DbTxn **tid);
virtual int close(u_int32_t);
virtual int dbbackup(
const char *dbfile, const char *target, u_int32_t flags);
virtual int dbremove(DbTxn *txn, const char *name, const char *subdb,
u_int32_t flags);
virtual int dbrename(DbTxn *txn, const char *name, const char *subdb,
const char *newname, u_int32_t flags);
virtual void err(int, const char *, ...);
virtual void errx(const char *, ...);
virtual int failchk(u_int32_t);
virtual int fileid_reset(const char *, u_int32_t);
virtual int get_alloc(db_malloc_fcn_type *, db_realloc_fcn_type *,
db_free_fcn_type *);
virtual void *get_app_private() const;
virtual int get_home(const char **);
virtual int get_open_flags(u_int32_t *);
virtual int open(const char *, u_int32_t, int);
virtual int remove(const char *, u_int32_t);
virtual int stat_print(u_int32_t flags);
virtual int set_alloc(db_malloc_fcn_type, db_realloc_fcn_type,
db_free_fcn_type);
virtual void set_app_private(void *);
virtual int get_backup_callbacks(
int (**)(DbEnv *, const char *, const char *, void **),
int (**)(DbEnv *, u_int32_t, u_int32_t, u_int32_t, u_int8_t *, void *),
int (**)(DbEnv *, const char *, void *));
virtual int set_backup_callbacks(
int (*)(DbEnv *, const char *, const char *, void **),
int (*)(DbEnv *, u_int32_t, u_int32_t, u_int32_t, u_int8_t *, void *),
int (*)(DbEnv *, const char *, void *));
virtual int get_backup_config(DB_BACKUP_CONFIG, u_int32_t *);
virtual int set_backup_config(DB_BACKUP_CONFIG, u_int32_t);
virtual int get_cachesize(u_int32_t *, u_int32_t *, int *);
virtual int set_cachesize(u_int32_t, u_int32_t, int);
virtual int get_cache_max(u_int32_t *, u_int32_t *);
virtual int set_cache_max(u_int32_t, u_int32_t);
virtual int get_create_dir(const char **);
virtual int set_create_dir(const char *);
virtual int get_data_dirs(const char ***);
virtual int set_data_dir(const char *);
virtual int get_encrypt_flags(u_int32_t *);
virtual int get_intermediate_dir_mode(const char **);
virtual int set_intermediate_dir_mode(const char *);
virtual int get_isalive(
int (**)(DbEnv *, pid_t, db_threadid_t, u_int32_t));
virtual int set_isalive(
int (*)(DbEnv *, pid_t, db_threadid_t, u_int32_t));
virtual int set_encrypt(const char *, u_int32_t);
virtual void get_errcall(
void (**)(const DbEnv *, const char *, const char *));
virtual void set_errcall(
void (*)(const DbEnv *, const char *, const char *));
virtual void get_errfile(FILE **);
virtual void set_errfile(FILE *);
virtual void get_errpfx(const char **);
virtual void set_errpfx(const char *);
virtual int set_event_notify(void (*)(DbEnv *, u_int32_t, void *));
virtual int get_flags(u_int32_t *);
virtual int set_flags(u_int32_t, int);
virtual bool is_bigendian();
virtual int lsn_reset(const char *, u_int32_t);
virtual int get_feedback(void (**)(DbEnv *, int, int));
virtual int set_feedback(void (*)(DbEnv *, int, int));
virtual int get_lg_bsize(u_int32_t *);
virtual int set_lg_bsize(u_int32_t);
virtual int get_lg_dir(const char **);
virtual int set_lg_dir(const char *);
virtual int get_lg_filemode(int *);
virtual int set_lg_filemode(int);
virtual int get_lg_max(u_int32_t *);
virtual int set_lg_max(u_int32_t);
virtual int get_lg_regionmax(u_int32_t *);
virtual int set_lg_regionmax(u_int32_t);
virtual int get_lk_conflicts(const u_int8_t **, int *);
virtual int set_lk_conflicts(u_int8_t *, int);
virtual int get_lk_detect(u_int32_t *);
virtual int set_lk_detect(u_int32_t);
virtual int get_lk_max_lockers(u_int32_t *);
virtual int set_lk_max_lockers(u_int32_t);
virtual int get_lk_max_locks(u_int32_t *);
virtual int set_lk_max_locks(u_int32_t);
virtual int get_lk_max_objects(u_int32_t *);
virtual int set_lk_max_objects(u_int32_t);
virtual int get_lk_partitions(u_int32_t *);
virtual int set_lk_partitions(u_int32_t);
virtual int get_lk_priority(u_int32_t, u_int32_t *);
virtual int set_lk_priority(u_int32_t, u_int32_t);
virtual int get_lk_tablesize(u_int32_t *);
virtual int set_lk_tablesize(u_int32_t);
virtual int get_memory_init(DB_MEM_CONFIG, u_int32_t *);
virtual int set_memory_init(DB_MEM_CONFIG, u_int32_t);
virtual int get_memory_max(u_int32_t *, u_int32_t *);
virtual int set_memory_max(u_int32_t, u_int32_t);
virtual int get_metadata_dir(const char **);
virtual int set_metadata_dir(const char *);
virtual int get_mp_mmapsize(size_t *);
virtual int set_mp_mmapsize(size_t);
virtual int get_mp_max_openfd(int *);
virtual int set_mp_max_openfd(int);
virtual int get_mp_max_write(int *, db_timeout_t *);
virtual int set_mp_max_write(int, db_timeout_t);
virtual int get_mp_pagesize(u_int32_t *);
virtual int set_mp_pagesize(u_int32_t);
virtual int get_mp_tablesize(u_int32_t *);
virtual int set_mp_tablesize(u_int32_t);
virtual void get_msgcall(void (**)(const DbEnv *, const char *));
virtual void set_msgcall(void (*)(const DbEnv *, const char *));
virtual void get_msgfile(FILE **);
virtual void set_msgfile(FILE *);
virtual int set_paniccall(void (*)(DbEnv *, int));
virtual int get_shm_key(long *);
virtual int set_shm_key(long);
virtual int get_timeout(db_timeout_t *, u_int32_t);
virtual int set_timeout(db_timeout_t, u_int32_t);
virtual int get_tmp_dir(const char **);
virtual int set_tmp_dir(const char *);
virtual int get_tx_max(u_int32_t *);
virtual int set_tx_max(u_int32_t);
virtual int get_app_dispatch(
int (**)(DbEnv *, Dbt *, DbLsn *, db_recops));
virtual int set_app_dispatch(int (*)(DbEnv *,
Dbt *, DbLsn *, db_recops));
virtual int get_tx_timestamp(time_t *);
virtual int set_tx_timestamp(time_t *);
virtual int get_verbose(u_int32_t which, int *);
virtual int set_verbose(u_int32_t which, int);
// Version information. Static methods, can be called at any time.
//
static char *version(int *major, int *minor, int *patch);
static char *full_version(int *family, int *release,
int *major, int *minor, int *patch);
// Convert DB errors to strings
static char *strerror(int);
// If an error is detected and the error call function
// or stream is set, a message is dispatched or printed.
// If a prefix is set, each message is prefixed.
//
// You can use set_errcall() or set_errfile() above to control
// error functionality. Alternatively, you can call
// set_error_stream() to force all errors to a C++ stream.
// It is unwise to mix these approaches.
//
virtual __DB_STD(ostream) *get_error_stream();
virtual void set_error_stream(__DB_STD(ostream) *);
virtual __DB_STD(ostream) *get_message_stream();
virtual void set_message_stream(__DB_STD(ostream) *);
// used internally
static void runtime_error(DbEnv *dbenv, const char *caller, int err,
int error_policy);
static void runtime_error_dbt(DbEnv *dbenv, const char *caller, Dbt *dbt,
int error_policy);
static void runtime_error_lock_get(DbEnv *dbenv, const char *caller,
int err, db_lockop_t op, db_lockmode_t mode,
Dbt *obj, DbLock lock, int index,
int error_policy);
// Lock functions
//
virtual int lock_detect(u_int32_t flags, u_int32_t atype, int *aborted);
virtual int lock_get(u_int32_t locker, u_int32_t flags, Dbt *obj,
db_lockmode_t lock_mode, DbLock *lock);
virtual int lock_id(u_int32_t *idp);
virtual int lock_id_free(u_int32_t id);
virtual int lock_put(DbLock *lock);
virtual int lock_stat(DB_LOCK_STAT **statp, u_int32_t flags);
virtual int lock_stat_print(u_int32_t flags);
virtual int lock_vec(u_int32_t locker, u_int32_t flags,
DB_LOCKREQ list[], int nlist, DB_LOCKREQ **elistp);
// Log functions
//
virtual int log_archive(char **list[], u_int32_t flags);
static int log_compare(const DbLsn *lsn0, const DbLsn *lsn1);
virtual int log_cursor(DbLogc **cursorp, u_int32_t flags);
virtual int log_file(DbLsn *lsn, char *namep, size_t len);
virtual int log_flush(const DbLsn *lsn);
virtual int log_get_config(u_int32_t, int *);
virtual int log_put(DbLsn *lsn, const Dbt *data, u_int32_t flags);
virtual int log_printf(DbTxn *, const char *, ...);
virtual int log_set_config(u_int32_t, int);
virtual int log_stat(DB_LOG_STAT **spp, u_int32_t flags);
virtual int log_stat_print(u_int32_t flags);
virtual int log_verify(DB_LOG_VERIFY_CONFIG *);
// Mpool functions
//
virtual int memp_fcreate(DbMpoolFile **dbmfp, u_int32_t flags);
virtual int memp_register(int ftype,
pgin_fcn_type pgin_fcn,
pgout_fcn_type pgout_fcn);
virtual int memp_stat(DB_MPOOL_STAT
**gsp, DB_MPOOL_FSTAT ***fsp, u_int32_t flags);
virtual int memp_stat_print(u_int32_t flags);
virtual int memp_sync(DbLsn *lsn);
virtual int memp_trickle(int pct, int *nwrotep);
// Mpool functions
//
virtual int mutex_alloc(u_int32_t, db_mutex_t *);
virtual int mutex_free(db_mutex_t);
virtual int mutex_get_align(u_int32_t *);
virtual int mutex_get_increment(u_int32_t *);
virtual int mutex_get_init(u_int32_t *);
virtual int mutex_get_max(u_int32_t *);
virtual int mutex_get_tas_spins(u_int32_t *);
virtual int mutex_lock(db_mutex_t);
virtual int mutex_set_align(u_int32_t);
virtual int mutex_set_increment(u_int32_t);
virtual int mutex_set_init(u_int32_t);
virtual int mutex_set_max(u_int32_t);
virtual int mutex_set_tas_spins(u_int32_t);
virtual int mutex_stat(DB_MUTEX_STAT **, u_int32_t);
virtual int mutex_stat_print(u_int32_t);
virtual int mutex_unlock(db_mutex_t);
// Transaction functions
//
virtual int txn_begin(DbTxn *pid, DbTxn **tid, u_int32_t flags);
virtual int txn_checkpoint(u_int32_t kbyte, u_int32_t min,
u_int32_t flags);
virtual int txn_recover(DbPreplist *preplist, long count,
long *retp, u_int32_t flags);
virtual int txn_stat(DB_TXN_STAT **statp, u_int32_t flags);
virtual int txn_stat_print(u_int32_t flags);
// Replication functions
//
virtual int rep_elect(u_int32_t, u_int32_t, u_int32_t);
virtual int rep_flush();
virtual int rep_process_message(Dbt *, Dbt *, int, DbLsn *);
virtual int rep_start(Dbt *, u_int32_t);
virtual int rep_stat(DB_REP_STAT **statp, u_int32_t flags);
virtual int rep_stat_print(u_int32_t flags);
virtual int rep_get_clockskew(u_int32_t *, u_int32_t *);
virtual int rep_set_clockskew(u_int32_t, u_int32_t);
virtual int rep_get_limit(u_int32_t *, u_int32_t *);
virtual int rep_set_limit(u_int32_t, u_int32_t);
virtual int rep_set_transport(int, int (*)(DbEnv *,
const Dbt *, const Dbt *, const DbLsn *, int, u_int32_t));
virtual int rep_set_request(u_int32_t, u_int32_t);
virtual int rep_get_request(u_int32_t *, u_int32_t *);
virtual int get_thread_count(u_int32_t *);
virtual int set_thread_count(u_int32_t);
virtual int get_thread_id_fn(
void (**)(DbEnv *, pid_t *, db_threadid_t *));
virtual int set_thread_id(void (*)(DbEnv *, pid_t *, db_threadid_t *));
virtual int get_thread_id_string_fn(
char *(**)(DbEnv *, pid_t, db_threadid_t, char *));
virtual int set_thread_id_string(char *(*)(DbEnv *,
pid_t, db_threadid_t, char *));
virtual int rep_set_config(u_int32_t, int);
virtual int rep_get_config(u_int32_t, int *);
virtual int rep_sync(u_int32_t flags);
// Advanced replication functions
//
virtual int rep_get_nsites(u_int32_t *n);
virtual int rep_set_nsites(u_int32_t n);
virtual int rep_get_priority(u_int32_t *priorityp);
virtual int rep_set_priority(u_int32_t priority);
virtual int rep_get_timeout(int which, db_timeout_t *timeout);
virtual int rep_set_timeout(int which, db_timeout_t timeout);
virtual int repmgr_channel(int eid, DbChannel **channel,
u_int32_t flags);
virtual int repmgr_get_ack_policy(int *policy);
virtual int repmgr_set_ack_policy(int policy);
virtual int repmgr_local_site(DbSite **site);
virtual int repmgr_msg_dispatch(void (*) (DbEnv *,
DbChannel *, Dbt *, u_int32_t, u_int32_t), u_int32_t flags);
virtual int repmgr_site(const char *host, u_int port, DbSite **site,
u_int32_t flags);
virtual int repmgr_site_by_eid(int eid, DbSite **site);
virtual int repmgr_site_list(u_int *countp, DB_REPMGR_SITE **listp);
virtual int repmgr_start(int nthreads, u_int32_t flags);
virtual int repmgr_stat(DB_REPMGR_STAT **statp, u_int32_t flags);
virtual int repmgr_stat_print(u_int32_t flags);
// Conversion functions
//
virtual ENV *get_ENV()
{
return imp_->env;
}
virtual DB_ENV *get_DB_ENV()
{
return imp_;
}
virtual const DB_ENV *get_const_DB_ENV() const
{
return imp_;
}
static DbEnv* get_DbEnv(DB_ENV *dbenv)
{
return dbenv ? (DbEnv *)dbenv->api1_internal : 0;
}
static const DbEnv* get_const_DbEnv(const DB_ENV *dbenv)
{
return dbenv ? (const DbEnv *)dbenv->api1_internal : 0;
}
u_int32_t get_create_flags() const
{
return construct_flags_;
}
// For internal use only.
static DbEnv* wrap_DB_ENV(DB_ENV *dbenv);
// These are public only because they need to be called
// via C functions. They should never be called by users
// of this class.
//
static int _app_dispatch_intercept(DB_ENV *dbenv, DBT *dbt, DB_LSN *lsn,
db_recops op);
static int _backup_close_intercept(DB_ENV *dbenv,
const char *dbname, void *handle);
static int _backup_open_intercept(DB_ENV *dbenv,
const char *dbname, const char *target, void **handle);
static int _backup_write_intercept(DB_ENV *dbenv, u_int32_t off_gbytes,
u_int32_t off_bytes, u_int32_t size, u_int8_t *buf, void *handle);
static void _paniccall_intercept(DB_ENV *dbenv, int errval);
static void _feedback_intercept(DB_ENV *dbenv, int opcode, int pct);
static void _event_func_intercept(DB_ENV *dbenv, u_int32_t, void *);
static int _isalive_intercept(DB_ENV *dbenv, pid_t pid,
db_threadid_t thrid, u_int32_t flags);
static int _rep_send_intercept(DB_ENV *dbenv, const DBT *cntrl,
const DBT *data, const DB_LSN *lsn, int id, u_int32_t flags);
static void _stream_error_function(const DB_ENV *dbenv,
const char *prefix, const char *message);
static void _stream_message_function(const DB_ENV *dbenv,
const char *message);
static void _thread_id_intercept(DB_ENV *dbenv, pid_t *pidp,
db_threadid_t *thridp);
static char *_thread_id_string_intercept(DB_ENV *dbenv, pid_t pid,
db_threadid_t thrid, char *buf);
static void _message_dispatch_intercept(DB_ENV *dbenv,
DB_CHANNEL *dbchannel, DBT *request, u_int32_t nrequest,
u_int32_t cb_flags);
private:
void cleanup();
int initialize(DB_ENV *dbenv);
int error_policy();
// For internal use only.
DbEnv(DB_ENV *, u_int32_t flags);
// no copying
DbEnv(const DbEnv &);
void operator = (const DbEnv &);
// instance data
DB_ENV *imp_;
int construct_error_;
u_int32_t construct_flags_;
__DB_STD(ostream) *error_stream_;
__DB_STD(ostream) *message_stream_;
int (*app_dispatch_callback_)(DbEnv *, Dbt *, DbLsn *, db_recops);
int (*backup_close_callback_)(DbEnv *, const char *, void *);
int (*backup_open_callback_)(
DbEnv *, const char *, const char *, void **);
int (*backup_write_callback_)(
DbEnv *, u_int32_t, u_int32_t, u_int32_t, u_int8_t *, void *);
int (*isalive_callback_)(DbEnv *, pid_t, db_threadid_t, u_int32_t);
void (*error_callback_)(const DbEnv *, const char *, const char *);
void (*feedback_callback_)(DbEnv *, int, int);
void (*message_callback_)(const DbEnv *, const char *);
void (*paniccall_callback_)(DbEnv *, int);
void (*event_func_callback_)(DbEnv *, u_int32_t, void *);
int (*rep_send_callback_)(DbEnv *, const Dbt *, const Dbt *,
const DbLsn *, int, u_int32_t);
void (*thread_id_callback_)(DbEnv *, pid_t *, db_threadid_t *);
char *(*thread_id_string_callback_)(DbEnv *, pid_t, db_threadid_t,
char *);
void (*message_dispatch_callback_)(DbEnv *, DbChannel *, Dbt *,
u_int32_t, u_int32_t);
};
//
// Heap record id
//
class _exported DbHeapRecordId : private DB_HEAP_RID
{
public:
db_pgno_t get_pgno() const { return pgno; }
void set_pgno(db_pgno_t value) { pgno = value; }
db_indx_t get_indx() const { return indx; }
void set_indx(db_indx_t value) { indx = value; }
DB_HEAP_RID *get_DB_HEAP_RID() { return (DB_HEAP_RID *)this; }
const DB_HEAP_RID *get_const_DB_HEAP_RID() const
{ return (const DB_HEAP_RID *)this; }
static DbHeapRecordId* get_DbHeapRecordId(DB_HEAP_RID *rid)
{ return (DbHeapRecordId *)rid; }
static const DbHeapRecordId* get_const_DbHeapRecordId(DB_HEAP_RID *rid)
{ return (const DbHeapRecordId *)rid; }
DbHeapRecordId(db_pgno_t pgno, db_indx_t indx);
DbHeapRecordId();
~DbHeapRecordId();
DbHeapRecordId(const DbHeapRecordId &);
DbHeapRecordId &operator = (const DbHeapRecordId &);
};
//
// Lock
//
class _exported DbLock
{
friend class DbEnv;
public:
DbLock();
DbLock(const DbLock &);
DbLock &operator = (const DbLock &);
protected:
// We can add data to this class if needed
// since its contained class is not allocated by db.
// (see comment at top)
DbLock(DB_LOCK);
DB_LOCK lock_;
};
//
// Log cursor
//
class _exported DbLogc : protected DB_LOGC
{
friend class DbEnv;
public:
int close(u_int32_t _flags);
int get(DbLsn *lsn, Dbt *data, u_int32_t _flags);
int version(u_int32_t *versionp, u_int32_t _flags);
private:
// No data is permitted in this class (see comment at top)
// Note: use Db::cursor() to get pointers to a Dbc,
// and call Dbc::close() rather than delete to release them.
//
DbLogc();
~DbLogc();
// no copying
DbLogc(const Dbc &);
DbLogc &operator = (const Dbc &);
};
//
// Log sequence number
//
class _exported DbLsn : public DB_LSN
{
friend class DbEnv; // friendship needed to cast to base class
friend class DbLogc; // friendship needed to cast to base class
};
//
// Memory pool file
//
class _exported DbMpoolFile
{
friend class DbEnv;
friend class Db;
public:
int close(u_int32_t flags);
int get(db_pgno_t *pgnoaddr, DbTxn *txn, u_int32_t flags, void *pagep);
int get_clear_len(u_int32_t *len);
int get_fileid(u_int8_t *fileid);
int get_flags(u_int32_t *flagsp);
int get_ftype(int *ftype);
int get_last_pgno(db_pgno_t *pgnop);
int get_lsn_offset(int32_t *offsetp);
int get_maxsize(u_int32_t *gbytes, u_int32_t *bytes);
int get_pgcookie(DBT *dbt);
int get_priority(DB_CACHE_PRIORITY *priorityp);
int get_transactional(void);
int open(const char *file, u_int32_t flags, int mode, size_t pagesize);
int put(void *pgaddr, DB_CACHE_PRIORITY priority, u_int32_t flags);
int set_clear_len(u_int32_t len);
int set_fileid(u_int8_t *fileid);
int set_flags(u_int32_t flags, int onoff);
int set_ftype(int ftype);
int set_lsn_offset(int32_t offset);
int set_maxsize(u_int32_t gbytes, u_int32_t bytes);
int set_pgcookie(DBT *dbt);
int set_priority(DB_CACHE_PRIORITY priority);
int sync();
virtual DB_MPOOLFILE *get_DB_MPOOLFILE()
{
return imp_;
}
virtual const DB_MPOOLFILE *get_const_DB_MPOOLFILE() const
{
return imp_;
}
private:
DB_MPOOLFILE *imp_;
// We can add data to this class if needed
// since it is implemented via a pointer.
// (see comment at top)
// Note: use DbEnv::memp_fcreate() to get pointers to a DbMpoolFile,
// and call DbMpoolFile::close() rather than delete to release them.
//
DbMpoolFile();
// Shut g++ up.
protected:
virtual ~DbMpoolFile();
private:
// no copying
DbMpoolFile(const DbMpoolFile &);
void operator = (const DbMpoolFile &);
};
//
// This is filled in and returned by the DbEnv::txn_recover() method.
//
class _exported DbPreplist
{
public:
DbTxn *txn;
u_int8_t gid[DB_GID_SIZE];
};
//
// A sequence record in a database
//
class _exported DbSequence
{
public:
DbSequence(Db *db, u_int32_t flags);
virtual ~DbSequence();
int open(DbTxn *txnid, Dbt *key, u_int32_t flags);
int initial_value(db_seq_t value);
int close(u_int32_t flags);
int remove(DbTxn *txnid, u_int32_t flags);
int stat(DB_SEQUENCE_STAT **sp, u_int32_t flags);
int stat_print(u_int32_t flags);
int get(DbTxn *txnid, int32_t delta, db_seq_t *retp, u_int32_t flags);
int get_cachesize(int32_t *sizep);
int set_cachesize(int32_t size);
int get_flags(u_int32_t *flagsp);
int set_flags(u_int32_t flags);
int get_range(db_seq_t *minp, db_seq_t *maxp);
int set_range(db_seq_t min, db_seq_t max);
Db *get_db();
Dbt *get_key();
virtual DB_SEQUENCE *get_DB_SEQUENCE()
{
return imp_;
}
virtual const DB_SEQUENCE *get_const_DB_SEQUENCE() const
{
return imp_;
}
static DbSequence* get_DbSequence(DB_SEQUENCE *seq)
{
return (DbSequence *)seq->api_internal;
}
static const DbSequence* get_const_DbSequence(const DB_SEQUENCE *seq)
{
return (const DbSequence *)seq->api_internal;
}
// For internal use only.
static DbSequence* wrap_DB_SEQUENCE(DB_SEQUENCE *seq);
private:
DbSequence(DB_SEQUENCE *seq);
// no copying
DbSequence(const DbSequence &);
DbSequence &operator = (const DbSequence &);
DB_SEQUENCE *imp_;
DBT key_;
};
//
// A site in replication group
//
class _exported DbSite
{
friend class DbEnv;
public:
int close();
int get_address(const char **hostp, u_int *port);
int get_config(u_int32_t which, u_int32_t *value);
int get_eid(int *eidp);
int remove();
int set_config(u_int32_t which, u_int32_t value);
virtual DB_SITE *get_DB_SITE()
{
return imp_;
}
virtual const DB_SITE *get_const_DB_SITE() const
{
return imp_;
}
private:
DbSite();
virtual ~DbSite();
// no copying
DbSite(const DbSite &);
DbSite &operator = (const DbSite &);
DB_SITE *imp_;
};
//
// Transaction
//
class _exported DbTxn
{
friend class DbEnv;
public:
int abort();
int commit(u_int32_t flags);
int discard(u_int32_t flags);
u_int32_t id();
int get_name(const char **namep);
int get_priority(u_int32_t *priorityp);
int prepare(u_int8_t *gid);
int set_name(const char *name);
int set_priority(u_int32_t priority);
int set_timeout(db_timeout_t timeout, u_int32_t flags);
virtual DB_TXN *get_DB_TXN()
{
return imp_;
}
virtual const DB_TXN *get_const_DB_TXN() const
{
return imp_;
}
static DbTxn* get_DbTxn(DB_TXN *txn)
{
return (DbTxn *)txn->api_internal;
}
static const DbTxn* get_const_DbTxn(const DB_TXN *txn)
{
return (const DbTxn *)txn->api_internal;
}
// For internal use only.
static DbTxn* wrap_DB_TXN(DB_TXN *txn);
void remove_child_txn(DbTxn *kid);
void add_child_txn(DbTxn *kid);
void set_parent(DbTxn *ptxn)
{
parent_txn_ = ptxn;
}
private:
DB_TXN *imp_;
// We use a TAILQ to store this object's kids of DbTxn objects, and
// each kid has a "parent_txn_" to point to this DbTxn object.
//
// If imp_ has a parent transaction which is not wrapped by DbTxn
// class, parent_txn_ will be NULL since we don't need to maintain
// this parent-kid relationship. This relationship only helps to
// delete unresolved kids when the parent is resolved.
DbTxn *parent_txn_;
// We can add data to this class if needed
// since it is implemented via a pointer.
// (see comment at top)
// Note: use DbEnv::txn_begin() to get pointers to a DbTxn,
// and call DbTxn::abort() or DbTxn::commit rather than
// delete to release them.
//
DbTxn(DbTxn *ptxn);
// For internal use only.
DbTxn(DB_TXN *txn, DbTxn *ptxn);
virtual ~DbTxn();
// no copying
DbTxn(const DbTxn &);
void operator = (const DbTxn &);
/*
* !!!
* Explicit representations of structures from queue.h.
* TAILQ_HEAD(__children, DbTxn) children;
*/
struct __children {
DbTxn *tqh_first;
DbTxn **tqh_last;
} children;
/*
* !!!
* Explicit representations of structures from queue.h.
* TAILQ_ENTRY(DbTxn) child_entry;
*/
struct {
DbTxn *tqe_next;
DbTxn **tqe_prev;
} child_entry;
};
//
// A chunk of data, maybe a key or value.
//
class _exported Dbt : private DBT
{
friend class Db;
friend class Dbc;
friend class DbEnv;
friend class DbLogc;
friend class DbSequence;
public:
// key/data
void *get_data() const { return data; }
void set_data(void *value) { data = value; }
// key/data length
u_int32_t get_size() const { return size; }
void set_size(u_int32_t value) { size = value; }
// RO: length of user buffer.
u_int32_t get_ulen() const { return ulen; }
void set_ulen(u_int32_t value) { ulen = value; }
// RO: get/put record length.
u_int32_t get_dlen() const { return dlen; }
void set_dlen(u_int32_t value) { dlen = value; }
// RO: get/put record offset.
u_int32_t get_doff() const { return doff; }
void set_doff(u_int32_t value) { doff = value; }
// flags
u_int32_t get_flags() const { return flags; }
void set_flags(u_int32_t value) { flags = value; }
// Conversion functions
DBT *get_DBT() { return (DBT *)this; }
const DBT *get_const_DBT() const { return (const DBT *)this; }
static Dbt* get_Dbt(DBT *dbt) { return (Dbt *)dbt; }
static const Dbt* get_const_Dbt(const DBT *dbt)
{ return (const Dbt *)dbt; }
Dbt(void *data, u_int32_t size);
Dbt();
~Dbt();
Dbt(const Dbt &);
Dbt &operator = (const Dbt &);
private:
// Note: no extra data appears in this class (other than
// inherited from DBT) since we need DBT and Dbt objects
// to have interchangable pointers.
//
// When subclassing this class, remember that callback
// methods like bt_compare, bt_prefix, dup_compare may
// internally manufacture DBT objects (which later are
// cast to Dbt), so such callbacks might receive objects
// not of your subclassed type.
};
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// multiple key/data/recno iterator classes
//
// DbMultipleIterator is a shared private base class for the three types
// of bulk-return Iterator; it should never be instantiated directly,
// but it handles the functionality shared by its subclasses.
class _exported DbMultipleIterator
{
public:
DbMultipleIterator(const Dbt &dbt);
protected:
u_int8_t *data_;
u_int32_t *p_;
};
class _exported DbMultipleKeyDataIterator : private DbMultipleIterator
{
public:
DbMultipleKeyDataIterator(const Dbt &dbt) : DbMultipleIterator(dbt) {}
bool next(Dbt &key, Dbt &data);
};
class _exported DbMultipleRecnoDataIterator : private DbMultipleIterator
{
public:
DbMultipleRecnoDataIterator(const Dbt &dbt) : DbMultipleIterator(dbt) {}
bool next(db_recno_t &recno, Dbt &data);
};
class _exported DbMultipleDataIterator : private DbMultipleIterator
{
public:
DbMultipleDataIterator(const Dbt &dbt) : DbMultipleIterator(dbt) {}
bool next(Dbt &data);
};
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// multiple key/data/recno builder classes
//
// DbMultipleBuilder is a shared private base class for the three types
// of bulk buffer builders; it should never be instantiated directly,
// but it handles the functionality shared by its subclasses.
class _exported DbMultipleBuilder
{
public:
DbMultipleBuilder(Dbt &dbt);
protected:
Dbt &dbt_;
void *p_;
};
class _exported DbMultipleDataBuilder : DbMultipleBuilder
{
public:
DbMultipleDataBuilder(Dbt &dbt) : DbMultipleBuilder(dbt) {}
bool append(void *dbuf, size_t dlen);
bool reserve(void *&ddest, size_t dlen);
};
class _exported DbMultipleKeyDataBuilder : DbMultipleBuilder
{
public:
DbMultipleKeyDataBuilder(Dbt &dbt) : DbMultipleBuilder(dbt) {}
bool append(void *kbuf, size_t klen, void *dbuf, size_t dlen);
bool reserve(void *&kdest, size_t klen, void *&ddest, size_t dlen);
};
class _exported DbMultipleRecnoDataBuilder
{
public:
DbMultipleRecnoDataBuilder(Dbt &dbt);
bool append(db_recno_t recno, void *dbuf, size_t dlen);
bool reserve(db_recno_t recno, void *&ddest, size_t dlen);
protected:
Dbt &dbt_;
void *p_;
};
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// Exception classes
//
// Almost any error in the DB library throws a DbException.
// Every exception should be considered an abnormality
// (e.g. bug, misuse of DB, file system error).
//
class _exported DbException : public __DB_STD(exception)
{
public:
virtual ~DbException() throw();
DbException(int err);
DbException(const char *description);
DbException(const char *description, int err);
DbException(const char *prefix, const char *description, int err);
int get_errno() const;
virtual const char *what() const throw();
DbEnv *get_env() const;
void set_env(DbEnv *dbenv);
DbException(const DbException &);
DbException &operator = (const DbException &);
private:
void describe(const char *prefix, const char *description);
char *what_;
int err_; // errno
DbEnv *dbenv_;
};
//
// A specific sort of exception that occurs when
// an operation is aborted to resolve a deadlock.
//
class _exported DbDeadlockException : public DbException
{
public:
virtual ~DbDeadlockException() throw();
DbDeadlockException(const char *description);
DbDeadlockException(const DbDeadlockException &);
DbDeadlockException &operator = (const DbDeadlockException &);
};
//
// A specific sort of exception that occurs when
// a lock is not granted, e.g. by lock_get or lock_vec.
// Note that the Dbt is only live as long as the Dbt used
// in the offending call.
//
class _exported DbLockNotGrantedException : public DbException
{
public:
virtual ~DbLockNotGrantedException() throw();
DbLockNotGrantedException(const char *prefix, db_lockop_t op,
db_lockmode_t mode, const Dbt *obj, const DbLock lock, int index);
DbLockNotGrantedException(const char *description);
DbLockNotGrantedException(const DbLockNotGrantedException &);
DbLockNotGrantedException &operator =
(const DbLockNotGrantedException &);
db_lockop_t get_op() const;
db_lockmode_t get_mode() const;
const Dbt* get_obj() const;
DbLock *get_lock() const;
int get_index() const;
private:
db_lockop_t op_;
db_lockmode_t mode_;
const Dbt *obj_;
DbLock *lock_;
int index_;
};
//
// A specific sort of exception that occurs when
// user declared memory is insufficient in a Dbt.
//
class _exported DbMemoryException : public DbException
{
public:
virtual ~DbMemoryException() throw();
DbMemoryException(Dbt *dbt);
DbMemoryException(const char *prefix, Dbt *dbt);
DbMemoryException(const DbMemoryException &);
DbMemoryException &operator = (const DbMemoryException &);
Dbt *get_dbt() const;
private:
Dbt *dbt_;
};
//
// A specific sort of exception that occurs when a change of replication
// master requires that all handles be re-opened.
//
class _exported DbRepHandleDeadException : public DbException
{
public:
virtual ~DbRepHandleDeadException() throw();
DbRepHandleDeadException(const char *description);
DbRepHandleDeadException(const DbRepHandleDeadException &);
DbRepHandleDeadException &operator = (const DbRepHandleDeadException &);
};
//
// A specific sort of exception that occurs when
// recovery is required before continuing DB activity.
//
class _exported DbRunRecoveryException : public DbException
{
public:
virtual ~DbRunRecoveryException() throw();
DbRunRecoveryException(const char *description);
DbRunRecoveryException(const DbRunRecoveryException &);
DbRunRecoveryException &operator = (const DbRunRecoveryException &);
};
//
// A specific sort of exception that occurs when
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
//
// Restore default compiler warnings
//
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif /* !_DB_CXX_H_ */
|
EvilMcJerkface/jessy
|
lib/berkeleydb_core/include/db_cxx.h
|
C
|
mit
| 49,028
|
<?php
// ::menu-left.html.twig
return array (
);
|
OVGS/backoffice
|
app/cache/dev/assetic/config/7/7372dcfe0e21249a0e6a08b12c1db568.php
|
PHP
|
mit
| 50
|
<?php namespace Office;
use Presenter_Oldenroll;
use Model_Claims;
use Model_Checks;
//use Model_Ebcard;
use DB;
class View_Ebcard_Daily extends Presenter_Oldenroll
{
function build_page()
{
}
function view()
{
}
}
|
slyxster/sabc
|
fuel/app/modules/office/classes/view/ebcard/daily.php
|
PHP
|
mit
| 236
|
import {
Link,
Text,
LinkProps,
useThemeConfig,
TextVariant,
} from "@artsy/palette"
import { Details_artwork } from "v2/__generated__/Details_artwork.graphql"
import * as React from "react";
import { createFragmentContainer, graphql } from "react-relay"
interface DetailsProps {
artwork: Details_artwork
includeLinks: boolean
hideSaleInfo?: boolean
hideArtistName?: boolean
hidePartnerName?: boolean
}
const ConditionalLink: React.FC<
Pick<DetailsProps, "includeLinks"> &
LinkProps &
React.AnchorHTMLAttributes<HTMLAnchorElement>
> = ({ includeLinks, children, ...rest }) => {
return includeLinks ? <Link {...rest}>{children}</Link> : <>{children}</>
}
const ArtistLine: React.FC<DetailsProps> = ({
artwork: { cultural_maker, artists },
includeLinks,
}) => {
const tokens = useThemeConfig({
v2: {
variant: "mediumText" as TextVariant,
},
v3: {
variant: "md" as TextVariant,
},
})
if (cultural_maker) {
return (
<Text variant={tokens.variant} overflowEllipsis>
{cultural_maker}
</Text>
)
}
if (artists && artists.length) {
return (
<Text variant={tokens.variant} overflowEllipsis>
{artists.map((artist, i) => {
if (!artist || !artist.href || !artist.name) return null
return (
<ConditionalLink
includeLinks={includeLinks}
href={artist.href}
key={i}
>
{artist.name}
{i !== artists.length - 1 && ", "}
</ConditionalLink>
)
})}
</Text>
)
}
return null
}
const TitleLine: React.FC<DetailsProps> = ({
includeLinks,
artwork: { title, date, href },
}) => {
const tokens = useThemeConfig({
v2: {
variant: "text" as TextVariant,
},
v3: {
variant: "md" as TextVariant,
},
})
return (
// @ts-expect-error STRICT_NULL_CHECK
<ConditionalLink includeLinks={includeLinks} href={href}>
<Text variant={tokens.variant} color="black60" overflowEllipsis>
<i>{title}</i>
{date && `, ${date}`}
</Text>
</ConditionalLink>
)
}
const PartnerLine: React.FC<DetailsProps> = ({
includeLinks,
artwork: { collecting_institution, partner },
}) => {
const tokens = useThemeConfig({
v2: {
variant: "text" as TextVariant,
},
v3: {
variant: "xs" as TextVariant,
},
})
if (collecting_institution) {
return (
<Text variant={tokens.variant} color="black60" overflowEllipsis>
{collecting_institution}
</Text>
)
}
if (partner) {
return (
// @ts-expect-error STRICT_NULL_CHECK
<ConditionalLink includeLinks={includeLinks} href={partner.href}>
<Text variant={tokens.variant} color="black60" overflowEllipsis>
{partner.name}
</Text>
</ConditionalLink>
)
}
return null
}
const SaleInfoLine: React.FC<DetailsProps> = props => {
const tokens = useThemeConfig({
v2: {
variant: "text" as TextVariant,
color: "black60",
fontWeight: "normal",
},
v3: {
variant: "xs" as TextVariant,
color: "black100",
fontWeight: "bold",
},
})
return (
<Text
variant={tokens.variant}
color={tokens.color}
fontWeight={tokens.fontWeight}
overflowEllipsis
>
<SaleMessage {...props} /> <BidInfo {...props} />
</Text>
)
}
const SaleMessage: React.FC<DetailsProps> = ({
artwork: { sale, sale_message, sale_artwork },
}) => {
if (sale?.is_auction && sale?.is_closed) {
return <>Bidding closed</>
}
if (sale?.is_auction) {
const highest_bid_display = sale_artwork?.highest_bid?.display
const opening_bid_display = sale_artwork?.opening_bid?.display
return <>{highest_bid_display || opening_bid_display || ""}</>
}
if (sale_message === "Contact For Price") {
return <>Contact for Price</>
}
return <>{sale_message}</>
}
const BidInfo: React.FC<DetailsProps> = ({
artwork: { sale, sale_artwork },
}) => {
const inRunningAuction = sale?.is_auction && !sale?.is_closed
if (!inRunningAuction) {
return null
}
// @ts-expect-error STRICT_NULL_CHECK
const bidderPositionCounts = sale_artwork?.counts.bidder_positions ?? 0
if (bidderPositionCounts === 0) {
return null
}
return (
<>
({bidderPositionCounts} bid{bidderPositionCounts === 1 ? "" : "s"})
</>
)
}
export const Details: React.FC<DetailsProps> = ({
hideArtistName,
hidePartnerName,
hideSaleInfo,
...rest
}) => {
return (
<>
{!hideArtistName && <ArtistLine {...rest} />}
<TitleLine {...rest} />
{!hidePartnerName && <PartnerLine {...rest} />}
{!hideSaleInfo && <SaleInfoLine {...rest} />}
</>
)
}
export const DetailsFragmentContainer = createFragmentContainer(Details, {
artwork: graphql`
fragment Details_artwork on Artwork {
href
title
date
sale_message: saleMessage
cultural_maker: culturalMaker
artists(shallow: true) {
id
href
name
}
collecting_institution: collectingInstitution
partner(shallow: true) {
name
href
}
sale {
is_auction: isAuction
is_closed: isClosed
}
sale_artwork: saleArtwork {
counts {
bidder_positions: bidderPositions
}
highest_bid: highestBid {
display
}
opening_bid: openingBid {
display
}
}
}
`,
})
|
artsy/force-public
|
src/v2/Components/Artwork/Details.tsx
|
TypeScript
|
mit
| 5,570
|
module NewEden
module Eve
EVE_ENDPOINTS = %w{ AllianceList CertificateTree ConquerableStationList ErrorList FacWarStats FacWarTopStats RefTypes SkillTree }
EVE_ENDPOINTS.each do |endpoint|
module_eval <<-RUBY
def eve_#{endpoint.underscore}
request("/eve/#{endpoint}.xml.aspx")
end
RUBY
end
def character_ids(*names)
request("/eve/CharacterID.xml.aspx", :post, :names => names.join(","))
end
alias :character_id :character_ids
def character_info(character_id)
request("/eve/CharacterInfo.xml.aspx", :post, :characterID => character_id)
end
def character_names(*ids)
request("/eve/CharacterName.xml.aspx", :post, :ids => ids.join(","))
end
alias :character_name :character_names
end
end
|
ealdent/neweden
|
lib/neweden/eve.rb
|
Ruby
|
mit
| 792
|
var searchData=
[
['thread_2eh',['thread.h',['../sys_2thread_8h.html',1,'(Global Namespace)'],['../lv2_2thread_8h.html',1,'(Global Namespace)']]],
['tty_2eh',['tty.h',['../tty_8h.html',1,'']]]
];
|
ps3dev/PSL1GHT
|
docs/search/files_f.js
|
JavaScript
|
mit
| 200
|
<?php
/*
* This file is part of the phlexible package.
*
* (c) Stephan Wentz <sw@brainbits.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Phlexible\Bundle\SiterootBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Siteroot
*
* @author Stephan Wentz <sw@brainbits.net>
*
* @ORM\Entity
* @ORM\Table(name="siteroot")
*/
class Siteroot
{
/**
* @var string
* @ORM\Id
* @ORM\Column(type="string", length=36, options={"fixed"=true})
*/
private $id;
/**
* @var bool
* @ORM\Column(name="is_default", type="boolean")
*/
private $default = false;
/**
* @var \DateTime
* @ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* @var string
* @ORM\Column(name="create_user_id", type="string", length=36, options={"fixed"=true})
*/
private $createUserId;
/**
* @var \DateTime
* @ORM\Column(name="modified_at", type="datetime")
*/
private $modifiedAt;
/**
* @var string
* @ORM\Column(name="modify_user_id", type="string", length=36, options={"fixed"=true})
*/
private $modifyUserId;
/**
* @var array
* @ORM\Column(name="special_tids", type="json_array")
*/
private $specialTids = [];
/**
* @var array
* @ORM\Column(type="json_array")
*/
private $titles = [];
/**
* @var array
* @ORM\Column(type="json_array")
*/
private $properties = [];
/**
* @var Navigation[]|ArrayCollection
* @ORM\OneToMany(targetEntity="Navigation", mappedBy="siteroot", cascade={"persist", "remove"})
*/
private $navigations;
/**
* @var Url[]|ArrayCollection
* @ORM\OneToMany(targetEntity="Url", mappedBy="siteroot", cascade={"persist", "remove"})
*/
private $urls;
/**
* Constructor.
*
* @param string $uuid
*/
public function __construct($uuid = null)
{
if (null !== $uuid) {
$this->id = $uuid;
}
$this->navigations = new ArrayCollection();
$this->urls = new ArrayCollection();
}
/**
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* @param bool $default
*
* @return $this
*/
public function setDefault($default)
{
$this->default = (bool) $default;
return $this;
}
/**
* @return bool
*/
public function isDefault()
{
return $this->default;
}
/**
* @param string $createUid
*
* @return $this
*/
public function setCreateUserId($createUid)
{
$this->createUserId = $createUid;
return $this;
}
/**
* @return string
*/
public function getCreateUserId()
{
return $this->createUserId;
}
/**
* @param \DateTime $createdAt
*
* @return $this
*/
public function setCreatedAt(\DateTime $createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* @param string $modifyUid
*
* @return $this
*/
public function setModifyUserId($modifyUid)
{
$this->modifyUserId = $modifyUid;
return $this;
}
/**
* @return string
*/
public function getModifyUserId()
{
return $this->modifyUserId;
}
/**
* @param \DateTime $modifiedAt
*
* @return $this
*/
public function setModifiedAt(\DateTime $modifiedAt)
{
$this->modifiedAt = $modifiedAt;
return $this;
}
/**
* @return \DateTime
*/
public function getModifiedAt()
{
return $this->modifiedAt;
}
/**
* Set all titles
*
* @param array $titles
*
* @return $this
*/
public function setTitles(array $titles)
{
$this->titles = $titles;
return $this;
}
/**
* Return all titles
*
* @return array
*/
public function getTitles()
{
return $this->titles;
}
/**
* Set title
*
* @param string $language
* @param string $title
*
* @return $this
*/
public function setTitle($language, $title)
{
$this->titles[$language] = $title;
return $this;
}
/**
* Return siteroot title
*
* @param string $language
*
* @return string
*/
public function getTitle($language = null)
{
$fallbackLanguage = key($this->titles);
if ($language === null) {
$language = $fallbackLanguage;
}
if (!empty($this->titles[$language])) {
return $this->titles[$language];
}
if (!empty($this->titles[$fallbackLanguage])) {
return $this->titles[$fallbackLanguage];
}
$title = false;
try {
$defaultUrl = $this->getDefaultUrl();
if ($defaultUrl) {
$title = $defaultUrl->getHostname();
}
} catch (\Exception $e) {
}
if (!$title) {
return '(No title)';
}
return $title;
}
/**
* @return Navigation[]
*/
public function getNavigations()
{
return $this->navigations;
}
/**
* @param Navigation $navigation
*
* @return $this
*/
public function addNavigation(Navigation $navigation)
{
if (!$this->navigations->contains($navigation)) {
$this->navigations->add($navigation);
$navigation->setSiteroot($this);
}
return $this;
}
/**
* @param Navigation $navigation
*
* @return $this
*/
public function removeNavigation(Navigation $navigation)
{
if ($this->navigations->contains($navigation)) {
$this->navigations->removeElement($navigation);
$navigation->setSiteroot(null);
}
return $this;
}
/**
* Return all special tids
*
* @return array
*/
public function getSpecialTids()
{
return $this->specialTids;
}
/**
* @param array $specialTids
*
* @return $this
*/
public function setSpecialTids(array $specialTids)
{
$this->specialTids = $specialTids;
return $this;
}
/**
* Return special tids for a language
*
* @param string $language
*
* @return array
*/
public function getSpecialTidsForLanguage($language = null)
{
$specialTids = [];
foreach ($this->specialTids as $specialTid) {
if ($specialTid['language'] === $language || $specialTid['language'] === null) {
$specialTids[$specialTid['name']] = $specialTid['treeId'];
}
}
return $specialTids;
}
/**
* Return a special tid
*
* @param string $language
* @param string $key
*
* @return string
*/
public function getSpecialTid($language, $key)
{
$languageSpecialTids = $this->getSpecialTidsForLanguage($language);
if (!empty($languageSpecialTids[$key])) {
return $languageSpecialTids[$key];
}
return null;
}
/**
* @param Url $url
*
* @return $this
*/
public function addUrl(Url $url)
{
if (!$this->urls->contains($url)) {
$this->urls->add($url);
$url->setSiteroot($this);
}
return $this;
}
/**
* @param Url $url
*
* @return $this
*/
public function removeUrl(Url $url)
{
if ($this->urls->contains($url)) {
$this->urls->removeElement($url);
$url->setSiteroot(null);
}
return $this;
}
/**
* @return Url[]
*/
public function getUrls()
{
return $this->urls;
}
/**
* Return the default url
*
* @param string $language
*
* @return Url
*/
public function getDefaultUrl($language = null)
{
foreach ($this->urls as $url) {
if ($url->isDefault()) {
return $url;
}
}
return null;
}
/**
* @param array $properties
*
* @return $this
*/
public function setProperties(array $properties)
{
$this->properties = $properties;
return $this;
}
/**
* @return array
*/
public function getProperties()
{
$properties = $this->properties;
return $properties;
}
/**
* @param string $key
* @param string $value
*
* @return $this
*/
public function setProperty($key, $value)
{
$this->properties[$key] = $value;
return $this;
}
/**
* @param string $key
* @param mixed $defaultValue
*
* @return string
*/
public function getProperty($key, $defaultValue = null)
{
if (empty($this->properties[$key])) {
return $defaultValue;
}
return $this->properties[$key];
}
}
|
temp/phlexible
|
src/Phlexible/Bundle/SiterootBundle/Entity/Siteroot.php
|
PHP
|
mit
| 9,454
|
/*
(Business: check ISBN-10) An ISBN-10 (International Standard Book Number)
consists of 10 digits: d1d2d3d4d5d6d7d8d9d10. The last digit, d10, is a checksum,
which is calculated from the other nine digits using the following formula:
(d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 +
d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11
If the checksum is 10, the last digit is denoted as X according to the ISBN-10
convention. Write a program that prompts the user to enter the first 9 digits and
displays the 10-digit ISBN (including leading zeros). Your program should read
the input as an integer. Here are sample runs:
*/
import java.util.Scanner;
public class Exercise_03_09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter the first 9 digits of a 10-digit ISBN
System.out.print("Enter the first 9 digits of an ISBN as integer: ");
int isbn = input.nextInt();
// Extract the digits of the ISBN
int d1 = isbn / 100000000;
int remainingDigits = isbn % 100000000;
int d2 = remainingDigits / 10000000;
remainingDigits %= 10000000;
int d3 = remainingDigits / 1000000;
remainingDigits %= 1000000;
int d4 = remainingDigits / 100000;
remainingDigits %= 100000;
int d5 = remainingDigits / 10000;
remainingDigits %= 10000;
int d6 = remainingDigits / 1000;
remainingDigits %= 1000;
int d7 = remainingDigits / 100;
remainingDigits %= 100;
int d8 = remainingDigits / 10;
remainingDigits %= 10;
int d9 = remainingDigits;
// Compute d10
int d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5
+ d6 * 6 + d7 * 7 + d8 * 8 + d9 * 9) % 11;
// Display the 10-digit ISBN
System.out.println("The ISBN-10 number is " + d1 + d2 + d3 + d4 + d5
+ d6 + d7 + d8 + d9);
if (d10 == 10)
System.out.println("X");
else
System.out.println(d10);
}
}
|
jsquared21/Intro-to-Java-Programming
|
Exercise_03/Exercise_03_09/Exercise_03_09.java
|
Java
|
mit
| 1,849
|
require 'test_helper'
class ForumServiceTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, ForumService
end
end
|
gialib/forum-service
|
test/forum_service_test.rb
|
Ruby
|
mit
| 140
|
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>File: 20090813164137_create_contributors.rb</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
<script type="text/javascript">
// <![CDATA[
function popupCode( url ) {
window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
}
function toggleCode( id ) {
if ( document.getElementById )
elem = document.getElementById( id );
else if ( document.all )
elem = eval( "document.all." + id );
else
return false;
elemStyle = elem.style;
if ( elemStyle.display != "block" ) {
elemStyle.display = "block"
} else {
elemStyle.display = "none"
}
return true;
}
// Make codeblocks hidden by default
document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
// ]]>
</script>
</head>
<body>
<div id="fileHeader">
<h1>20090813164137_create_contributors.rb</h1>
<table class="header-table">
<tr class="top-aligned-row">
<td><strong>Path:</strong></td>
<td>db/migrate/20090813164137_create_contributors.rb
</td>
</tr>
<tr class="top-aligned-row">
<td><strong>Last Update:</strong></td>
<td>Thu Aug 13 10:08:27 -0700 2009</td>
</tr>
</table>
</div>
<!-- banner header -->
<div id="bodyContent">
<div id="contextContent">
</div>
</div>
<!-- if includes -->
<div id="section">
<!-- if method_list -->
</div>
<div id="validator-badges">
<p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>
</body>
</html>
|
jeffp/wizardly-examples
|
rdoc/files/db/migrate/20090813164137_create_contributors_rb.html
|
HTML
|
mit
| 2,084
|
---
title: Send
category: send
mailchimp: true
description: Upload a list and schedule your email.
order: 5
---
|
fordhamumc/email-docs
|
src/send.html
|
HTML
|
mit
| 112
|
using System;
namespace GoldenFox.Internal.Constraints
{
public class From : IConstraint
{
private readonly DateTime _from;
public From(DateTime from)
{
_from = @from;
}
public ConstraintResult Contains(DateTime dateTime)
{
var passed = _from <= dateTime;
return new ConstraintResult { Passed = passed, ClosestValidFutureInput = passed ? dateTime : _from, };
}
}
}
|
mattiasnordqvist/Golden-Fox
|
GoldenFox/Internal/Constraints/From.cs
|
C#
|
mit
| 474
|
#ifndef UTILS_H
#define UTILS_H
#include <algorithm>
#include <functional>
#include <cctype>
#include <locale>
namespace renderlib{
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&); \
void operator=(const TypeName&)
#define BUFFER_OFFSET(i) ((void*)(i))
// trim from start
static inline std::string <rim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string &rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string &trim(std::string &s) {
return ltrim(rtrim(s));
}
} //namespace renderlib
#endif // UTILS_H
|
kristofe/VolumeRenderer
|
renderlib/include/utils.h
|
C
|
mit
| 993
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TravellingSalesman
{
public class Point
{
public double X
{
get
{
return Coordinate[ 0 ];
}
set
{
Coordinate[ 0 ] = value;
}
}
public double Y
{
get
{
return Coordinate[ 1 ];
}
set
{
Coordinate[ 1 ] = value;
}
}
public double Z
{
get
{
return Coordinate[ 2 ];
}
set
{
Coordinate[ 2 ] = value;
}
}
public double[] Coordinate
{
get
{
return m_Coord;
}
set
{
m_Coord = value;
}
}
public Point()
: this( 0, 0, 0 )
{
}
public Point( double x, double y, double z )
{
m_Coord = new double[] { x, y, z };
}
override public string ToString()
{
return string.Concat( "(", X.ToString(), ", ", Y.ToString(), ", ", Z.ToString(), ")" );
}
public Point( Point pt )
: this( 0, 0, 0 )
{
for( int i = 0; i < m_TotalCoordNum; i++ ) {
m_Coord[ i ] = pt.m_Coord[ i ];
}
}
public Point Clone()
{
return new Point( this.X, this.Y, this.Z );
}
public Point CrossProduct( Point other )
{
// u x v = ( u2v3 - u3v2 )i + (u3v1 - u1v3)j + (u1v2 - u2v1)k
double i = this.Coordinate[ 1 ] * other.Coordinate[ 2 ] - this.Coordinate[ 2 ] * other.Coordinate[ 1 ];
double j = this.Coordinate[ 2 ] * other.Coordinate[ 0 ] - this.Coordinate[ 0 ] * other.Coordinate[ 2 ];
double k = this.Coordinate[ 0 ] * other.Coordinate[ 1 ] - this.Coordinate[ 1 ] * other.Coordinate[ 0 ];
Point ret = new Point( i, j, k );
return ret;
}
public double Distance()
{
double ret = Math.Sqrt( this.X * this.X + this.Y * this.Y + this.Z * this.Z );
return ret;
}
public static Point operator +( Point a, Point b )
{
Point tmp = new Point();
for( int i = 0; i < m_TotalCoordNum; i++ ) {
tmp.Coordinate[ i ] = a.Coordinate[ i ] + b.Coordinate[ i ];
}
return tmp;
}
public static Point operator -( Point a )
{
return ( ( new Point() ) - a );
}
public static Point operator -( Point a, Point b )
{
Point tmp = new Point();
for( int i = 0; i < m_TotalCoordNum; i++ ) {
tmp.Coordinate[ i ] = a.Coordinate[ i ] - b.Coordinate[ i ];
}
return tmp;
}
public static Point operator /( Point a, double Number ){
Point tmp = new Point();
for( int i = 0; i < a.Coordinate.Length; i++ ) {
tmp.Coordinate[ i ] = a.Coordinate[ i ] / Number;
}
return tmp;
}
public static Point operator *( Point a, double Number )
{
Point tmp = new Point();
for( int i = 0; i < a.Coordinate.Length; i++ ) {
tmp.Coordinate[ i ] = a.Coordinate[ i ] * Number;
}
return tmp;
}
double[] m_Coord;
const int m_TotalCoordNum = 3;
}
}
|
Lounarok/TravelingSalesmanInCSharp
|
TravellingSalesman/Point.cs
|
C#
|
mit
| 2,863
|
## 属性描述符
属性分为数据属性和访问器属性。
数据属性、访问器属性属性描述符共有的键:
- configurable: default false。可配置性。当其为true时,该属性的属性描述符才能修改,同时该属性可以用delete从对象上删除
- enumerable: default true(***MDN误***)。可枚举性。当其为true时,表示该属性可以出现在for...in循环以及Object.keys(obj)里
数据属性的属性描述符独有的键:
- value: default undefined。该属性对应的值,可以是任何javascript有效值(数值,对象,函数等)。
- writable: default true。可写性。当且仅当其为true时,value才能通过"obj.attr = " 赋值
访问器属性独有的键:
- get: default undefined。一个给属性提供 getter 的方法。在读取属性时调用的函数。方法执行时没有参数传入,但是会传入this对象(***由于继承关系,这里的this并不一定是定义该属性的对象***,这个要怎么理解呢??)
- set: default undefined。一个给属性提供 setter 的方法。在写入属性时调用的函数。该方法将接受唯一参数,即该属性新的参数值。
## Object.defineProperty
该方法会直接在一个对象上定义一个新属性的属性描述符,或者修改一个对象的现有属性, 并返回这个对象。
### 语法:
```js
Object.defineProperty(obj, prop, descriptor)
```
Params:
- obj:要定义属性的对象
- prop:要定义或修改的属性名称
- descriptor:将被定义或修改的属性的属性描述符
Return:
- 这个对象
### 用法示例1
```js
Object.defineProperty(person1, 'name', {
configurable: true,
enumberable: true,
writable: true,
name: 'Bonnie'
})
```
### 用法示例2
```js
var book = {
_year:2004,
edition:1
}
Object.defineProperty(book, 'year', {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue>2004) {
this._year = newValue;
this.edition += newValue-2004;
}
}
})
```
|
wangyichen1064431086/workNote
|
tipsForTech/JavaScript/62.(12月已复习)属性描述符.md
|
Markdown
|
mit
| 2,035
|
> 本文最初发表于[博客园](),并在[GitHub](https://github.com/qianguyihao/Web)上持续更新**前端的系列文章**。欢迎在GitHub上关注我,一起入门和进阶前端。
> 以下是正文。
## 前言
jQuery提供的一组网页中常见的动画效果,这些动画是标准的、有规律的效果;同时还提供给我们了自定义动画的功能。
## 显示动画
方式一:
```javascript
$("div").show();
```
解释:无参数,表示让指定的元素直接显示出来。其实这个方法的底层就是通过`display: block;`实现的。
方式二:
```javascript
$("div").show(2000);
```
解释:通过控制元素的宽高、透明度、display属性,逐渐显示,2秒后显示完毕。
效果如下:

方式三:
```javascript
$("div").show("slow");
```
参数可以是:
- slow 慢:600ms
- normal 正常:400ms
- fast 快:200ms
解释:和方式二类似,也是通过控制元素的宽高、透明度、display属性,逐渐显示。
方式四:
```javascript
//show(毫秒值,回调函数;
$("div").show(5000,function () {
alert("动画执行完毕!");
});
```
解释:动画执行完后,立即执行回调函数。
**总结:**
上面的四种方式几乎一致:参数可以有两个,第一个是动画的执行时长,第二个是动画结束后执行的回调函数。
## 隐藏动画
方式参照上面的show()方法的方式。如下:
```javascript
$(selector).hide();
$(selector).hide(1000);
$(selector).hide("slow");
$(selector).hide(1000, function(){});
```
**显示和隐藏的来回切换:**
显示和隐藏的来回切换采用的是toggle()方法:就是先执行show(),再执行hide()。
同样是四种方式:
```javascript
$(selector).toggle();
```
## 滑入和滑出
**1、滑入动画效果**:(类似于生活中的卷帘门)
```javascript
$(selector).slideDown(speed, 回调函数);
```
解释:下拉动画,显示元素。
注意:省略参数或者传入不合法的字符串,那么则使用默认值:400毫秒(同样适用于fadeIn/slideDown/slideUp)
**2 滑出动画效果:**
```javascript
$(selector).slideUp(speed, 回调函数);
```
解释:上拉动画,隐藏元素。
**3、滑入滑出切换动画效果:**
```javascript
$(selector).slideToggle(speed, 回调函数);
```
参数解释同show()方法。
举例:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 300px;
height: 300px;
display: none;
background-color: pink;
}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
$(function () {
//点击按钮后产生动画
$("button:eq(0)").click(function () {
//滑入动画: slideDown(毫秒值,回调函数[显示完毕执行什么]);
$("div").slideDown(2000, function () {
alert("动画执行完毕!");
});
})
//滑出动画
$("button:eq(1)").click(function () {
//滑出动画:slideUp(毫秒值,回调函数[显示完毕后执行什么]);
$("div").slideUp(2000, function () {
alert("动画执行完毕!");
});
})
$("button:eq(2)").click(function () {
//滑入滑出切换(同样有四种用法)
$("div").slideToggle(1000);
})
})
</script>
</head>
<body>
<button>滑入</button>
<button>滑出</button>
<button>切换</button>
<div></div>
</body>
</html>
```

## 淡入淡出动画
1、淡入动画效果:
```javascript
$(selector).fadeIn(speed, callback);
```
作用:让元素以淡淡的进入视线的方式展示出来。
2、淡出动画效果:
```javascript
$(selector).fadeOut(1000);
```
作用:让元素以渐渐消失的方式隐藏起来
3、淡入淡出切换动画效果:
```javascript
$(selector).fadeToggle('fast', callback);
```
作用:通过改变透明度,切换匹配元素的显示或隐藏状态。
参数的含义同show()方法。
代码举例:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 300px;
height: 300px;
display: none;
/*opacity: 1;*/
background-color: pink;
}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
$(function () {
//点击按钮后产生动画
$("button:eq(0)").click(function () {
// //淡入动画用法1: fadeIn(); 不加参数
$("div").fadeIn();
// //淡入动画用法2: fadeIn(2000); 毫秒值
// $("div").fadeIn(2000);
// //通过控制 透明度和display
//淡入动画用法3: fadeIn(字符串); slow慢:600ms normal正常:400ms fast快:200ms
// $("div").fadeIn("slow");
// $("div").fadeIn("fast");
// $("div").fadeIn("normal");
//淡入动画用法4: fadeIn(毫秒值,回调函数[显示完毕执行什么]);
// $("div").fadeIn(5000,function () {
// alert("动画执行完毕!");
// });
})
//滑出动画
$("button:eq(1)").click(function () {
// //滑出动画用法1: fadeOut(); 不加参数
// $("div").fadeOut();
// //滑出动画用法2: fadeOut(2000); 毫秒值
// $("div").fadeOut(2000); //通过这个方法实现的:display: none;
// //通过控制 透明度和display
//滑出动画用法3: fadeOut(字符串); slow慢:600ms normal正常:400ms fast快:200ms
// $("div").fadeOut("slow");
// $("div").fadeOut("fast");
// $("div").fadeOut("normal");
//滑出动画用法1: fadeOut(毫秒值,回调函数[显示完毕执行什么]);
// $("div").fadeOut(2000,function () {
// alert("动画执行完毕!");
// });
})
$("button:eq(2)").click(function () {
//滑入滑出切换
//同样有四种用法
$("div").fadeToggle(1000);
})
$("button:eq(3)").click(function () {
//改透明度
//同样有四种用法
$("div").fadeTo(1000, 0.5, function () {
alert(1);
});
})
})
</script>
</head>
<body>
<button>淡入</button>
<button>淡出</button>
<button>切换</button>
<button>改透明度为0.5</button>
<div></div>
</body>
</html>
```
## 自定义动画
```javascript
$(selector).animate({params}, speed, callback);
```
作用:执行一组CSS属性的自定义动画。
- 第一个参数表示:要执行动画的CSS属性(必选)
- 第二个参数表示:执行动画时长(可选)
- 第三个参数表示:动画执行完后,立即执行的回调函数(可选)
代码举例:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
position: absolute;
left: 20px;
top: 30px;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
jQuery(function () {
$("button").click(function () {
var json = {"width": 500, "height": 500, "left": 300, "top": 300, "border-radius": 100};
var json2 = {
"width": 100,
"height": 100,
"left": 100,
"top": 100,
"border-radius": 100,
"background-color": "red"
};
//自定义动画
$("div").animate(json, 1000, function () {
$("div").animate(json2, 1000, function () {
alert("动画执行完毕!");
});
});
})
})
</script>
</head>
<body>
<button>自定义动画</button>
<div></div>
</body>
</html>
```
## 停止动画
```javascript
$(selector).stop(true, false);
```
**里面的两个参数,有不同的含义。**
第一个参数:
- true:后续动画不执行。
- false:后续动画会执行。
第二个参数:
- true:立即执行完成当前动画。
- false:立即停止当前动画。
PS:参数如果都不写,默认两个都是false。实际工作中,直接写stop()用的多。
**效果演示:**
当第二个参数为true时,效果如下:

当第二个参数为false时,效果如下:

这个**后续动画**我们要好好理解,来看个例子。
**案例:鼠标悬停时,弹出下拉菜单(下拉时带动画)**
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
ul {
list-style: none;
}
.wrap {
width: 330px;
height: 30px;
margin: 100px auto 0;
padding-left: 10px;
background-color: pink;
}
.wrap li {
background-color: green;
}
.wrap > ul > li {
float: left;
margin-right: 10px;
position: relative;
}
.wrap a {
display: block;
height: 30px;
width: 100px;
text-decoration: none;
color: #000;
line-height: 30px;
text-align: center;
}
.wrap li ul {
position: absolute;
top: 30px;
display: none;
}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
//入口函数
$(document).ready(function () {
//需求:鼠标放入一级li中,让他里面的ul显示。移开隐藏。
var jqli = $(".wrap>ul>li");
//绑定事件
jqli.mouseenter(function () {
$(this).children("ul").stop().slideDown(1000);
});
//绑定事件(移开隐藏)
jqli.mouseleave(function () {
$(this).children("ul").stop().slideUp(1000);
});
});
</script>
</head>
<body>
<div class="wrap">
<ul>
<li>
<a href="javascript:void(0);">一级菜单1</a>
<ul>
<li><a href="javascript:void(0);">二级菜单1</a></li>
<li><a href="javascript:void(0);">二级菜单2</a></li>
<li><a href="javascript:void(0);">二级菜单3</a></li>
</ul>
</li>
<li>
<a href="javascript:void(0);">一级菜单1</a>
<ul>
<li><a href="javascript:void(0);">二级菜单1</a></li>
<li><a href="javascript:void(0);">二级菜单2</a></li>
<li><a href="javascript:void(0);">二级菜单3</a></li>
</ul>
</li>
<li>
<a href="javascript:void(0);">一级菜单1</a>
<ul>
<li><a href="javascript:void(0);">二级菜单1</a></li>
<li><a href="javascript:void(0);">二级菜单2</a></li>
<li><a href="javascript:void(0);">二级菜单3</a></li>
</ul>
</li>
</ul>
</div>
</body>
</html>
```
效果如下:

上方代码中,关键的地方在于,用了stop函数,再执行动画前,先停掉之前的动画。
如果去掉stop()函数,效果如下:(不是我们期望的效果)

### stop方法的总结
当调用stop()方法后,队列里面的下一个动画将会立即开始。
但是,如果参数clearQueue被设置为true,那么队列面剩余的动画就被删除了,并且永远也不会执行。
如果参数jumpToEnd被设置为true,那么当前动画会停止,但是参与动画的每一个CSS属性将被立即设置为它们的目标值。比如:slideUp()方法,那么元素会立即隐藏掉。如果存在回调函数,那么回调函数也会立即执行。
注意:如果元素动画还没有执行完,此时调用stop()方法,那么动画将会停止。并且动画没有执行完成,那么回调函数也不会被执行。
## 举例:右下角的弹出广告
代码实现:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
.ad {
position: fixed;
right: 0;
bottom: 0;
width: 230px;
height: 120px;
background-image: url(images/ad.jpg);
display: none;
}
.ad span {
position: absolute;
right: 0;
top: 0;
width: 40px;
height: 18px;
background-image: url(images/h.jpg);
cursor: pointer;
}
</style>
<script src="jquery-1.11.1.js"></script>
<script>
$(function () {
//需求:然广告ad部分,先滑入,在滑出,在淡入。然后绑定事件,点击span弹出
//步骤:
$(".ad").slideDown(1000).slideUp(1000).fadeIn(1000).children("span").click(function () {
$(this).parent().fadeOut(1000);
});
//第二种写法
// $(".ad").slideDown(1000, function () {
// $(".ad").slideUp(1000, function () {
// $(".ad").fadeIn(1000, function () {
// $(".ad").children("span").click(function () {
// $(this).parent().fadeOut(1000, function () {
// alert("执行完毕!");
// });
// });
// });
// });
// })
})
</script>
</head>
<body>
<div class="ani">我是内容</div>
<div class="ad">
<span></span>
</div>
</body>
</html>
```
效果如下:

## 我的公众号
想学习<font color=#0000ff>**代码之外的技能**</font>?不妨关注我的微信公众号:**千古壹号**(id:`qianguyihao`)。
扫一扫,你将发现另一个全新的世界,而这将是一场美丽的意外:

|
ilao5/ilao5.github.io
|
customs/note/webstudy/_book/04-JavaScript基础/52-jQuery动画详解.md
|
Markdown
|
mit
| 15,204
|
// wb_t@CÌCN[h
#include <tchar.h> // TCHAR^
#include <stdio.h> // WüoÍ
#include <winsock2.h> // Windows\Pbg
#include <windows.h> // WWindowsAPI
// _tmainÖÌè`
int _tmain(int argc, TCHAR *argv[]){ // mainÖÌTCHARÅ.
// ÏÌé¾
WSADATA wsaData; // WinSockÌú»ÉKvÈWSADATA\¢ÌÏwsaData.
int iRet; // ú»ÌÊiRet.
int soc; // \Pbgt@CfBXNv^soc.
u_short ns_port; // |[gÔÌlbg[NoCgI\_l.
// WinSockÌú»
iRet = WSAStartup(MAKEWORD(2, 2), &wsaData); // WSAStartupÅWinSockÌú».
if (iRet){ // 0ÅÈ¢ê.
// G[.
_tprintf(_T("Error!(iRet = %d.)\n"), iRet); // ßèlðoÍ.
WSACleanup(); // WSACleanupÅI¹.
return -1; // -1ðÔµÄÙíI¹.
}
// ú»¬÷bZ[W.
_tprintf(_T("WSAStartup success!\n")); // "WSAStartup success!"ÆoÍ.
// \PbgÌì¬
soc = socket(AF_INET, SOCK_STREAM, 0); // socketÅ\Pbgì¬.
if (soc == -1){ // socª-1Èç.
// G[
_tprintf(_T("socket Error!\n")); // "socket Error!"ÆoÍ.
WSACleanup(); // WSACleanupÅI¹.
return -1; // -1ðÔµÄÙíI¹.
}
// socÌlðoÍ.
_tprintf(_T("soc = %d\n"), soc); // socÌlðoÍ.
// |[gÔÌÏ·.
ns_port = htons(4000); // htonsÅ|[gÔðlbg[NoCgI\_ÉÏ·.
// |[gÔÌoÍ.
_tprintf(_T("port = %04x, ns_port = %04x\n"), 4000, ns_port); // |[gÔÆlbg[NoCgI\_È|[gÔðoÍ.
// \Pbgt@CfBXNv^ð¶é.
closesocket(soc); // closesocketÅsocð¶é.
// WinSockÌI¹.
WSACleanup(); // WSACleanupÅI¹.
// vOÌI¹.
return 0;
}
|
bg1bgst333/Sample
|
winapi/htons/htons/src/htons/htons/htons.cpp
|
C++
|
mit
| 1,664
|
from flask import (Flask, session, render_template, request, redirect,
url_for, make_response, Blueprint, current_app)
import requests
import json
from datetime import datetime, timedelta
from flask.ext.cors import CORS, cross_origin
bp = Blueprint('audioTag', __name__)
def create_app(blueprint=bp):
app = Flask(__name__)
app.register_blueprint(blueprint)
app.config.from_pyfile('config.py')
CORS(app, allow_headers=('Content-Type', 'Authorization'))
return app
@bp.route('/', methods=['GET'])
@cross_origin()
def index():
# if auth_tok is in session already..
if 'auth_tok' in session:
auth_tok = session['auth_tok']
# check if it has expired
oauth_token_expires_in_endpoint = current_app.config.get(
'SWTSTORE_URL')+'/oauth/token-expires-in'
resp = requests.get(oauth_token_expires_in_endpoint)
expires_in = json.loads(resp.text)['expires_in']
# added for backwared compatibility. previous session stores did not
# have issued key
try:
check = datetime.utcnow() - auth_tok['issued']
if check > timedelta(seconds=expires_in):
# TODO: try to refresh the token before signing out the user
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
"""access token did not expire"""
pass
# if issued key is not there, reset the session
except KeyError:
auth_tok = {'access_token': '', 'refresh_token': ''}
else:
auth_tok = {'access_token': '', 'refresh_token': ''}
# print 'existing tokens'
# print auth_tok
# payload = {'what': 'img-anno',
# 'access_token': auth_tok['access_token']}
# req = requests.get(current_app.config.get(
# 'SWTSTORE_URL', 'SWTSTORE_URL') + '/api/sweets/q', params=payload)
# sweets = req.json()
return render_template('index.html', access_token=auth_tok['access_token'],
refresh_token=auth_tok['refresh_token'],
config=current_app.config,
url=request.args.get('where'))
@bp.route('/authenticate', methods=['GET'])
def authenticateWithOAuth():
auth_tok = None
code = request.args.get('code')
# prepare the payload
payload = {
'scopes': 'email context',
'client_secret': current_app.config.get('APP_SECRET'),
'code': code,
'redirect_uri': current_app.config.get('REDIRECT_URI'),
'grant_type': 'authorization_code',
'client_id': current_app.config.get('APP_ID')
}
# token exchange endpoint
oauth_token_x_endpoint = current_app.config.get(
'SWTSTORE_URL', 'SWTSTORE_URL') + '/oauth/token'
resp = requests.post(oauth_token_x_endpoint, data=payload)
auth_tok = json.loads(resp.text)
if 'error' in auth_tok:
return make_response(auth_tok['error'], 200)
# set sessions etc
session['auth_tok'] = auth_tok
session['auth_tok']['issued'] = datetime.utcnow()
return redirect(url_for('audioTag.index'))
@bp.route('/admin', methods=['GET', 'POST'])
def admin():
if request.method == 'POST':
phone = request.form.get('usertel')
print repr(phone)
return render_template('admin.html')
@bp.route('/upload', methods=['GET', 'POST'])
def upload():
return render_template('upload_url.html')
if __name__ == '__main__':
app = create_app()
app.run(debug=app.config.get('DEBUG'),
host=app.config.get('HOST'))
|
janastu/audio-tagger
|
servers/audioApp.py
|
Python
|
mit
| 3,589
|
/*
* grunt-pip
* https://github.com/davidshrader/grunt-pip
*
* Copyright (c) 2014 david.shrader
* Licensed under the MIT license.
*/
module.exports = function(grunt) {
'use strict';
//var exec = require('exec');
var exec = require('child_process').exec;
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
grunt.registerMultiTask('pip', 'Grunt plug-in to install Python packages via PIP.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
vritualenv: 'venv',
verbose: false
});
var args = []
args.push(options.vritualenv);
if (options.verbose) {
args.push('-v');
}
grunt.log.writeln(args);
var done = this.async();
grunt.util.spawn({
cmd: 'virtualenv',
args: args
}, function(error, result, code) {
grunt.log.writeln(result);
done(error);
});
// grunt.util.spawn({
// cmd: ['ls'],
// args: ['-l']
// }, function(error, result, code) {
// grunt.log.writeln('hey there');
// grunt.log.writeln(error);
// grunt.log.writeln(code);
// done();
// });
// check to see if virtualenv command is available
// if (options.vritualenv !== 'venv') {
// grunt.fatal('\'virtualenv\' command not found');
// }
// exec('ls', function (error, stdout, stderr) {
// grunt.log.writeln('hey there');
// console.log('stdout: ' + stdout);
// console.log('stderr: ' + stderr);
// if (error !== null) {
// console.log('exec error: ' + error);
// };
// });
// exec(['ls', '-l'], function(err, out, code) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// });
// var cmd = 'virtualenv ' + options.virtualenv + '\n';
// cmd += 'python benjamint.py';
// exec(cmd, function(err, stdout) {
// if (err instanceof Error)
// throw err;
// process.stderr.write(err);
// process.stdout.write(out);
// process.exit(code);
// // grunt.log.write(stdout);
// });
// var vritualenv = options.virtualenv;
// grunt.log.writeln(vritualenv);
// var verbose = options.verbose;
// grunt.log.writeln(verbose);
// var modules = options.modules;
// grunt.log.writeln(modules);
});
};
|
dshrader38/grunt-pip
|
tasks/pip.js
|
JavaScript
|
mit
| 2,524
|
import Data.Tree
import Data.Tree.Zipper
import Data.Maybe
import Test.QuickCheck
import System.Random
import Text.Show.Functions
instance Arbitrary a => Arbitrary (Tree a) where
arbitrary = sized arbTree
where
arbTree n = do lbl <- arbitrary
children <- resize (n-1) arbitrary
return (Node lbl children)
coarbitrary t =
coarbitrary (rootLabel t) .
variant (length (subForest t)) .
flip (foldr coarbitrary) (subForest t)
instance Arbitrary a => Arbitrary (TreeLoc a) where
arbitrary = do
tree <- resize 8 arbitrary
lefts <- resize 5 arbitrary
rights <- resize 5 arbitrary
parents <- resize 3 arbitrary
return (Loc tree lefts rights parents)
prop_LeftRight :: TreeLoc Int -> Property
prop_LeftRight loc = label "prop_LeftRight" $
case left loc of
Just lloc -> right lloc == Just loc
Nothing -> True
prop_LeftFirst :: TreeLoc Int -> Property
prop_LeftFirst loc = label "prop_LeftFirst" $
isFirst loc ==> left loc == Nothing
prop_RightLast :: TreeLoc Int -> Property
prop_RightLast loc = label "prop_RightLast" $
isLast loc ==> right loc == Nothing
prop_RootParent :: TreeLoc Int -> Property
prop_RootParent loc = label "prop_RootParent" $
isRoot loc ==> parent loc == Nothing
prop_FirstChild :: TreeLoc Int -> Property
prop_FirstChild loc = label "prop_FirstChild" $
case firstChild loc of
Just floc -> parent floc == Just loc && left floc == Nothing
Nothing -> isLeaf loc
prop_LastChild :: TreeLoc Int -> Property
prop_LastChild loc = label "prop_LastChild" $
case lastChild loc of
Just lloc -> parent lloc == Just loc && right lloc == Nothing
Nothing -> isLeaf loc
prop_FindChild :: TreeLoc Int -> Property
prop_FindChild loc = label "prop_FindChild" $
forAll arbitrary (\f -> maybe True (\sloc -> f (tree sloc) && parent sloc == Just loc) (findChild f loc))
prop_SetGetLabel :: TreeLoc Int -> Property
prop_SetGetLabel loc = label "prop_SetGetLabel" $
forAll arbitrary (\x -> getLabel (setLabel x loc) == x)
prop_ModifyLabel :: TreeLoc Int -> Property
prop_ModifyLabel loc = label "prop_ModifyLabel" $
forAll arbitrary (\f -> getLabel (modifyLabel f loc) == f (getLabel loc))
prop_UpDown :: TreeLoc Int -> Property
prop_UpDown loc = label "prop_UpDown" $
case parent loc of
Just ploc -> getChild (getNodeIndex loc) ploc == Just loc
Nothing -> True
prop_RootChild :: TreeLoc Int -> Property
prop_RootChild loc = label "prop_RootChild" $
isChild loc == not (isRoot loc)
prop_ChildrenLeaf :: TreeLoc Int -> Property
prop_ChildrenLeaf loc = label "prop_ChildrenLeaf" $
hasChildren loc == not (isLeaf loc)
prop_FromToTree :: TreeLoc Int -> Property
prop_FromToTree loc = label "prop_FromToTree" $
tree (fromTree (toTree loc)) == tree (root loc)
prop_FromToForest :: TreeLoc Int -> Property
prop_FromToForest loc = label "prop_FromToForest" $
isFirst (root loc) ==> fromForest (toForest loc) == Just (root loc)
prop_FromTree :: Tree Int -> Property
prop_FromTree tree = label "prop_FromTree" $
left (fromTree tree) == Nothing &&
right (fromTree tree) == Nothing &&
parent (fromTree tree) == Nothing
prop_FromForest :: Property
prop_FromForest = label "prop_FromForest" $
fromForest ([] :: Forest Int) == Nothing
prop_InsertLeft :: TreeLoc Int -> Property
prop_InsertLeft loc = label "prop_InsertLeft" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertLeft t loc) == t &&
rights (insertLeft t loc) == tree loc : rights loc
prop_InsertRight :: TreeLoc Int -> Property
prop_InsertRight loc = label "prop_InsertRight" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertRight t loc) == t &&
lefts (insertRight t loc) == tree loc : lefts loc
prop_InsertDownFirst :: TreeLoc Int -> Property
prop_InsertDownFirst loc = label "prop_InsertDownFirst" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertDownFirst t loc) == t &&
left (insertDownFirst t loc) == Nothing &&
fmap getLabel (parent (insertDownFirst t loc)) == Just (getLabel loc) &&
fmap tree (right (insertDownFirst t loc)) == fmap tree (firstChild loc)
prop_InsertDownLast :: TreeLoc Int -> Property
prop_InsertDownLast loc = label "prop_InsertDownLast" $
forAll (resize 10 arbitrary) $ \t ->
tree (insertDownLast t loc) == t &&
right (insertDownLast t loc) == Nothing &&
fmap getLabel (parent (insertDownLast t loc)) == Just (getLabel loc) &&
fmap tree (left (insertDownLast t loc)) == fmap tree (lastChild loc)
prop_InsertDownAt :: TreeLoc Int -> Property
prop_InsertDownAt loc = label "prop_InsertDownAt" $
forAll (resize 10 arbitrary) $ \t ->
forAll (resize 10 arbitrary) $ \n ->
maybe t tree (insertDownAt n t loc) == t &&
fmap lefts (getChild n loc) == fmap lefts (insertDownAt n t loc) &&
fmap tree (getChild n loc) == fmap tree (insertDownAt n t loc >>= right) &&
fmap rights (getChild n loc) == fmap rights (insertDownAt n t loc >>= right) &&
maybe (getLabel loc) getLabel (insertDownAt n t loc >>= parent) == getLabel loc
prop_Delete :: TreeLoc Int -> Property
prop_Delete loc = label "prop_Delete" $
if not (isLast loc)
then fmap (\loc -> tree loc : rights loc) (delete loc) == Just (rights loc) &&
fmap lefts (delete loc) == Just (lefts loc)
else if not (isFirst loc)
then fmap rights (delete loc) == Just (rights loc) &&
fmap (\loc -> tree loc : lefts loc) (delete loc) == Just (lefts loc)
else fmap (insertDownFirst (tree loc)) (delete loc) == Just loc
main = do
testProp prop_LeftRight
testProp prop_LeftFirst
testProp prop_RightLast
testProp prop_RootParent
testProp prop_FirstChild
testProp prop_LastChild
testProp prop_FindChild
testProp prop_SetGetLabel
testProp prop_ModifyLabel
testProp prop_UpDown
testProp prop_RootChild
testProp prop_ChildrenLeaf
testProp prop_FromToTree
testProp prop_FromToForest
testProp prop_FromTree
testProp prop_FromForest
testProp prop_InsertLeft
testProp prop_InsertRight
testProp prop_InsertDownFirst
testProp prop_InsertDownLast
testProp prop_InsertDownAt
testProp prop_Delete
testProp :: Testable a => a -> IO ()
testProp = check (defaultConfig{-configEvery = \n args -> ""-})
|
yav/haskell-zipper
|
test.hs
|
Haskell
|
mit
| 6,455
|
'use strict';
const writeFile = require('../index');
const chai = require('chai');
const expect = chai.expect;
const rimraf = require('rimraf');
const root = process.cwd();
const fs = require('fs');
const broccoli = require('broccoli');
let builder;
chai.Assertion.addMethod('sameStatAs', function(otherStat) {
this.assert(
this._obj.mode === otherStat.mode,
'expected mode ' + this._obj.mode + ' to be same as ' + otherStat.mode,
'expected mode ' + this._obj.mode + ' to not the same as ' + otherStat.mode
);
this.assert(
this._obj.size === otherStat.size,
'expected size ' + this._obj.size + ' to be same as ' + otherStat.size,
'expected size ' + this._obj.size + ' to not the same as ' + otherStat.size
);
this.assert(
this._obj.mtime.getTime() === otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to be same as ' + otherStat.mtime.getTime(),
'expected mtime ' + this._obj.mtime.getTime() + ' to not the same as ' + otherStat.mtime.getTime()
);
});
describe('broccoli-file-creator', function() {
afterEach(function() {
if (builder) {
builder.cleanup();
}
});
function read(path) {
return fs.readFileSync(path, 'UTF8');
}
it('creates the file specified', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/something.js')).to.eql(content);
});
});
it('creates the file specified in a non-existent directory', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/somewhere/something.js', content);
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/somewhere/something.js')).to.eql(content);
});
});
it('if the content is a function, that functions return value or fulfillment value is used', function() {
const CONTENT = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('the-file.txt', () => Promise.resolve(CONTENT));
builder = new broccoli.Builder(tree);
return builder.build().then(result => {
expect(read(result.directory + '/the-file.txt')).to.eql(CONTENT);
});
});
it('correctly caches', function() {
const content = 'ZOMG, ZOMG, HOLY MOLY!!!';
const tree = writeFile('/something.js', content);
builder = new broccoli.Builder(tree);
var stat;
return builder.build().then(result => {
stat = fs.lstatSync(result.directory + '/something.js');
return builder.build();
}).then(result => {
var newStat = fs.lstatSync(result.directory + '/something.js');
expect(newStat).to.be.sameStatAs(stat);
});
});
});
|
rwjblue/broccoli-file-creator
|
tests/index.js
|
JavaScript
|
mit
| 2,836
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Samples Pack (ogl-samples.g-truc.net)
///
/// Copyright (c) 2004 - 2014 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///////////////////////////////////////////////////////////////////////////////////
#include "test.hpp"
namespace
{
char const * VERT_SHADER_SOURCE_RENDER("gl-440/fbo-render.vert");
char const * FRAG_SHADER_SOURCE_RENDER("gl-440/fbo-render.frag");
char const * VERT_SHADER_SOURCE_SPLASH("gl-440/fbo-splash.vert");
char const * FRAG_SHADER_SOURCE_SPLASH("gl-440/fbo-splash.frag");
char const * TEXTURE_DIFFUSE("kueken1-bgr8.dds");
GLsizei const VertexCount(4);
GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v2fv2f);
glf::vertex_v2fv2f const VertexData[VertexCount] =
{
glf::vertex_v2fv2f(glm::vec2(-1.0f,-1.0f), glm::vec2(0.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 1.0f,-1.0f), glm::vec2(1.0f, 1.0f)),
glf::vertex_v2fv2f(glm::vec2( 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
glf::vertex_v2fv2f(glm::vec2(-1.0f, 1.0f), glm::vec2(0.0f, 0.0f))
};
GLsizei const ElementCount(6);
GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort);
GLushort const ElementData[ElementCount] =
{
0, 1, 2,
2, 3, 0
};
namespace texture
{
enum type
{
DIFFUSE,
COLORBUFFER,
MAX
};
}//namespace texture
namespace pipeline
{
enum type
{
RENDER,
SPLASH,
MAX
};
}//namespace pipeline
namespace buffer
{
enum type
{
VERTEX,
ELEMENT,
TRANSFORM,
MAX
};
}//namespace buffer
}//namespace
class gl_440_fbo_without_attachment : public test
{
public:
gl_440_fbo_without_attachment(int argc, char* argv[]) :
test(argc, argv, "gl-440-fbo-without-attachment", test::CORE, 4, 2),
FramebufferName(0),
Supersampling(2)
{}
private:
std::array<GLuint, pipeline::MAX> PipelineName;
std::array<GLuint, pipeline::MAX> ProgramName;
std::array<GLuint, texture::MAX> TextureName;
std::array<GLuint, pipeline::MAX> SamplerName;
std::array<GLuint, buffer::MAX> BufferName;
std::array<GLuint, pipeline::MAX> VertexArrayName;
GLuint FramebufferName;
GLuint const Supersampling;
bool initProgram()
{
bool Validated(true);
if(Validated)
{
compiler Compiler;
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE_RENDER, "--version 420 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE_RENDER, "--version 420 --profile core");
Validated = Validated && Compiler.check();
ProgramName[pipeline::RENDER] = glCreateProgram();
glProgramParameteri(ProgramName[pipeline::RENDER], GL_PROGRAM_SEPARABLE, GL_TRUE);
glAttachShader(ProgramName[pipeline::RENDER], VertShaderName);
glAttachShader(ProgramName[pipeline::RENDER], FragShaderName);
glLinkProgram(ProgramName[pipeline::RENDER]);
Validated = Validated && Compiler.checkProgram(ProgramName[pipeline::RENDER]);
}
if(Validated)
{
compiler Compiler;
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE_SPLASH, "--version 420 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE_SPLASH, "--version 420 --profile core");
Validated = Validated && Compiler.check();
ProgramName[pipeline::SPLASH] = glCreateProgram();
glProgramParameteri(ProgramName[pipeline::SPLASH], GL_PROGRAM_SEPARABLE, GL_TRUE);
glAttachShader(ProgramName[pipeline::SPLASH], VertShaderName);
glAttachShader(ProgramName[pipeline::SPLASH], FragShaderName);
glLinkProgram(ProgramName[pipeline::SPLASH]);
Validated = Validated && Compiler.checkProgram(ProgramName[pipeline::SPLASH]);
}
if(Validated)
{
glGenProgramPipelines(pipeline::MAX, &PipelineName[0]);
glUseProgramStages(PipelineName[pipeline::RENDER], GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT, ProgramName[pipeline::RENDER]);
glUseProgramStages(PipelineName[pipeline::SPLASH], GL_VERTEX_SHADER_BIT | GL_FRAGMENT_SHADER_BIT, ProgramName[pipeline::SPLASH]);
}
return Validated;
}
bool initSampler()
{
glGenSamplers(pipeline::MAX, &SamplerName[0]);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glSamplerParameterfv(SamplerName[pipeline::RENDER], GL_TEXTURE_BORDER_COLOR, &glm::vec4(0.0f)[0]);
glSamplerParameterf(SamplerName[pipeline::RENDER], GL_TEXTURE_MIN_LOD, -1000.f);
glSamplerParameterf(SamplerName[pipeline::RENDER], GL_TEXTURE_MAX_LOD, 1000.f);
glSamplerParameterf(SamplerName[pipeline::RENDER], GL_TEXTURE_LOD_BIAS, 0.0f);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_COMPARE_MODE, GL_NONE);
glSamplerParameteri(SamplerName[pipeline::RENDER], GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glSamplerParameterfv(SamplerName[pipeline::SPLASH], GL_TEXTURE_BORDER_COLOR, &glm::vec4(0.0f)[0]);
glSamplerParameterf(SamplerName[pipeline::SPLASH], GL_TEXTURE_MIN_LOD, -1000.f);
glSamplerParameterf(SamplerName[pipeline::SPLASH], GL_TEXTURE_MAX_LOD, 1000.f);
glSamplerParameterf(SamplerName[pipeline::SPLASH], GL_TEXTURE_LOD_BIAS, 0.0f);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_COMPARE_MODE, GL_NONE);
glSamplerParameteri(SamplerName[pipeline::SPLASH], GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);
return this->checkError("initSampler");
}
bool initBuffer()
{
bool Validated(true);
glGenBuffers(buffer::MAX, &BufferName[0]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementSize, ElementData, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, BufferName[buffer::VERTEX]);
glBufferData(GL_SHADER_STORAGE_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
GLint UniformBufferOffset(0);
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, &UniformBufferOffset);
GLint UniformBlockSize = glm::max(GLint(sizeof(glm::mat4)), UniformBufferOffset);
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]);
glBufferData(GL_UNIFORM_BUFFER, UniformBlockSize, nullptr, GL_DYNAMIC_DRAW);
glBindBuffer(GL_UNIFORM_BUFFER, 0);
return Validated;
}
bool initTexture()
{
bool Validated(true);
gli::texture2D Texture(gli::load_dds((getDataDirectory() + TEXTURE_DIFFUSE).c_str()));
assert(!Texture.empty());
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(texture::MAX, &TextureName[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(Texture.levels() - 1));
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
glTexStorage2D(GL_TEXTURE_2D, static_cast<GLint>(Texture.levels()), gli::internal_format(Texture.format()),
static_cast<GLsizei>(Texture.dimensions().x),
static_cast<GLsizei>(Texture.dimensions().y));
for(std::size_t Level = 0; Level < Texture.levels(); ++Level)
{
glTexSubImage2D(GL_TEXTURE_2D, GLint(Level),
0, 0,
static_cast<GLsizei>(Texture[Level].dimensions().x),
static_cast<GLsizei>(Texture[Level].dimensions().y),
GL_BGR, GL_UNSIGNED_BYTE,
Texture[Level].data());
}
glm::ivec2 WindowSize(this->getWindowSize());
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0);
glTexStorage2D(GL_TEXTURE_2D, static_cast<GLint>(1), GL_RGBA8,
static_cast<GLsizei>(WindowSize.x * this->Supersampling),
static_cast<GLsizei>(WindowSize.y * this->Supersampling));
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
return Validated;
}
bool initVertexArray()
{
bool Validated(true);
glGenVertexArrays(pipeline::MAX, &VertexArrayName[0]);
glBindVertexArray(VertexArrayName[pipeline::RENDER]);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
glBindVertexArray(0);
glBindVertexArray(VertexArrayName[pipeline::SPLASH]);
glBindVertexArray(0);
return Validated;
}
bool initFramebuffer()
{
bool Validated(true);
glm::ivec2 WindowSize(this->getWindowSize());
glGenFramebuffers(1, &FramebufferName);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_WIDTH, WindowSize.x * this->Supersampling);
glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_HEIGHT, WindowSize.y * this->Supersampling);
glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_LAYERS, 1);
glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_SAMPLES, 1);
glFramebufferParameteri(GL_FRAMEBUFFER, GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS, GL_TRUE);
if(!this->checkFramebuffer(FramebufferName))
return false;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
bool begin()
{
bool Validated(true);
Validated = Validated && this->checkExtension("GL_ARB_framebuffer_no_attachments");
Validated = Validated && this->checkExtension("GL_ARB_clear_texture");
Validated = Validated && this->checkExtension("GL_ARB_shader_storage_buffer_object");
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initVertexArray();
if(Validated)
Validated = initTexture();
if(Validated)
Validated = initSampler();
if(Validated)
Validated = initFramebuffer();
return Validated;
}
bool end()
{
glDeleteSamplers(pipeline::MAX, &SamplerName[0]);
glDeleteProgramPipelines(pipeline::MAX, &PipelineName[0]);
glDeleteProgram(ProgramName[pipeline::SPLASH]);
glDeleteProgram(ProgramName[pipeline::RENDER]);
glDeleteFramebuffers(1, &FramebufferName);
glDeleteTextures(texture::MAX, &TextureName[0]);
glDeleteVertexArrays(pipeline::MAX, &VertexArrayName[0]);
return true;
}
bool render()
{
glm::vec2 WindowSize(this->getWindowSize());
{
glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]);
glm::mat4* Pointer = (glm::mat4*)glMapBufferRange(
GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4),
GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);
glm::mat4 Projection = glm::perspectiveFov(glm::pi<float>() * 0.25f, WindowSize.x, WindowSize.y, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
*Pointer = Projection * this->view() * Model;
glUnmapBuffer(GL_UNIFORM_BUFFER);
}
// Render
glClearTexImage(TextureName[texture::COLORBUFFER], 0, GL_RGBA, GL_FLOAT, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);
glViewportIndexedf(0, 0, 0, WindowSize.x * this->Supersampling, WindowSize.y * this->Supersampling);
glBindFramebuffer(GL_FRAMEBUFFER, FramebufferName);
glBindSampler(0, this->SamplerName[pipeline::RENDER]);
glBindVertexArray(this->VertexArrayName[pipeline::RENDER]);
glBindProgramPipeline(PipelineName[pipeline::RENDER]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::DIFFUSE]);
glBindImageTexture(semantic::image::DIFFUSE, TextureName[texture::COLORBUFFER], 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA8);
glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantic::storage::VERTEX, BufferName[buffer::VERTEX]);
glDrawElementsInstancedBaseVertexBaseInstance(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, 0, 1, 0, 0);
// Splash
glViewportIndexedf(0, 0, 0, WindowSize.x, WindowSize.y);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindSampler(0, this->SamplerName[pipeline::SPLASH]);
glBindVertexArray(this->VertexArrayName[pipeline::SPLASH]);
glBindProgramPipeline(PipelineName[pipeline::SPLASH]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, TextureName[texture::COLORBUFFER]);
glDrawArraysInstancedBaseInstance(GL_TRIANGLES, 0, 3, 1, 0);
return true;
}
};
int main(int argc, char* argv[])
{
int Error(0);
gl_440_fbo_without_attachment Test(argc, argv);
Error += Test();
return Error;
}
|
spetz911/almaty3d
|
tests/gl-440-fbo-without-attachment.cpp
|
C++
|
mit
| 14,656
|
package redis.clients.util;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Sharded<R, S extends ShardInfo<R>> {
public static final int DEFAULT_WEIGHT = 1;
private TreeMap<Long, S> nodes;
private final Hashing algo;
private final Map<ShardInfo<R>, R> resources = new LinkedHashMap<ShardInfo<R>, R>();
/**
* The default pattern used for extracting a key tag. The pattern must have a group (between
* parenthesis), which delimits the tag to be hashed. A null pattern avoids applying the regular
* expression for each lookup, improving performance a little bit is key tags aren't being used.
*/
private Pattern tagPattern = null;
// the tag is anything between {}
public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern.compile("\\{(.+?)\\}");
public Sharded(List<S> shards) {
this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works
// with 64-bits not 128
}
public Sharded(List<S> shards, Hashing algo) {
this.algo = algo;
initialize(shards);
}
public Sharded(List<S> shards, Pattern tagPattern) {
this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good
// as we works with
// 64-bits not 128
}
public Sharded(List<S> shards, Hashing algo, Pattern tagPattern) {
this.algo = algo;
this.tagPattern = tagPattern;
initialize(shards);
}
private void initialize(List<S> shards) {
nodes = new TreeMap<Long, S>();
for (int i = 0; i != shards.size(); ++i) {
final S shardInfo = shards.get(i);
if (shardInfo.getName() == null) for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo);
}
else for (int n = 0; n < 160 * shardInfo.getWeight(); n++) {
nodes.put(this.algo.hash(shardInfo.getName() + "*" + n), shardInfo);
}
resources.put(shardInfo, shardInfo.createResource());
}
}
public R getShard(byte[] key) {
return resources.get(getShardInfo(key));
}
public R getShard(String key) {
return resources.get(getShardInfo(key));
}
public S getShardInfo(byte[] key) {
SortedMap<Long, S> tail = nodes.tailMap(algo.hash(key));
if (tail.isEmpty()) {
return nodes.get(nodes.firstKey());
}
return tail.get(tail.firstKey());
}
public S getShardInfo(String key) {
return getShardInfo(SafeEncoder.encode(getKeyTag(key)));
}
/**
* A key tag is a special pattern inside a key that, if preset, is the only part of the key hashed
* in order to select the server for this key.
* @see <a href="http://redis.io/topics/partitioning">partitioning</a>
* @param key
* @return The tag if it exists, or the original key
*/
public String getKeyTag(String key) {
if (tagPattern != null) {
Matcher m = tagPattern.matcher(key);
if (m.find()) return m.group(1);
}
return key;
}
public Collection<S> getAllShardInfo() {
return Collections.unmodifiableCollection(nodes.values());
}
public Collection<R> getAllShards() {
return Collections.unmodifiableCollection(resources.values());
}
}
|
yapei123/jedis
|
src/main/java/redis/clients/util/Sharded.java
|
Java
|
mit
| 3,350
|
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Entrar</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('login') }}">
{{ csrf_field() }}
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email" class="col-md-4 control-label">E-Mail</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required autofocus>
@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="password" class="col-md-4 control-label">Senha</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control" name="password" required>
@if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
@endif
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Lembrar-me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-4">
<button type="submit" class="btn btn-primary">
Entrar
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
Esqueci minha senha
</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
|
LaysCR/Sistema-de-Emprestimo-de-Livros
|
resources/views/auth/login.blade.php
|
PHP
|
mit
| 3,052
|
module W00tify
module ActionViewExtensions
# This module includes twitter-related support
#
# Example:
#
# link_to_email 'email'
#
module CommonHelper
# TODO: handle block
def link_to_email(item, *args, &block)
options = args.extract_options!
handle = item && case
when item.respond_to?(:mail)
item.mail
when item.respond_to?(:email)
item.email
when item.respond_to?(:to_s)
item.to_s
when item.is_a?(String)
item
end
return unless handle.present?
url = "mailto:#{handle}"
link_to handle, url, options
end
# give it user object or plain url to create link
# TODO: handle block
def link_to_website(item, *args, &block)
options = args.extract_options!
handle = item && case
when item.respond_to?(:website)
item.website
when item.respond_to?(:web)
item.web
when item.respond_to?(:url)
item.url
when item.respond_to?(:to_s)
item.to_s
when item.is_a?(String)
item
end
return unless handle.present?
url = (handle =~ /^http/i) ? handle : "http://#{handle}"
site_name = options.delete( :site_name ) || url.sub(/^http[s]?:\/\//,'')
link_to site_name, url, options
end
end
end
end
|
tardate/w00tify
|
lib/w00tify/common/common_helper.rb
|
Ruby
|
mit
| 1,419
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Clifton.WebSocketService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Clifton.WebSocketService")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("146cb16e-5232-42da-a182-ecfd8f5de260")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
cliftonm/clifton
|
Clifton.Web/Clifton.WebSocketService/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,442
|
<!DOCTYPE html>
<html lang="en" ng-app="app">
<head>
<meta charset="UTF-8" />
<title>Boilerplate</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link href="/favicon.ico" type="image/x-icon" rel="icon" />
<link href="/favicon.ico" type="image/x-icon" rel="shortcut icon" />
<link href="assets/css/libs.css" rel="stylesheet" />
<link href="assets/css/main.css" rel="stylesheet" />
<script src="assets/js/libs.js"></script>
<script src="assets/js/main.js"></script>
</head>
<body>
<div class="main">
<ng-include src="'app/views/elements/header.html'"></ng-include>
<ng-view></ng-view>
<ng-include src="app/views/elements/footer.html"></ng-include>
</div>
<ng-include src="'app/views/elements/loader.html'" ng-show="isLoading"></ng-include>
</body>
</html>
|
Mistermoz/Angular-Parse-Restangular
|
index.html
|
HTML
|
mit
| 889
|
/**
* 邮件通知
*/
const config = require('../config').email
const nodemailer = require('nodemailer')
let smtpTransport = null
module.exports = {
send(tip, title, message) {
if (!smtpTransport) {
smtpTransport = nodemailer.createTransport({
pool:true,
service:config.service,
auth:{
user:config.from,
pass:config.pass
}
})
}
console.log(`sending email to ${config.to}:${title} ${message}`)
if (config.filter.indexOf(tip.level) > -1) {
console.log('email filterd')
return
}
smtpTransport.sendMail({
from:config.from,
to:config.to,
subject:message,
html:title
}, (e, res) => e ? console.error('send email failed:' + e) : console.log('send email success.'))
}
}
|
JQKid/3aClient
|
resources/app/notify/email.js
|
JavaScript
|
mit
| 763
|
# NADA
Simple gem for interacting with NADA's web services. This gem is under active development
and is likely to change completely.
## Installation
Add this line to your application's Gemfile:
gem 'nada'
And then execute:
$ bundle
Or install it yourself as:
$ gem install nada
## Usage
TODO: Write usage instructions here
## Testing
To run the tests, you need to set the following environment variables
These can be set in a .env file at the root of the project
NADA_USERNAME=<Your username>
NADA_PASSWORD=<Your password>
Now you can run rake
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
|
elchingon/nada
|
README.md
|
Markdown
|
mit
| 810
|
/* header created automatically with -DGEN_TREES_H */
// * [# filter:thirdparty\zlib #]
local const ct_data static_ltree[L_CODES+2] = {
{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
};
local const ct_data static_dtree[D_CODES] = {
{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
};
const uch _dist_code[DIST_CODE_LEN] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
local const int base_length[LENGTH_CODES] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
local const int base_dist[D_CODES] = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
|
InfernoEngine/engine
|
dev/src/base/memory/src/thirdparty/zlib/trees.h
|
C
|
mit
| 8,478
|
// Creates a hot reloading development environment
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const DashboardPlugin = require('webpack-dashboard/plugin');
const config = require('./config/webpack.config.development');
const app = express();
const compiler = webpack(config);
// Apply CLI dashboard for your webpack dev server
compiler.apply(new DashboardPlugin());
const host = process.env.HOST || 'localhost';
const port = process.env.PORT || 3000;
function log() {
arguments[0] = '\nWebpack: ' + arguments[0];
console.log.apply(console, arguments);
}
app.use(webpackDevMiddleware(compiler, {
noInfo: true,
publicPath: "/",
stats: {
colors: true
},
historyApiFallback: true
}));
app.use(webpackHotMiddleware(compiler));
app.get('/css/*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'),{
headers:{
"Content-Type":"text/css"
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './src/app.html'));
});
app.listen(port, host, (err) => {
if (err) {
log(err);
return;
}
const exec = require('child_process').exec;
exec("cd src && electron main.dev.js", (err, stdout, stderr) => {
if (err) {
log(err);
return;
}
log("Electron Started");
});
log(' App is listening at http://%s:%s', host, port);
});
|
InvertedX/Dose-Host-Manager
|
dev-server.js
|
JavaScript
|
mit
| 1,535
|
<div class="jumbotron section-header" >
<div class="container" >
<h1>Services</h1>
<p> The SNHC provides two services: a basic care-focused clinic on Saturday mornings and a specialty-care clinic Wednesday evenings.</p>
</div>
</div>
<div ng-controller="DateListCtrl" class="container">
<h1>Upcoming Clinic Dates</h1>
<table class="table table-striped" >
<tr ng-repeat="event in data.items | limitTo:5 ">
<td> <strong>{{event.summary}}</strong> </td>
<td> {{ event.start.dateTime | date:"MMMM d, y h:mm" }} - {{event.end.dateTime | date: "h:mm a"}} </td>
</tr>
</table>
<p class="text-muted"/>For more dates, visit our <a href="https://www.google.com/calendar/embed?src=7eie7k06g255baksfshfhp0m28%40group.calendar.google.com&ctz=America/Chicago">Google Calendar</a>.</p>
<h1>Saturday Clinic Days</h1>
<p> The Saturday Neighborhood Health Clinic (SNHC) is a free clinic for the uninsured, run by medical students and staffed by physicians from Washington University School of Medicine in St. Louis, Missouri.
We provide basic services much like those you would find at a primary care provider's office: preventative care, treatment of acute or chronic medical conditions, women's health, physical exams, vaccinations, referrals, and prescription refills, among others.
We do not provide pediatric care, dental service, or referrals for dental care.
</p>
<p> Any adult patient seeking our services is welcome at our clinic.
However, SNHC is not currently equipped to function as a long-term medical home.
We strongly encourage our patients to set up routine appointments with primary care physicians after visiting the SHNC.
Please visit our resources page for help with finding medications and other local health centers.
</p>
<p> The SNHC is located in the Forest Park Southeast neighborhood in St. Louis, Missouri.
The clinic is held in the Family Health Care Center facility at 4352 Manchester Avenue on most Saturdays from 9:00AM to 12:00PM.
</p>
<p> We do not take appointments.
Patients are seen on a first come, first serve basis.
Due to the limited number of staff members we have at the clinic, we can only see the first 9 patients who come in each Saturday.
We encourage you to arrive as early as possible in order to ensure that you can be seen in a timely manner.
</p>
<h1>Wednesday Specialty Nights</h1>
<p> The Wednesday Specialty Nights provide free medical specialty services for uninsured patients.
Specialty services currently include a depression and anxiety clinc located at 620 S Taylor Avenue on the fourth Wednesday of the month.
The services offered vary by week, so please check our Google calendar for the most up to date information.
</p>
</div>
|
SaturdayNeighborhoodHealthClinic/snhc-web
|
app/partials/services.html
|
HTML
|
mit
| 2,786
|
/****************************************/
/* Level One - Concatenation Exercises */
/****************************************/
/*
Return a string that will add a "Hello" string in front of the name
ie:
sayHello("Jesse") => Hello Jesse
sayHello("Mat") => Hello Mat
*/
function sayHello(name) {
}
/*
Create a full name using the first and last parameters and store into a variable
Then return a string that will add a "Hello" string in front of the full name
ie:
sayHelloAdv("Jesse", "Wang") => Hello Jesse Wang
sayHelloAdv("Alex", "Pelan") => Hello Alex Pelan
*/
function sayHelloAdv(first, last) {
}
/*
Return a string that will display how many points a player made
ie:
playerStats("Steph Curry", 32") => Steph Curry made 32 points
playerStats("Meghan", 12) => Meghan made 12 points
*/
function playerStats(player, points) {
}
/*
Return a number that will be the total score in points made
ie:
calculateScore(1, 0) => 2
calculateScore(0, 1) => 3
calculateScore(8, 6) => 34
*/
function calculateScore(twoPointersMade, threePointersMade) {
}
/*
Calculates the totalScore a player has made
Then return a string that will display the total score a player made
ie:
playerStatsAdv("Steph Curry", 6, 7) => "Steph Curry made 33 points"
playerStatsAdv("Meghan", 4, 2) => "Meghan made 14 points"
*/
function playerStatsAdv(player, twoPointersMade, threePointersMade) {
}
|
jwang1919/jsExercises-April5-2016
|
level-one.js
|
JavaScript
|
mit
| 1,498
|
<?php
/**
* OUTRAGEbot - PHP 5.3 based IRC bot
*
* Author: Jannis Pohl <mave1337@gmail.com>
*
* Version: 2.0.0-Alpha
* Git commit: 0638fa8bb13e1aca64885a4be9e6b7d78aab0af7
* Committed at: Wed Aug 24 23:16:56 BST 2011
*
* Licence: http://www.typefish.co.uk/licences/
*/
class RSS extends Script
{
private
$aSubscriptions = array();
private static
$sBitlyLogin = '',
$sBitlyApiKey = '';
/**
* Called when the Script is loaded.
*/
public function onConstruct()
{
$ps3 = array('#ps3');
$this->addSubscription('ps3news', 'http://feeds.feedburner.com/ps3news/KXsI?format=xml', 60, $ps3);
$this->addSubscription('psx-scene', 'http://www.psx-scene.com/forums/external.php?type=RSS2&forumids=6', 60, $ps3);
$this->addSubscription('ps3-hacks', 'http://www.ps3-hacks.com/feed/', 60, $ps3);
}
/**
* Called when the Script is removed.
*/
public function onDestruct()
{
foreach ($this->aSubscriptions as $aSubscription)
{
$this->removeTimer($aSubscription['timerKey']);
}
}
private function secureMessage($sTarget, $sMessage)
{
$sMessage = str_replace(array("\r", "\n"), "", $sMessage);
return $this->Message($sTarget, $sMessage);
}
private static function cleanString($string)
{
// :(
return str_replace(array("“", "”"), '"', $string);
}
private static function shortenUrl($sURL)
{
$sShort = file_get_contents("http://api.bit.ly/v3/shorten?login=" . self::$sBitlyLogin . "&apiKey=" . self::$sBitlyApiKey . "&longUrl=" . urlencode($sURL) ."&format=txt");
return strlen($sShort) <= 7 || substr($sShort, 0, 7) != "http://" ? 'N/A' : $sShort;
}
private static function getRssFeed($sURL, $iNum = 5)
{
$aNews = array();
$sData = file_get_contents($sURL);
if (strpos($sData, "</item>") > 0)
{
preg_match_all("/<item.*>(.+)<\/item>/Uism", $sData, $aItems);
$iAtom = 0;
}
elseif (strpos($data, "</entry>") > 0)
{
preg_match_all("/<entry.*>(.+)<\/entry>/Uism", $sData, $aItems);
$iAtom = 1;
}
preg_match("/<?xml.*encoding=\"(.+)\".*?>/Uism", $sData, $aEncoding);
$sEncoding = $aEncoding[1];
$i = 0;
foreach ($aItems[1] as $sItem)
{
if ($i == $iNum)
{
break;
}
++$i;
preg_match("/<title.*>(.+)<\/title>/Uism", $sItem, $aTitle);
if ($iAtom == 0)
{
preg_match("/<link>(.+)<\/link>/Uism", $sItem, $aLink);
}
elseif ($iAtom == 1)
{
preg_match("/<link.*alternate.*text\/html.*href=[\"\'](.+)[\"\'].*\/>/Uism", $aItem, $aLink);
}
/*if ($atom == 0)
{
preg_match("/<description>(.*)<\/description>/Uism", $item, $description);
}
elseif ($atom == 1)
{
preg_match("/<summary.*>(.*)<\/summary>/Uism", $item, $description);
}*/
$aTitle = preg_replace('/<!\[CDATA\[(.+)\]\]>/Uism', '$1', $aTitle);
//$description = preg_replace('/<!\[CDATA\[(.+)\]\]>/Uism', '$1', $description);
$aLink = preg_replace('/<!\[CDATA\[(.+)\]\]>/Uism', '$1', $aLink);
$sTitle = html_entity_decode(self::cleanString($aTitle[1]), ENT_QUOTES, $sEncoding);
$sLink = html_entity_decode(self::cleanString($aLink[1]), ENT_QUOTES, $sEncoding);
$aNews[] = array($sTitle, $sLink);
}
return $aNews;
}
private static function getLatestNews($sURL)
{
$aNews = self::getRssFeed($sURL, 1);
return $aNews[0];
}
public function timerCallback($iTimer)
{
$aTimer =& $this->aSubscriptions[$iTimer];
$aLatestNews = self::getLatestNews($aTimer['url']);
if (($sHash = md5($aLatestNews[0])) != $aTimer['latestNewsHash'])
{
$aTimer['latestNewsHash'] = $sHash;
$sNews = $aLatestNews[0];
if (strlen($sNews) > 300)
{
$sNews = substr($sNews, 0, 300) . ' ' . Format::Colour . '14...' . Format::Colour;
}
$sMessage = Format::Colour . '14[' . Format::Colour . '15rss' . Format::Colour . '14] ' . Format::Colour . '10('
. Format::Colour . '11' . $aTimer['prefix'] . Format::Colour . '10)' . Format::Colour . ' '
. $sNews . ' ' . Format::Colour . '14::' . Format::Colour . ' ' . self::shortenUrl($aLatestNews[1]);
foreach ($aTimer['messageTargets'] as $sTarget)
{
$this->secureMessage($sTarget, $sMessage);
}
}
}
private function addSubscription($sPrefix, $sURL, $iInterval, $aMessageTargets)
{
$aLatestNews = self::getLatestNews($sURL);
$sLatestNewsHash = md5($aLatestNews[0]);
$iNewTimer = count($this->aSubscriptions);
$sTimerKey = $this->addTimer(array($this, 'timerCallback'), $iInterval, -1, array($iNewTimer));
$this->aSubscriptions[$iNewTimer] = array
(
"prefix" => $sPrefix,
"url" => $sURL,
"messageTargets" => $aMessageTargets,
"latestNewsHash" => $sLatestNewsHash,
"timerKey" => $sTimerKey
);
}
}
|
Zarthus/zcnr-bot
|
Scripts/RSS/Default.php
|
PHP
|
mit
| 5,266
|
/**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.test.framework.datafactory;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.ApiException;
import com.mozu.api.ApiContext;
import com.mozu.test.framework.core.TestFailException;
import com.mozu.api.resources.platform.adminuser.AdminUserResource;
/** <summary>
* Displays the user accounts and account details associated with a developer or Mozu tenant administrator. Email addresses uniquely identify admin user accounts.
* </summary>
*/
public class AdminUserFactory
{
public static com.mozu.api.contracts.tenant.TenantCollection getTenantScopesForUser(ApiContext apiContext, String userId, int expectedCode, int successCode) throws Exception
{
return getTenantScopesForUser(apiContext, userId, null, expectedCode, successCode );
}
public static com.mozu.api.contracts.tenant.TenantCollection getTenantScopesForUser(ApiContext apiContext, String userId, String responseFields, int expectedCode, int successCode) throws Exception
{
com.mozu.api.contracts.tenant.TenantCollection returnObj = new com.mozu.api.contracts.tenant.TenantCollection();
AdminUserResource resource = new AdminUserResource(apiContext);
try
{
returnObj = resource.getTenantScopesForUser( userId, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException(e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
else
return null;
}
if(expectedCode != successCode)
throw new TestFailException(successCode, Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
return returnObj;
}
public static com.mozu.api.contracts.core.User getUser(ApiContext apiContext, String userId, int expectedCode, int successCode) throws Exception
{
return getUser(apiContext, userId, null, expectedCode, successCode );
}
public static com.mozu.api.contracts.core.User getUser(ApiContext apiContext, String userId, String responseFields, int expectedCode, int successCode) throws Exception
{
com.mozu.api.contracts.core.User returnObj = new com.mozu.api.contracts.core.User();
AdminUserResource resource = new AdminUserResource(apiContext);
try
{
returnObj = resource.getUser( userId, responseFields);
}
catch (ApiException e)
{
if(e.getHttpStatusCode() != expectedCode)
throw new TestFailException(e.getHttpStatusCode(), Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
else
return null;
}
if(expectedCode != successCode)
throw new TestFailException(successCode, Thread.currentThread().getStackTrace()[2].getMethodName(), expectedCode, "");
return returnObj;
}
}
|
eileenzhuang1/mozu-java
|
mozu-java-test/src/main/java/com/mozu/test/framework/datafactory/AdminUserFactory.java
|
Java
|
mit
| 2,965
|
package fpinscala.localeffects
import fpinscala.monads._
import scala.collection.mutable
object Mutable {
def quicksort(xs: List[Int]): List[Int] =
if (xs.isEmpty) xs
else {
val arr = xs.toArray
def swap(x: Int, y: Int) = {
val tmp = arr(x)
arr(x) = arr(y)
arr(y) = tmp
}
def partition(l: Int, r: Int, pivot: Int) = {
val pivotVal = arr(pivot)
swap(pivot, r)
var j = l
for (i <- l until r) if (arr(i) < pivotVal) {
swap(i, j)
j += 1
}
swap(j, r)
j
}
def qs(l: Int, r: Int): Unit = if (l < r) {
val pi = partition(l, r, l + (r - l) / 2)
qs(l, pi - 1)
qs(pi + 1, r)
}
qs(0, arr.length - 1)
arr.toList
}
}
sealed trait ST[S, A] { self =>
protected def run(s: S): (A, S)
def map[B](f: A => B): ST[S, B] = new ST[S, B] {
def run(s: S) = {
val (a, s1) = self.run(s)
(f(a), s1)
}
}
def flatMap[B](f: A => ST[S, B]): ST[S, B] = new ST[S, B] {
def run(s: S) = {
val (a, s1) = self.run(s)
f(a).run(s1)
}
}
}
object ST {
def apply[S, A](a: => A) = {
lazy val memo = a
new ST[S, A] {
def run(s: S) = (memo, s)
}
}
def runST[A](st: RunnableST[A]): A =
st[Null].run(null)._1
}
sealed trait STRef[S, A] {
protected var cell: A
def read: ST[S, A] = ST(cell)
def write(a: => A): ST[S, Unit] = new ST[S, Unit] {
def run(s: S) = {
cell = a
((), s)
}
}
}
object STRef {
def apply[S, A](a: A): ST[S, STRef[S, A]] =
ST(new STRef[S, A] {
var cell = a
})
}
trait RunnableST[A] {
def apply[S]: ST[S, A]
}
// Scala requires an implicit Manifest for constructing arrays.
sealed abstract class STArray[S, A](implicit manifest: Manifest[A]) {
protected def value: Array[A]
def size: ST[S, Int] = ST(value.size)
// Write a value at the give index of the array
def write(i: Int, a: A): ST[S, Unit] = new ST[S, Unit] {
def run(s: S) = {
value(i) = a
((), s)
}
}
// Read the value at the given index of the array
def read(i: Int): ST[S, A] = ST(value(i))
// Turn the array into an immutable list
def freeze: ST[S, List[A]] = ST(value.toList)
// Exercise 1: Add a combinator on STArray to fill the array from a Map where each key in the map represents an index into the array,
// and the value under that key is written to the array at that index.
def fill(xs: Map[Int, A]): ST[S, Unit] =
xs.foldRight(ST[S, Unit](())) {
case ((i, a), st) =>
st.flatMap(_ => write(i, a))
}
def swap(i: Int, j: Int): ST[S, Unit] =
for {
x <- read(i)
y <- read(j)
_ <- write(i, y)
_ <- write(j, x)
} yield ()
}
object STArray {
// Construct an array of the given size filled with the value v
def apply[S, A: Manifest](sz: Int, v: A): ST[S, STArray[S, A]] =
ST(new STArray[S, A] {
lazy val value = Array.fill(sz)(v)
})
def fromList[S, A: Manifest](xs: List[A]): ST[S, STArray[S, A]] =
ST(new STArray[S, A] {
lazy val value = xs.toArray
})
}
object Immutable {
def noop[S] = ST[S, Unit](())
// Exercise 2: Write the purely functional versions of partition and qs
def partition[S](a: STArray[S, Int], l: Int, r: Int, pivot: Int): ST[S, Int] =
for {
pivotVal <- a.read(pivot)
_ <- a.swap(pivot, r)
j <- STRef(l)
_ <- (l until r).foldLeft(noop[S]) { (st, i) =>
for {
_ <- st
iVal <- a.read(i)
_ <- if (iVal < pivotVal) swapAndAdvance(a, i, j) else noop[S]
} yield ()
}
jVal <- j.read
_ <- a.swap(jVal, r)
} yield jVal
def qs[S](a: STArray[S, Int], l: Int, r: Int): ST[S, Unit] =
if (l < r)
for {
i <- partition(a, l, r, l + (r - l) / 2)
_ <- qs(a, l, i - 1)
_ <- qs(a, i + 1, r)
} yield ()
else
noop[S]
private def swapAndAdvance[S](
a: STArray[S, Int],
i: Int,
j: STRef[S, Int]): ST[S, Unit] =
for {
jVal <- j.read
_ <- a.swap(i, jVal)
_ <- j.write(jVal + 1)
} yield ()
def quicksort(xs: List[Int]): List[Int] =
if (xs.isEmpty) xs
else
ST.runST(new RunnableST[List[Int]] {
def apply[S] =
for {
arr <- STArray.fromList(xs)
size <- arr.size
_ <- qs(arr, 0, size - 1)
sorted <- arr.freeze
} yield sorted
})
}
import scala.collection.mutable.HashMap
// Exercise 3: Come up with a minimal set of primitive combinators for creating and manipulating hash maps.
sealed trait STHashMap[S, K, V] {
protected val value: mutable.HashMap[K, V]
def size: ST[S, Int] = ST(value.size)
def get(key: K): ST[S, Option[V]] = ST(value.get(key))
def append(entry: (K, V)): ST[S, Unit] = ST(value += entry)
def +=(entry: (K, V)): ST[S, Unit] = append(entry)
def remove(key: K): ST[S, Unit] = ST(value -= key)
def -=(key: K): ST[S, Unit] = remove(key)
def freeze: ST[S, List[(K, V)]] = ST(value.toList)
def isDefinedAt(key: K): ST[S, Boolean] = ST(value.isDefinedAt(key))
}
object STHashMap {
def fromList[S, K, V](seed: List[(K, V)]): ST[S, STHashMap[S, K, V]] = ST {
new STHashMap[S, K, V] {
override protected val value: mutable.HashMap[K, V] =
mutable.HashMap(seed: _*)
}
}
}
|
goboss/fpinscala
|
exercises/src/main/scala/fpinscala/localeffects/LocalEffects.scala
|
Scala
|
mit
| 5,415
|
var net = require('net');
var client = net.connect(4444, '192.168.99.100');
client.setEncoding('utf8');
setInterval(function() {
console.log("sending...")
var msg = Math.floor(Math.random()*10000);
client.write('send mytopic 123 bajs'+msg+'\n');
}, 250)
client.on('data', function(data) {
console.log('data was', data)
})
|
mpj/boiler-bay
|
client-produce.js
|
JavaScript
|
mit
| 333
|
#include "clean_type.hpp"
#include <type_traits>
namespace {
typedef int const& T1;
typedef int T2;
static_assert(!std::is_same<T1, T2>::value, "Should be the same");
};
|
mirandaconrado/compile-utils
|
src/clean_type.cpp
|
C++
|
mit
| 178
|
<?php
$this->db->select('username, email');
$this->db->from('user');
$this->db->where('username', 'test');
$query = $this->db->get();
foreach ($query->result() as $row)
{
echo $row->username;
echo '<br />';
echo $row->email;
echo '<br />';
}
echo '<hr />';
var_dump(session_destroy());
|
mikkt/spinat
|
application/views/pages/test.php
|
PHP
|
mit
| 312
|
/*
*********************************************************************************************************
* uC/CPU
* CPU CONFIGURATION & PORT LAYER
*
* (c) Copyright 2004-2011; Micrium, Inc.; Weston, FL
*
* All rights reserved. Protected by international copyright laws.
*
* uC/CPU is provided in source form to registered licensees ONLY. It is
* illegal to distribute this source code to any third party unless you receive
* written permission by an authorized Micrium representative. Knowledge of
* the source code may NOT be used to develop a similar product.
*
* Please help us continue to provide the Embedded community with the finest
* software available. Your honesty is greatly appreciated.
*
* You can contact us at www.micrium.com.
*********************************************************************************************************
*/
/*
*********************************************************************************************************
*
* CPU PORT FILE
*
* ARM-Cortex-M4
* GNU C Compiler
*
* Filename : cpu.h
* Version : V1.29.01.00
* Programmer(s) : JJL
* BAN
*********************************************************************************************************
*/
/*
*********************************************************************************************************
* MODULE
*
* Note(s) : (1) This CPU header file is protected from multiple pre-processor inclusion through use of
* the CPU module present pre-processor macro definition.
*********************************************************************************************************
*/
#ifndef CPU_MODULE_PRESENT /* See Note #1. */
#define CPU_MODULE_PRESENT
/*
*********************************************************************************************************
* CPU INCLUDE FILES
*
* Note(s) : (1) The following CPU files are located in the following directories :
*
* (a) \<Your Product Application>\cpu_cfg.h
*
* (b) (1) \<CPU-Compiler Directory>\cpu_def.h
* (2) \<CPU-Compiler Directory>\<cpu>\<compiler>\cpu*.*
*
* where
* <Your Product Application> directory path for Your Product's Application
* <CPU-Compiler Directory> directory path for common CPU-compiler software
* <cpu> directory name for specific CPU
* <compiler> directory name for specific compiler
*
* (2) Compiler MUST be configured to include as additional include path directories :
*
* (a) '\<Your Product Application>\' directory See Note #1a
*
* (b) (1) '\<CPU-Compiler Directory>\' directory See Note #1b1
* (2) '\<CPU-Compiler Directory>\<cpu>\<compiler>\' directory See Note #1b2
*
* (3) Since NO custom library modules are included, 'cpu.h' may ONLY use configurations from
* CPU configuration file 'cpu_cfg.h' that do NOT reference any custom library definitions.
*
* In other words, 'cpu.h' may use 'cpu_cfg.h' configurations that are #define'd to numeric
* constants or to NULL (i.e. NULL-valued #define's); but may NOT use configurations to
* custom library #define's (e.g. DEF_DISABLED or DEF_ENABLED).
*********************************************************************************************************
*/
#include <cpu_def.h>
#include <cpu_cfg.h> /* See Note #3. */
/*$PAGE*/
/*
*********************************************************************************************************
* CONFIGURE STANDARD DATA TYPES
*
* Note(s) : (1) Configure standard data types according to CPU-/compiler-specifications.
*
* (2) (a) (1) 'CPU_FNCT_VOID' data type defined to replace the commonly-used function pointer
* data type of a pointer to a function which returns void & has no arguments.
*
* (2) Example function pointer usage :
*
* CPU_FNCT_VOID FnctName;
*
* FnctName();
*
* (b) (1) 'CPU_FNCT_PTR' data type defined to replace the commonly-used function pointer
* data type of a pointer to a function which returns void & has a single void
* pointer argument.
*
* (2) Example function pointer usage :
*
* CPU_FNCT_PTR FnctName;
* void *p_obj
*
* FnctName(p_obj);
*********************************************************************************************************
*/
typedef void CPU_VOID;
typedef char CPU_CHAR; /* 8-bit character */
typedef unsigned char CPU_BOOLEAN; /* 8-bit boolean or logical */
typedef unsigned char CPU_INT08U; /* 8-bit unsigned integer */
typedef signed char CPU_INT08S; /* 8-bit signed integer */
typedef unsigned short CPU_INT16U; /* 16-bit unsigned integer */
typedef signed short CPU_INT16S; /* 16-bit signed integer */
typedef unsigned int CPU_INT32U; /* 32-bit unsigned integer */
typedef signed int CPU_INT32S; /* 32-bit signed integer */
typedef unsigned long long CPU_INT64U; /* 64-bit unsigned integer */
typedef signed long long CPU_INT64S; /* 64-bit signed integer */
typedef float CPU_FP32; /* 32-bit floating point */
typedef double CPU_FP64; /* 64-bit floating point */
typedef volatile CPU_INT08U CPU_REG08; /* 8-bit register */
typedef volatile CPU_INT16U CPU_REG16; /* 16-bit register */
typedef volatile CPU_INT32U CPU_REG32; /* 32-bit register */
typedef volatile CPU_INT64U CPU_REG64; /* 64-bit register */
typedef void (*CPU_FNCT_VOID)(void); /* See Note #2a. */
typedef void (*CPU_FNCT_PTR )(void *p_obj); /* See Note #2b. */
/*$PAGE*/
/*
*********************************************************************************************************
* CPU WORD CONFIGURATION
*
* Note(s) : (1) Configure CPU_CFG_ADDR_SIZE, CPU_CFG_DATA_SIZE, & CPU_CFG_DATA_SIZE_MAX with CPU's &/or
* compiler's word sizes :
*
* CPU_WORD_SIZE_08 8-bit word size
* CPU_WORD_SIZE_16 16-bit word size
* CPU_WORD_SIZE_32 32-bit word size
* CPU_WORD_SIZE_64 64-bit word size
*
* (2) Configure CPU_CFG_ENDIAN_TYPE with CPU's data-word-memory order :
*
* (a) CPU_ENDIAN_TYPE_BIG Big- endian word order (CPU words' most significant
* octet @ lowest memory address)
* (b) CPU_ENDIAN_TYPE_LITTLE Little-endian word order (CPU words' least significant
* octet @ lowest memory address)
*********************************************************************************************************
*/
/* Define CPU word sizes (see Note #1) : */
#define CPU_CFG_ADDR_SIZE CPU_WORD_SIZE_32 /* Defines CPU address word size (in octets). */
#define CPU_CFG_DATA_SIZE CPU_WORD_SIZE_32 /* Defines CPU data word size (in octets). */
#define CPU_CFG_DATA_SIZE_MAX CPU_WORD_SIZE_64 /* Defines CPU maximum word size (in octets). */
#define CPU_CFG_ENDIAN_TYPE CPU_ENDIAN_TYPE_LITTLE /* Defines CPU data word-memory order (see Note #2). */
/*
*********************************************************************************************************
* CONFIGURE CPU ADDRESS & DATA TYPES
*********************************************************************************************************
*/
/* CPU address type based on address bus size. */
#if (CPU_CFG_ADDR_SIZE == CPU_WORD_SIZE_32)
typedef CPU_INT32U CPU_ADDR;
#elif (CPU_CFG_ADDR_SIZE == CPU_WORD_SIZE_16)
typedef CPU_INT16U CPU_ADDR;
#else
typedef CPU_INT08U CPU_ADDR;
#endif
/* CPU data type based on data bus size. */
#if (CPU_CFG_DATA_SIZE == CPU_WORD_SIZE_32)
typedef CPU_INT32U CPU_DATA;
#elif (CPU_CFG_DATA_SIZE == CPU_WORD_SIZE_16)
typedef CPU_INT16U CPU_DATA;
#else
typedef CPU_INT08U CPU_DATA;
#endif
typedef CPU_DATA CPU_ALIGN; /* Defines CPU data-word-alignment size. */
typedef CPU_ADDR CPU_SIZE_T; /* Defines CPU standard 'size_t' size. */
/*
*********************************************************************************************************
* CPU STACK CONFIGURATION
*
* Note(s) : (1) Configure CPU_CFG_STK_GROWTH in 'cpu.h' with CPU's stack growth order :
*
* (a) CPU_STK_GROWTH_LO_TO_HI CPU stack pointer increments to the next higher stack
* memory address after data is pushed onto the stack
* (b) CPU_STK_GROWTH_HI_TO_LO CPU stack pointer decrements to the next lower stack
* memory address after data is pushed onto the stack
*********************************************************************************************************
*/
#define CPU_CFG_STK_GROWTH CPU_STK_GROWTH_HI_TO_LO /* Defines CPU stack growth order (see Note #1). */
typedef CPU_INT32U CPU_STK; /* Defines CPU stack word size (in octets). */
typedef CPU_ADDR CPU_STK_SIZE; /* Defines CPU stack size (in number of CPU_STKs). */
/*$PAGE*/
/*
*********************************************************************************************************
* CRITICAL SECTION CONFIGURATION
*
* Note(s) : (1) Configure CPU_CFG_CRITICAL_METHOD with CPU's/compiler's critical section method :
*
* Enter/Exit critical sections by ...
*
* CPU_CRITICAL_METHOD_INT_DIS_EN Disable/Enable interrupts
* CPU_CRITICAL_METHOD_STATUS_STK Push/Pop interrupt status onto stack
* CPU_CRITICAL_METHOD_STATUS_LOCAL Save/Restore interrupt status to local variable
*
* (a) CPU_CRITICAL_METHOD_INT_DIS_EN is NOT a preferred method since it does NOT support
* multiple levels of interrupts. However, with some CPUs/compilers, this is the only
* available method.
*
* (b) CPU_CRITICAL_METHOD_STATUS_STK is one preferred method since it supports multiple
* levels of interrupts. However, this method assumes that the compiler provides C-level
* &/or assembly-level functionality for the following :
*
* ENTER CRITICAL SECTION :
* (1) Push/save interrupt status onto a local stack
* (2) Disable interrupts
*
* EXIT CRITICAL SECTION :
* (3) Pop/restore interrupt status from a local stack
*
* (c) CPU_CRITICAL_METHOD_STATUS_LOCAL is one preferred method since it supports multiple
* levels of interrupts. However, this method assumes that the compiler provides C-level
* &/or assembly-level functionality for the following :
*
* ENTER CRITICAL SECTION :
* (1) Save interrupt status into a local variable
* (2) Disable interrupts
*
* EXIT CRITICAL SECTION :
* (3) Restore interrupt status from a local variable
*
* (2) Critical section macro's most likely require inline assembly. If the compiler does NOT
* allow inline assembly in C source files, critical section macro's MUST call an assembly
* subroutine defined in a 'cpu_a.asm' file located in the following software directory :
*
* \<CPU-Compiler Directory>\<cpu>\<compiler>\
*
* where
* <CPU-Compiler Directory> directory path for common CPU-compiler software
* <cpu> directory name for specific CPU
* <compiler> directory name for specific compiler
*
* (3) (a) To save/restore interrupt status, a local variable 'cpu_sr' of type 'CPU_SR' MAY need
* to be declared (e.g. if 'CPU_CRITICAL_METHOD_STATUS_LOCAL' method is configured).
*
* (1) 'cpu_sr' local variable SHOULD be declared via the CPU_SR_ALLOC() macro which, if
* used, MUST be declared following ALL other local variables.
*
* Example :
*
* void Fnct (void)
* {
* CPU_INT08U val_08;
* CPU_INT16U val_16;
* CPU_INT32U val_32;
* CPU_SR_ALLOC(); MUST be declared after ALL other local variables
* :
* :
* }
*
* (b) Configure 'CPU_SR' data type with the appropriate-sized CPU data type large enough to
* completely store the CPU's/compiler's status word.
*********************************************************************************************************
*/
/*$PAGE*/
/* Configure CPU critical method (see Note #1) : */
#define CPU_CFG_CRITICAL_METHOD CPU_CRITICAL_METHOD_STATUS_LOCAL
typedef CPU_INT32U CPU_SR; /* Defines CPU status register size (see Note #3b). */
/* Allocates CPU status register word (see Note #3a). */
#if (CPU_CFG_CRITICAL_METHOD == CPU_CRITICAL_METHOD_STATUS_LOCAL)
#define CPU_SR_ALLOC() CPU_SR cpu_sr = (CPU_SR)0
#else
#define CPU_SR_ALLOC()
#endif
#define CPU_INT_DIS() do { cpu_sr = CPU_SR_Save(); } while (0) /* Save CPU status word & disable interrupts.*/
#define CPU_INT_EN() do { CPU_SR_Restore(cpu_sr); } while (0) /* Restore CPU status word. */
#ifdef CPU_CFG_INT_DIS_MEAS_EN
/* Disable interrupts, ... */
/* & start interrupts disabled time measurement.*/
#define CPU_CRITICAL_ENTER() do { CPU_INT_DIS(); \
CPU_IntDisMeasStart(); } while (0)
/* Stop & measure interrupts disabled time, */
/* ... & re-enable interrupts. */
#define CPU_CRITICAL_EXIT() do { CPU_IntDisMeasStop(); \
CPU_INT_EN(); } while (0)
#else
#define CPU_CRITICAL_ENTER() do { CPU_INT_DIS(); } while (0) /* Disable interrupts. */
#define CPU_CRITICAL_EXIT() do { CPU_INT_EN(); } while (0) /* Re-enable interrupts. */
#endif
/*$PAGE*/
/*
*********************************************************************************************************
* CPU COUNT ZEROS CONFIGURATION
*
* Note(s) : (1) (a) Configure CPU_CFG_LEAD_ZEROS_ASM_PRESENT to define count leading zeros bits
* function(s) in :
*
* (1) 'cpu_a.asm', if CPU_CFG_LEAD_ZEROS_ASM_PRESENT #define'd in 'cpu.h'/
* 'cpu_cfg.h' to enable assembly-optimized function(s)
*
* (2) 'cpu_core.c', if CPU_CFG_LEAD_ZEROS_ASM_PRESENT NOT #define'd in 'cpu.h'/
* 'cpu_cfg.h' to enable C-source-optimized function(s) otherwise
*
* (b) Configure CPU_CFG_TRAIL_ZEROS_ASM_PRESENT to define count trailing zeros bits
* function(s) in :
*
* (1) 'cpu_a.asm', if CPU_CFG_TRAIL_ZEROS_ASM_PRESENT #define'd in 'cpu.h'/
* 'cpu_cfg.h' to enable assembly-optimized function(s)
*
* (2) 'cpu_core.c', if CPU_CFG_TRAIL_ZEROS_ASM_PRESENT NOT #define'd in 'cpu.h'/
* 'cpu_cfg.h' to enable C-source-optimized function(s) otherwise
*********************************************************************************************************
*/
/* Configure CPU count leading zeros bits ... */
#define CPU_CFG_LEAD_ZEROS_ASM_PRESENT /* ... assembly-version (see Note #1a). */
/* Configure CPU count trailing zeros bits ... */
#define CPU_CFG_TRAIL_ZEROS_ASM_PRESENT /* ... assembly-version (see Note #1b). */
/*$PAGE*/
/*
*********************************************************************************************************
* FUNCTION PROTOTYPES
*********************************************************************************************************
*/
void CPU_IntDis (void);
void CPU_IntEn (void);
void CPU_IntSrcDis (CPU_INT08U pos);
void CPU_IntSrcEn (CPU_INT08U pos);
void CPU_IntSrcPendClr(CPU_INT08U pos);
CPU_INT16S CPU_IntSrcPrioGet(CPU_INT08U pos);
void CPU_IntSrcPrioSet(CPU_INT08U pos,
CPU_INT08U prio);
CPU_SR CPU_SR_Save (void);
void CPU_SR_Restore (CPU_SR cpu_sr);
void CPU_WaitForInt (void);
void CPU_WaitForExcept(void);
CPU_DATA CPU_RevBits (CPU_DATA val);
void CPU_BitBandClr (CPU_ADDR addr,
CPU_INT08U bit_nbr);
void CPU_BitBandSet (CPU_ADDR addr,
CPU_INT08U bit_nbr);
/*$PAGE*/
/*
*********************************************************************************************************
* INTERRUPT SOURCES
*********************************************************************************************************
*/
#define CPU_INT_STK_PTR 0u
#define CPU_INT_RESET 1u
#define CPU_INT_NMI 2u
#define CPU_INT_HFAULT 3u
#define CPU_INT_MEM 4u
#define CPU_INT_BUSFAULT 5u
#define CPU_INT_USAGEFAULT 6u
#define CPU_INT_RSVD_07 7u
#define CPU_INT_RSVD_08 8u
#define CPU_INT_RSVD_09 9u
#define CPU_INT_RSVD_10 10u
#define CPU_INT_SVCALL 11u
#define CPU_INT_DBGMON 12u
#define CPU_INT_RSVD_13 13u
#define CPU_INT_PENDSV 14u
#define CPU_INT_SYSTICK 15u
#define CPU_INT_EXT0 16u
/*
*********************************************************************************************************
* CPU REGISTERS
*********************************************************************************************************
*/
#define CPU_REG_NVIC_NVIC (*((CPU_REG32 *)(0xE000E004))) /* Int Ctrl'er Type Reg. */
#define CPU_REG_NVIC_ST_CTRL (*((CPU_REG32 *)(0xE000E010))) /* SysTick Ctrl & Status Reg. */
#define CPU_REG_NVIC_ST_RELOAD (*((CPU_REG32 *)(0xE000E014))) /* SysTick Reload Value Reg. */
#define CPU_REG_NVIC_ST_CURRENT (*((CPU_REG32 *)(0xE000E018))) /* SysTick Current Value Reg. */
#define CPU_REG_NVIC_ST_CAL (*((CPU_REG32 *)(0xE000E01C))) /* SysTick Calibration Value Reg. */
#define CPU_REG_NVIC_SETEN(n) (*((CPU_REG32 *)(0xE000E100 + (n) * 4u))) /* IRQ Set En Reg. */
#define CPU_REG_NVIC_CLREN(n) (*((CPU_REG32 *)(0xE000E180 + (n) * 4u))) /* IRQ Clr En Reg. */
#define CPU_REG_NVIC_SETPEND(n) (*((CPU_REG32 *)(0xE000E200 + (n) * 4u))) /* IRQ Set Pending Reg. */
#define CPU_REG_NVIC_CLRPEND(n) (*((CPU_REG32 *)(0xE000E280 + (n) * 4u))) /* IRQ Clr Pending Reg. */
#define CPU_REG_NVIC_ACTIVE(n) (*((CPU_REG32 *)(0xE000E300 + (n) * 4u))) /* IRQ Active Reg. */
#define CPU_REG_NVIC_PRIO(n) (*((CPU_REG32 *)(0xE000E400 + (n) * 4u))) /* IRQ Prio Reg. */
#define CPU_REG_NVIC_CPUID (*((CPU_REG32 *)(0xE000ED00))) /* CPUID Base Reg. */
#define CPU_REG_NVIC_ICSR (*((CPU_REG32 *)(0xE000ED04))) /* Int Ctrl State Reg. */
#define CPU_REG_NVIC_VTOR (*((CPU_REG32 *)(0xE000ED08))) /* Vect Tbl Offset Reg. */
#define CPU_REG_NVIC_AIRCR (*((CPU_REG32 *)(0xE000ED0C))) /* App Int/Reset Ctrl Reg. */
#define CPU_REG_NVIC_SCR (*((CPU_REG32 *)(0xE000ED10))) /* System Ctrl Reg. */
#define CPU_REG_NVIC_CCR (*((CPU_REG32 *)(0xE000ED14))) /* Cfg Ctrl Reg. */
#define CPU_REG_NVIC_SHPRI1 (*((CPU_REG32 *)(0xE000ED18))) /* System Handlers 4 to 7 Prio. */
#define CPU_REG_NVIC_SHPRI2 (*((CPU_REG32 *)(0xE000ED1C))) /* System Handlers 8 to 11 Prio. */
#define CPU_REG_NVIC_SHPRI3 (*((CPU_REG32 *)(0xE000ED20))) /* System Handlers 12 to 15 Prio. */
#define CPU_REG_NVIC_SHCSR (*((CPU_REG32 *)(0xE000ED24))) /* System Handler Ctrl & State Reg. */
#define CPU_REG_NVIC_CFSR (*((CPU_REG32 *)(0xE000ED28))) /* Configurable Fault Status Reg. */
#define CPU_REG_NVIC_HFSR (*((CPU_REG32 *)(0xE000ED2C))) /* Hard Fault Status Reg. */
#define CPU_REG_NVIC_DFSR (*((CPU_REG32 *)(0xE000ED30))) /* Debug Fault Status Reg. */
#define CPU_REG_NVIC_MMFAR (*((CPU_REG32 *)(0xE000ED34))) /* Mem Manage Addr Reg. */
#define CPU_REG_NVIC_BFAR (*((CPU_REG32 *)(0xE000ED38))) /* Bus Fault Addr Reg. */
#define CPU_REG_NVIC_AFSR (*((CPU_REG32 *)(0xE000ED3C))) /* Aux Fault Status Reg. */
#define CPU_REG_NVIC_PFR0 (*((CPU_REG32 *)(0xE000ED40))) /* Processor Feature Reg 0. */
#define CPU_REG_NVIC_PFR1 (*((CPU_REG32 *)(0xE000ED44))) /* Processor Feature Reg 1. */
#define CPU_REG_NVIC_DFR0 (*((CPU_REG32 *)(0xE000ED48))) /* Debug Feature Reg 0. */
#define CPU_REG_NVIC_AFR0 (*((CPU_REG32 *)(0xE000ED4C))) /* Aux Feature Reg 0. */
#define CPU_REG_NVIC_MMFR0 (*((CPU_REG32 *)(0xE000ED50))) /* Memory Model Feature Reg 0. */
#define CPU_REG_NVIC_MMFR1 (*((CPU_REG32 *)(0xE000ED54))) /* Memory Model Feature Reg 1. */
#define CPU_REG_NVIC_MMFR2 (*((CPU_REG32 *)(0xE000ED58))) /* Memory Model Feature Reg 2. */
#define CPU_REG_NVIC_MMFR3 (*((CPU_REG32 *)(0xE000ED5C))) /* Memory Model Feature Reg 3. */
#define CPU_REG_NVIC_ISAFR0 (*((CPU_REG32 *)(0xE000ED60))) /* ISA Feature Reg 0. */
#define CPU_REG_NVIC_ISAFR1 (*((CPU_REG32 *)(0xE000ED64))) /* ISA Feature Reg 1. */
#define CPU_REG_NVIC_ISAFR2 (*((CPU_REG32 *)(0xE000ED68))) /* ISA Feature Reg 2. */
#define CPU_REG_NVIC_ISAFR3 (*((CPU_REG32 *)(0xE000ED6C))) /* ISA Feature Reg 3. */
#define CPU_REG_NVIC_ISAFR4 (*((CPU_REG32 *)(0xE000ED70))) /* ISA Feature Reg 4. */
#define CPU_REG_NVIC_SW_TRIG (*((CPU_REG32 *)(0xE000EF00))) /* Software Trigger Int Reg. */
#define CPU_REG_MPU_TYPE (*((CPU_REG32 *)(0xE000ED90))) /* MPU Type Reg. */
#define CPU_REG_MPU_CTRL (*((CPU_REG32 *)(0xE000ED94))) /* MPU Ctrl Reg. */
#define CPU_REG_MPU_REG_NBR (*((CPU_REG32 *)(0xE000ED98))) /* MPU Region Nbr Reg. */
#define CPU_REG_MPU_REG_BASE (*((CPU_REG32 *)(0xE000ED9C))) /* MPU Region Base Addr Reg. */
#define CPU_REG_MPU_REG_ATTR (*((CPU_REG32 *)(0xE000EDA0))) /* MPU Region Attrib & Size Reg. */
#define CPU_REG_DBG_CTRL (*((CPU_REG32 *)(0xE000EDF0))) /* Debug Halting Ctrl & Status Reg. */
#define CPU_REG_DBG_SELECT (*((CPU_REG32 *)(0xE000EDF4))) /* Debug Core Reg Selector Reg. */
#define CPU_REG_DBG_DATA (*((CPU_REG32 *)(0xE000EDF8))) /* Debug Core Reg Data Reg. */
#define CPU_REG_DBG_INT (*((CPU_REG32 *)(0xE000EDFC))) /* Debug Except & Monitor Ctrl Reg. */
/*$PAGE*/
/*
*********************************************************************************************************
* CPU REGISTER BITS
*********************************************************************************************************
*/
/* ---------- SYSTICK CTRL & STATUS REG BITS ---------- */
#define CPU_REG_NVIC_ST_CTRL_COUNTFLAG 0x00010000
#define CPU_REG_NVIC_ST_CTRL_CLKSOURCE 0x00000004
#define CPU_REG_NVIC_ST_CTRL_TICKINT 0x00000002
#define CPU_REG_NVIC_ST_CTRL_ENABLE 0x00000001
/* -------- SYSTICK CALIBRATION VALUE REG BITS -------- */
#define CPU_REG_NVIC_ST_CAL_NOREF 0x80000000
#define CPU_REG_NVIC_ST_CAL_SKEW 0x40000000
/* -------------- INT CTRL STATE REG BITS ------------- */
#define CPU_REG_NVIC_ICSR_NMIPENDSET 0x80000000
#define CPU_REG_NVIC_ICSR_PENDSVSET 0x10000000
#define CPU_REG_NVIC_ICSR_PENDSVCLR 0x08000000
#define CPU_REG_NVIC_ICSR_PENDSTSET 0x04000000
#define CPU_REG_NVIC_ICSR_PENDSTCLR 0x02000000
#define CPU_REG_NVIC_ICSR_ISRPREEMPT 0x00800000
#define CPU_REG_NVIC_ICSR_ISRPENDING 0x00400000
#define CPU_REG_NVIC_ICSR_RETTOBASE 0x00000800
/* ------------- VECT TBL OFFSET REG BITS ------------- */
#define CPU_REG_NVIC_VTOR_TBLBASE 0x20000000
/* ------------ APP INT/RESET CTRL REG BITS ----------- */
#define CPU_REG_NVIC_AIRCR_ENDIANNESS 0x00008000
#define CPU_REG_NVIC_AIRCR_SYSRESETREQ 0x00000004
#define CPU_REG_NVIC_AIRCR_VECTCLRACTIVE 0x00000002
#define CPU_REG_NVIC_AIRCR_VECTRESET 0x00000001
/* --------------- SYSTEM CTRL REG BITS --------------- */
#define CPU_REG_NVIC_SCR_SEVONPEND 0x00000010
#define CPU_REG_NVIC_SCR_SLEEPDEEP 0x00000004
#define CPU_REG_NVIC_SCR_SLEEPONEXIT 0x00000002
/* ----------------- CFG CTRL REG BITS ---------------- */
#define CPU_REG_NVIC_CCR_STKALIGN 0x00000200
#define CPU_REG_NVIC_CCR_BFHFNMIGN 0x00000100
#define CPU_REG_NVIC_CCR_DIV_0_TRP 0x00000010
#define CPU_REG_NVIC_CCR_UNALIGN_TRP 0x00000008
#define CPU_REG_NVIC_CCR_USERSETMPEND 0x00000002
#define CPU_REG_NVIC_CCR_NONBASETHRDENA 0x00000001
/* ------- SYSTEM HANDLER CTRL & STATE REG BITS ------- */
#define CPU_REG_NVIC_SHCSR_USGFAULTENA 0x00040000
#define CPU_REG_NVIC_SHCSR_BUSFAULTENA 0x00020000
#define CPU_REG_NVIC_SHCSR_MEMFAULTENA 0x00010000
#define CPU_REG_NVIC_SHCSR_SVCALLPENDED 0x00008000
#define CPU_REG_NVIC_SHCSR_BUSFAULTPENDED 0x00004000
#define CPU_REG_NVIC_SHCSR_MEMFAULTPENDED 0x00002000
#define CPU_REG_NVIC_SHCSR_USGFAULTPENDED 0x00001000
#define CPU_REG_NVIC_SHCSR_SYSTICKACT 0x00000800
#define CPU_REG_NVIC_SHCSR_PENDSVACT 0x00000400
#define CPU_REG_NVIC_SHCSR_MONITORACT 0x00000100
#define CPU_REG_NVIC_SHCSR_SVCALLACT 0x00000080
#define CPU_REG_NVIC_SHCSR_USGFAULTACT 0x00000008
#define CPU_REG_NVIC_SHCSR_BUSFAULTACT 0x00000002
#define CPU_REG_NVIC_SHCSR_MEMFAULTACT 0x00000001
/* -------- CONFIGURABLE FAULT STATUS REG BITS -------- */
#define CPU_REG_NVIC_CFSR_DIVBYZERO 0x02000000
#define CPU_REG_NVIC_CFSR_UNALIGNED 0x01000000
#define CPU_REG_NVIC_CFSR_NOCP 0x00080000
#define CPU_REG_NVIC_CFSR_INVPC 0x00040000
#define CPU_REG_NVIC_CFSR_INVSTATE 0x00020000
#define CPU_REG_NVIC_CFSR_UNDEFINSTR 0x00010000
#define CPU_REG_NVIC_CFSR_BFARVALID 0x00008000
#define CPU_REG_NVIC_CFSR_STKERR 0x00001000
#define CPU_REG_NVIC_CFSR_UNSTKERR 0x00000800
#define CPU_REG_NVIC_CFSR_IMPRECISERR 0x00000400
#define CPU_REG_NVIC_CFSR_PRECISERR 0x00000200
#define CPU_REG_NVIC_CFSR_IBUSERR 0x00000100
#define CPU_REG_NVIC_CFSR_MMARVALID 0x00000080
#define CPU_REG_NVIC_CFSR_MSTKERR 0x00000010
#define CPU_REG_NVIC_CFSR_MUNSTKERR 0x00000008
#define CPU_REG_NVIC_CFSR_DACCVIOL 0x00000002
#define CPU_REG_NVIC_CFSR_IACCVIOL 0x00000001
/* ------------ HARD FAULT STATUS REG BITS ------------ */
#define CPU_REG_NVIC_HFSR_DEBUGEVT 0x80000000
#define CPU_REG_NVIC_HFSR_FORCED 0x40000000
#define CPU_REG_NVIC_HFSR_VECTTBL 0x00000002
/* ------------ DEBUG FAULT STATUS REG BITS ----------- */
#define CPU_REG_NVIC_DFSR_EXTERNAL 0x00000010
#define CPU_REG_NVIC_DFSR_VCATCH 0x00000008
#define CPU_REG_NVIC_DFSR_DWTTRAP 0x00000004
#define CPU_REG_NVIC_DFSR_BKPT 0x00000002
#define CPU_REG_NVIC_DFSR_HALTED 0x00000001
/*$PAGE*/
/*
*********************************************************************************************************
* CPU REGISTER MASK
*********************************************************************************************************
*/
#define CPU_MSK_NVIC_ICSR_VECT_ACTIVE 0x000001FF
/*$PAGE*/
/*
*********************************************************************************************************
* CONFIGURATION ERRORS
*********************************************************************************************************
*/
#ifndef CPU_CFG_ADDR_SIZE
#error "CPU_CFG_ADDR_SIZE not #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#elif ((CPU_CFG_ADDR_SIZE != CPU_WORD_SIZE_08) && \
(CPU_CFG_ADDR_SIZE != CPU_WORD_SIZE_16) && \
(CPU_CFG_ADDR_SIZE != CPU_WORD_SIZE_32) && \
(CPU_CFG_ADDR_SIZE != CPU_WORD_SIZE_64))
#error "CPU_CFG_ADDR_SIZE illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#endif
#ifndef CPU_CFG_DATA_SIZE
#error "CPU_CFG_DATA_SIZE not #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#elif ((CPU_CFG_DATA_SIZE != CPU_WORD_SIZE_08) && \
(CPU_CFG_DATA_SIZE != CPU_WORD_SIZE_16) && \
(CPU_CFG_DATA_SIZE != CPU_WORD_SIZE_32) && \
(CPU_CFG_DATA_SIZE != CPU_WORD_SIZE_64))
#error "CPU_CFG_DATA_SIZE illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#endif
#ifndef CPU_CFG_DATA_SIZE_MAX
#error "CPU_CFG_DATA_SIZE_MAX not #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#elif ((CPU_CFG_DATA_SIZE_MAX != CPU_WORD_SIZE_08) && \
(CPU_CFG_DATA_SIZE_MAX != CPU_WORD_SIZE_16) && \
(CPU_CFG_DATA_SIZE_MAX != CPU_WORD_SIZE_32) && \
(CPU_CFG_DATA_SIZE_MAX != CPU_WORD_SIZE_64))
#error "CPU_CFG_DATA_SIZE_MAX illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_WORD_SIZE_08 8-bit alignment]"
#error " [ || CPU_WORD_SIZE_16 16-bit alignment]"
#error " [ || CPU_WORD_SIZE_32 32-bit alignment]"
#error " [ || CPU_WORD_SIZE_64 64-bit alignment]"
#endif
#if (CPU_CFG_DATA_SIZE_MAX < CPU_CFG_DATA_SIZE)
#error "CPU_CFG_DATA_SIZE_MAX illegally #define'd in 'cpu.h' "
#error " [MUST be >= CPU_CFG_DATA_SIZE]"
#endif
/*$PAGE*/
#ifndef CPU_CFG_ENDIAN_TYPE
#error "CPU_CFG_ENDIAN_TYPE not #define'd in 'cpu.h' "
#error " [MUST be CPU_ENDIAN_TYPE_BIG ]"
#error " [ || CPU_ENDIAN_TYPE_LITTLE]"
#elif ((CPU_CFG_ENDIAN_TYPE != CPU_ENDIAN_TYPE_BIG ) && \
(CPU_CFG_ENDIAN_TYPE != CPU_ENDIAN_TYPE_LITTLE))
#error "CPU_CFG_ENDIAN_TYPE illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_ENDIAN_TYPE_BIG ]"
#error " [ || CPU_ENDIAN_TYPE_LITTLE]"
#endif
#ifndef CPU_CFG_STK_GROWTH
#error "CPU_CFG_STK_GROWTH not #define'd in 'cpu.h' "
#error " [MUST be CPU_STK_GROWTH_LO_TO_HI]"
#error " [ || CPU_STK_GROWTH_HI_TO_LO]"
#elif ((CPU_CFG_STK_GROWTH != CPU_STK_GROWTH_LO_TO_HI) && \
(CPU_CFG_STK_GROWTH != CPU_STK_GROWTH_HI_TO_LO))
#error "CPU_CFG_STK_GROWTH illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_STK_GROWTH_LO_TO_HI]"
#error " [ || CPU_STK_GROWTH_HI_TO_LO]"
#endif
#ifndef CPU_CFG_CRITICAL_METHOD
#error "CPU_CFG_CRITICAL_METHOD not #define'd in 'cpu.h' "
#error " [MUST be CPU_CRITICAL_METHOD_INT_DIS_EN ]"
#error " [ || CPU_CRITICAL_METHOD_STATUS_STK ]"
#error " [ || CPU_CRITICAL_METHOD_STATUS_LOCAL]"
#elif ((CPU_CFG_CRITICAL_METHOD != CPU_CRITICAL_METHOD_INT_DIS_EN ) && \
(CPU_CFG_CRITICAL_METHOD != CPU_CRITICAL_METHOD_STATUS_STK ) && \
(CPU_CFG_CRITICAL_METHOD != CPU_CRITICAL_METHOD_STATUS_LOCAL))
#error "CPU_CFG_CRITICAL_METHOD illegally #define'd in 'cpu.h' "
#error " [MUST be CPU_CRITICAL_METHOD_INT_DIS_EN ]"
#error " [ || CPU_CRITICAL_METHOD_STATUS_STK ]"
#error " [ || CPU_CRITICAL_METHOD_STATUS_LOCAL]"
#endif
/*$PAGE*/
/*
*********************************************************************************************************
* MODULE END
*
* Note(s) : (1) See 'cpu.h MODULE'.
*********************************************************************************************************
*/
#endif /* End of CPU module include. */
|
Michel-GPescie/uCOS_stm32
|
os/ucos/cpu/ARM-Cortex-M4/cpu.h
|
C
|
mit
| 40,806
|
import Template7Context from './context';
const Template7Utils = {
quoteSingleRexExp: new RegExp('\'', 'g'),
quoteDoubleRexExp: new RegExp('"', 'g'),
isFunction(func) {
return typeof func === 'function';
},
escape(string = '') {
return string
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
},
helperToSlices(string) {
const { quoteDoubleRexExp, quoteSingleRexExp } = Template7Utils;
const helperParts = string.replace(/[{}#}]/g, '').trim().split(' ');
const slices = [];
let shiftIndex;
let i;
let j;
for (i = 0; i < helperParts.length; i += 1) {
let part = helperParts[i];
let blockQuoteRegExp;
let openingQuote;
if (i === 0) slices.push(part);
else if (part.indexOf('"') === 0 || part.indexOf('\'') === 0) {
blockQuoteRegExp = part.indexOf('"') === 0 ? quoteDoubleRexExp : quoteSingleRexExp;
openingQuote = part.indexOf('"') === 0 ? '"' : '\'';
// Plain String
if (part.match(blockQuoteRegExp).length === 2) {
// One word string
slices.push(part);
} else {
// Find closed Index
shiftIndex = 0;
for (j = i + 1; j < helperParts.length; j += 1) {
part += ` ${helperParts[j]}`;
if (helperParts[j].indexOf(openingQuote) >= 0) {
shiftIndex = j;
slices.push(part);
break;
}
}
if (shiftIndex) i = shiftIndex;
}
} else if (part.indexOf('=') > 0) {
// Hash
const hashParts = part.split('=');
const hashName = hashParts[0];
let hashContent = hashParts[1];
if (!blockQuoteRegExp) {
blockQuoteRegExp = hashContent.indexOf('"') === 0 ? quoteDoubleRexExp : quoteSingleRexExp;
openingQuote = hashContent.indexOf('"') === 0 ? '"' : '\'';
}
if (hashContent.match(blockQuoteRegExp).length !== 2) {
shiftIndex = 0;
for (j = i + 1; j < helperParts.length; j += 1) {
hashContent += ` ${helperParts[j]}`;
if (helperParts[j].indexOf(openingQuote) >= 0) {
shiftIndex = j;
break;
}
}
if (shiftIndex) i = shiftIndex;
}
const hash = [hashName, hashContent.replace(blockQuoteRegExp, '')];
slices.push(hash);
} else {
// Plain variable
slices.push(part);
}
}
return slices;
},
stringToBlocks(string) {
const blocks = [];
let i;
let j;
if (!string) return [];
const stringBlocks = string.split(/({{[^{^}]*}})/);
for (i = 0; i < stringBlocks.length; i += 1) {
let block = stringBlocks[i];
if (block === '') continue;
if (block.indexOf('{{') < 0) {
blocks.push({
type: 'plain',
content: block,
});
} else {
if (block.indexOf('{/') >= 0) {
continue;
}
block = block
.replace(/{{([#/])*([ ])*/, '{{$1')
.replace(/([ ])*}}/, '}}');
if (block.indexOf('{#') < 0 && block.indexOf(' ') < 0 && block.indexOf('else') < 0) {
// Simple variable
blocks.push({
type: 'variable',
contextName: block.replace(/[{}]/g, ''),
});
continue;
}
// Helpers
const helperSlices = Template7Utils.helperToSlices(block);
let helperName = helperSlices[0];
const isPartial = helperName === '>';
const helperContext = [];
const helperHash = {};
for (j = 1; j < helperSlices.length; j += 1) {
const slice = helperSlices[j];
if (Array.isArray(slice)) {
// Hash
helperHash[slice[0]] = slice[1] === 'false' ? false : slice[1];
} else {
helperContext.push(slice);
}
}
if (block.indexOf('{#') >= 0) {
// Condition/Helper
let helperContent = '';
let elseContent = '';
let toSkip = 0;
let shiftIndex;
let foundClosed = false;
let foundElse = false;
let depth = 0;
for (j = i + 1; j < stringBlocks.length; j += 1) {
if (stringBlocks[j].indexOf('{{#') >= 0) {
depth += 1;
}
if (stringBlocks[j].indexOf('{{/') >= 0) {
depth -= 1;
}
if (stringBlocks[j].indexOf(`{{#${helperName}`) >= 0) {
helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
toSkip += 1;
} else if (stringBlocks[j].indexOf(`{{/${helperName}`) >= 0) {
if (toSkip > 0) {
toSkip -= 1;
helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
} else {
shiftIndex = j;
foundClosed = true;
break;
}
} else if (stringBlocks[j].indexOf('else') >= 0 && depth === 0) {
foundElse = true;
} else {
if (!foundElse) helperContent += stringBlocks[j];
if (foundElse) elseContent += stringBlocks[j];
}
}
if (foundClosed) {
if (shiftIndex) i = shiftIndex;
if (helperName === 'raw') {
blocks.push({
type: 'plain',
content: helperContent,
});
} else {
blocks.push({
type: 'helper',
helperName,
contextName: helperContext,
content: helperContent,
inverseContent: elseContent,
hash: helperHash,
});
}
}
} else if (block.indexOf(' ') > 0) {
if (isPartial) {
helperName = '_partial';
if (helperContext[0]) {
if (helperContext[0].indexOf('[') === 0) helperContext[0] = helperContext[0].replace(/[[\]]/g, '');
else helperContext[0] = `"${helperContext[0].replace(/"|'/g, '')}"`;
}
}
blocks.push({
type: 'helper',
helperName,
contextName: helperContext,
hash: helperHash,
});
}
}
}
return blocks;
},
parseJsVariable(expression, replace, object) {
return expression.split(/([+ \-*/^()&=|<>!%:?])/g).reduce((arr, part) => {
if (!part) {
return arr;
}
if (part.indexOf(replace) < 0) {
arr.push(part);
return arr;
}
if (!object) {
arr.push(JSON.stringify(''));
return arr;
}
let variable = object;
if (part.indexOf(`${replace}.`) >= 0) {
part.split(`${replace}.`)[1].split('.').forEach((partName) => {
if (partName in variable) variable = variable[partName];
else variable = undefined;
});
}
if (
(typeof variable === 'string')
|| Array.isArray(variable)
|| (variable.constructor && variable.constructor === Object)
) {
variable = JSON.stringify(variable);
}
if (variable === undefined) variable = 'undefined';
arr.push(variable);
return arr;
}, []).join('');
},
parseJsParents(expression, parents) {
return expression.split(/([+ \-*^()&=|<>!%:?])/g).reduce((arr, part) => {
if (!part) {
return arr;
}
if (part.indexOf('../') < 0) {
arr.push(part);
return arr;
}
if (!parents || parents.length === 0) {
arr.push(JSON.stringify(''));
return arr;
}
const levelsUp = part.split('../').length - 1;
const parentData = levelsUp > parents.length ? parents[parents.length - 1] : parents[levelsUp - 1];
let variable = parentData;
const parentPart = part.replace(/..\//g, '');
parentPart.split('.').forEach((partName) => {
if (typeof variable[partName] !== 'undefined') variable = variable[partName];
else variable = 'undefined';
});
if (variable === false || variable === true) {
arr.push(JSON.stringify(variable));
return arr;
}
if (variable === null || variable === 'undefined') {
arr.push(JSON.stringify(''));
return arr;
}
arr.push(JSON.stringify(variable));
return arr;
}, []).join('');
},
getCompileVar(name, ctx, data = 'data_1') {
let variable = ctx;
let parts;
let levelsUp = 0;
let newDepth;
if (name.indexOf('../') === 0) {
levelsUp = name.split('../').length - 1;
newDepth = variable.split('_')[1] - levelsUp;
variable = `ctx_${newDepth >= 1 ? newDepth : 1}`;
parts = name.split('../')[levelsUp].split('.');
} else if (name.indexOf('@global') === 0) {
variable = 'Template7.global';
parts = name.split('@global.')[1].split('.');
} else if (name.indexOf('@root') === 0) {
variable = 'root';
parts = name.split('@root.')[1].split('.');
} else {
parts = name.split('.');
}
for (let i = 0; i < parts.length; i += 1) {
const part = parts[i];
if (part.indexOf('@') === 0) {
let dataLevel = data.split('_')[1];
if (levelsUp > 0) {
dataLevel = newDepth;
}
if (i > 0) {
variable += `[(data_${dataLevel} && data_${dataLevel}.${part.replace('@', '')})]`;
} else {
variable = `(data_${dataLevel} && data_${dataLevel}.${part.replace('@', '')})`;
}
} else if (Number.isFinite ? Number.isFinite(part) : Template7Context.isFinite(part)) {
variable += `[${part}]`;
} else if (part === 'this' || part.indexOf('this.') >= 0 || part.indexOf('this[') >= 0 || part.indexOf('this(') >= 0) {
variable = part.replace('this', ctx);
} else {
variable += `.${part}`;
}
}
return variable;
},
getCompiledArguments(contextArray, ctx, data) {
const arr = [];
for (let i = 0; i < contextArray.length; i += 1) {
if (/^['"]/.test(contextArray[i])) arr.push(contextArray[i]);
else if (/^(true|false|\d+)$/.test(contextArray[i])) arr.push(contextArray[i]);
else {
arr.push(Template7Utils.getCompileVar(contextArray[i], ctx, data));
}
}
return arr.join(', ');
},
};
export default Template7Utils;
|
nolimits4web/Template7
|
src/utils.js
|
JavaScript
|
mit
| 10,591
|
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
number = 0
for i in range(len(s)):
number = number * 26 + ord(s[i]) - ord('A') + 1
return number
|
FeiZhan/Algo-Collection
|
answers/leetcode/Excel Sheet Column Number/Excel Sheet Column Number.py
|
Python
|
mit
| 255
|
cd C:\wamp64\www\frenchtech
php bin/console cache:clear --no-warmup
|
paoudom/frenchtech2
|
cacheclear.bat
|
Batchfile
|
mit
| 67
|
package com.wavesplatform.features
sealed trait BlockchainFeatureStatus
object BlockchainFeatureStatus {
case object Undefined extends BlockchainFeatureStatus
case object Approved extends BlockchainFeatureStatus
case object Activated extends BlockchainFeatureStatus
def promote(status: BlockchainFeatureStatus): BlockchainFeatureStatus = {
status match {
case Undefined => Approved
case Approved => Activated
case Activated => Activated
}
}
}
|
wavesplatform/Waves
|
node/src/main/scala/com/wavesplatform/features/BlockchainFeatureStatus.scala
|
Scala
|
mit
| 484
|
const _evaluate = function(stateData) {
if(stateData.fireKey)
return "Yellow"
};
module.exports = function(Anystate) {
Anystate.prototype._evaluate = _evaluate
}
|
tinnguyenhuuletrong/fsm
|
test/codeBase-js/fsm.color/tmp/Anystate.evaluate.js
|
JavaScript
|
mit
| 168
|
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators.
// Website & Documentation: http://html-agility-pack.net
// Forum & Issues: https://github.com/zzzprojects/html-agility-pack
// License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2017. All rights reserved.
#if !METRO
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.XPath;
#pragma warning disable 0649
namespace HtmlAgilityPack
{
/// <summary>
/// Represents an HTML navigator on an HTML document seen as a data store.
/// </summary>
public class HtmlNodeNavigator : XPathNavigator
{
#region Fields
private int _attindex;
private HtmlNode _currentnode;
private readonly HtmlDocument _doc;
private readonly HtmlNameTable _nametable;
internal bool Trace;
#endregion
#region Constructors
internal HtmlNodeNavigator()
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
Reset();
}
internal HtmlNodeNavigator(HtmlDocument doc, HtmlNode currentNode)
{
if (currentNode == null)
{
throw new ArgumentNullException("currentNode");
}
if (currentNode.OwnerDocument != doc)
{
throw new ArgumentException(HtmlDocument.HtmlExceptionRefNotChild);
}
if (doc == null)
{
// keep in message, currentNode.OwnerDocument also null.
throw new Exception("Oops! The HtmlDocument cannot be null.");
}
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
_doc = doc;
_nametable = new HtmlNameTable();
Reset();
_currentnode = currentNode;
}
private HtmlNodeNavigator(HtmlNodeNavigator nav)
{
if (nav == null)
{
throw new ArgumentNullException("nav");
}
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
_doc = nav._doc;
_currentnode = nav._currentnode;
_attindex = nav._attindex;
_nametable = nav._nametable; // REVIEW: should we do this?
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public HtmlNodeNavigator(Stream stream)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(stream);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, bool detectEncodingFromByteOrderMarks)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(stream, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(stream, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(stream, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document.</param>
public HtmlNodeNavigator(TextReader reader)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(reader);
Reset();
}
#if !(NETSTANDARD1_3 || NETSTANDARD1_6)
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
public HtmlNodeNavigator(string path)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(path);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, bool detectEncodingFromByteOrderMarks)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(path, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
public HtmlNodeNavigator(string path, Encoding encoding)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(path, encoding);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks);
Reset();
}
/// <summary>
/// Initializes a new instance of the HtmlNavigator and loads an HTML document from a file.
/// </summary>
/// <param name="path">The complete file path to be read.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the file.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public HtmlNodeNavigator(string path, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
_doc = new HtmlDocument();
_nametable = new HtmlNameTable();
_doc.Load(path, encoding, detectEncodingFromByteOrderMarks, buffersize);
Reset();
}
#endif
#endregion
#region Properties
/// <summary>
/// Gets the base URI for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string BaseURI
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">");
#endif
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the current HTML document.
/// </summary>
public HtmlDocument CurrentDocument
{
get { return _doc; }
}
/// <summary>
/// Gets the current HTML node.
/// </summary>
public HtmlNode CurrentNode
{
get { return _currentnode; }
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasAttributes
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">" + (_currentnode.Attributes.Count > 0));
#endif
return (_currentnode.Attributes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node has child nodes.
/// </summary>
public override bool HasChildren
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">" + (_currentnode.ChildNodes.Count > 0));
#endif
return (_currentnode.ChildNodes.Count > 0);
}
}
/// <summary>
/// Gets a value indicating whether the current node is an empty element.
/// </summary>
public override bool IsEmptyElement
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">" + !HasChildren);
#endif
// REVIEW: is this ok?
return !HasChildren;
}
}
/// <summary>
/// Gets the name of the current HTML node without the namespace prefix.
/// </summary>
public override string LocalName
{
get
{
if (_attindex != -1)
{
#if TRACE_NAVIGATOR
InternalTrace("att>" + _currentnode.Attributes[_attindex].Name);
#endif
return _nametable.GetOrAdd(_currentnode.Attributes[_attindex].Name);
}
#if TRACE_NAVIGATOR
InternalTrace("node>" + _currentnode.Name);
#endif
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the qualified name of the current node.
/// </summary>
public override string Name
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">" + _currentnode.Name);
#endif
return _nametable.GetOrAdd(_currentnode.Name);
}
}
/// <summary>
/// Gets the namespace URI (as defined in the W3C Namespace Specification) of the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string NamespaceURI
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(">");
#endif
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the <see cref="XmlNameTable"/> associated with this implementation.
/// </summary>
public override XmlNameTable NameTable
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return _nametable;
}
}
/// <summary>
/// Gets the type of the current node.
/// </summary>
public override XPathNodeType NodeType
{
get
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
#if TRACE_NAVIGATOR
InternalTrace(">" + XPathNodeType.Comment);
#endif
return XPathNodeType.Comment;
case HtmlNodeType.Document:
#if TRACE_NAVIGATOR
InternalTrace(">" + XPathNodeType.Root);
#endif
return XPathNodeType.Root;
case HtmlNodeType.Text:
#if TRACE_NAVIGATOR
InternalTrace(">" + XPathNodeType.Text);
#endif
return XPathNodeType.Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
#if TRACE_NAVIGATOR
InternalTrace(">" + XPathNodeType.Attribute);
#endif
return XPathNodeType.Attribute;
}
#if TRACE_NAVIGATOR
InternalTrace(">" + XPathNodeType.Element);
#endif
return XPathNodeType.Element;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the prefix associated with the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string Prefix
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return _nametable.GetOrAdd(string.Empty);
}
}
/// <summary>
/// Gets the text value of the current node.
/// </summary>
public override string Value
{
get
{
#if TRACE_NAVIGATOR
InternalTrace("nt=" + _currentnode.NodeType);
#endif
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
#if TRACE_NAVIGATOR
InternalTrace(">" + ((HtmlCommentNode) _currentnode).Comment);
#endif
return ((HtmlCommentNode) _currentnode).Comment;
case HtmlNodeType.Document:
#if TRACE_NAVIGATOR
InternalTrace(">");
#endif
return "";
case HtmlNodeType.Text:
#if TRACE_NAVIGATOR
InternalTrace(">" + ((HtmlTextNode) _currentnode).Text);
#endif
return ((HtmlTextNode) _currentnode).Text;
case HtmlNodeType.Element:
{
if (_attindex != -1)
{
#if TRACE_NAVIGATOR
InternalTrace(">" + _currentnode.Attributes[_attindex].Value);
#endif
return _currentnode.Attributes[_attindex].Value;
}
return _currentnode.InnerText;
}
default:
throw new NotImplementedException("Internal error: Unhandled HtmlNodeType: " +
_currentnode.NodeType);
}
}
}
/// <summary>
/// Gets the xml:lang scope for the current node.
/// Always returns string.Empty in the case of HtmlNavigator implementation.
/// </summary>
public override string XmlLang
{
get
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return _nametable.GetOrAdd(string.Empty);
}
}
#endregion
#region Public Methods
/// <summary>
/// Creates a new HtmlNavigator positioned at the same node as this HtmlNavigator.
/// </summary>
/// <returns>A new HtmlNavigator object positioned at the same node as the original HtmlNavigator.</returns>
public override XPathNavigator Clone()
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return new HtmlNodeNavigator(this);
}
/// <summary>
/// Gets the value of the HTML attribute with the specified LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>The value of the specified HTML attribute. String.Empty or null if a matching attribute is not found or if the navigator is not positioned on an element node.</returns>
public override string GetAttribute(string localName, string namespaceURI)
{
#if TRACE_NAVIGATOR
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
#endif
HtmlAttribute att = _currentnode.Attributes[localName];
if (att == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">null");
#endif
return null;
}
#if TRACE_NAVIGATOR
InternalTrace(">" + att.Value);
#endif
return att.Value;
}
/// <summary>
/// Returns the value of the namespace node corresponding to the specified local name.
/// Always returns string.Empty for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns string.Empty for the HtmlNavigator implementation.</returns>
public override string GetNamespace(string name)
{
#if TRACE_NAVIGATOR
InternalTrace("name=" + name);
#endif
return string.Empty;
}
/// <summary>
/// Determines whether the current HtmlNavigator is at the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator that you want to compare against.</param>
/// <returns>true if the two navigators have the same position, otherwise, false.</returns>
public override bool IsSamePosition(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
#if TRACE_NAVIGATOR
InternalTrace(">" + (nav._currentnode == _currentnode));
#endif
return (nav._currentnode == _currentnode);
}
/// <summary>
/// Moves to the same position as the specified HtmlNavigator.
/// </summary>
/// <param name="other">The HtmlNavigator positioned on the node that you want to move to.</param>
/// <returns>true if successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveTo(XPathNavigator other)
{
HtmlNodeNavigator nav = other as HtmlNodeNavigator;
if (nav == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false (nav is not an HtmlNodeNavigator)");
#endif
return false;
}
#if TRACE_NAVIGATOR
InternalTrace("moveto oid=" + nav.GetHashCode()
+ ", n:" + nav._currentnode.Name
+ ", a:" + nav._attindex);
#endif
if (nav._doc == _doc)
{
_currentnode = nav._currentnode;
_attindex = nav._attindex;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
// we don't know how to handle that
#if TRACE_NAVIGATOR
InternalTrace(">false (???)");
#endif
return false;
}
/// <summary>
/// Moves to the HTML attribute with matching LocalName and NamespaceURI.
/// </summary>
/// <param name="localName">The local name of the HTML attribute.</param>
/// <param name="namespaceURI">The namespace URI of the attribute. Unsupported with the HtmlNavigator implementation.</param>
/// <returns>true if the HTML attribute is found, otherwise, false. If false, the position of the navigator does not change.</returns>
public override bool MoveToAttribute(string localName, string namespaceURI)
{
#if TRACE_NAVIGATOR
InternalTrace("localName=" + localName + ", namespaceURI=" + namespaceURI);
#endif
int index = _currentnode.Attributes.GetAttributeIndex(localName);
if (index == -1)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_attindex = index;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the first sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the first sibling node, false if there is no first sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToFirst()
{
if (_currentnode.ParentNode == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
if (_currentnode.ParentNode.FirstChild == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_currentnode = _currentnode.ParentNode.FirstChild;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the first HTML attribute.
/// </summary>
/// <returns>true if the navigator is successful moving to the first HTML attribute, otherwise, false.</returns>
public override bool MoveToFirstAttribute()
{
if (!HasAttributes)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_attindex = 0;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the first child of the current node.
/// </summary>
/// <returns>true if there is a first child node, otherwise false.</returns>
public override bool MoveToFirstChild()
{
if (!_currentnode.HasChildNodes)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_currentnode = _currentnode.ChildNodes[0];
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves the XPathNavigator to the first namespace node of the current element.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return false;
}
/// <summary>
/// Moves to the node that has an attribute of type ID whose value matches the specified string.
/// </summary>
/// <param name="id">A string representing the ID value of the node to which you want to move. This argument does not need to be atomized.</param>
/// <returns>true if the move was successful, otherwise false. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToId(string id)
{
#if TRACE_NAVIGATOR
InternalTrace("id=" + id);
#endif
HtmlNode node = _doc.GetElementbyId(id);
if (node == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_currentnode = node;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves the XPathNavigator to the namespace node with the specified local name.
/// Always returns false for the HtmlNavigator implementation.
/// </summary>
/// <param name="name">The local name of the namespace node.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNamespace(string name)
{
#if TRACE_NAVIGATOR
InternalTrace("name=" + name);
#endif
return false;
}
/// <summary>
/// Moves to the next sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the next sibling node, false if there are no more siblings or if the navigator is currently positioned on an attribute node. If false, the position of the navigator is unchanged.</returns>
public override bool MoveToNext()
{
if (_currentnode.NextSibling == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
#if TRACE_NAVIGATOR
InternalTrace("_c=" + _currentnode.CloneNode(false).OuterHtml);
InternalTrace("_n=" + _currentnode.NextSibling.CloneNode(false).OuterHtml);
#endif
_currentnode = _currentnode.NextSibling;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the next HTML attribute.
/// </summary>
/// <returns></returns>
public override bool MoveToNextAttribute()
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
if (_attindex >= (_currentnode.Attributes.Count - 1))
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_attindex++;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves the XPathNavigator to the next namespace node.
/// Always returns falsefor the HtmlNavigator implementation.
/// </summary>
/// <param name="scope">An XPathNamespaceScope value describing the namespace scope.</param>
/// <returns>Always returns false for the HtmlNavigator implementation.</returns>
public override bool MoveToNextNamespace(XPathNamespaceScope scope)
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
return false;
}
/// <summary>
/// Moves to the parent of the current node.
/// </summary>
/// <returns>true if there is a parent node, otherwise false.</returns>
public override bool MoveToParent()
{
if (_currentnode.ParentNode == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_currentnode = _currentnode.ParentNode;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the previous sibling of the current node.
/// </summary>
/// <returns>true if the navigator is successful moving to the previous sibling node, false if there is no previous sibling or if the navigator is currently positioned on an attribute node.</returns>
public override bool MoveToPrevious()
{
if (_currentnode.PreviousSibling == null)
{
#if TRACE_NAVIGATOR
InternalTrace(">false");
#endif
return false;
}
_currentnode = _currentnode.PreviousSibling;
#if TRACE_NAVIGATOR
InternalTrace(">true");
#endif
return true;
}
/// <summary>
/// Moves to the root node to which the current node belongs.
/// </summary>
public override void MoveToRoot()
{
_currentnode = _doc.DocumentNode;
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
}
#endregion
#region Internal Methods
#if TRACE_NAVIGATOR
[Conditional("TRACE")]
internal void InternalTrace(object traceValue)
{
if (!Trace)
{
return;
}
#if !(NETSTANDARD1_3 || NETSTANDARD1_6)
StackFrame sf = new StackFrame(1);
string name = sf.GetMethod().Name;
#else
string name = "";
#endif
string nodename = _currentnode == null ? "(null)" : _currentnode.Name;
string nodevalue;
if (_currentnode == null)
{
nodevalue = "(null)";
}
else
{
switch (_currentnode.NodeType)
{
case HtmlNodeType.Comment:
nodevalue = ((HtmlCommentNode) _currentnode).Comment;
break;
case HtmlNodeType.Document:
nodevalue = "";
break;
case HtmlNodeType.Text:
nodevalue = ((HtmlTextNode) _currentnode).Text;
break;
default:
nodevalue = _currentnode.CloneNode(false).OuterHtml;
break;
}
}
HtmlAgilityPack.Trace.WriteLine(string.Format("oid={0},n={1},a={2},v={3},{4}", GetHashCode(), nodename, _attindex, nodevalue, traceValue), "N!" + name);
}
#endif
#endregion
#region Private Methods
private void Reset()
{
#if TRACE_NAVIGATOR
InternalTrace(null);
#endif
_currentnode = _doc.DocumentNode;
_attindex = -1;
}
#endregion
}
}
#endif
|
zzzprojects/html-agility-pack
|
src/HtmlAgilityPack.Shared/HtmlNodeNavigator.cs
|
C#
|
mit
| 26,968
|
---
layout: default
title: OpenCL matrix-multiplication SGEMM tutorial
current: 5
tutorial_page: 9
---
<h2>Kernel 7: Wider loads with register blocking</h2>
In one of our earlier kernels we used wider data-types to get 64-bit or 128-bit loads and stores. Let's re-integrate that in our latest version with 2D register blocking. We'll do this for loads only.
<br/><br/>
The launch configuration and the constants remain the same. The kernel is also quite similar, with the main exceptions in the part where we are loading from off-chip memory:
<br><br>
<ul>
<li>We now load float2 or float4 values from off-chip memory. Therefore, the loop over the amount of loads per thread has been reduced by a factor WIDTH. The same holds for the indexing into the vector arrays.</li>
<li>Since we now have a slightly different access pattern when storing data into Asub and Bsub, we choose to swap the column and row indices of Bsub back to how they are for Asub. This does require more local memory loads (LDS instead of LDS.64) in the computational loop, but since this is now cached using register tiling, its impact is not that big. The main new advantage is that we can now also store data into Bsub using vector data-types. Note that since Asub and Bsub are not declared as vectors, the stores into Asub and Bsub look scalar from a coding-perspective, but they become 64-bit or 128-bit stores (STS.128) when compiled. We can now also remove the padding, giving us that extra bit of local memory back.</li>
</ul>
<br>
Note that we still have the restriction that TSM has to be equal to TSN. This restriction can be removed by creating two loops when loading, one over LPTA with indices constrained to TSM and one over LPTB with indices constrained to TSN. We'll implement this in our final version.
<br/><br>
<pre class="prettyprint linenums lang-cuda">
// Wider loads combined with 2D register blocking
__kernel void myGEMM7(const int M, const int N, const int K,
const __global floatX* A,
const __global floatX* B,
__global float* C) {
// Thread identifiers
const int tidm = get_local_id(0); // Local row ID (max: TSM/WPTM)
const int tidn = get_local_id(1); // Local col ID (max: TSN/WPTN)
const int offsetM = TSM*get_group_id(0); // Work-group offset
const int offsetN = TSN*get_group_id(1); // Work-group offset
// Local memory to fit a tile of A and B
__local float Asub[TSK][TSM];
__local float Bsub[TSK][TSN];
// Allocate register space
float Areg;
float Breg[WPTN];
float acc[WPTM][WPTN];
// Initialise the accumulation registers
for (int wm=0; wm<WPTM; wm++) {
for (int wn=0; wn<WPTN; wn++) {
acc[wm][wn] = 0.0f;
}
}
// Loop over all tiles
int numTiles = K/TSK;
for (int t=0; t<numTiles; t++) {
// Load one tile of A and B into local memory
for (int la=0; la<LPTA/WIDTH; la++) {
int tid = tidn*RTSM + tidm;
int id = la*RTSN*RTSM + tid;
int row = id % (TSM/WIDTH);
int col = id / (TSM/WIDTH);
// Load the values (wide vector load)
int tiledIndex = TSK*t + col;
floatX vecA = A[tiledIndex*(M/WIDTH) + offsetM/WIDTH + row];
floatX vecB = B[tiledIndex*(N/WIDTH) + offsetN/WIDTH + row];
// Store the loaded vectors into local memory
#if WIDTH == 1
Asub[col][row] = vecA;
Asub[col][row] = vecA;
#elif WIDTH == 2
Asub[col][WIDTH*row + 0] = vecA.x;
Asub[col][WIDTH*row + 1] = vecA.y;
#elif WIDTH == 4
Asub[col][WIDTH*row + 0] = vecA.x;
Asub[col][WIDTH*row + 1] = vecA.y;
Asub[col][WIDTH*row + 2] = vecA.z;
Asub[col][WIDTH*row + 3] = vecA.w;
#endif
#if WIDTH == 1
Bsub[col][row] = vecB;
Bsub[col][row] = vecB;
#elif WIDTH == 2
Bsub[col][WIDTH*row + 0] = vecB.x;
Bsub[col][WIDTH*row + 1] = vecB.y;
#elif WIDTH == 4
Bsub[col][WIDTH*row + 0] = vecB.x;
Bsub[col][WIDTH*row + 1] = vecB.y;
Bsub[col][WIDTH*row + 2] = vecB.z;
Bsub[col][WIDTH*row + 3] = vecB.w;
#endif
}
// Synchronise to make sure the tile is loaded
barrier(CLK_LOCAL_MEM_FENCE);
// Loop over the values of a single tile
for (int k=0; k<TSK; k++) {
// Cache the values of Bsub in registers
for (int wn=0; wn<WPTN; wn++) {
int col = tidn + wn*RTSN;
Breg[wn] = Bsub[k][col];
}
// Perform the computation
for (int wm=0; wm<WPTM; wm++) {
int row = tidm + wm*RTSM;
Areg = Asub[k][row];
for (int wn=0; wn<WPTN; wn++) {
acc[wm][wn] += Areg * Breg[wn];
}
}
}
// Synchronise before loading the next tile
barrier(CLK_LOCAL_MEM_FENCE);
}
// Store the final results in C
for (int wm=0; wm<WPTM; wm++) {
int globalRow = offsetM + tidm + wm*RTSM;
for (int wn=0; wn<WPTN; wn++) {
int globalCol = offsetN + tidn + wn*RTSN;
C[globalCol*M + globalRow] = acc[wm][wn];
}
}
}
</pre><br>
After inspection of the assembly code, we see that we went from 16 32-bit loads (LD) and local stores (STS) to 4 128-bit loads (LD.128) and local stores (STS.128) for a vector width of 4 floats.
<br/><br/>
Performance with WIDTH equal to 4 is slightly worse compared to our previous kernel. As before, this is because everything is very sensitive to register pressure and compiler optimisations. Luckily these wider loads will be paying off for the next couple of kernels, so we'll definitely keep them in.
<br/><br/>
<img id="blogimage" src="/tutorial/images/performance7.png" alt="Performance of myGEMM"></img>
<br/><br/>
|
CNugteren/cnugteren.github.io
|
tutorial/pages/page9.html
|
HTML
|
mit
| 6,174
|
<?php
namespace RectorPrefix20210615;
if (\class_exists('Tx_Extbase_Property_Exception_InvalidFormatException')) {
return;
}
class Tx_Extbase_Property_Exception_InvalidFormatException
{
}
\class_alias('Tx_Extbase_Property_Exception_InvalidFormatException', 'Tx_Extbase_Property_Exception_InvalidFormatException', \false);
|
RectorPHP/Rector
|
vendor/ssch/typo3-rector/stubs/Tx_Extbase_Property_Exception_InvalidFormatException.php
|
PHP
|
mit
| 328
|
# Test for handling incoming ICMP messages
## Status
| Num | Abbrev. | Description | Status
|:-----:|:---------:|:--------------------------|:-----------------:
0 |echorep |Echo reply |:white_check_mark:
3 |unreach |Destination unreachable |
4 |squench |Packet loss, slow down |
5 |redir |Shorter route exists |
6 |althost |Alternate host address |
8 |echoreq |Echo request |:white_check_mark:
9 |routeradv |Router advertisement |
10 |routersol |Router solicitation |
11 |timex |Time exceeded |
12 |paramprob |Invalid IP header |
13 |timereq |Timestamp request |
14 |timerep |Timestamp reply |
15 |inforeq |Information request |:white_check_mark:
16 |inforep |Information reply |:white_check_mark:
17 |maskreq |Address mask request |:white_check_mark:
18 |maskrep |Address mask reply |:white_check_mark:
30 |trace |Traceroute |
31 |dataconv |Data conversion problem |
32 |mobredir |Mobile host redirection |
33 |ipv6-where |IPv6 where-are-you |
34 |ipv6-here |IPv6 i-am-here |
35 |mobregreq |Mobile registration request|
36 |mobregrep |Mobile registration reply |
39 |skip |SKIP |
40 |photuris |Photuris |
| Num | Abbrev. | Type | Description | Status
|:----:|:------------: |:-------------:|:-----------------------------------:|:------:
0 |net-unr |unreach |Network unreachable |:white_check_mark:
1 |host-unr |unreach |Host unreachable |:white_check_mark:
2 |proto-unr |unreach |Protocol unreachable |:white_check_mark:
3 |port-unr |unreach |Port unreachable |:white_check_mark:
4 |needfrag |unreach |Fragmentation needed but DF bit set |:white_check_mark:
5 |srcfail |unreach |Source routing failed |:white_check_mark:
6 |net-unk |unreach |Network unknown |:white_check_mark:
7 |host-unk |unreach |Host unknown |:white_check_mark:
8 |isolate |unreach |Host isolated |
9 |net-prohib |unreach |Network administratively prohibited |:white_check_mark:
10 |host-prohib |unreach |Host administratively prohibited |:white_check_mark:
11 |net-tos |unreach |Invalid TOS for network |:white_check_mark:
12 |host-tos |unreach |Invalid TOS for host |:white_check_mark:
13 |filter-prohib |unreach |Prohibited access |
14 |host-preced |unreach |Precedence violation |:white_check_mark:
15 |cutoff-preced |unreach |Precedence cutoff |:white_check_mark:
0 |redir-net |redir |Shorter route for network |
1 |redir-host |redir |Shorter route for host |
2 |redir-tos-net |redir |Shorter route for TOS and network |
3 |redir-tos-host |redir |Shorter route for TOS and host |
0 |normal-adv |routeradv |Normal advertisement |
16 |common-adv |routeradv |Selective advertisement |
0 |transit |timex |Time exceeded in transit |
1 |reassemb |timex |Time exceeded in reassembly |
0 |badhead |paramprob |Invalid option pointer |
1 |optmiss |paramprob |Missing option |
2 |badlen |paramprob |Invalid length |
1 |unknown-ind |photuris |Unknown security index |
2 |auth-fail |photuris |Authentication failed |
3 |decrypt-fail |photuris |Decryption failed |
|
shivrai/TCP-IP-Regression-TestSuite
|
icmp/README.md
|
Markdown
|
mit
| 3,973
|
#!/usr/bin/env node
var fs = require("fs");
var path = require("path");
var optimist = require("optimist");
var argv = optimist.argv;
var to_center = [-119.95388, 37.913055];
var FILE_IN = path.resolve(argv._[0]);
var FILE_OUT = path.resolve(argv._[1]);
var geojson = JSON.parse(fs.readFileSync(FILE_IN));
var get_center = function(pg){
var b = [pg[0][0],pg[0][0],pg[0][1],pg[0][1]];
pg.forEach(function(p){
if (b[0] < p[0]) b[0] = p[0];
if (b[1] > p[0]) b[1] = p[0];
if (b[2] < p[1]) b[2] = p[1];
if (b[3] > p[1]) b[3] = p[1];
});
return [((b[0]+b[1])/2),((b[2]+b[3])/2)];
};
var from_center = null;
var move_shape = function(coords) {
var xScale = Math.cos(from_center[1]*3.14159/180)/Math.cos(to_center[1]*3.14159/180);
var dy = from_center[1]-to_center[1];
coords.forEach(function(v,k){
coords[k] = [
(v[0]-from_center[0])*xScale+to_center[0],
v[1]-dy
]
});
return coords;
}
switch (geojson["features"][0]["geometry"]["type"]) {
case "Polygon":
var from_center = get_center(geojson["features"][0]["geometry"]["coordinates"][0]);
geojson["features"][0]["geometry"]["coordinates"][0] = move_shape(geojson["features"][0]["geometry"]["coordinates"][0]);
break;
case "MultiPolygon":
var centers = [];
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v){
centers.push(get_center(v[0]));
});
var from_center = get_center(centers);
geojson["features"][0]["geometry"]["coordinates"].forEach(function(v,k){
geojson["features"][0]["geometry"]["coordinates"][k][0] = move_shape(v[0])
});
break;
}
fs.writeFileSync(FILE_OUT, JSON.stringify(geojson,null,'\t'));
|
opendatacity/fire
|
bin/move.js
|
JavaScript
|
mit
| 1,640
|
/*
hinclude.js -- HTML Includes (version 0.9)
Copyright (c) 2005-2011 Mark Nottingham <mnot@mnot.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
See http://www.mnot.net/javascript/hinclude/ for documentation.
*/
var hinclude = {
set_content_async: function (element, req) {
if (req.readyState == 4) {
if (req.status == 200 | req.status == 304) {
element.innerHTML = req.responseText;
}
element.className = "include_" + req.status;
}
},
buffer: new Array(),
set_content_buffered: function (element, req) {
if (req.readyState == 4) {
hinclude.buffer.push(new Array(element, req));
hinclude.outstanding--;
if (hinclude.outstanding == 0) {
hinclude.show_buffered_content();
}
}
},
show_buffered_content: function () {
while (hinclude.buffer.length > 0) {
var include = hinclude.buffer.pop();
if (include[1].status == 200 | include[1].status == 304) {
include[0].innerHTML = include[1].responseText;
}
include[0].className = "include_" + include[1].status;
}
},
outstanding: 0,
run: function () {
var mode = this.get_meta("include_mode", "buffered");
var callback = function(element, req) {};
var includes = document.getElementsByTagName("hx:include");
if (includes.length == 0) { // remove ns for IE
includes = document.getElementsByTagName("include");
}
if (mode == "async") {
callback = this.set_content_async;
} else if (mode == "buffered") {
callback = this.set_content_buffered;
var timeout = this.get_meta("include_timeout", 2.5) * 1000;
setTimeout("hinclude.show_buffered_content()", timeout);
}
for (var i=0; i < includes.length; i++) {
this.include(includes[i], includes[i].getAttribute("src"), callback);
}
},
include: function (element, url, incl_cb) {
var scheme = url.substring(0,url.indexOf(":"));
if (scheme.toLowerCase() == "data") { // just text/plain for now
var data = unescape(url.substring(url.indexOf(",") + 1, url.length));
element.innerHTML = data;
} else {
var req = false;
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch(e) {
req = false;
}
} else if (window.ActiveXObject) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
req = false;
}
}
if (req) {
this.outstanding++;
req.onreadystatechange = function() {
incl_cb(element, req);
};
try {
req.open("GET", url, true);
req.send("");
} catch (e) {
this.outstanding--;
alert("Include error: " + url + " (" + e + ")");
}
}
}
},
get_meta: function (name, value_default) {
var metas = document.getElementsByTagName("meta");
for (var m=0; m < metas.length; m++) {
var meta_name = metas[m].getAttribute("name");
if (meta_name == name) {
return metas[m].getAttribute("content");
}
}
return value_default;
},
/*
* (c)2006 Dean Edwards/Matthias Miller/John Resig
* Special thanks to Dan Webb's domready.js Prototype extension
* and Simon Willison's addLoadEvent
*
* For more info, see:
* http://dean.edwards.name/weblog/2006/06/again/
*
* Thrown together by Jesse Skinner (http://www.thefutureoftheweb.com/)
*/
addDOMLoadEvent: function(func) {
if (! window.__load_events) {
var init = function () {
// quit if this function has already been called
if (arguments.callee.done) return;
arguments.callee.done = true;
if (window.__load_timer) {
clearInterval(window.__load_timer);
window.__load_timer = null;
}
for (var i=0; i < window.__load_events.length; i++) {
window.__load_events[i]();
}
window.__load_events = null;
// clean up the __ie_onload event
/*@cc_on @*/
/*@if (@_win32)
document.getElementById("__ie_onload").onreadystatechange = "";
/*@end @*/
};
// for Mozilla/Opera9
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
// for Internet Explorer
/*@cc_on @*/
/*@if (@_win32)
document.write(
"<scr"
+ "ipt id=__ie_onload defer src=javascript:void(0)><\/scr"
+ "ipt>"
);
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
window.__load_timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init();
}
}, 10);
}
// for other browsers
window.onload = init;
window.__load_events = [];
}
window.__load_events.push(func);
}
};
hinclude.addDOMLoadEvent(function() { hinclude.run(); });
|
catchamonkey/chris.sedlmayr.co.uk
|
src/Sedlmayr/Bundle/LayoutBundle/Resources/public/js/hinclude.js
|
JavaScript
|
mit
| 6,301
|
# Encoding: utf-8
require 'askari/type'
# The .stub_key_value macro sets up *many* let declarations of facts about an HBase key
# value and its place in a schema:
#
# * row_key
# * row_key_encoded
# * row_key_type
# * family
# * family_encoded
# * qualifier_name
# * qualifier_schema
# * qualifier_type
# * qualifier
# * qualifier_encoded
# * value_type
# * value
# * value_encoded
# * timestamp
# * key_value: a double resembling an HBase KeyValue
module KeyValueHelpers
def stub_key_value(options = {})
stub_key_value_qualifier_schema(options)
stub_key_value_row_key(options)
stub_key_value_family(options)
stub_key_value_qualifier(options)
stub_key_value_value(options)
stub_key_value_timestamp(options)
stub_key_value_itself(options)
end
private
def stub_key_value_prefix(options)
prefix = options.fetch(:prefix, '')
prefix == '' ? '' : "#{prefix}_"
end
def stub_key_value_qualifier_schema(options)
prefix = stub_key_value_prefix(options)
qualifier_name = options.fetch(:qualifier_name)
let("#{prefix}qualifier_name") { qualifier_name.to_sym }
let("#{prefix}qualifier_schema") { relation_schema.qualifiers[qualifier_name.to_s] }
end
def stub_key_value_row_key(options)
prefix = stub_key_value_prefix(options)
row_key = options.fetch(:row_key)
let("#{prefix}row_key") { row_key }
let("#{prefix}row_key_type") { Askari::Type[relation_schema.row_key_type] }
stub_key_value_row_key_encoded(options)
end
def stub_key_value_family(options)
prefix = stub_key_value_prefix(options)
let("#{prefix}family") { (send "#{prefix}qualifier_schema").family_name }
let("#{prefix}family_encoded") { (send "#{prefix}family").to_java_bytes }
end
def stub_key_value_qualifier(options)
prefix = stub_key_value_prefix(options)
qualifier = options.fetch(:qualifier)
let("#{prefix}qualifier") { qualifier }
let("#{prefix}qualifier_type") do
Askari::Type[(send "#{prefix}qualifier_schema").qualifier_type]
end
stub_key_value_qualifier_encoded(options)
end
def stub_key_value_value(options)
prefix = stub_key_value_prefix(options)
value = options.fetch(:value)
let("#{prefix}value") { value }
let("#{prefix}value_type") do
Askari::Type[(send "#{prefix}qualifier_schema").value_type]
end
stub_key_value_value_encoded(options)
end
def stub_key_value_timestamp(options)
prefix = stub_key_value_prefix(options)
timestamp = options.fetch(:timestamp)
let("#{prefix}timestamp") { timestamp }
end
def stub_key_value_row_key_encoded(options)
prefix = stub_key_value_prefix(options)
let("#{prefix}row_key_encoded") do
(send "#{prefix}row_key_type").encode(options.fetch(:row_key))
end
end
def stub_key_value_qualifier_encoded(options)
prefix = stub_key_value_prefix(options)
let("#{prefix}qualifier_encoded") do
(send "#{prefix}qualifier_type").encode(options.fetch(:qualifier))
end
end
def stub_key_value_value_encoded(options)
prefix = stub_key_value_prefix(options)
let("#{prefix}value_encoded") do
(send "#{prefix}value_type").encode(options.fetch(:value))
end
end
def stub_key_value_itself(options)
prefix = stub_key_value_prefix(options)
let("#{prefix}key_value") do
double(
"#{prefix}key_value",
row: (send "#{prefix}row_key_encoded"),
family: (send "#{prefix}family_encoded"),
qualifier: (send "#{prefix}qualifier_encoded"),
value: (send "#{prefix}value_encoded"),
timestamp: options.fetch(:timestamp))
end
end
end
shared_context 'key-value', :key_value do |relation_name|
let(:relation_schema) { schema.current_version.relation(relation_name) }
extend KeyValueHelpers
end
|
pombredanne/askari
|
lib/askari/spec_helpers/key_value.rb
|
Ruby
|
mit
| 3,812
|
/*
* 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 net.mum.cs472;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author 985219
*/
@WebServlet(name = "TableServlet", urlPatterns = {"/TableServlet"})
public class TableServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TableServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TableServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
Student[] table = new Student[]{
new Student("dewei", 23),
new Student("jill", 33),
new Student("kim", 18)
};
request.setAttribute("students", table);
RequestDispatcher dispatcher
= request.getRequestDispatcher("table.jsp");
dispatcher.forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
RequestDispatcher dispatcher
= request.getRequestDispatcher("table.jsp");
dispatcher.forward(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
xiangdewei/B_WAP
|
ForEachDemo/src/java/net/mum/cs472/TableServlet.java
|
Java
|
mit
| 3,556
|
import { AfterViewChecked, Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
// subscribe を保持するための Subscription を import
import { Subscription } from 'rxjs';
// サービスを登録するための import
// アプリ全体でのサービスの共有、コンポーネント単位でのサービスの共有に関わらず、ここの import は必要
import { DataShareService } from '../../../service/data-share/data-share.service';
@Component({
selector: 'app-data-share-a',
templateUrl: './data-share-a.component.html',
styleUrls: ['../../../style/common.css', './data-share-a.component.css'],
// サービスを登録する
// コンポーネントで DI する場合はこのコメントアウトを外す
// providers: [
// DataShareService
// ]
})
export class DataShareAComponent implements OnInit, OnDestroy, AfterViewChecked {
/**
* DataShareService の変数の参照を取得するプロパティ
*
* @type {string}
*/
public serviceProp = 'Initialized by Component-A';
/**
* subscribe を保持するための Subscription
*
* @private
* @type {Subscription}
*/
private subscription!: Subscription;
/**
* サービスで共有するデータが更新されたかをチェックするためのデータ
*
* @type {string}
*/
private preData: string = this.serviceProp;
/**
* コンストラクタ. ServiceSample1Component のインスタンスを生成する
*
* @param dataShareService 共通サービス
*/
constructor(private dataShareService: DataShareService, private element: ElementRef) {}
/**
* ライフサイクルメソッド。コンポーネントの初期化で使用する
*/
ngOnInit(): void {
// イベント登録
// サービスで共有しているデータが更新されたら発火されるイベントをキャッチする
this.subscription = this.dataShareService.sharedDataSource$.subscribe((msg: any) => {
console.log('[Component-A] shared data updated.');
this.serviceProp = msg;
});
}
/**
* コンポーネント終了時の処理
*/
ngOnDestroy(): void {
// リソースリーク防止のため DataShareService から subcribe したオブジェクトを破棄する
this.subscription.unsubscribe();
}
/**
* View の変更検知処理
*/
ngAfterViewChecked(): void {
// 泥臭いがデータ変更が検知されたら描画する
// TODO: もっとスマートなやり方があるはず...
if (this.preData !== this.serviceProp) {
this.element.nativeElement.querySelector('.updated-data').style.visibility = 'visible';
}
}
/**
* ボタンクリック時のイベントハンドラ
*/
onClicSendMessage() {
// DataShareService のデータ更新を行う
console.log('[Component-A] onClicSendMessage fired.');
this.dataShareService.onNotifySharedDataChanged('Updated by Component-A.');
}
}
|
ksh-fthr/angular-work
|
src/app/component/data-share/data-share-a/data-share-a.component.ts
|
TypeScript
|
mit
| 2,982
|
using System;
using JetBrains.Annotations;
using Reusable.Collections;
namespace Reusable.IOnymous
{
[PublicAPI]
public readonly struct MimeType : IEquatable<MimeType>
{
public MimeType(string name) => Name = name;
[AutoEqualityProperty]
public SoftString Name { get; }
public bool IsNull => this == Null;
public static readonly MimeType Null = new MimeType(string.Empty);
/// <summary>
/// Any document that contains text and is theoretically human readable
/// </summary>
public static readonly MimeType Text = new MimeType("text/plain");
public static readonly MimeType Json = new MimeType("application/json");
/// <summary>
/// Any kind of binary data, especially data that will be executed or interpreted somehow.
/// </summary>
public static readonly MimeType Binary = new MimeType("application/octet-stream");
public override bool Equals(object obj) => obj is MimeType format && Equals(format);
public bool Equals(MimeType other) => AutoEquality<MimeType>.Comparer.Equals(this, other);
public override int GetHashCode() => AutoEquality<MimeType>.Comparer.GetHashCode(this);
public override string ToString() => Name.ToString();
public static bool operator ==(MimeType left, MimeType right) => left.Equals(right);
public static bool operator !=(MimeType left, MimeType right) => !(left == right);
}
}
|
he-dev/Reusable
|
Reusable.IOnymous/src/MimeType.cs
|
C#
|
mit
| 1,495
|
MCU = atmega32u4
ARCH = AVR8
BOARD = NONE
F_CPU = 16000000
F_USB = $(F_CPU)
OPTIMIZATION = s
TARGET = virtual_serial
SRC = $(TARGET).c descriptors.c $(LUFA_SRC_USB) $(LUFA_SRC_USBCLASS)
LUFA_PATH = ../../../lufa/LUFA
CC_FLAGS = -DUSE_LUFA_CONFIG_HEADER -IConfig/
LD_FLAGS =
all:
include $(LUFA_PATH)/Build/lufa_core.mk
include $(LUFA_PATH)/Build/lufa_sources.mk
include $(LUFA_PATH)/Build/lufa_build.mk
|
snoremac/avrlaunch
|
lufa/Makefile
|
Makefile
|
mit
| 471
|
// Copyright (c) 2009-2012 The Bitcoin Developers
// Copyright (c) 2013-2014 smilecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <vector>
#include <string>
#ifdef WIN32
#include <windows.h>
#endif
#include "crypter.h"
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0],
(unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV);
if (i != (int)WALLET_CRYPTO_KEY_SIZE)
{
OPENSSL_cleanse(chKey, sizeof(chKey));
OPENSSL_cleanse(chIV, sizeof(chIV));
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE)
return false;
memcpy(&chKey[0], &chNewKey[0], sizeof chKey);
memcpy(&chIV[0], &chNewIV[0], sizeof chIV);
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext)
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCK_SIZE - 1 bytes
int nLen = vchPlaintext.size();
int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0;
vchCiphertext = std::vector<unsigned char> (nCLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen);
if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchCiphertext.resize(nCLen + nFLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext)
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
int nPLen = nLen, nFLen = 0;
vchPlaintext = CKeyingMaterial(nPLen);
EVP_CIPHER_CTX ctx;
bool fOk = true;
EVP_CIPHER_CTX_init(&ctx);
if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV);
if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen);
if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen);
EVP_CIPHER_CTX_cleanup(&ctx);
if (!fOk) return false;
vchPlaintext.resize(nPLen + nFLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_KEY_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE);
if(!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
|
smilecoin/smilecoin
|
src/crypter.cpp
|
C++
|
mit
| 3,991
|
import unittest
class PilhaVaziaErro(Exception):
pass
class Pilha():
def __init__(self):
self.lista=[]
def empilhar(self,valor):
self.lista.append(valor)
def vazia(self):
return not bool(self.lista)
def topo(self):
try:
return self.lista[-1]
except IndexError:
raise PilhaVaziaErro
def desempilhar(self):
if (self.lista):
return self.lista.pop(-1)
else:
raise PilhaVaziaErro
class PilhaTestes(unittest.TestCase):
def test_topo_lista_vazia(self):
pilha = Pilha()
self.assertTrue(pilha.vazia())
self.assertRaises(PilhaVaziaErro, pilha.topo)
def test_empilhar_um_elemento(self):
pilha = Pilha()
pilha.empilhar('A')
self.assertFalse(pilha.vazia())
self.assertEqual('A', pilha.topo())
def test_empilhar_dois_elementos(self):
pilha = Pilha()
pilha.empilhar('A')
pilha.empilhar('B')
self.assertFalse(pilha.vazia())
self.assertEqual('B', pilha.topo())
def test_desempilhar_pilha_vazia(self):
pilha = Pilha()
self.assertRaises(PilhaVaziaErro, pilha.desempilhar)
def test_desempilhar(self):
pilha = Pilha()
letras = 'ABCDE'
for letra in letras:
pilha.empilhar(letra)
for letra_em_ordem_reversa in reversed(letras):
letra_desempilhada = pilha.desempilhar()
self.assertEqual(letra_em_ordem_reversa, letra_desempilhada)
|
lucas2109/estruturaDados
|
pilha.py
|
Python
|
mit
| 1,546
|
<?php
namespace Matthimatiker\CommandLockingBundle\Locking;
/**
* Null implementation of a lock manager. Simulates successful locking.
*/
class NullLockManager implements LockManagerInterface
{
/**
* Obtains a lock for the provided name.
*
* The lock must be released before it can be obtained again.
*
* @param string $name
* @return boolean True if the lock was obtained, false otherwise.
*/
public function lock($name)
{
return true;
}
/**
* Releases the lock with the provided name.
*
* If the lock does not exist, then this method will do nothing.
*
* @param string $name
*/
public function release($name)
{
}
}
|
Matthimatiker/CommandLockingBundle
|
Locking/NullLockManager.php
|
PHP
|
mit
| 727
|
-- Examples from chapter 5
-- http://learnyouahaskell.com/recursion
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n-1) x
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' _ [] = []
take' n (x:xs)
| n <= 0 = []
| otherwise = x : take' (n-1) xs
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
repeat' :: a -> [a]
repeat' x = x : repeat' x
zip' :: [a] -> [b] -> [(a,b)]
zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
|
Sgoettschkes/learning
|
haskell/LearnYouAHaskell/05.hs
|
Haskell
|
mit
| 902
|
package bibliotheque;
/**
* @author Adeline Leger
*/
import bibliotheque.BibliographieSource;
import bibliotheque.Collection;
import bibliotheque.Article;
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.util.*;
public class BibliographieReader implements XMLReader{
private ContentHandler handler;
private AttributesImpl atts = new AttributesImpl();
//methode qui vont etre utilisees par le transformer
public ContentHandler getContentHandler(){
return handler;
}
public void setContentHandler(ContentHandler handler){
this.handler = handler;
}
public void parse(InputSource input) throws IOException,SAXException{
/**
* This fonction structurs the XML File
*
* @param input
* It is the bibliography
*/
if(!(input instanceof BibliographieSource)){
String m = "Le seul argument possible pour parse est une BibliographieSource";
throw new SAXException(m);
}
if(handler == null){
throw new SAXException("Pas de ContentHandler");
}
BibliographieSource source = (BibliographieSource)input;
List<Collection> collections = source.getCollections();
handler.startDocument();
handler.startElement("", "bibliography", "bibliography", atts); // Root
for(int i =0; i<collections.size(); i++){
List<Article> articles = source.getArticles1(collections.get(i));
atts.addAttribute("","name","name","",String.valueOf(collections.get(i).getName()));
handler.startElement("", "collection", "collection", atts); //Trunc
atts.clear();
for (int k=0;k < articles.size();k++){ //Branch
atts.addAttribute("","id","id","",String.valueOf(articles.get(k).getId()));
handler.startElement("", "article", "article", atts); //sheet
//System.out.println(articles.get(k).getId());
atts.clear();
handler.startElement("", "author", "author", atts);
char[] author = articles.get(k).getAuthor().toCharArray();
handler.characters(author,0,author.length);
handler.endElement("", "author", "author");
handler.startElement("", "title", "title", atts);
char[] title = articles.get(k).getTitle().toCharArray();
handler.characters(title,0,title.length);
handler.endElement("", "title", "title");
handler.startElement("", "journal", "journal", atts);
char[] journal = articles.get(k).getJournal().toCharArray();
handler.characters(journal,0,journal.length);
handler.endElement("", "journal", "journal");
handler.startElement("", "year", "year", atts);
char[] year = articles.get(k).getYear().toCharArray();
handler.characters(year,0,year.length);
handler.endElement("", "year", "year");
handler.startElement("", "number", "number", atts);
char[] number = articles.get(k).getNumber().toCharArray();
handler.characters(number,0,number.length);
handler.endElement("", "number", "number");
handler.startElement("", "pages", "pages", atts);
char[] pages = articles.get(k).getPages().toCharArray();
handler.characters(pages,0,pages.length);
handler.endElement("", "pages", "pages");
handler.startElement("", "month", "month", atts);
char[] month = articles.get(k).getMonth().toCharArray();
handler.characters(month,0,month.length);
handler.endElement("", "month", "month");
handler.startElement("", "doi", "doi", atts);
char[] doi = articles.get(k).getDoi().toCharArray();
handler.characters(doi,0,doi.length);
handler.endElement("", "doi", "doi");
handler.startElement("", "url", "url", atts);
char[] url = articles.get(k).getUrl().toCharArray();
handler.characters(url,0,url.length);
handler.endElement("", "url", "url");
handler.startElement("", "keywords", "keywords", atts);
char[] keywords = articles.get(k).getKeywords().toCharArray();
handler.characters(keywords,0,keywords.length);
handler.endElement("", "keywords", "keywords");
handler.startElement("", "abstracts", "abstracts", atts);
char[] abstracts = articles.get(k).getAbstracts().toCharArray();
handler.characters(abstracts,0,abstracts.length);
handler.endElement("", "abstracts", "abstracts");
handler.startElement("", "pdf", "pdf", atts);
char[] pdf = articles.get(k).getPdf().toCharArray();
handler.characters(pdf,0,pdf.length);
handler.endElement("", "pdf", "pdf");
char[] tag=null;
int j=0;
String[] tags=articles.get(k).getTag();
for( j=0; j<tags.length; j++ ){
handler.startElement("", "tag", "tag", atts);
tag = tags[j].toCharArray();
handler.characters(tag,0,tag.length);
handler.endElement("", "tag", "tag");
}
handler.endElement("", "article", "article");
}
handler.endElement("", "collection", "collection");
}
handler.endElement("", "bibliography", "bibliography");
handler.endDocument();
}
public void parse(String systemId) throws IOException,SAXException{
String m = "Le seul argument possible pour parse est une BibliographieSource";
throw new SAXException(m);
}
// autres methodes a implementer
public DTDHandler getDTDHandler(){
return null;
}
public EntityResolver getEntityResolver(){
return null;
}
public ErrorHandler getErrorHandler(){
return null;
}
public boolean getFeature(String name){
return false;
}
public Object getProperty(String name){
return null;
}
public void setDTDHandler(DTDHandler handler){
}
public void setEntityResolver(EntityResolver resolver){
}
public void setErrorHandler(ErrorHandler handler){
}
public void setFeature(String name, boolean value){
}
public void setProperty(String name, Object value){
}
}
|
piatf/miniproject_java
|
Application/bibliotheque/BibliographieReader.java
|
Java
|
mit
| 5,670
|
angular.module("soundipic.model", [
])
.service("model", function() {
var imageSrc,
imageData;
function srcToData(src) {
var image = new Image();
image.src = imageSrc;
var width = image.width,
height = image.height;
var canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(image, 0, 0, width, height);
return context.getImageData(0, 0, width, height);
}
function dataToSrc(data) {
var canvas = document.createElement("canvas"),
context = canvas.getContext("2d");
context.putImageData(data, 0, 0);
return canvas.toDataURL("image/jpg");
}
function getImageData() {
if (!imageSrc) {
return null;
}
}
return {
imageSrc: function(src) {
if (src) {
imageSrc = src;
imageData = srcToData(src);
}
return imageSrc;
},
imageData: function(data) {
if (data) {
imageData = data;
imageSrc = dataToSrc(data);
}
return imageData;
}
};
})
;
|
godds/soundipic
|
src/app/model.js
|
JavaScript
|
mit
| 1,115
|
version https://git-lfs.github.com/spec/v1
oid sha256:5a4b87becf4d55857fc2346606917d9c17ea96ba34d8cda9efdd44b97576c0f7
size 2824
|
yogeshsaroya/new-cdnjs
|
ajax/libs/jquery-ui-map/3.0-rc1/jquery.ui.map.services.js
|
JavaScript
|
mit
| 129
|
/**
* This header is generated by class-dump-z 0.1-11o.
* class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3.
*/
#import "UIKit-Structs.h"
#import <UIKit/UIView.h>
@interface UITabBarButtonBadge : UIView {
UIView* _value;
UIView* _background;
UIView* _alternate;
}
-(id)initWithValue:(id)value blinks:(BOOL)blinks;
-(void)dealloc;
-(CGSize)sizeThatFits:(CGSize)fits;
-(void)setValue:(id)value;
-(void)layoutSubviews;
-(void)setBlinks:(BOOL)blinks;
@end
|
codyd51/libPassword
|
libPassPrefs/include/UIKit/UITabBarButtonBadge.h
|
C
|
mit
| 481
|
//
// GameManager.h
// spaceViking_1_0_1
//
// Created by Mac Owner on 1/27/13.
//
//
#import <Foundation/Foundation.h>
#import "Constants.h"
#import "SimpleAudioEngine.h"
@interface GameManager : NSObject
{
BOOL isMusicON;
BOOL isSoundEffectsON;
BOOL hasPlayerDied;
SceneTypes currentScene;
NSUInteger counterKill;
// Added for audio
BOOL hasAudioBeenInitialized;
GameManagerSoundState managerSoundState;
SimpleAudioEngine *soundEngine;
NSMutableDictionary *listOfSoundEffectFiles;
NSMutableDictionary *soundEffectsState;
}
@property (readwrite) GameManagerSoundState managerSoundState;
@property (nonatomic, retain) NSMutableDictionary *listOfSoundEffectFiles;
@property (nonatomic, retain) NSMutableDictionary *soundEffectsState;
@property (readwrite,assign) NSUInteger counterKill;
@property (readwrite) BOOL isMusicON;
@property (readwrite) BOOL isSoundEffectsON;
@property (readwrite) BOOL hasPlayerDied;
+(GameManager*)sharedGameManager; // 1
-(void)runSceneWithID:(SceneTypes)sceneID; // 2
-(void)openSiteWithLinkType:(LinkTypes)linkTypeToOpen ;
-(void)setupAudioEngine;
-(ALuint)playSoundEffect:(NSString*)soundEffectKey;
-(void)stopSoundEffect:(ALuint)soundEffectID;
-(void)playBackgroundTrack:(NSString*)trackFileName;
-(CGSize)getDimensionsOfCurrentScene;
@end
|
gneil90/enchiridion
|
templateARC/templateARC/GameManager.h
|
C
|
mit
| 1,316
|
{% load staticfiles %}
<!-- ##JavaScript Scripts Files -->
<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>
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/jquery.js' %}"></script>
<!-- Bootstrap core JavaScript Scripts Files -->
<script src="{% static 'js/bootstrap.min.js'%}"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="{% static 'js/ie10-viewport-bug-workaround.js'%}"></script>
<!-- ##JavaScript Scripts Files END -->
|
danteio/Dante-Dev
|
templates/javascript.html
|
HTML
|
mit
| 655
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class RegisterModel extends CI_Model
{
function reg_event(){
$this->load->database();
if(isset($_POST['submit'])) {
$name = $_POST['event_name'];
$provider = $_POST['event_provider'];
$category = $_POST['category'];
$date = $_POST['e_date'];
$stime = $_POST['start_time'];
$etime = $_POST['end_time'];
$sql = $this->db->query("INSERT INTO event (event_name,event_provider,category,e_date,start_time,end_time) VALUES ('$name','$provider','$category','$date','$stime','$etime')");
return 1;
}
}
function select_table($id)
{
$this->load->database();
$result = $this->db->query("SELECT * FROM event ORDER BY event_id");
return $result;
}
}
?>
|
Gothami94/eventRegistration
|
application/models/RegisterModel.php
|
PHP
|
mit
| 813
|
/*global define*/
define({
"_widgetLabel": "Netoli manęs",
"searchHeaderText": "Ieškoti adreso arba rasti žemėlapyje",
"invalidSearchLayerMsg": "Netinkamai sukonfigūruota sluoksnių paieška",
"bufferSliderText": "Rezultatus pateikti ${BufferDistance} ${BufferUnit}",
"bufferTextboxLabel": "Rezultatus pateikti diapazone (${BufferUnit})",
"invalidBufferDistance": "Įvesta buferio atstumo reikšmė yra netinkama.",
"bufferSliderValueString": "Nurodykite atstumą, didesnį nei 0",
"unableToCreateBuffer": "Rezultatų nerasta",
"selectLocationToolTip": "Nustatyti vietą",
"noFeatureFoundText": "Nieko nerasta ",
"unableToFetchResults": "Nepavyko rasti rezultatų sluoksnyje (-iuose):",
"informationTabTitle": "Informacija",
"directionTabTitle": "Maršrutai",
"failedToGenerateRouteMsg": "Nepavyko sugeneruoti maršruto.",
"geometryServicesNotFound": "Geometrijos paslauga negalima.",
"allPopupsDisabledMsg": "Nesukonfigūruoti iškylantys langai, rezultatų pateikti negalima.",
"worldGeocoderName": "Adresas",
"searchLocationTitle": "Ieškota vieta",
"unknownAttachmentExt": "FAILAS",
"proximityButtonTooltip": "Paieška šalia",
"approximateDistanceTitle": "Apytikslis atstumas: ${DistanceToLocation}",
"toggleTip": "Spustelėkite, norėdami parodyti/paslėpti filtravimo nustatymus",
"filterTitle": "Pasirinkti taikytinus filtrus",
"clearFilterButton": "Išvalyti visus filtrus",
"bufferDistanceLabel": "Buferio atstumas",
"units": {
"miles": {
"displayText": "Mylios",
"acronym": "mi."
},
"kilometers": {
"displayText": "Kilometrai",
"acronym": "km"
},
"feet": {
"displayText": "Pėdos",
"acronym": "pėdos"
},
"meters": {
"displayText": "Metrai",
"acronym": "m"
}
}
});
|
tmcgee/cmv-wab-widgets
|
wab/2.15/widgets/NearMe/nls/lt/strings.js
|
JavaScript
|
mit
| 1,815
|
(function() {
'use strict';
angular
.module('socialprofileApp')
.provider('AlertService', AlertService);
function AlertService () {
this.toast = false;
/*jshint validthis: true */
this.$get = getService;
this.showAsToast = function(isToast) {
this.toast = isToast;
};
getService.$inject = ['$timeout', '$sce', '$translate'];
function getService ($timeout, $sce,$translate) {
var toast = this.toast,
alertId = 0, // unique id for each alert. Starts from 0.
alerts = [],
timeout = 5000; // default timeout
return {
factory: factory,
isToast: isToast,
add: addAlert,
closeAlert: closeAlert,
closeAlertByIndex: closeAlertByIndex,
clear: clear,
get: get,
success: success,
error: error,
info: info,
warning : warning
};
function isToast() {
return toast;
}
function clear() {
alerts = [];
}
function get() {
return alerts;
}
function success(msg, params, position) {
return this.add({
type: 'success',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function error(msg, params, position) {
return this.add({
type: 'danger',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function warning(msg, params, position) {
return this.add({
type: 'warning',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function info(msg, params, position) {
return this.add({
type: 'info',
msg: msg,
params: params,
timeout: timeout,
toast: toast,
position: position
});
}
function factory(alertOptions) {
var alert = {
type: alertOptions.type,
msg: $sce.trustAsHtml(alertOptions.msg),
id: alertOptions.alertId,
timeout: alertOptions.timeout,
toast: alertOptions.toast,
position: alertOptions.position ? alertOptions.position : 'top right',
scoped: alertOptions.scoped,
close: function (alerts) {
return closeAlert(this.id, alerts);
}
};
if(!alert.scoped) {
alerts.push(alert);
}
return alert;
}
function addAlert(alertOptions, extAlerts) {
alertOptions.alertId = alertId++;
alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params);
var that = this;
var alert = this.factory(alertOptions);
if (alertOptions.timeout && alertOptions.timeout > 0) {
$timeout(function () {
that.closeAlert(alertOptions.alertId, extAlerts);
}, alertOptions.timeout);
}
return alert;
}
function closeAlert(id, extAlerts) {
var thisAlerts = extAlerts ? extAlerts : alerts;
return closeAlertByIndex(thisAlerts.map(function(e) { return e.id; }).indexOf(id), thisAlerts);
}
function closeAlertByIndex(index, thisAlerts) {
return thisAlerts.splice(index, 1);
}
}
}
})();
|
josedab/yeoman-jhipster-examples
|
jhipster-300-gateway/src/main/webapp/app/components/alert/alert.service.js
|
JavaScript
|
mit
| 4,374
|
$script:dscModuleName = 'DnsServerDsc'
$script:dscResourceName = 'DSC_DnsServerRootHint'
function Invoke-TestSetup
{
try
{
Import-Module -Name DscResource.Test -Force -ErrorAction 'Stop'
}
catch [System.IO.FileNotFoundException]
{
throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -Tasks build" first.'
}
$script:testEnvironment = Initialize-TestEnvironment `
-DSCModuleName $script:dscModuleName `
-DSCResourceName $script:dscResourceName `
-ResourceType 'Mof' `
-TestType 'Unit'
Import-Module (Join-Path -Path $PSScriptRoot -ChildPath 'Stubs\DnsServer.psm1') -Force
}
function Invoke-TestCleanup
{
Restore-TestEnvironment -TestEnvironment $script:testEnvironment
}
Invoke-TestSetup
try
{
InModuleScope $script:dscResourceName {
#region Pester Test Initialization
$rootHints = @(
[PSCustomObject] @{
NameServer = @{
RecordData = @{
NameServer = 'B.ROOT-SERVERS.NET.'
}
}
IPAddress = @{
RecordData = @{
IPv4Address = @{
IPAddressToString = [IPAddress] '199.9.14.201'
}
}
}
},
[PSCustomObject] @{
NameServer = @{
RecordData = @{
NameServer = 'M.ROOT-SERVERS.NET.'
}
}
IPAddress = @{
RecordData = @{
IPv4Address = @{
IPAddressToString = [IPAddress] '202.12.27.33'
}
}
}
}
)
$rootHintsHashtable = Convert-RootHintsToHashtable -RootHints $rootHints
$rootHintsCim = ConvertTo-CimInstance -Hashtable $rootHintsHashtable
#endregion
#region Function Get-TargetResource
Describe 'DSC_DnsServerRootHint\Get-TargetResource' {
Mock -CommandName Assert-Module
It 'Returns a "System.Collections.Hashtable" object type' {
Mock -CommandName Get-DnsServerRootHint -MockWith { return $rootHints }
$targetResource = Get-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose
$targetResource -is [System.Collections.Hashtable] | Should Be $true
}
It "Returns NameServer = <PredefinedValue> when root hints exist" {
Mock -CommandName Get-DnsServerRootHint -MockWith { return $rootHints }
$targetResource = Get-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose
Test-DscDnsParameterState -CurrentValues $targetResource.NameServer -DesiredValues $rootHintsHashtable | Should -Be $true
}
It "Returns an empty NameServer when root hints don't exist" {
Mock -CommandName Get-DnsServerRootHint -MockWith { return @() }
$targetResource = Get-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose
$targetResource.NameServer.Count | Should Be 0
}
}
#endregion
#region Function Test-TargetResource
Describe 'DSC_DnsServerRootHint\Test-TargetResource' {
Mock -CommandName Assert-Module
It 'Returns a "System.Boolean" object type' {
Mock -CommandName Get-DnsServerRootHint -MockWith { return $rootHints }
$targetResource = Test-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose
$targetResource -is [System.Boolean] | Should Be $true
}
It 'Passes when forwarders match' {
Mock -CommandName Get-DnsServerRootHint -MockWith { return $rootHints }
Test-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose | Should Be $true
}
It "Fails when root hints don't match" {
Mock -CommandName Get-DnsServerRootHint -MockWith { return @{ NameServer = @() } }
Test-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose | Should Be $false
}
}
#endregion
#region Function Set-TargetResource
Describe 'DSC_DnsServerRootHint\Set-TargetResource' {
It "Calls Add-DnsServerRootHint 2 times" {
Mock -CommandName Remove-DnsServerRootHint -MockWith { }
Mock -CommandName Add-DnsServerRootHint -MockWith { }
Mock -CommandName Get-DnsServerRootHint -MockWith { }
Set-TargetResource -IsSingleInstance Yes -NameServer $rootHintsCim -Verbose
Assert-MockCalled -CommandName Add-DnsServerRootHint -Times 2 -Exactly -Scope It
}
}
} #end InModuleScope
}
finally
{
Invoke-TestCleanup
}
|
PowerShell/xDnsServer
|
tests/Unit/DSC_DnsServerRootHint.Tests.ps1
|
PowerShell
|
mit
| 5,078
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading;
using Logrila.Logging;
using Redola.ActorModel.Framing;
namespace Redola.ActorModel
{
public class CenterActorDirectory : IActorDirectory
{
private ILog _log = Logger.Get<CenterActorDirectory>();
private CenterActorDirectoryConfiguration _configuration;
private IActorChannel _centerChannel;
private readonly object _openLock = new object();
public CenterActorDirectory(CenterActorDirectoryConfiguration configuration)
{
if (configuration == null)
throw new ArgumentNullException("configuration");
_configuration = configuration;
}
public ActorIdentity CenterActor { get { return _configuration.CenterActor; } }
public ActorChannelConfiguration ChannelConfiguration { get { return _configuration.ChannelConfiguration; } }
public void Open()
{
}
public void Close()
{
lock (_openLock)
{
if (_centerChannel != null)
{
_centerChannel.Close();
_centerChannel.ChannelDataReceived -= OnCenterChannelDataReceived;
_centerChannel = null;
}
}
}
public bool Active
{
get
{
if (_centerChannel == null)
return false;
return _centerChannel.Active;
}
}
public void Register(ActorIdentity localActor)
{
if (localActor == null)
throw new ArgumentNullException("localActor");
lock (_openLock)
{
if (this.Active)
throw new InvalidOperationException(
string.Format("Center actor [{0}] has already been registered.", this.CenterActor));
_log.DebugFormat("Connecting to center actor [{0}].", this.CenterActor);
var centerChannel = BuildCenterActorChannel(localActor);
centerChannel.Open();
int retryTimes = 1;
TimeSpan retryPeriod = TimeSpan.FromMilliseconds(100);
while (true)
{
if (centerChannel.Active)
break;
Thread.Sleep(retryPeriod);
if (centerChannel.Active)
break;
retryTimes++;
if (retryTimes > 300)
{
centerChannel.Close();
throw new InvalidOperationException(
string.Format("Cannot connect to center actor [{0}] after wait [{1}] milliseconds.",
this.CenterActor, retryTimes * (int)retryPeriod.TotalMilliseconds));
}
}
_log.DebugFormat("Connected to center actor [{0}].", this.CenterActor);
_centerChannel = centerChannel;
_centerChannel.ChannelDataReceived += OnCenterChannelDataReceived;
}
}
public void Deregister(ActorIdentity localActor)
{
}
private IActorChannel BuildCenterActorChannel(ActorIdentity localActor)
{
IPAddress centerActorAddress = ResolveIPAddress(this.CenterActor.Address);
int centerActorPort = -1;
if (!int.TryParse(this.CenterActor.Port, out centerActorPort) || centerActorPort < 0)
throw new InvalidOperationException(string.Format(
"Invalid center actor port, [{0}].", this.CenterActor));
var centerActorEndPoint = new IPEndPoint(centerActorAddress, centerActorPort);
var centerConnector = new ActorTransportConnector(centerActorEndPoint, this.ChannelConfiguration.TransportConfiguration);
var centerChannel = new ActorConnectorReconnectableChannel(
localActor, centerConnector, this.ChannelConfiguration);
return centerChannel;
}
private void OnCenterChannelDataReceived(object sender, ActorChannelDataReceivedEventArgs e)
{
ActorFrameHeader actorChangeNotificationFrameHeader = null;
bool isHeaderDecoded = this.ChannelConfiguration.FrameBuilder.TryDecodeFrameHeader(
e.Data, e.DataOffset, e.DataLength,
out actorChangeNotificationFrameHeader);
if (isHeaderDecoded && actorChangeNotificationFrameHeader.OpCode == OpCode.Change)
{
byte[] payload;
int payloadOffset;
int payloadCount;
this.ChannelConfiguration.FrameBuilder.DecodePayload(
e.Data, e.DataOffset, actorChangeNotificationFrameHeader,
out payload, out payloadOffset, out payloadCount);
var actorChangeNotificationData = this.ChannelConfiguration.FrameBuilder.ControlFrameDataDecoder.DecodeFrameData<ActorIdentityCollection>(
payload, payloadOffset, payloadCount);
var actors = actorChangeNotificationData != null ? actorChangeNotificationData.Items : null;
if (actors != null && actors.Any())
{
_log.DebugFormat("Actor changed, ActorType[{0}], AvailableCount[{1}].", actors.First().Type, actors.Count);
RaiseActorsChanged(actors);
}
}
}
public IPEndPoint LookupRemoteActorEndPoint(string actorType, string actorName)
{
if (string.IsNullOrEmpty(actorType))
throw new ArgumentNullException("actorType");
if (string.IsNullOrEmpty(actorName))
throw new ArgumentNullException("actorName");
var endpoints = LookupRemoteActorEndPoints(
actorType,
(actors) =>
{
return actors.Where(a => a.Type == actorType && a.Name == actorName);
});
if (endpoints == null || endpoints.Count() == 0)
throw new ActorNotFoundException(string.Format(
"Cannot lookup remote actor, Type[{0}], Name[{1}].", actorType, actorName));
if (endpoints.Count() > 1)
throw new ActorNotFoundException(string.Format(
"Duplicate remote actor found, Type[{0}], Name[{1}].", actorType, actorName));
return endpoints.Single();
}
public IEnumerable<IPEndPoint> LookupRemoteActorEndPoints(string actorType)
{
if (string.IsNullOrEmpty(actorType))
throw new ArgumentNullException("actorType");
var endpoints = LookupRemoteActorEndPoints(
actorType,
(actors) =>
{
return actors.Where(a => a.Type == actorType);
});
if (endpoints == null || !endpoints.Any())
throw new ActorNotFoundException(string.Format(
"Cannot lookup remote actor, Type[{0}].", actorType));
return endpoints;
}
public IEnumerable<ActorIdentity> LookupRemoteActors(string actorType)
{
if (string.IsNullOrEmpty(actorType))
throw new ArgumentNullException("actorType");
var remoteActors = LookupRemoteActors(
actorType,
(actors) =>
{
return actors.Where(a => a.Type == actorType);
});
if (remoteActors == null || !remoteActors.Any())
throw new ActorNotFoundException(string.Format(
"Cannot lookup remote actor, Type[{0}].", actorType));
return remoteActors;
}
private IEnumerable<IPEndPoint> LookupRemoteActorEndPoints(string actorType, Func<IEnumerable<ActorIdentity>, IEnumerable<ActorIdentity>> matchActorFunc)
{
var remoteActors = LookupRemoteActors(actorType, matchActorFunc);
if (remoteActors != null && remoteActors.Any())
{
return remoteActors.Select(a => ConvertActorToEndPoint(a));
}
return null;
}
private IEnumerable<ActorIdentity> LookupRemoteActors(string actorType, Func<IEnumerable<ActorIdentity>, IEnumerable<ActorIdentity>> matchActorFunc)
{
var actorLookupCondition = new ActorIdentityLookup()
{
Type = actorType,
};
var actorLookupRequestData = this.ChannelConfiguration.FrameBuilder.ControlFrameDataEncoder.EncodeFrameData(actorLookupCondition);
var actorLookupRequest = new WhereFrame(actorLookupRequestData);
var actorLookupRequestBuffer = this.ChannelConfiguration.FrameBuilder.EncodeFrame(actorLookupRequest);
ManualResetEventSlim waitingResponse = new ManualResetEventSlim(false);
ActorChannelDataReceivedEventArgs lookupResponseEvent = null;
EventHandler<ActorChannelDataReceivedEventArgs> onDataReceived =
(s, e) =>
{
lookupResponseEvent = e;
waitingResponse.Set();
};
_centerChannel.ChannelDataReceived += onDataReceived;
_centerChannel.BeginSend(_centerChannel.Identifier, actorLookupRequestBuffer);
bool lookedup = waitingResponse.Wait(TimeSpan.FromSeconds(15));
_centerChannel.ChannelDataReceived -= onDataReceived;
waitingResponse.Dispose();
if (lookedup && lookupResponseEvent != null)
{
ActorFrameHeader actorLookupResponseFrameHeader = null;
bool isHeaderDecoded = this.ChannelConfiguration.FrameBuilder.TryDecodeFrameHeader(
lookupResponseEvent.Data, lookupResponseEvent.DataOffset, lookupResponseEvent.DataLength,
out actorLookupResponseFrameHeader);
if (isHeaderDecoded && actorLookupResponseFrameHeader.OpCode == OpCode.Here)
{
byte[] payload;
int payloadOffset;
int payloadCount;
this.ChannelConfiguration.FrameBuilder.DecodePayload(
lookupResponseEvent.Data, lookupResponseEvent.DataOffset, actorLookupResponseFrameHeader,
out payload, out payloadOffset, out payloadCount);
var actorLookupResponseData = this.ChannelConfiguration.FrameBuilder.ControlFrameDataDecoder.DecodeFrameData<ActorIdentityCollection>(
payload, payloadOffset, payloadCount);
var actors = actorLookupResponseData != null ? actorLookupResponseData.Items : null;
if (actors != null)
{
_log.DebugFormat("Lookup actors, ActorType[{0}], Count[{1}].", actorType, actors.Count);
var matchedActors = matchActorFunc(actors);
if (matchedActors != null && matchedActors.Any())
{
_log.DebugFormat("Resolve actors, ActorType[{0}], Count[{1}].", actorType, matchedActors.Count());
return matchedActors;
}
}
}
}
return null;
}
private IPAddress ResolveIPAddress(string host)
{
IPAddress remoteIPAddress = null;
IPAddress ipAddress;
if (IPAddress.TryParse(host, out ipAddress))
{
remoteIPAddress = ipAddress;
}
else
{
if (host.ToLowerInvariant() == "localhost")
{
remoteIPAddress = IPAddress.Parse(@"127.0.0.1");
}
else
{
IPAddress[] addresses = Dns.GetHostAddresses(host);
if (addresses.Any())
{
remoteIPAddress = addresses.First();
}
else
{
throw new InvalidOperationException(
string.Format("Cannot resolve host [{0}] from DNS.", host));
}
}
}
return remoteIPAddress;
}
private IPEndPoint ConvertActorToEndPoint(ActorIdentity actor)
{
var actorAddress = ResolveIPAddress(actor.Address);
int actorPort = int.Parse(actor.Port);
return new IPEndPoint(actorAddress, actorPort);
}
public event EventHandler<ActorsChangedEventArgs> ActorsChanged;
private void RaiseActorsChanged(IEnumerable<ActorIdentity> actors)
{
if (ActorsChanged != null)
{
ActorsChanged(this, new ActorsChangedEventArgs(actors));
}
}
}
}
|
gaochundong/Redola
|
Redola/Redola.ActorModel/Actor/Directory/CenterActorDirectory/CenterActorDirectory.cs
|
C#
|
mit
| 13,272
|
/* Searcher.cpp
*
* Kubo Ryosuke
*/
#include "Searcher.h"
#include "tree/Worker.h"
#include "tree/NodeStat.h"
#include "see/See.h"
#include "core/def.h"
#include "core/move/MoveGenerator.h"
#include "logger/Logger.h"
#include <iomanip>
#include <algorithm>
#include <cmath>
#define ENABLE_HIST_REUSE 1
#define ENABLE_LMR 1
#define ENABLE_SMOOTH_FUT 1
#define ENABLE_RAZORING 1
#define ENABLE_MOVE_COUNT_PRUNING 1
#define ENABLE_PROBCUT 1
#define ENABLE_HASH_MOVE 1
#define ENABLE_KILLER_MOVE 1
#define ENABLE_SHEK 1
#define ENABLE_MATE_1PLY 1
#define ENABLE_MATE_3PLY 1
#define ENABLE_MATE_HISTORY 1
#define ENABLE_STORE_PV 1
#define ENABLE_SINGULAR_EXTENSION 1
#define SHALLOW_SEE 0 // should be 0
#define ENABLE_MOVE_COUNT_EXPT 0
#define ENABLE_FUT_EXPT 0
#define ENABLE_RAZOR_EXPT 0
#define ENABLE_PROBCUT_EXPT 0
#define ENABLE_MATE_HIST_EXPT 0
#define ENABLE_ROOT_MOVES_SHUFFLE 0
// debugging flags
#define DEBUG_ROOT_MOVES 0
#define DEBUG_TREE 0
#define DEBUG_NODE 0
#define ITERATE_INFO_THRESHOLD 3 // must be greater than or equal to 2
#if ENABLE_MATE_3PLY && !ENABLE_MATE_1PLY
# error
#endif
namespace {
CONSTEXPR_CONST int MAIN_TREEID = 0;
CONSTEXPR_CONST int MAIN_WORKER_ID = 0;
} // namespace
namespace sunfish {
namespace expt {
class PruningCounter {
uint64_t succ_[64];
uint64_t fail_[64];
int index(int depth) const {
return std::min(std::max(depth / Searcher::Depth1Ply, 0), 64);
}
public:
void clear() {
memset(succ_, 0, sizeof(succ_));
memset(fail_, 0, sizeof(fail_));
}
void succ(int depth) {
succ_[index(depth)]++;
}
void fail(int depth) {
fail_[index(depth)]++;
}
uint64_t succ(int depth) const {
return succ_[index(depth)];
}
uint64_t fail(int depth) const {
return fail_[index(depth)];
}
void print() const {
for (int i = 0; i < 64; i++) {
uint64_t s = succ_[i];
uint64_t f = fail_[i];
if (s != 0 || f != 0) {
float r = (float)f / (s + f) * 100.0;
Loggers::warning << " " << i << ": " << f << "/" << (s+f) << " (" << r << "%)";
}
}
}
};
#if ENABLE_MOVE_COUNT_EXPT
uint64_t count_sum;
uint64_t count_num;
PruningCounter move_count_based_pruning;
#endif
#if ENABLE_FUT_EXPT
PruningCounter futility_pruning;
#endif
#if ENABLE_RAZOR_EXPT
PruningCounter razoring;
#endif
#if ENABLE_PROBCUT_EXPT
PruningCounter probcut;
#endif
#if ENABLE_MATE_HIST_EXPT
PruningCounter mate_hist;
PruningCounter mate_hist_n;
#endif
} // namespace expt
namespace search_param {
#if ENABLE_SMOOTH_FUT
CONSTEXPR_CONST int FUT_DEPTH = Searcher::Depth1Ply * 9;
#else
CONSTEXPR_CONST int FUT_DEPTH = Searcher::Depth1Ply * 3;
#endif
CONSTEXPR_CONST int EXT_CHECK = Searcher::Depth1Ply;
CONSTEXPR_CONST int EXT_ONEREP = Searcher::Depth1Ply * 1 / 2;
CONSTEXPR_CONST int EXT_RECAP = Searcher::Depth1Ply * 1 / 4;
CONSTEXPR_CONST int EXT_RECAP2 = Searcher::Depth1Ply * 1 / 2;
CONSTEXPR_CONST int REC_THRESHOLD = Searcher::Depth1Ply * 3;
CONSTEXPR_CONST int RAZOR_DEPTH = Searcher::Depth1Ply * 4;
CONSTEXPR_CONST int QUIES_RELIEVE_PLY = 7;
}
namespace search_func {
inline int recDepth(int depth) {
return (depth < Searcher::Depth1Ply * 9 / 2 ?
Searcher::Depth1Ply * 3 / 2 :
depth - Searcher::Depth1Ply * 3);
}
inline int nullDepth(int depth) {
return (depth < Searcher::Depth1Ply * 26 / 4 ? depth - Searcher::Depth1Ply * 12 / 4 :
(depth <= Searcher::Depth1Ply * 30 / 4 ? Searcher::Depth1Ply * 14 / 4 : depth - Searcher::Depth1Ply * 16 / 4));
}
inline int futilityMargin(int depth, int count) {
#if ENABLE_SMOOTH_FUT
return (depth < Searcher::Depth1Ply * 3 ? 400 :
140 / Searcher::Depth1Ply * std::max(depth, 0)) - 8 * count;
#else
return 400 - 8 * count;
#endif
}
inline int razorMargin(int depth) {
return 256 + 64 / Searcher::Depth1Ply * std::max(depth, 0);
}
inline int futilityMoveCounts(bool improving, int depth) {
int d = depth + (improving ? Searcher::Depth1Ply * 1 / 4 : 0);
int x = (d * d) / (Searcher::Depth1Ply * Searcher::Depth1Ply);
int a = improving ? 9 : 6;
return 2 + x * a / 10;
}
inline uint64_t excludedHash(const Move& move) {
CONSTEXPR_CONST uint64_t key = 0xc7ebffd8801628a7llu;
uint32_t m = Move::serialize(move);
return key ^ m;
}
}
/**
* コンストラクタ
*/
Searcher::Searcher()
: trees_(nullptr)
, workers_(nullptr)
, forceInterrupt_(false)
, isRunning_(false) {
initConfig();
history_.init();
}
/**
* コンストラクタ
*/
Searcher::Searcher(Evaluator& eval)
: trees_(nullptr)
, workers_(nullptr)
, eval_(eval)
, forceInterrupt_(false)
, isRunning_(false) {
initConfig();
history_.init();
}
/**
* デストラクタ
*/
Searcher::~Searcher() {
releaseTrees();
releaseWorkers();
}
/**
* tree の確保
*/
void Searcher::allocateTrees() {
if (trees_ == nullptr) {
trees_ = new Tree[config_.treeSize];
}
}
/**
* worker の確保
*/
void Searcher::allocateWorkers() {
if (workers_ == nullptr) {
workers_ = new Worker[config_.workerSize];
}
}
/**
* tree の再確保
*/
void Searcher::reallocateTrees() {
if (trees_ != nullptr) {
delete[] trees_;
}
trees_ = new Tree[config_.treeSize];
}
/**
* worker の再確保
*/
void Searcher::reallocateWorkers() {
if (workers_ != nullptr) {
delete[] workers_;
}
workers_ = new Worker[config_.workerSize];
}
/**
* tree の解放
*/
void Searcher::releaseTrees() {
if (trees_ != nullptr) {
delete[] trees_;
trees_ = nullptr;
}
}
/**
* worker の解放
*/
void Searcher::releaseWorkers() {
if (workers_ != nullptr) {
delete[] workers_;
workers_ = nullptr;
}
}
/**
* worker の取得
*/
Worker& Searcher::getWorker(Tree& tree) {
return workers_[tree.getTlp().workerId];
}
void Searcher::mergeInfo() {
memset(&info_, 0, sizeof(SearchInfoBase));
for (int id = 0; id < config_.workerSize; id++) {
auto& worker = workers_[id];
info_.failHigh += worker.info.failHigh;
info_.failHighFirst += worker.info.failHighFirst;
info_.failHighIsHash += worker.info.failHighIsHash;
info_.failHighIsKiller1 += worker.info.failHighIsKiller1;
info_.failHighIsKiller2 += worker.info.failHighIsKiller2;
info_.hashProbed += worker.info.hashProbed;
info_.hashHit += worker.info.hashHit;
info_.hashExact += worker.info.hashExact;
info_.hashLower += worker.info.hashLower;
info_.hashUpper += worker.info.hashUpper;
info_.hashStore += worker.info.hashStore;
info_.hashNew += worker.info.hashNew;
info_.hashUpdate += worker.info.hashUpdate;
info_.hashCollision += worker.info.hashCollision;
info_.hashReject += worker.info.hashReject;
info_.mateProbed += worker.info.mateProbed;
info_.mateHit += worker.info.mateHit;
info_.expand += worker.info.expand;
info_.expandHashMove += worker.info.expandHashMove;
info_.shekProbed += worker.info.shekProbed;
info_.shekSuperior += worker.info.shekSuperior;
info_.shekInferior += worker.info.shekInferior;
info_.shekEqual += worker.info.shekEqual;
info_.nullMovePruning += worker.info.nullMovePruning;
info_.nullMovePruningTried += worker.info.nullMovePruningTried;
info_.futilityPruning += worker.info.futilityPruning;
info_.extendedFutilityPruning += worker.info.extendedFutilityPruning;
info_.moveCountPruning += worker.info.moveCountPruning;
info_.razoring += worker.info.razoring;
info_.razoringTried += worker.info.razoringTried;
info_.probcut += worker.info.probcut;
info_.probcutTried += worker.info.probcutTried;
info_.singular += worker.info.singular;
info_.singularChecked += worker.info.singularChecked;
info_.expanded += worker.info.expanded;
info_.checkExtension += worker.info.checkExtension;
info_.onerepExtension += worker.info.onerepExtension;
info_.recapExtension += worker.info.recapExtension;
info_.split += worker.info.split;
info_.node += worker.info.node;
info_.qnode += worker.info.qnode;
}
}
/**
* 前処理
*/
void Searcher::before(const Board& initialBoard, bool fastStart) {
#if ENABLE_MOVE_COUNT_EXPT
expt::move_count_based_pruning.clear();
#endif
#if ENABLE_FUT_EXPT
expt::futility_pruning.clear();
#endif
#if ENABLE_RAZOR_EXPT
expt::razoring.clear();
#endif
#if ENABLE_PROBCUT_EXPT
expt::probcut.clear();
#endif
#if ENABLE_MATE_HIST_EXPT
expt::mate_hist.clear();
expt::mate_hist_n.clear();
#endif
if (isRunning_.load()) {
Loggers::error << __FILE_LINE__ << ": Searcher is already running!!!";
}
allocateTrees();
allocateWorkers();
// tree の初期化
for (int id = 0; id < config_.treeSize; id++) {
auto& tree = trees_[id];
tree.init(id, initialBoard, eval_, record_);
}
idleTreeCount_.store(config_.treeSize - 1);
// worker の初期化
for (int id = 0; id < config_.workerSize; id++) {
auto& worker = workers_[id];
worker.init(id, this);
if (id != MAIN_WORKER_ID) {
worker.startOnChildThread();
}
}
idleWorkerCount_.store(config_.workerSize - 1);
// 最初の tree を確保
auto& tree0 = trees_[MAIN_TREEID];
auto& worker0 = workers_[MAIN_WORKER_ID];
tree0.use(MAIN_WORKER_ID);
worker0.startOnCurrentThread(MAIN_TREEID);
// timer 初期化
timer_.set();
forceInterrupt_.store(false);
isRunning_.store(true);
timeManager_.init();
if (fastStart) {
return;
}
// transposition table
tt_.evolve(); // 世代更新
// hisotory heuristic
#if ENABLE_HIST_REUSE
history_.reduce();
#else
history_.init();
#endif
// mate
mateHistory_.clear();
// gains
gains_.clear();
}
/**
* 後処理
*/
void Searcher::after() {
#if ENABLE_MOVE_COUNT_EXPT
Loggers::warning << "move count based pruning:";
expt::move_count_based_pruning.print();
#endif
#if ENABLE_FUT_EXPT
Loggers::warning << "futility pruning:";
expt::futility_pruning.print();
#endif
#if ENABLE_RAZOR_EXPT
Loggers::warning << "razoring:";
expt::razoring.print();
#endif
#if ENABLE_PROBCUT_EXPT
Loggers::warning << "probcut:";
expt::probcut.print();
#endif
#if ENABLE_MATE_HIST_EXPT
Loggers::warning << "mate history:";
expt::mate_hist.print();
Loggers::warning << "mate history (n):";
expt::mate_hist_n.print();
#endif
if (!isRunning_.load()) {
Loggers::error << __FILE_LINE__ << ": Searcher is not running???";
}
// worker の停止
for (int id = 1; id < config_.workerSize; id++) {
auto& worker = workers_[id];
if (config_.threadPooling) {
worker.sleep();
} else {
worker.stop();
}
}
// tree の解放
for (int id = 0; id < config_.treeSize; id++) {
auto& tree = trees_[id];
tree.release(record_);
}
// 探索情報集計
mergeInfo();
// 探索情報収集
auto& tree0 = trees_[0];
info_.time = timer_.get();
info_.nps = (info_.node + info_.qnode) / info_.time;
info_.move = tree0.getPV().get(0).move;
info_.pv.copy(tree0.getPV());
isRunning_.store(false);
forceInterrupt_.store(false);
}
std::string Searcher::getInfoString() const {
auto format = [](int64_t value) {
std::ostringstream oss;
oss << std::setw(8) << (value);
return oss.str();
};
auto format2 = [](int64_t value, int64_t total) {
std::ostringstream oss;
oss << std::setw(8) << (value) << '/' << std::setw(8) << (total)
<< " (" << std::setw(5) << std::fixed << std::setprecision(1)<< ((float)(value) / ((total)!=0?(total):1) * 100.0) << "%)";
return oss.str();
};
std::vector<std::pair<std::string, std::string>> lines;
lines.emplace_back("nodes ", format (info_.node));
lines.emplace_back("quies-nodes ", format (info_.qnode));
lines.emplace_back("all-nodes ", format ((info_.node + info_.qnode)));
lines.emplace_back("time ", format (info_.time));
lines.emplace_back("nps ", format (std::ceil(info_.nps)));
lines.emplace_back("eval ", format (info_.eval.int32()));
lines.emplace_back("split ", format (info_.split));
lines.emplace_back("fail high first", format2(info_.failHighFirst, info_.failHigh));
lines.emplace_back("fail high hash ", format2(info_.failHighIsHash, info_.failHigh));
lines.emplace_back("fail high kill1", format2(info_.failHighIsKiller1, info_.failHigh));
lines.emplace_back("fail high kill2", format2(info_.failHighIsKiller2, info_.failHigh));
lines.emplace_back("expand hash ", format2(info_.expandHashMove, info_.expand));
lines.emplace_back("hash hit ", format2(info_.hashHit, info_.hashProbed));
lines.emplace_back("hash extract ", format2(info_.hashExact, info_.hashProbed));
lines.emplace_back("hash lower ", format2(info_.hashLower, info_.hashProbed));
lines.emplace_back("hash upper ", format2(info_.hashUpper, info_.hashProbed));
lines.emplace_back("hash new ", format2(info_.hashNew, info_.hashStore));
lines.emplace_back("hash update ", format2(info_.hashUpdate, info_.hashStore));
lines.emplace_back("hash collide ", format2(info_.hashCollision, info_.hashStore));
lines.emplace_back("hash reject ", format2(info_.hashReject, info_.hashStore));
lines.emplace_back("mate hit ", format2(info_.mateHit, info_.mateProbed));
lines.emplace_back("shek superior ", format2(info_.shekSuperior, info_.shekProbed));
lines.emplace_back("shek inferior ", format2(info_.shekInferior, info_.shekProbed));
lines.emplace_back("shek equal ", format2(info_.shekEqual, info_.shekProbed));
lines.emplace_back("null mv pruning", format2(info_.nullMovePruning, info_.nullMovePruningTried));
lines.emplace_back("fut pruning ", format (info_.futilityPruning));
lines.emplace_back("ext fut pruning", format (info_.extendedFutilityPruning));
lines.emplace_back("mov cnt pruning", format (info_.moveCountPruning));
lines.emplace_back("razoring ", format2(info_.razoring, info_.razoringTried));
lines.emplace_back("probcut ", format2(info_.probcut, info_.probcutTried));
lines.emplace_back("singular ", format2(info_.singular, info_.singularChecked));
lines.emplace_back("check extension", format2(info_.checkExtension, info_.expanded));
lines.emplace_back("1rep extension ", format2(info_.onerepExtension, info_.expanded));
lines.emplace_back("recap extension", format2(info_.recapExtension, info_.expanded));
const int columns = 2;
int rows = (lines.size() + columns - 1) / columns;
int maxLength[columns];
memset(maxLength, 0, sizeof(int) * columns);
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
int index = column * rows + row;
if (index >= (int)lines.size()) { continue; }
int length = lines[index].first.length() + lines[index].second.length();
maxLength[column] = std::max(maxLength[column], length);
}
}
std::ostringstream oss;
oss << "Search Info:\n";
for (int row = 0; row < rows; row++) {
oss << " ";
for (int column = 0; column < columns; column++) {
int index = column * rows + row;
if (index >= (int)lines.size()) { continue; }
int length = lines[index].first.length() + lines[index].second.length();
int padding = maxLength[column] - length + 1;
oss << " * " << lines[index].first << ":" << lines[index].second;
bool isLastColumn = column == columns - 1;
if (isLastColumn) { break; }
for (int i = 0; i < padding; i++) {
oss << ' ';
}
}
oss << '\n';
}
return oss.str();
}
/**
* SHEK と千日手検出のための過去の棋譜をクリアします。
*/
void Searcher::clearRecord() {
record_.clear();
}
/**
* SHEK と千日手検出のために過去の棋譜をセットします。
*/
void Searcher::setRecord(const Record& record) {
for (unsigned i = 0; i < record.getCount(); i++) {
record_.push_back(record.getMoveAt(i));
}
}
/**
* 探索中断判定
*/
inline bool Searcher::isInterrupted(Tree& tree) {
if (tree.getTlp().shutdown.load()) {
}
if (forceInterrupt_.load()) {
return true;
}
if (config_.enableLimit && timer_.get() >= config_.limitSeconds) {
return true;
}
return false;
}
/**
* 探索を強制的に打ち切ります。
*/
void Searcher::forceInterrupt() {
forceInterrupt_.store(true);
}
/**
* get see value
*/
template <bool shallow>
Value Searcher::searchSee(const Board& board, const Move& move, Value alpha, Value beta) {
See see;
return see.search<shallow>(board, move, alpha, beta);
}
/**
* sort moves by see
*/
void Searcher::sortSee(Tree& tree, int offset, Value standPat, Value alpha, bool enableKiller, bool estimate, bool exceptSmallCapture, bool isQuies) {
const auto& board = tree.getBoard();
auto& node = tree.getCurrentNode();
auto& worker = getWorker(tree);
#if !ENABLE_KILLER_MOVE
assert(node.killer1.isEmpty());
assert(node.killer2.isEmpty());
#endif // ENABLE_KILLER_MOVE
assert(offset == 0 || offset == 1);
assert(tree.getNextMove() + offset <= tree.getEnd());
if (enableKiller) {
node.capture1 = Move::empty();
node.capture2 = Move::empty();
node.cvalue1 = -Value::Inf;
node.cvalue2 = -Value::Inf;
}
for (auto ite = tree.getNextMove() + offset; ite != tree.getEnd(); ) {
const Move& move = *ite;
Value value;
if (exceptSmallCapture) {
auto captured = tree.getBoard().getBoardPiece(move.to()).kindOnly();
if ((captured == Piece::Pawn && !move.promote()) ||
(captured.isEmpty() && move.piece() != Piece::Pawn)) {
ite = tree.getMoves().remove(ite);
continue;
}
}
if (isQuies) {
// futility pruning
if (standPat + tree.estimate(move, eval_) + gains_.get(move) <= alpha) {
worker.info.futilityPruning++;
ite = tree.getMoves().remove(ite);
continue;
}
}
#if SHALLOW_SEE
value = searchSee<true>(board, move, -1, Value::PieceInf);
#else
value = searchSee<false>(board, move, -1, Value::PieceInf);
#endif
if (estimate) {
value += tree.estimate<true>(move, eval_);
}
if (enableKiller) {
if (value > node.cvalue1) {
node.capture2 = node.capture1;
node.cvalue2 = node.cvalue1;
node.capture1 = move;
node.cvalue1 = value;
} else if (value > node.cvalue2) {
node.capture2 = move;
node.cvalue2 = value;
}
}
if (!isQuies) {
if ((node.expStat & HashDone) && move == node.hash) {
ite = tree.getMoves().remove(ite);
continue;
}
}
if (enableKiller) {
if (move == node.killer1) {
node.expStat |= Killer1Added;
auto captured = board.getBoardPiece(move.to());
Value kvalue = tree.getKiller1Value() + material::pieceExchange(captured);
value = Value::max(value, kvalue);
} else if (move == node.killer2) {
node.expStat |= Killer2Added;
auto captured = board.getBoardPiece(move.to());
Value kvalue = tree.getKiller2Value() + material::pieceExchange(captured);
value = Value::max(value, kvalue);
}
}
tree.setSortValue(ite, value.int32());
ite++;
}
if (enableKiller) {
if (!(node.expStat & Killer1Added) && node.killer1 != node.hash
&& tree.getKiller1Value() >= Value::Zero
&& board.isValidMoveStrict(node.killer1)) {
node.expStat |= Killer1Added;
auto ite = tree.addMove(node.killer1);
Value kvalue = tree.getKiller1Value();
tree.setSortValue(ite, kvalue.int32());
}
if (!(node.expStat & Killer2Added) && node.killer2 != node.hash
&& tree.getKiller2Value() >= Value::Zero
&& board.isValidMoveStrict(node.killer2)) {
node.expStat |= Killer2Added;
auto ite = tree.addMove(node.killer2);
Value kvalue = tree.getKiller2Value();
tree.setSortValue(ite, kvalue.int32());
}
}
tree.sortAfterCurrent(offset);
if (isQuies) {
for (auto ite = tree.getNextMove() + offset; ite != tree.getEnd(); ite++) {
if (tree.getSortValue(ite) < 0) {
tree.removeAfter(ite);
break;
}
}
}
}
/**
* except prior moves
*/
void Searcher::exceptPriorMoves(Tree& tree) {
auto& node = tree.getCurrentNode();
#if !ENABLE_KILLER_MOVE
assert(node.killer1.isEmpty());
assert(node.killer2.isEmpty());
#endif // ENABLE_KILLER_MOVE
for (auto ite = tree.getNextMove(); ite != tree.getEnd(); ) {
const Move& move = *ite;
if ((node.expStat & HashDone) && move == node.hash) {
ite = tree.getMoves().remove(ite);
continue;
}
if (((node.expStat & Killer1Done) && move == node.killer1) ||
((node.expStat & Killer2Done) && move == node.killer2)) {
ite = tree.getMoves().remove(ite);
continue;
}
ite++;
}
}
/**
* pick best move by history
*/
bool Searcher::pickOneHistory(Tree& tree) {
Moves::iterator best = tree.getEnd();
uint32_t bestValue = 0;
for (auto ite = tree.getNextMove(); ite != tree.getEnd(); ) {
const Move& move = *ite;
auto key = History::getKey(move);
auto data = history_.getData(key);
auto value = History::getRatio(data);
if (value > bestValue) {
best = ite;
bestValue = value;
}
ite++;
}
if (best != tree.getEnd()) {
Move temp = *tree.getNextMove();
*tree.getNextMove() = *best;
*best = temp;
return true;
}
return false;
}
/**
* sort moves by history
*/
void Searcher::sortHistory(Tree& tree) {
for (auto ite = tree.getNextMove(); ite != tree.getEnd(); ) {
const Move& move = *ite;
auto key = History::getKey(move);
auto data = history_.getData(key);
auto ratio = History::getRatio(data);
tree.setSortValue(ite, (int32_t)ratio);
ite++;
}
tree.sortAfterCurrent();
}
/**
* update history
*/
void Searcher::updateHistory(Tree& tree, int depth, const Move& move) {
CONSTEXPR_CONST int HistPerDepth = 8;
int value = std::max(depth * HistPerDepth / Depth1Ply, 1);
const auto& moves = tree.getCurrentNode().histMoves;
for (auto ite = moves.begin(); ite != moves.end(); ite++) {
assert(ite != tree.getEnd());
auto key = History::getKey(*ite);
if (ite->equals(move)) {
history_.add(key, value, value);
} else {
history_.add(key, value, 0);
}
}
}
/**
* get LMR depth
*/
int Searcher::getReductionDepth(bool improving, int depth, int count, const Move& move, bool isNullWindow) {
auto key = History::getKey(move);
auto data = history_.getData(key);
auto good = History::getGoodCount(data) + 1;
auto appear = History::getAppearCount(data) + 2;
assert(good < appear);
int reduced = 0;
if (!isNullWindow) {
if (good * 20 < appear) {
reduced += Depth1Ply * 3 / 2;
} else if (good * 7 < appear) {
reduced += Depth1Ply * 2 / 2;
} else if (good * 3 < appear) {
reduced += Depth1Ply * 1 / 2;
}
} else {
if (good * 10 < appear) {
reduced += Depth1Ply * 4 / 2;
} else if (good * 6 < appear) {
reduced += Depth1Ply * 3 / 2;
} else if (good * 4 < appear) {
reduced += Depth1Ply * 2 / 2;
} else if (good * 2 < appear) {
reduced += Depth1Ply * 1 / 2;
}
}
if (!improving && depth < Depth1Ply * 9) {
if (count >= 24) {
reduced += Depth1Ply * 4 / 2;
} else if (count >= 18) {
reduced += Depth1Ply * 3 / 2;
} else if (count >= 12) {
reduced += Depth1Ply * 2 / 2;
} else if (count >= 6) {
reduced += Depth1Ply * 1 / 2;
}
}
return reduced;
}
/**
* get next move
*/
bool Searcher::nextMove(Tree& tree) {
auto& moves = tree.getMoves();
auto& node = tree.getCurrentNode();
auto& worker = getWorker(tree);
const auto& board = tree.getBoard();
while (true) {
if (!tree.isThroughPhase() && tree.getNextMove() != tree.getEnd()) {
tree.selectNextMove();
node.count++;
const Move& move = *tree.getCurrentMove();
if (move == node.hash) {
node.expStat |= HashDone;
} else if (move == node.killer1) {
node.expStat |= Killer1Done;
} else if (move == node.killer2) {
node.expStat |= Killer2Done;
} else if (move == node.capture1) {
node.expStat |= Capture1Done;
} else if (move == node.capture2) {
node.expStat |= Capture2Done;
}
return true;
}
switch (node.genPhase) {
case GenPhase::Hash:
{
Move hashMove = node.hash;
if (!hashMove.isEmpty() && board.isValidMoveStrict(hashMove)) {
tree.addMove(hashMove);
tree.setThroughPhase(true);
worker.info.expandHashMove++;
}
node.genPhase = GenPhase::Capture;
}
break;
case GenPhase::Capture:
tree.setThroughPhase(false);
if (tree.isChecking()) {
int offset = moves.end() - tree.getNextMove();
MoveGenerator::generateEvasion(board, moves);
sortSee(tree, offset, Value::Zero, Value::Zero, false, true, false, false);
node.genPhase = GenPhase::End;
break;
} else {
int offset = moves.end() - tree.getNextMove();
MoveGenerator::generateCap(board, moves);
sortSee(tree, offset, Value::Zero, Value::Zero, true, false, false, false);
node.genPhase = GenPhase::History1;
break;
}
case GenPhase::History1:
node.count = 0;
MoveGenerator::generateNoCap(board, moves);
MoveGenerator::generateDrop(board, moves);
exceptPriorMoves(tree);
node.genPhase = GenPhase::History2;
tree.setThroughPhase(true);
if (pickOneHistory(tree)) {
tree.selectNextMove();
return true;
}
break;
case GenPhase::History2:
node.genPhase = GenPhase::Misc;
tree.setThroughPhase(true);
if (pickOneHistory(tree)) {
tree.selectNextMove();
return true;
}
break;
case GenPhase::Misc:
sortHistory(tree);
node.genPhase = GenPhase::End;
tree.setThroughPhase(false);
break;
case GenPhase::CaptureOnly:
assert(false);
case GenPhase::End:
return false;
}
}
}
/**
* get next move
*/
bool Searcher::nextMoveQuies(Tree& tree, int qply, Value standPat, Value alpha) {
auto& moves = tree.getMoves();
auto& node = tree.getCurrentNode();
const auto& board = tree.getBoard();
while (true) {
if (tree.getNextMove() != tree.getEnd()) {
tree.selectNextMove();
return true;
}
switch (node.genPhase) {
case GenPhase::Hash: // fall through
case GenPhase::Capture: // fall through
case GenPhase::History1:
case GenPhase::History2:
case GenPhase::Misc:
assert(false);
break;
case GenPhase::CaptureOnly:
if (tree.isChecking()) {
MoveGenerator::generateEvasion(board, moves);
sortHistory(tree);
node.genPhase = GenPhase::End;
break;
} else {
MoveGenerator::generateCap(board, moves);
if (qply >= search_param::QUIES_RELIEVE_PLY) {
sortSee(tree, 0, standPat, alpha, false, false, true, true);
} else {
sortSee(tree, 0, standPat, alpha, false, false, false, true);
}
node.genPhase = GenPhase::End;
break;
}
case GenPhase::End:
return false;
}
}
}
/**
* store PV-nodes to TT
*/
void Searcher::storePV(Tree& tree, const PV& pv, int ply) {
if (ply >= pv.size()) {
return;
}
int depth = pv.get(ply).depth;
if (depth <= 0) {
return;
}
const auto& move = pv.get(ply).move;
if (move.isEmpty()) {
return;
}
if (tree.makeMoveFast(move)) {
storePV(tree, pv, ply + 1);
tree.unmakeMoveFast();
}
auto hash = tree.getBoard().getHash();
tt_.entryPV(hash, depth, Move::serialize16(move));
}
bool Searcher::isNeedMateSearch(Tree& tree, bool black, int depth) {
#if ENABLE_MATE_HISTORY
if (tree.getPly() <= 6 || depth >= 3 * Depth1Ply) {
return true;
}
const Board& board = tree.getBoard();
Square king = black ? board.getWKingSquare() : board.getBKingSquare();
Move move = tree.getPreFrontMove();
uint64_t data = mateHistory_.getData(king, move);
assert(data <= MateHistory::Max);
uint32_t mated = MateHistory::getMated(data);
uint32_t probed = MateHistory::getProbed(data);
assert(mated <= probed);
return (mated * 82) + 17 >= probed;
#else
return true;
#endif
}
void Searcher::updateMateHistory(Tree& tree, bool black, bool mate) {
#if ENABLE_MATE_HISTORY
if (tree.getPly() <= 1) {
return;
}
const Board& board = tree.getBoard();
Square king = black ? board.getWKingSquare() : board.getBKingSquare();
Move move = tree.getPreFrontMove();
mateHistory_.update(king, move, mate);
#endif
}
/**
* quiesence search
*/
Value Searcher::qsearch(Tree& tree, bool black, int qply, Value alpha, Value beta) {
#if DEBUG_NODE
bool debug = false;
#if 0
if (tree.debug__matchPath("-4233GI +5968OU -8586FU")) {
std::cout << "#-- debug quies node begin --#" << std::endl;
std::cout << tree.debug__getPath() << std::endl;
debug = true;
}
#endif
#endif
#if DEBUG_TREE
{
for (int i = 0; i < tree.getPly(); i++) {
std::cout << ' ';
}
std::cout << tree.debug__getFrontMove().toString() << std::endl;
}
#endif
auto& worker = getWorker(tree);
worker.info.qnode++;
// stand-pat
Value standPat = tree.getValue() * (black ? 1 : -1);
// beta-cut
if (standPat >= beta) {
return standPat;
}
// スタックサイズの限界
if (tree.isStackFull()) {
return standPat;
}
#if ENABLE_MATE_1PLY || ENABLE_MATE_3PLY
{
// search mate in 3 ply
bool mate = false;
worker.info.mateProbed++;
if (mateTable_.get(tree.getBoard().getHash(), mate)) {
worker.info.mateHit++;
} else if (isNeedMateSearch(tree, black, 0)) {
# if ENABLE_MATE_3PLY
mate = Mate::mate3Ply(tree);
# else
mate = Mate::mate1Ply(tree.getBoard());
# endif
mateTable_.set(tree.getBoard().getHash(), mate);
updateMateHistory(tree, black, mate);
#if ENABLE_MATE_HIST_EXPT
if (mate) {
expt::mate_hist_n.fail(0);
} else {
expt::mate_hist_n.succ(0);
}
} else {
if (ENABLE_MATE_3PLY ? Mate::mate3Ply(tree) : Mate::mate1Ply(tree.getBoard())) {
expt::mate_hist.fail(0);
} else {
expt::mate_hist.succ(0);
}
#endif
}
if (mate) {
# if ENABLE_MATE_3PLY
return Value::Inf - tree.getPly() - 3;
# else
return Value::Inf - tree.getPly() - 1;
#endif
}
}
#endif
alpha = Value::max(alpha, standPat);
// 合法手生成
auto& moves = tree.getMoves();
moves.clear();
tree.initGenPhase(GenPhase::CaptureOnly);
while (nextMoveQuies(tree, qply, standPat, alpha)) {
// make move
if (!tree.makeMove(eval_)) {
continue;
}
// reccursive call
Value currval;
currval = -qsearch(tree, !black, qply + 1, -beta, -alpha);
// unmake move
tree.unmakeMove();
// 中断判定
if (isInterrupted(tree)) {
return Value::Zero;
}
// 値更新
if (currval > alpha) {
alpha = currval;
tree.updatePV(0);
// beta-cut
if (currval >= beta) {
break;
}
}
}
return alpha;
}
void Searcher::updateKiller(Tree& tree, const Move& move) {
auto& node = tree.getCurrentNode();
const auto& board = tree.getBoard();
Piece captured = board.getBoardPiece(move.to());
Value capVal = material::pieceExchange(captured);
if (move == node.capture1) {
if ((node.expStat & Killer1Done) && move != node.killer1) {
node.kvalue1 = node.cvalue1 - capVal - 1;
}
if ((node.expStat & Killer2Done) && move != node.killer2) {
node.kvalue2 = node.cvalue1 - capVal - 1;
}
} else if (move == node.killer1) {
if ((node.expStat & Capture1Done) &&
node.kvalue2 + capVal <= node.cvalue1) {
node.kvalue2 = node.cvalue1 - capVal + 1;
}
Piece captured2 = board.getBoardPiece(node.killer2.to());
Value capVal2 = material::pieceExchange(captured2);
if ((node.expStat & Killer2Done) &&
node.kvalue1 + capVal <= node.kvalue2 + capVal2) {
node.kvalue1 = node.kvalue2 + capVal2 - capVal + 1;
}
} else if (move == node.killer2) {
if ((node.expStat & Capture1Done) &&
node.kvalue2 + capVal <= node.cvalue1) {
node.kvalue2 = node.cvalue1 - capVal + 1;
}
Piece captured1 = board.getBoardPiece(node.killer1.to());
Value capVal1 = material::pieceExchange(captured1);
if ((node.expStat & Killer1Done) &&
node.kvalue2 + capVal <= node.kvalue1 + capVal1) {
node.kvalue2 = node.kvalue1 + capVal1 - capVal + 1;
}
Move::swap(node.killer1, node.killer2);
Value::swap(node.kvalue1, node.kvalue2);
} else {
if (node.expStat & Killer1Done) {
Value val = searchSee<false>(board, move, -1, Value::PieceInf) - capVal + 1;
node.kvalue1 = Value::min(node.kvalue1, val);
}
node.killer2 = node.killer1;
node.kvalue2 = node.kvalue1;
node.killer1 = move;
node.kvalue1 = node.cvalue1 - capVal + 1;
}
if (tree.getBoard().getBoardPiece(move.to()).isEmpty() &&
(!move.promote() || move.piece() == Piece::Silver)) {
node.nocap2 = node.nocap1;
node.nocap1 = move;
}
}
/**
* nega-max search
*/
Value Searcher::search(Tree& tree, bool black, int depth, Value alpha, Value beta, NodeStat stat) {
#if DEBUG_TREE
{
for (int i = 0; i < tree.getPly(); i++) {
std::cout << ' ';
}
std::cout << tree.debug__getFrontMove().toString() << std::endl;
}
#endif // DEBUG_TREE
#if DEBUG_NODE
bool debug = false;
#if 0
if (tree.debug__matchPath("-0095KA")) {
std::cout << "#-- debug node begin --#" << std::endl;
std::cout << tree.debug__getPath() << std::endl;
std::cout << "alpha=" << alpha.int32() << " beta=" << beta.int32() << " depth=" << depth << std::endl;
debug = true;
}
#endif
#endif // DEBUG_NODE
auto& worker = getWorker(tree);
#if ENABLE_SHEK
#if !defined(NLEARN)
if (!config_.learning)
#endif
{
// SHEK
ShekStat shekStat = tree.checkShek();
worker.info.shekProbed++;
switch (shekStat) {
case ShekStat::Superior:
// 過去の局面に対して優位な局面
tree.getCurrentNode().isHistorical = true;
worker.info.shekSuperior++;
return Value::Inf - tree.getPly();
case ShekStat::Inferior:
// 過去の局面に対して劣る局面
tree.getCurrentNode().isHistorical = true;
worker.info.shekInferior++;
return -Value::Inf + tree.getPly();
case ShekStat::Equal:
// 過去の局面に等しい局面
worker.info.shekEqual++;
switch(tree.getCheckRepStatus()) {
case RepStatus::Win:
tree.getCurrentNode().isHistorical = true;
return Value::Inf - tree.getPly();
case RepStatus::Lose:
tree.getCurrentNode().isHistorical = true;
return -Value::Inf + tree.getPly();
case RepStatus::None:
assert(false);
default:
tree.getCurrentNode().isHistorical = true;
return Value::Zero;
}
default:
break;
}
}
#endif // ENABLE_SHEK
// スタックサイズの限界
if (tree.isStackFull()) {
tree.getCurrentNode().isHistorical = true;
return tree.getValue() * (black ? 1 : -1);
}
// 静止探索の結果を返す。
if (!tree.isChecking() && depth < Depth1Ply) {
return qsearch(tree, black, 0, alpha, beta);
}
// hash
uint64_t hash = tree.getBoard().getHash();
if (!tree.getExcluded().isEmpty()) {
hash ^= search_func::excludedHash(tree.getExcluded());
}
#if ENABLE_PREFETCH
// prefetch
tt_.prefetch(hash);
#endif // ENABLE_PREFETCH
Value oldAlpha = alpha;
// distance pruning
{
Value value = -Value::Inf + tree.getPly();
if (value > alpha) {
if (value >= beta) {
return value;
}
alpha = value;
} else {
value = Value::Inf - tree.getPly() - 1;
if (value <= alpha) {
return value;
}
}
}
worker.info.node++;
bool isNullWindow = (beta == alpha + 1);
// transposition table
Move hashMove = Move::empty();
Value hashValue;
uint32_t hashValueType;
int hashDepth;
#if !defined(NLEARN)
if (!config_.learning)
#endif
{
TTE tte;
worker.info.hashProbed++;
if (tt_.get(hash, tte)) {
hashDepth = tte.getDepth();
if (depth < search_param::REC_THRESHOLD ||
hashDepth >= search_func::recDepth(depth)) {
hashValue = tte.getValue(tree.getPly());
hashValueType = tte.getValueType();
// 前回の結果で枝刈り
if (stat.isHashCut() && isNullWindow) {
// 現在のノードに対して優位な条件の場合
if (hashDepth >= depth ||
((hashValueType == TTE::Lower || hashValueType == TTE::Exact) && hashValue >= Value::Mate) ||
((hashValueType == TTE::Upper || hashValueType == TTE::Exact) && hashValue <= -Value::Mate)) {
if (hashValueType == TTE::Exact) {
// 確定値
worker.info.hashExact++;
return hashValue;
} else if (hashValueType == TTE::Lower && hashValue >= beta) {
// 下界値
worker.info.hashLower++;
return hashValue;
} else if (hashValueType == TTE::Upper && hashValue <= alpha) {
// 上界値
worker.info.hashUpper++;
return hashValue;
}
}
// 十分なマージンを加味して beta 値を超える場合
if ((hashValueType == TTE::Lower || hashValueType == TTE::Exact) &&
!tree.isChecking() && !tree.isCheckingOnFrontier()) {
if (depth < search_param::FUT_DEPTH && hashValue >= beta + search_func::futilityMargin(depth, 0)) {
return beta;
}
}
}
if (hashValueType == TTE::Upper || hashValueType == TTE::Exact) {
// alpha 値を割るなら recursion 不要
if (hashValue <= alpha && hashDepth >= search_func::recDepth(depth)) {
stat.unsetRecursion();
}
// beta を超えないなら null move pruning を省略
if (hashValue < beta && hashDepth >= search_func::nullDepth(depth)) {
stat.unsetNullMove();
}
}
// 前回の最善手を取得
hashMove = Move::deserialize16(tte.getMove(), tree.getBoard());
if (tte.isMateThreat()) {
stat.setMateThreat();
}
}
worker.info.hashHit++;
}
}
Value standPat = tree.getValue() * (black ? 1 : -1);
bool improving = !tree.hasPrefrontierNode() ||
standPat >= tree.getPrefrontValue() * (black ? 1 : -1);
bool isFirst = true;
Move best = Move::empty();
bool doSingularExtension = false;
#if ENABLE_RAZOR_EXPT
bool isRazoring = false;
#endif
#if ENABLE_PROBCUT_EXPT
bool isProbcut = false;
#endif
if (!tree.isChecking()) {
#if ENABLE_MATE_1PLY || ENABLE_MATE_3PLY
if (stat.isMate()) {
// search mate in 3 ply
bool mate = false;
worker.info.mateProbed++;
if (mateTable_.get(tree.getBoard().getHash(), mate)) {
worker.info.mateHit++;
} else if (isNeedMateSearch(tree, black, depth)) {
# if ENABLE_MATE_3PLY
mate = Mate::mate3Ply(tree);
# else
mate = Mate::mate1Ply(tree.getBoard());
# endif
mateTable_.set(tree.getBoard().getHash(), mate);
updateMateHistory(tree, black, mate);
#if ENABLE_MATE_HIST_EXPT
if (mate) {
expt::mate_hist_n.fail(0);
} else {
expt::mate_hist_n.succ(0);
}
} else {
if (ENABLE_MATE_3PLY ? Mate::mate3Ply(tree) : Mate::mate1Ply(tree.getBoard())) {
expt::mate_hist.fail(depth);
} else {
expt::mate_hist.succ(depth);
}
#endif
}
if (mate) {
# if ENABLE_MATE_3PLY
alpha = Value::Inf - tree.getPly() - 3;
# else
alpha = Value::Inf - tree.getPly() - 1;
# endif
goto hash_store;
}
}
#endif
if (!stat.isMateThreat()) {
#if ENABLE_RAZORING
// razoring
if (depth < search_param::RAZOR_DEPTH && hashMove.isEmpty() &&
alpha > -Value::Mate && beta < Value::Mate) {
Value razorAlpha = alpha - search_func::razorMargin(depth);
if (standPat <= razorAlpha) {
worker.info.razoringTried++;
Value qval = qsearch(tree, black, 0, razorAlpha, razorAlpha+1);
if (qval <= razorAlpha) {
#if ENABLE_RAZOR_EXPT
isRazoring = true;
#else
worker.info.razoring++;
return qval;
#endif
}
}
}
#endif
// null move pruning
if (isNullWindow && stat.isNullMove() && beta <= standPat && depth >= Depth1Ply * 2) {
auto newStat = NodeStat().unsetNullMove();
int newDepth = search_func::nullDepth(depth);
worker.info.nullMovePruningTried++;
// make move
tree.makeNullMove();
Value currval = -search(tree, !black, newDepth, -beta, -beta+1, newStat);
// unmake move
tree.unmakeNullMove();
// 中断判定
if (isInterrupted(tree)) {
return Value::Zero;
}
// beta-cut
if (currval >= beta) {
tree.updatePVNull(depth);
tree.getCurrentNode().isHistorical = tree.getChildNode().isHistorical;
worker.info.nullMovePruning++;
alpha = beta;
if (newDepth < Depth1Ply) {
goto hash_store;
}
goto search_end;
}
// mate threat
if (currval <= -Value::Mate) {
stat.setMateThreat();
}
}
#if ENABLE_PROBCUT
if (isNullWindow && depth >= Depth1Ply * 5 && beta > -Value::Mate && beta < Value::Mate) {
Value pcBeta = beta + 200;
int bcDepth = depth - Depth1Ply * 4;
Value val = search(tree, black, bcDepth, pcBeta-1, pcBeta, stat);
worker.info.probcutTried++;
if (val >= pcBeta) {
#if ENABLE_PROBCUT_EXPT
isProbcut = true;
#else
worker.info.probcut++;
return pcBeta;
#endif
}
}
#endif
}
}
// recursive iterative-deepening search
if (hashMove.isEmpty() && stat.isRecursion() && depth >= search_param::REC_THRESHOLD) {
auto newStat = NodeStat(stat).unsetNullMove().unsetMate().unsetHashCut();
search(tree, black, search_func::recDepth(depth), alpha, beta, newStat);
// 中断判定
if (isInterrupted(tree)) {
return Value::Zero;
}
// ハッシュ表から前回の最善手を取得
TTE tte;
if (tt_.get(hash, tte)) {
hashMove = Move::deserialize16(tte.getMove(), tree.getBoard());
hashValue = tte.getValue(tree.getPly());
hashValueType = tte.getValueType();
hashDepth = tte.getDepth();
}
}
#if ENABLE_SINGULAR_EXTENSION
// singular extension
if (!hashMove.isEmpty() &&
tree.getExcluded().isEmpty() &&
!tree.isChecking() &&
depth >= Depth1Ply * 8 &&
hashValue < Value::Mate &&
hashValue > -Value::Mate &&
(hashValueType == TTE::Lower || hashValueType == TTE::Exact) &&
hashDepth >= depth - Depth1Ply * 3 &&
tree.getBoard().isValidMoveStrict(hashMove) &&
!tree.getBoard().isCheck(hashMove) &&
!(stat.isRecapture() && tree.isRecapture(hashMove) &&
(hashMove == tree.getCapture1() ||
(hashMove == tree.getCapture2() && tree.getCapture1Value() < tree.getCapture2Value() + 180)))) {
auto newStat = NodeStat(stat).unsetNullMove().unsetMate().unsetHashCut();
Value sBeta = hashValue - 4 * depth / Depth1Ply;
tree.setExcluded(hashMove);
Value val = search(tree, black, depth / 2, sBeta-1, sBeta, newStat);
tree.setExcluded(Move::empty());
worker.info.singularChecked++;
if (val < sBeta) {
worker.info.singular++;
doSingularExtension = true;
}
}
#endif
tree.initGenPhase();
worker.info.expand++;
#if ENABLE_HASH_MOVE
tree.setHash(hashMove);
#else
tree.setHash(Move::empty());
#endif
while (nextMove(tree)) {
Move move = *tree.getCurrentMove();
if (move == tree.getExcluded()) {
continue;
}
worker.info.expanded++;
// depth
int newDepth = depth - Depth1Ply;
// stat
NodeStat newStat = NodeStat::Default;
isNullWindow = (beta == alpha + 1);
const auto& board = tree.getBoard();
bool isCheckCurr = board.isCheck(move);
bool isCheckPrev = tree.isChecking();
bool isCheck = isCheckCurr || isCheckPrev;
Piece captured = board.getBoardPiece(move.to());
int count = tree.getCurrentNode().count;
if (!isCheckCurr && captured.isEmpty() &&
(!move.promote() || move.piece() == Piece::Silver)) {
tree.getCurrentNode().histMoves.add(move);
}
// extensions
if (isCheckCurr) {
// check
newDepth += search_param::EXT_CHECK;
worker.info.checkExtension++;
} else if (isCheckPrev && isFirst && tree.getGenPhase() == GenPhase::End && tree.getNextMove() == tree.getEnd()) {
// one-reply
newDepth += search_param::EXT_ONEREP;
worker.info.onerepExtension++;
} else if (!isCheckPrev && stat.isRecapture() && tree.isRecapture(move) &&
(move == tree.getCapture1() ||
(move == tree.getCapture2() && tree.getCapture1Value() < tree.getCapture2Value() + 180))
) {
// recapture
Move fmove = tree.getFrontMove();
if (!move.promote() && fmove.piece() == fmove.captured()) {
newDepth += search_param::EXT_RECAP2;
} else {
newDepth += search_param::EXT_RECAP;
}
newStat.unsetRecapture();
worker.info.recapExtension++;
} else if (move == hashMove && doSingularExtension) {
newDepth += Depth1Ply;
}
// late move reduction
int reduced = 0;
#if ENABLE_LMR
if (!isFirst && !isCheckPrev && newDepth >= Depth1Ply && !stat.isMateThreat() &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!tree.isPriorMove(move)) {
reduced = getReductionDepth(improving, newDepth, count, move, isNullWindow);
newDepth -= reduced;
}
#endif // ENABLE_LMR
#if ENABLE_MOVE_COUNT_EXPT
bool isMoveCountPrun = false;
#endif
#if ENABLE_MOVE_COUNT_PRUNING
// move count based pruning
if (!isCheckPrev && newDepth < Depth1Ply * 12 &&
alpha > oldAlpha && !stat.isMateThreat() &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!tree.isPriorMove(move) &&
count >= search_func::futilityMoveCounts(improving, depth)) {
#if ENABLE_MOVE_COUNT_EXPT
isMoveCountPrun = true;
#else
isFirst = false;
worker.info.moveCountPruning++;
continue;
#endif
}
#endif
#if ENABLE_FUT_EXPT
bool isFutPrun = false;
#endif
// futility pruning
if (!isCheck && newDepth < search_param::FUT_DEPTH && alpha > -Value::Mate) {
Value futAlpha = alpha;
if (newDepth >= Depth1Ply) { futAlpha -= search_func::futilityMargin(newDepth, count); }
if (standPat + tree.estimate(move, eval_) + gains_.get(move) <= futAlpha) {
#if ENABLE_FUT_EXPT
isFutPrun = true;
#else
isFirst = false;
worker.info.futilityPruning++;
continue;
#endif
}
}
// prune moves with negative SEE
if (!isCheck && newDepth < Depth1Ply * 2 && isNullWindow &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!tree.isPriorMove(move)) {
if (searchSee<true>(board, move, -1, 0) < Value::Zero) {
isFirst = false;
continue;
}
}
// make move
if (!tree.makeMove(eval_)) {
continue;
}
Value newStandPat = tree.getValue() * (black ? 1 : -1);
// extended futility pruning
if (!isCheck && alpha > -Value::Mate) {
if ((newDepth < Depth1Ply && newStandPat <= alpha) ||
(newDepth < search_param::FUT_DEPTH && newStandPat + search_func::futilityMargin(newDepth, count) <= alpha)) {
#if ENABLE_FUT_EXPT
isFutPrun = true;
#else
tree.unmakeMove();
isFirst = false;
worker.info.extendedFutilityPruning++;
continue;
#endif
}
}
// reccursive call
Value currval;
if (isFirst) {
currval = -search(tree, !black, newDepth, -beta, -alpha, newStat);
} else {
// nega-scout
currval = -search(tree, !black, newDepth, -alpha-1, -alpha, newStat);
if (!isInterrupted(tree) && currval > alpha && reduced > 0) {
newDepth += reduced;
currval = -search(tree, !black, newDepth, -alpha-1, -alpha, newStat);
}
if (!isInterrupted(tree) && currval > alpha && currval < beta && !isNullWindow) {
currval = -search(tree, !black, newDepth, -beta, -alpha, newStat);
}
}
// unmake move
tree.unmakeMove();
// 中断判定
if (isInterrupted(tree)) {
return Value::Zero;
}
// update gain
gains_.update(move, newStandPat - standPat - tree.estimate(move, eval_));
tree.getCurrentNode().isHistorical |= tree.getChildNode().isHistorical;
// 値更新
if (currval > alpha) {
#if ENABLE_MOVE_COUNT_EXPT
if (isMoveCountPrun) { expt::move_count_based_pruning.fail(newDepth); }
#endif
#if ENABLE_FUT_EXPT
if (isFutPrun) { expt::futility_pruning.fail(newDepth); }
#endif
alpha = currval;
best = move;
if (!isNullWindow) {
tree.updatePV(depth);
}
// beta-cut
if (currval >= beta) {
tree.getCurrentNode().isHistorical = tree.getChildNode().isHistorical;
worker.info.failHigh++;
if (isFirst) {
worker.info.failHighFirst++;
}
if (move == tree.getHash()) {
worker.info.failHighIsHash++;
} else if (move == tree.getKiller1()) {
worker.info.failHighIsKiller1++;
} else if (move == tree.getKiller2()) {
worker.info.failHighIsKiller2++;
}
break;
}
} else {
#if ENABLE_MOVE_COUNT_EXPT
if (isMoveCountPrun) { expt::move_count_based_pruning.succ(newDepth); }
#endif
#if ENABLE_FUT_EXPT
if (isFutPrun) { expt::futility_pruning.succ(newDepth); }
#endif
}
// split
if ((depth >= Depth1Ply * 4 || (depth >= Depth1Ply * 3 && rootDepth_ < Depth1Ply * 12)) &&
(!isCheckPrev || tree.getEnd() - tree.getCurrentMove() >= 4) &&
idleWorkerCount_.load() >= 1 && idleTreeCount_.load() >= 2) {
if (split(tree, black, depth, alpha, beta, best, standPat, stat, improving)) {
worker.info.split++;
if (isInterrupted(tree)) {
return Value::Zero;
}
if (tree.getTlp().alpha > alpha) {
alpha = tree.getTlp().alpha;
best = tree.getTlp().best;
}
break;
}
}
isFirst = false;
}
if (!best.isEmpty() && !tree.isChecking()) {
#if ENABLE_KILLER_MOVE
updateKiller(tree, best);
#endif // ENABLE_KILLER_MOVE
if (tree.getBoard().getBoardPiece(best.to()).isEmpty() &&
(!best.promote() || best.piece() == Piece::Silver)) {
updateHistory(tree, depth, best);
}
}
hash_store:
if (
#if !defined(NLEARN)
!config_.learning &&
#endif
!tree.getCurrentNode().isHistorical) {
TTStatus status = tt_.entry(hash, oldAlpha, beta, alpha, depth, tree.getPly(), Move::serialize16(best), stat);
switch (status) {
case TTStatus::New: worker.info.hashNew++; break;
case TTStatus::Update: worker.info.hashUpdate++; break;
case TTStatus::Collide: worker.info.hashCollision++; break;
case TTStatus::Reject: worker.info.hashReject++; break;
default: break;
}
worker.info.hashStore++;
}
#if ENABLE_RAZOR_EXPT
if (oldAlpha != alpha) {
if (isRazoring) { expt::razoring.fail(depth); }
} else {
if (isRazoring) { expt::razoring.succ(depth); }
}
#endif
#if ENABLE_PROBCUT_EXPT
if (alpha >= beta) {
if (isProbcut) { expt::probcut.succ(depth); }
} else {
if (isProbcut) { expt::probcut.fail(depth); }
}
#endif
search_end:
return alpha;
}
void Searcher::releaseTree(int tid) {
auto& tree = trees_[tid];
auto& parent = trees_[tree.getTlp().parentTreeId];
tree.unuse();
idleTreeCount_.fetch_add(1);
parent.getTlp().childCount.fetch_sub(1);
}
/**
* split
*/
bool Searcher::split(Tree& parent, bool black, int depth, Value alpha, Value beta, Move best, Value standPat, NodeStat stat, bool improving) {
int currTreeId = Tree::InvalidId;
{
std::lock_guard<std::mutex> lock(splitMutex_);
if (idleTreeCount_.load() <= 1 || idleWorkerCount_.load() == 0) {
return false;
}
// カレントスレッドに割り当てる tree を決定
for (int tid = 1; tid < config_.treeSize; tid++) {
auto& tree = trees_[tid];
if (!tree.getTlp().used) {
currTreeId = tid;
tree.use(parent, parent.getTlp().workerId);
idleTreeCount_.fetch_sub(1);
break;
}
}
// 他の worker と tree を確保
int childCount = 1;
for (int wid = 0; wid < config_.workerSize; wid++) {
auto& worker = workers_[wid];
if (!worker.job.load()) {
for (int tid = 1; tid < config_.treeSize; tid++) {
auto& tree = trees_[tid];
if (!tree.getTlp().used) {
tree.use(parent, wid);
idleTreeCount_.fetch_sub(1);
worker.setJob(tid);
idleWorkerCount_.fetch_sub(1);
childCount++;
if (idleTreeCount_.load() == 0 || idleWorkerCount_.load() == 0) {
goto lab_assign_end;
}
break;
}
}
}
}
lab_assign_end:
;
parent.getTlp().childCount.store(childCount);
parent.getTlp().black = black;
parent.getTlp().depth = depth;
parent.getTlp().alpha = alpha;
parent.getTlp().beta = beta;
parent.getTlp().best = best;
parent.getTlp().standPat = standPat;
parent.getTlp().stat = stat;
parent.getTlp().improving = improving;
}
auto& tree = trees_[currTreeId];
auto& worker = workers_[parent.getTlp().workerId];
worker.swapTree(currTreeId);
searchTlp(tree);
worker.swapTree(parent.getTlp().treeId);
{
std::lock_guard<std::mutex> lock(splitMutex_);
tree.unuse();
idleTreeCount_.fetch_add(1);
parent.getTlp().childCount.fetch_sub(1);
}
if (!tree.getTlp().shutdown.load()) {
// suspend
worker.waitForJob(&parent);
} else {
// wait for brothers
while (true) {
if (parent.getTlp().childCount.load() == 0) {
break;
}
std::this_thread::yield();
}
}
return true;
}
void Searcher::searchTlp(Tree& tree) {
{
std::lock_guard<std::mutex> lock(splitMutex_);
}
auto& parent = trees_[tree.getTlp().parentTreeId];
auto& worker = getWorker(tree);
bool black = parent.getTlp().black;
int depth = parent.getTlp().depth;
Value beta = parent.getTlp().beta;
Value standPat = parent.getTlp().standPat;
NodeStat stat = parent.getTlp().stat;
bool improving = parent.getTlp().improving;
tree.initGenPhase();
while (true) {
Move move;
Value alpha;
const auto& board = tree.getBoard();
bool isCheckCurr;
bool isCheckPrev = tree.isChecking();
bool isCheck;
bool isPriorMove;
Piece captured;
int count;
{
std::lock_guard<std::mutex> lock(parent.getMutex());
if (!nextMove(parent)) {
return;
}
move = *parent.getCurrentMove();
count = parent.getCurrentNode().count;
alpha = parent.getTlp().alpha;
captured = board.getBoardPiece(move.to());
isCheckCurr = board.isCheck(move);
isCheck = isCheckCurr || isCheckPrev;
isPriorMove = parent.isPriorMove(move);
if (!isCheckCurr && captured.isEmpty() &&
(!move.promote() || move.piece() == Piece::Silver)) {
parent.getCurrentNode().histMoves.add(move);
}
}
tree.addMove(move);
tree.selectNextMove();
// depth
int newDepth = depth - Depth1Ply;
// stat
NodeStat newStat = NodeStat::Default;
bool isNullWindow = (beta == alpha + 1);
// extensions
if (isCheckCurr) {
// check
newDepth += search_param::EXT_CHECK;
worker.info.checkExtension++;
} else if (!isCheckPrev && stat.isRecapture() && parent.isRecapture(move) &&
(move == parent.getCapture1() ||
(move == parent.getCapture2() && parent.getCapture1Value() < parent.getCapture2Value() + 180))
) {
// recapture
Move fmove = parent.getFrontMove();
if (!move.promote() && fmove.piece() == fmove.captured()) {
newDepth += search_param::EXT_RECAP2;
} else {
newDepth += search_param::EXT_RECAP;
}
newStat.unsetRecapture();
worker.info.recapExtension++;
}
// late move reduction
int reduced = 0;
#if ENABLE_LMR
if (!isCheckPrev && newDepth >= Depth1Ply && !stat.isMateThreat() &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!isPriorMove) {
reduced = getReductionDepth(improving, newDepth, count, move, isNullWindow);
newDepth -= reduced;
}
#endif // ENABLE_LMR
#if ENABLE_MOVE_COUNT_PRUNING
// move count based pruning
if (!isCheckPrev && newDepth < Depth1Ply * 12 &&
/*alpha > oldAlpha &&*/ !stat.isMateThreat() &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!tree.isPriorMove(move) &&
count >= search_func::futilityMoveCounts(improving, depth)) {
worker.info.moveCountPruning++;
continue;
}
#endif
// futility pruning
if (!isCheck && newDepth < search_param::FUT_DEPTH && alpha > -Value::Mate) {
Value futAlpha = alpha;
if (newDepth >= Depth1Ply) { futAlpha -= search_func::futilityMargin(newDepth, count); }
if (standPat + tree.estimate(move, eval_) + gains_.get(move) <= futAlpha) {
worker.info.futilityPruning++;
continue;
}
}
if (newDepth < Depth1Ply * 2 && isNullWindow && !isCheck &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver) &&
!isPriorMove) {
if (searchSee<true>(board, move, -1, 0) < Value::Zero) {
continue;
}
}
if (!tree.makeMove(eval_)) {
continue;
}
Value newStandPat = tree.getValue() * (black ? 1 : -1);
// extended futility pruning
if (!isCheck && alpha > -Value::Mate) {
if ((newDepth < Depth1Ply && newStandPat <= alpha) ||
(newDepth < search_param::FUT_DEPTH && newStandPat + search_func::futilityMargin(newDepth, count) <= alpha)) {
tree.unmakeMove();
worker.info.extendedFutilityPruning++;
continue;
}
}
// nega-scout
Value currval = -search(tree, !black, newDepth, -alpha-1, -alpha, newStat);
if (!isInterrupted(tree) && currval > alpha && reduced > 0) {
newDepth += reduced;
currval = -search(tree, !black, newDepth, -alpha-1, -alpha, newStat);
}
if (!isInterrupted(tree) && currval > alpha && currval < beta && !isNullWindow) {
currval = -search(tree, !black, newDepth, -beta, -alpha, newStat);
}
// unmake move
tree.unmakeMove();
// 中断判定
if (isInterrupted(tree)) {
return;
}
// update gain
gains_.update(move, newStandPat - standPat - tree.estimate(move, eval_));
{
std::lock_guard<std::mutex> lock(parent.getMutex());
if (tree.getTlp().shutdown.load()) {
return;
}
// 値更新
if (currval > parent.getTlp().alpha) {
parent.getTlp().alpha = currval;
parent.getTlp().best = move;
if (!isNullWindow) {
parent.updatePV(depth, tree);
}
// beta-cut
if (currval >= parent.getTlp().beta) {
parent.getCurrentNode().isHistorical = tree.getChildNode().isHistorical;
worker.info.failHigh++;
if (move == parent.getHash()) {
worker.info.failHighIsHash++;
} else if (move == parent.getKiller1()) {
worker.info.failHighIsKiller1++;
} else if (move == parent.getKiller2()) {
worker.info.failHighIsKiller2++;
}
shutdownSiblings(parent);
}
}
}
}
}
void Searcher::shutdownSiblings(Tree& parent) {
std::lock_guard<std::mutex> lock(splitMutex_);
for (int id = 0; id < config_.treeSize; id++) {
int parentId = trees_[id].getTlp().parentTreeId;
while (parentId != Tree::InvalidId) {
if (parentId == parent.getTlp().treeId) {
trees_[id].getTlp().shutdown.store(true);
break;
}
parentId = trees_[parentId].getTlp().parentTreeId;
}
}
}
/**
* search on root node
*/
Value Searcher::searchRoot(Tree& tree, int depth, Value alpha, Value beta, Move& best,
bool breakOnFailLow /*= false*/, bool forceFullWindow /*= false*/) {
const auto& board = tree.getBoard();
bool black = board.isBlack();
bool isFirst = true;
Value oldAlpha = alpha;
rootDepth_ = depth;
while (nextMove(tree)) {
Move move = *tree.getCurrentMove();
// depth
int newDepth = depth - Depth1Ply;
bool isCheckPrev = board.isChecking();
bool isCheckCurr = board.isCheck(move);
Piece captured = board.getBoardPiece(move.to());
// extensions
if (isCheckCurr) {
// check
newDepth += search_param::EXT_CHECK;
info_.checkExtension++;
}
// late move reduction
int reduced = 0;
#if ENABLE_LMR
if (!isFirst && newDepth >= Depth1Ply * 2 && !isCheckPrev &&
captured.isEmpty() && (!move.promote() || move.piece() == Piece::Silver)) {
reduced = Depth1Ply;
newDepth -= reduced;
}
#endif // ENABLE_LMR
// make move
bool ok = tree.makeMove(eval_);
assert(ok);
Value currval;
if (forceFullWindow) {
currval = -search(tree, !black, newDepth, -beta, -oldAlpha);
} else if (isFirst) {
// full window search
currval = -search(tree, !black, newDepth, -beta, -alpha);
} else {
// nega-scout
currval = -search(tree, !black, newDepth, -alpha-1, -alpha);
if (!isInterrupted(tree) && currval >= alpha + 1 && reduced != 0) {
// full depth
newDepth += reduced;
currval = -search(tree, !black, newDepth, -alpha-1, -alpha);
}
if (!isInterrupted(tree) && currval >= alpha + 1) {
// full window search
currval = -search(tree, !black, newDepth, -beta, -alpha);
}
}
// unmake move
tree.unmakeMove();
// 中断判定
if (isInterrupted(tree)) {
return alpha;
}
if (breakOnFailLow && isFirst && currval <= alpha && currval > -Value::Mate) {
return currval;
}
// ソート用に値をセット
auto index = tree.getIndexByMove(move);
if (forceFullWindow || currval > alpha) {
rootValues_[index] = currval.int32();
} else {
rootValues_[index] = -Value::Inf;
}
timeManager_.addMove(move, currval);
// 値更新
if (currval > alpha) {
// update alpha
alpha = currval;
best = move;
tree.updatePV(depth);
if (depth >= Depth1Ply * ITERATE_INFO_THRESHOLD || currval >= Value::Mate) {
showPV(depth / Depth1Ply, tree.getPV(), black ? currval : -currval);
}
info_.lastDepth = depth / Depth1Ply;
// beta-cut or update best move
if (alpha >= beta) {
return alpha;
}
}
isFirst = false;
}
return alpha;
}
/**
* aspiration search
* @return {負けたか中断された場合にfalseを返します。}
*/
bool Searcher::searchAsp(int depth, Move& best, Value baseAlpha, Value baseBeta, Value& valueRef) {
auto& tree0 = trees_[0];
Value baseVal = valueRef;
baseVal = Value::max(baseVal, baseAlpha);
baseVal = Value::min(baseVal, baseBeta);
CONSTEXPR_CONST int wmax = 3;
int lower = 0;
int upper = 0;
const Value alphas[wmax] = { baseVal-198, baseVal-793, -Value::Mate };
const Value betas[wmax] = { baseVal+198, baseVal+793, Value::Mate };
Value value = alphas[lower];
while (true) {
timeManager_.startDepth();
const Value alpha = Value::max(alphas[lower], baseAlpha);
const Value beta = Value::min(betas[upper], baseBeta);
value = searchRoot(tree0, depth, alpha, beta, best, true);
// 中断判定
if (isInterrupted(tree0)) {
return false;
}
// 値が確定
if (value > alpha && value < beta) {
break;
}
bool retry = false;
if (value <= baseAlpha || value >= baseBeta) {
break;
}
// alpha 値を広げる
while (value <= alphas[lower] && alphas[lower] > baseAlpha && lower != wmax - 1) {
lower++;
assert(lower < wmax);
retry = true;
tree0.selectFirstMove();
}
// beta 値を広げる
while (value >= betas[upper] && betas[upper] < baseBeta && upper != wmax - 1) {
upper++;
assert(upper < wmax);
retry = true;
tree0.selectPreviousMove();
}
if (!retry) { break; }
}
if (depth >= Depth1Ply * ITERATE_INFO_THRESHOLD ||
value >= Value::Mate || value <= -Value::Mate) {
showEndOfIterate(depth / Depth1Ply);
}
info_.lastDepth = depth / Depth1Ply;
tree0.setSortValues(rootValues_);
tree0.sortAll();
info_.eval = value;
valueRef = value;
if (value <= -Value::Mate) {
return false;
}
if (!config_.ponder && config_.enableTimeManagement) {
float limit = config_.enableLimit ? config_.limitSeconds : 0.0;
if (timeManager_.isEasy(limit, timer_.get())) {
return false;
}
}
return true;
}
void Searcher::showPV(int depth, const PV& pv, const Value& value) {
if (!config_.logging) {
return;
}
// 探索情報集計
mergeInfo();
uint64_t node = info_.node + info_.qnode;
std::ostringstream oss;
if (info_.lastDepth == depth) {
oss << " ";
} else {
oss << std::setw(2) << depth << ": ";
}
oss << std::setw(10) << node << ": ";
oss << pv.toString() << ": ";
oss << value.int32();
Loggers::message << oss.str();
}
void Searcher::showEndOfIterate(int depth) {
if (!config_.logging) {
return;
}
// 探索情報集計
mergeInfo();
uint64_t node = info_.node + info_.qnode;
float seconds = timer_.get();
std::ostringstream oss;
if (info_.lastDepth == depth) {
oss << " ";
} else {
oss << std::setw(2) << depth << ": ";
}
oss << std::setw(10) << node;
oss << ": " << seconds << "sec";
Loggers::message << oss.str();
}
void Searcher::generateMovesOnRoot() {
auto& tree0 = trees_[0];
auto& moves = tree0.getMoves();
const auto& board = tree0.getBoard();
// 合法手生成
tree0.initGenPhase();
MoveGenerator::generate(board, moves);
tree0.resetGenPhase();
// 非合法手除去
for (auto ite = moves.begin(); ite != moves.end();) {
if (!board.isValidMove(*ite)) {
ite = moves.remove(ite);
} else {
++ite;
}
}
#if ENABLE_ROOT_MOVES_SHUFFLE
// シャッフル
random_.shuffle(moves.begin(), moves.end());
#endif
}
/**
* 指定した局面に対して探索を実行します。
* @return {負けたか中断された場合にfalseを返します。}
*/
bool Searcher::search(const Board& initialBoard, Move& best,
Value alpha, Value beta, bool fastStart) {
// 前処理
before(initialBoard, fastStart);
auto& tree0 = trees_[0];
int depth = config_.maxDepth;
generateMovesOnRoot();
Value value = searchRoot(tree0, depth * Depth1Ply + Depth1Ply / 2, alpha, beta, best);
info_.lastDepth = depth;
info_.eval = value;
bool result = value > alpha;
// 中断判定
if (isInterrupted(tree0)) {
result = false;
}
// 後処理
after();
return result;
}
/**
* iterative deepening search from root node
* @return {負けたか深さ1で中断された場合にfalseを返します。}
*/
bool Searcher::idsearch(Move& best, Value alpha, Value beta) {
auto& tree0 = trees_[0];
bool result = false;
generateMovesOnRoot();
Value value = searchRoot(tree0, Depth1Ply, -Value::Inf, Value::Inf, best, false, true);
tree0.setSortValues(rootValues_);
tree0.sortAll();
for (int depth = 1; depth <= config_.maxDepth; depth++) {
bool cont = searchAsp(depth * Depth1Ply + Depth1Ply / 2, best, alpha, beta, value);
#if DEBUG_ROOT_MOVES
std::ostringstream oss;
for (auto ite = tree0.getBegin(); ite != tree0.getEnd(); ite++) {
oss << ' ' << (*ite).toString() << '[' << tree0.getSortValue(ite) << ']';
}
Loggers::debug << oss.str();
#endif
#if ENABLE_STORE_PV
storePV(tree0, tree0.getPV(), 0);
#endif // ENABLE_STORE_PV
if (value >= beta) {
result = true;
break;
}
if (value <= alpha) {
result = false;
break;
}
if (!cont) {
break;
}
result = true;
timeManager_.nextDepth();
}
return result;
}
/**
* 指定した局面に対して反復深化探索を実行します。
* @return {負けたか深さ1で中断された場合にfalseを返します。}
*/
bool Searcher::idsearch(const Board& initialBoard, Move& best,
Value alpha, Value beta, bool fastStart) {
// 前処理
before(initialBoard, fastStart);
bool result = idsearch(best, alpha, beta);
// 後処理
after();
return result;
}
} // namespace sunfish
|
sunfish-shogi/sunfish3
|
src/searcher/Searcher.cpp
|
C++
|
mit
| 70,626
|
#nullable enable
using Dock.Model.ReactiveUI.Controls;
namespace Core2D.ViewModels.Docking.Tools.Properties;
public class DataPropertiesViewModel : Tool
{
}
|
wieslawsoltes/Core2D
|
src/Core2D/ViewModels/Docking/Tools/Properties/DataPropertiesViewModel.cs
|
C#
|
mit
| 161
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/// <reference types="node" />
import * as cluster from 'cluster';
import {resolve} from '../../../../src/ngtsc/file_system';
import {Logger} from '../../logging/logger';
import {PackageJsonUpdater} from '../../writing/package_json_updater';
import {AnalyzeEntryPointsFn} from '../api';
import {CreateTaskCompletedCallback, Task, TaskCompletedCallback, TaskQueue} from '../tasks/api';
import {stringifyTask} from '../tasks/utils';
import {MessageFromWorker, TaskCompletedMessage, UpdatePackageJsonMessage} from './api';
import {Deferred, sendMessageToWorker} from './utils';
/**
* The cluster master is responsible for analyzing all entry-points, planning the work that needs to
* be done, distributing it to worker-processes and collecting/post-processing the results.
*/
export class ClusterMaster {
private finishedDeferred = new Deferred<void>();
private processingStartTime: number = -1;
private taskAssignments = new Map<number, Task|null>();
private taskQueue: TaskQueue;
private onTaskCompleted: TaskCompletedCallback;
constructor(
private workerCount: number, private logger: Logger,
private pkgJsonUpdater: PackageJsonUpdater, analyzeEntryPoints: AnalyzeEntryPointsFn,
createTaskCompletedCallback: CreateTaskCompletedCallback) {
if (!cluster.isMaster) {
throw new Error('Tried to instantiate `ClusterMaster` on a worker process.');
}
this.taskQueue = analyzeEntryPoints();
this.onTaskCompleted = createTaskCompletedCallback(this.taskQueue);
}
run(): Promise<void> {
if (this.taskQueue.allTasksCompleted) {
return Promise.resolve();
}
// Set up listeners for worker events (emitted on `cluster`).
cluster.on('online', this.wrapEventHandler(worker => this.onWorkerOnline(worker.id)));
cluster.on(
'message', this.wrapEventHandler((worker, msg) => this.onWorkerMessage(worker.id, msg)));
cluster.on(
'exit',
this.wrapEventHandler((worker, code, signal) => this.onWorkerExit(worker, code, signal)));
// Since we have pending tasks at the very minimum we need a single worker.
cluster.fork();
return this.finishedDeferred.promise.then(() => this.stopWorkers(), err => {
this.stopWorkers();
return Promise.reject(err);
});
}
/** Try to find available (idle) workers and assign them available (non-blocked) tasks. */
private maybeDistributeWork(): void {
let isWorkerAvailable = false;
// First, check whether all tasks have been completed.
if (this.taskQueue.allTasksCompleted) {
const duration = Math.round((Date.now() - this.processingStartTime) / 100) / 10;
this.logger.debug(`Processed tasks in ${duration}s.`);
return this.finishedDeferred.resolve();
}
// Look for available workers and available tasks to assign to them.
for (const [workerId, assignedTask] of Array.from(this.taskAssignments)) {
if (assignedTask !== null) {
// This worker already has a job; check other workers.
continue;
} else {
// This worker is available.
isWorkerAvailable = true;
}
// This worker needs a job. See if any are available.
const task = this.taskQueue.getNextTask();
if (task === null) {
// No suitable work available right now.
break;
}
// Process the next task on the worker.
this.taskAssignments.set(workerId, task);
sendMessageToWorker(workerId, {type: 'process-task', task});
isWorkerAvailable = false;
}
if (!isWorkerAvailable) {
const spawnedWorkerCount = Object.keys(cluster.workers).length;
if (spawnedWorkerCount < this.workerCount) {
this.logger.debug('Spawning another worker process as there is more work to be done.');
cluster.fork();
} else {
// If there are no available workers or no available tasks, log (for debugging purposes).
this.logger.debug(
`All ${spawnedWorkerCount} workers are currently busy and cannot take on more work.`);
}
} else {
const busyWorkers = Array.from(this.taskAssignments)
.filter(([_workerId, task]) => task !== null)
.map(([workerId]) => workerId);
const totalWorkerCount = this.taskAssignments.size;
const idleWorkerCount = totalWorkerCount - busyWorkers.length;
this.logger.debug(
`No assignments for ${idleWorkerCount} idle (out of ${totalWorkerCount} total) ` +
`workers. Busy workers: ${busyWorkers.join(', ')}`);
if (busyWorkers.length === 0) {
// This is a bug:
// All workers are idle (meaning no tasks are in progress) and `taskQueue.allTasksCompleted`
// is `false`, but there is still no assignable work.
throw new Error(
'There are still unprocessed tasks in the queue and no tasks are currently in ' +
`progress, yet the queue did not return any available tasks: ${this.taskQueue}`);
}
}
}
/** Handle a worker's exiting. (Might be intentional or not.) */
private onWorkerExit(worker: cluster.Worker, code: number|null, signal: string|null): void {
// If the worker's exiting was intentional, nothing to do.
if (worker.exitedAfterDisconnect) return;
// The worker exited unexpectedly: Determine it's status and take an appropriate action.
const currentTask = this.taskAssignments.get(worker.id);
this.logger.warn(
`Worker #${worker.id} exited unexpectedly (code: ${code} | signal: ${signal}).\n` +
` Current assignment: ${(currentTask == null) ? '-' : stringifyTask(currentTask)}`);
if (currentTask == null) {
// The crashed worker process was not in the middle of a task:
// Just spawn another process.
this.logger.debug(`Spawning another worker process to replace #${worker.id}...`);
this.taskAssignments.delete(worker.id);
cluster.fork();
} else {
// The crashed worker process was in the middle of a task:
// Impossible to know whether we can recover (without ending up with a corrupted entry-point).
throw new Error(
'Process unexpectedly crashed, while processing format property ' +
`${currentTask.formatProperty} for entry-point '${currentTask.entryPoint.path}'.`);
}
}
/** Handle a message from a worker. */
private onWorkerMessage(workerId: number, msg: MessageFromWorker): void {
if (!this.taskAssignments.has(workerId)) {
const knownWorkers = Array.from(this.taskAssignments.keys());
throw new Error(
`Received message from unknown worker #${workerId} (known workers: ` +
`${knownWorkers.join(', ')}): ${JSON.stringify(msg)}`);
}
switch (msg.type) {
case 'error':
throw new Error(`Error on worker #${workerId}: ${msg.error}`);
case 'task-completed':
return this.onWorkerTaskCompleted(workerId, msg);
case 'update-package-json':
return this.onWorkerUpdatePackageJson(workerId, msg);
default:
throw new Error(
`Invalid message received from worker #${workerId}: ${JSON.stringify(msg)}`);
}
}
/** Handle a worker's coming online. */
private onWorkerOnline(workerId: number): void {
if (this.taskAssignments.has(workerId)) {
throw new Error(`Invariant violated: Worker #${workerId} came online more than once.`);
}
if (this.processingStartTime === -1) {
this.logger.debug('Processing tasks...');
this.processingStartTime = Date.now();
}
this.taskAssignments.set(workerId, null);
this.maybeDistributeWork();
}
/** Handle a worker's having completed their assigned task. */
private onWorkerTaskCompleted(workerId: number, msg: TaskCompletedMessage): void {
const task = this.taskAssignments.get(workerId) || null;
if (task === null) {
throw new Error(
`Expected worker #${workerId} to have a task assigned, while handling message: ` +
JSON.stringify(msg));
}
this.onTaskCompleted(task, msg.outcome, msg.message);
this.taskQueue.markTaskCompleted(task);
this.taskAssignments.set(workerId, null);
this.maybeDistributeWork();
}
/** Handle a worker's request to update a `package.json` file. */
private onWorkerUpdatePackageJson(workerId: number, msg: UpdatePackageJsonMessage): void {
const task = this.taskAssignments.get(workerId) || null;
if (task === null) {
throw new Error(
`Expected worker #${workerId} to have a task assigned, while handling message: ` +
JSON.stringify(msg));
}
const expectedPackageJsonPath = resolve(task.entryPoint.path, 'package.json');
const parsedPackageJson = task.entryPoint.packageJson;
if (expectedPackageJsonPath !== msg.packageJsonPath) {
throw new Error(
`Received '${msg.type}' message from worker #${workerId} for '${msg.packageJsonPath}', ` +
`but was expecting '${expectedPackageJsonPath}' (based on task assignment).`);
}
// NOTE: Although the change in the parsed `package.json` will be reflected in tasks objects
// locally and thus also in future `process-task` messages sent to worker processes, any
// processes already running and processing a task for the same entry-point will not get
// the change.
// Do not rely on having an up-to-date `package.json` representation in worker processes.
// In other words, task processing should only rely on the info that was there when the
// file was initially parsed (during entry-point analysis) and not on the info that might
// be added later (during task processing).
this.pkgJsonUpdater.writeChanges(msg.changes, msg.packageJsonPath, parsedPackageJson);
}
/** Stop all workers and stop listening on cluster events. */
private stopWorkers(): void {
const workers = Object.values(cluster.workers) as cluster.Worker[];
this.logger.debug(`Stopping ${workers.length} workers...`);
cluster.removeAllListeners();
workers.forEach(worker => worker.kill());
}
/**
* Wrap an event handler to ensure that `finishedDeferred` will be rejected on error (regardless
* if the handler completes synchronously or asynchronously).
*/
private wrapEventHandler<Args extends unknown[]>(fn: (...args: Args) => void|Promise<void>):
(...args: Args) => Promise<void> {
return async(...args: Args) => {
try {
await fn(...args);
} catch (err) {
this.finishedDeferred.reject(err);
}
};
}
}
|
Toxicable/angular
|
packages/compiler-cli/ngcc/src/execution/cluster/master.ts
|
TypeScript
|
mit
| 10,825
|
jest
.dontMock('../resolvers')
.dontMock('../queries')
import { fromJS } from 'immutable'
describe('resolvers', () => {
let resolvers
beforeEach(() => {
resolvers = require('../resolvers')
})
it('retrieves a value', () => {
const {value} = resolvers
const mockVal = 'testing-wow'
expect(value(mockVal)).toBe(mockVal)
})
it('constructs a proper get query', () => {
const {get, value} = resolvers
expect(get('testing')).toEqual({
testing: value,
})
})
it('constructs a valid getIn query', () => {
const {getIn, value} = resolvers
expect(getIn('one', 'two', 'three')).toEqual({
one: {
two: {
three: value,
},
},
})
})
it('constructs a valid index query', () => {
const {index} = resolvers
const indexResolver = index(['users'])
const mockCache = fromJS({
users: {
'123': {
name: 'one',
friends: {
'456': true,
'789': true,
},
},
'456': { name: 'two' },
'789': { name: 'three' },
},
})
const mockState = { firebase: mockCache }
const value = mockCache.getIn(['users', '123', 'friends'])
expect(
indexResolver.subscriptions(value)
).toEqual([
['users', '456'],
['users', '789'],
])
expect(
indexResolver.values(value, mockState, {}).toJS()
).toEqual({
'456': { name: 'two' },
'789': { name: 'three' },
})
})
})
|
colbyr/redux-firebase
|
src/__tests__/resolvers-test.js
|
JavaScript
|
mit
| 1,505
|
# How to make maps in python
There are a number of packages which you can use to make great looking maps of your data
with python. Two of these which are very popular are [`basemap`](http://matplotlib.org/basemap/) and [`cartopy`](http://scitools.org.uk/cartopy/). My personal
choice (LM) is `cartopy` and that is what we will use in this class.

This is one of the sample maps that we are going to make. It shows the Indian subcontinent and the Himalayan collision zone along with Earthquake data and strain rate data. The "contours" on the left hand map are flow lines of the plate velocity.
In order to make maps like this we have to get very familiar with the cartopy package, we also have to get comfortable with manipulation of the data which is usually stored as 2d arrays / images.
### Structure of the lesson
The first thing we have to do is to make sure we all have copies of all the data. Most of this is open source and available for download on the web. There are some python packages (of course) to help with this and I have put everything into a notebook for you. You have to run this before trying any of the exercises will work. Some of the data I had to download and process a bit beforehand (aka here is one I prepared earlier) and this notebook will make a copy of those files to ensure nothing gets irretrievably broken.
- <a href="/notebooks/Notebooks/Mapping/0 - Preliminaries.ipynb" target="_blank"> <!--_--> Notebook: Preliminaries </a>
Next we will move on to a simple example to become familiar with the way that cartopy works
- <a href="/notebooks/Notebooks/Mapping/1 - Introducting Cartopy.ipynb"target="_blank"> <!--_--> Notebook: Starting with Cartopy </a>
Plotting maps is often a matter of wrestling with _map projections_. Cartopy has a full range of projections built in. These can involve significant computation so we may not be able to try all of them. We also introduce the idea of a GeoTIFF which is an image format which also carries some information about the geographical extent of the image - this greatly enhances the transportability and useablility of the images.
- <a href="/notebooks/Notebooks/Mapping/2 - Images and GeoTIFFs.ipynb"target="_blank"> <!--_ --> Notebook: Images </a>
Now we take some data on magnetic intensity for the Australian continent and use the array manipulation capability of numpy to mask out areas we don't want to see. We then use _cartopy features_ to superimpose this map on a background global map.
- <a href="/notebooks/Notebooks/Mapping/3 - Working with real data.ipynb"target="_blank"> <!--_--> Notebook: Plotting our downloaded datasets </a>
Some of the datasets we have downloaded (sea floor age, strain rate) are better off as contour maps so that we have control over the colouring, so we can emphasise particular parts of the data range and so that we can show contour lines on top of an image.
- <a href="/notebooks/Notebooks/Mapping/4 - Contouring Global Data.ipynb"target="_blank"> <!--_--> Notebook: Contour maps </a>
Some data are scattered clouds of points like the locations of earthquake epicentres. We can plot these data just as we would plot a scatter graph but also in any projection we choose. Also introducing a few pieces of the `obspy` package which grabs the data from the various earthquake databases (and a lot more that we are not going to touch on here).
- <a href="/notebooks/Notebooks/Mapping/5 - Working with point data.ipynb"target="_blank"> <!--_ --> Notebook: Seismicity / point data </a>
Cartopy has a built in capability to query and download data from the [space shuttle radar topography mission](http://www2.jpl.nasa.gov/srtm/) and plot it. There are other on line services (google maps, for example) which also allow you to download data on the fly. Cartopy has built in support for many of these.
- <a href="/notebooks/Notebooks/Mapping/6 - Working with Shuttle Radar Topography.ipynb" target="_blank"> <!--_ --> Notebook: Shuttle Radar Topography </a>
- <a href="/notebooks/Notebooks/Mapping/7 - Working with on-demand mapping services.ipynb" target="_blank"> <!--_ --> Notebook: On-demand mapping services </a>
We downloaded global plate motion vectors in various reference frames. These are vector data (velocity arrows) and can be plotted in various ways
- <a href="/notebooks/Notebooks/Mapping/8 - Global Plate Motions ++ .ipynb" target="_blank"> <!--_ --> Notebook: Plate motion vectors </a>
Finally, we take pieces of all these examples and build the map above.
- <a href="/notebooks/Notebooks/Mapping/9 - Himalaya region maps and images.ipynb" target="_blank"> <!--_ --> Notebook: Himalayan region </a>
(You can read the article it came from in [SIAM news](https://sinews.siam.org/DetailsPage/tabid/607/ArticleID/685/Computational-Plate-Tectonics-and-the-Geological-Record-in-the-Continents.aspx) and see some other cartopy maps)
---
### Help me !!
* [Louis Moresi's Home Page](http://www.moresi.info)
* [email Louis Moresi](mailto:Louis.Moresi@unimelb.edu.au)
* [`cartopy` home page](http://scitools.org.uk/cartopy/)
* [`basemap` home page](http://matplotlib.org/basemap/)
|
lmoresi/UoM-VIEPS-Intro-to-Python
|
docs/MakingMapsWithPython.md
|
Markdown
|
mit
| 5,204
|
//*********************** Lab 1 **************************
// Program written by:
// - Steven Prickett EID: srp2389
// - Kelvin Le EID: kl24956
// Date Created: 1/22/2015
// Date Modified: 1/25/2015
//
// Lab number: 1
//
// Brief description of the program:
// -
//
// Hardware connections:
// - Outputs:
// - PA2 Screen SSI SCK (SSI0Clk)
// - PA3 Screen SSI CS (SSI0Fss)
// - PA5 Screen SSI TX (SSI0Tx)
// - PA6 Screen Data/Command Pin (GPIO)
// - PA7 Screen RESET Pin (GPIO)
// - Inputs:
// -
//
// Peripherals used:
// - TIMER0 ADC0 trigger
//*********************************************************
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "tm4c123gh6pm.h"
#include "debug.h"
#include "pll.h"
#include "st7735.h"
#include "usb_uart.h"
#include "systick.h"
#include "pwm.h"
#include "adc.h"
#include "timer0.h"
#include "interpreter.h"
#include "debug.h"
#define LCD_WIDTH 128
#define LCD_HEIGHT 160
#define OUTPUT_UART_ENABLED (true)
#define OUTPUT_SCREEN_ENABLED (false)
// prototypes for functions defined in startup.s
void DisableInterrupts(void); // Disable interrupts
void EnableInterrupts(void); // Enable interrupts
long StartCritical (void); // previous I bit, disable interrupts
void EndCritical(long sr); // restore I bit to previous value
void WaitForInterrupt(void); // low power mode
// global variables
uint32_t msElapsed = 0;
char stringBuffer[16];
bool updateScreen = false;
uint32_t dd=0;
uint32_t loopcount=0;
int main(void){
DisableInterrupts();
//////////////////////// perhipheral initialization ////////////////////////
// init PLL to 80Mhz
PLL_Init();
// init screen, use white as text color
Output_Init();
Output_Color(ST7735_WHITE);
//Output_Clear();
// init usb uart, generate interrupts when data received via usb
USB_UART_Init();
USB_UART_Enable_Interrupt();
// init systick to generate an interrupt every 1ms (every 80000 cycles)
//SysTick_Init(80000);
// init and enable PWM
// PWM0A_Init(40000, 20000);
// PWM0A_Enable();
// init debug LEDs
DEBUG_Init();
// global enable interrupts
EnableInterrupts();
//////////////////////// main loop ////////////////////////
while(1){
WaitForInterrupt();
/*
if (updateScreen){
updateScreen = false;
// screen stuff here
}
*/
if (USB_BufferReady){
USB_BufferReady = false;
//INTER_HandleBuffer();
loopcount++;
dd++;
// experimental test comment
}
}
}
// this is used for printf to output to both the screen and the usb uart
int fputc(int ch, FILE *f){
if (OUTPUT_SCREEN_ENABLED) ST7735_OutChar(ch); // output to screen
if (OUTPUT_UART_ENABLED) USB_UART_PrintChar(ch); // output via usb uart
return 1;
}
|
kle8309/OS_PROJECT
|
main.c
|
C
|
mit
| 2,906
|
package com.tikal.logregator.s3;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.event.S3EventNotification;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tikal.logregator.LogEntry;
import com.tikal.logregator.LogSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.List;
/**
* Created by haimcohen on 07/12/2016.
*/
public class LogEntryLambdaListener implements RequestHandler<S3Event, String> {
Logger logger = LoggerFactory.getLogger(LogEntryLambdaListener.class);
@Override
public String handleRequest(S3Event input, Context context) {
AmazonS3 s3Client = new AmazonS3Client();
List<S3EventNotification.S3EventNotificationRecord> records = input.getRecords();
ObjectMapper mapper = new ObjectMapper();
LogSender kafkaSender = new LogSender();
records.forEach(record -> {
String srcBucket = record.getS3().getBucket().getName();
// Object key may have spaces or unicode non-ASCII characters.
String srcKey = record.getS3().getObject().getKey();
try {
logger.info("Param from env:" + System.getenv("TEST_KEY"));
S3Object s3Object = s3Client.getObject(new GetObjectRequest(
srcBucket, srcKey));
InputStream is = s3Object.getObjectContent();
InputStreamReader r = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(r);
String line = null;
while((line = reader.readLine()) != null) {
LogEntry entry = LogEntry.parse(line);
String json = mapper.writeValueAsString(entry);
//TODO Send file to kafka
logger.info("sending to kafka the following json: " + json);
kafkaSender.sendMessage(json);
}
logger.info("Handling bucket " + srcBucket + " and key " + srcKey);
} catch (IOException e) {
logger.error("Unable handling s3 object " + srcBucket+"/"+srcKey+": " + e.getMessage(), e);
}
});
return null;
}
}
|
barkanido/logregator
|
src/main/java/com/tikal/logregator/s3/LogEntryLambdaListener.java
|
Java
|
mit
| 2,583
|
# Docker: emscripten
[](https://store.docker.com/community/images/trzeci/emscripten/) [](https://microbadger.com/images/trzeci/emscripten/)
A complete container that is required to compile C++ code with [Emscripten](http://emscripten.org). The goal was to provide a container that includes the most popular development packages and it's also easy to extend.
Since tag 1.37.16 this container bases on https://hub.docker.com/r/trzeci/emscripten-slim/
## Structure
Each tag was build from [Dockerfile](https://github.com/trzecieu/emscripten-docker/blob/master/docker/trzeci/emscripten/Dockerfile)
* Base system: **trzeci/emscripten-slim**
* Installed packages:
* `ant` : **1.9.9-1+deb9u1**
* `build-essential` : **12.3**
* `ca-certificates` : **20161130+nmu1+deb9u1**
* `curl` : **7.52.1-5+deb9u9**
* `gcc` : **4:6.3.0-4**
* `git` : **1:2.11.0-3+deb9u4**
* `iproute2` : **4.9.0-1+deb9u1**
* `iputils-ping` : **3:20161105-1**
* `libidn11` : **1.33-1**
* `make` : **4.1-9.1**
* `openjdk-8-jre-headless` : **8u181-b13-2~deb9u1**
* `openssh-client` : **1:7.4p1-10+deb9u4**
* `python` : **2.7.13-2**
* `python-pip` : **9.0.1-2**
* `unzip` : **6.0-21**
* `wget` : **1.18-5+deb9u2**
* `zip` : **3.0-11+b1**
* Extra packages:
* `cmake`: **3.14.3**
## Tag schema
### latest
The default version (aka `latest`) points at [the latest tagged release](https://github.com/kripken/emscripten/releases) by Emscripten.
### Version release
`sdk-tag-{VERSION}-{BITS}`
* **VERSION**: One of the official [Emscripten tag](https://github.com/kripken/emscripten/tags) released since 1.34.1
* **BITS**: `["32bit", "64bit"]`
Example: `sdk-tag-1.34.4-64bit`
### Branch release
`sdk-{BRANCH}-{BITS}`
* **BRANCH**: `["incoming", "master"]`
* **BITS**: `["32bit", "64bit"]`
Example: `sdk-master-32bit`
## Usage
Start volume should be mounted in `/src`.
For start point every Emscripten command is available. For the instance: `emcc`, `em++`, `emmake`, `emar` etc.
To compile a single file:
`docker run --rm -v $(pwd):/src trzeci/emscripten emcc helloworld.cpp -o helloworld.js --closure 1`
Hello World:
```bash
printf '#include <iostream>\nint main() { std::cout<<"HELLO FROM DOCKER C++"<<std::endl; return 0; }' > helloworld.cpp
docker run \
--rm \
-v $(pwd):/src \
-u emscripten \
trzeci/emscripten \
emcc helloworld.cpp -o helloworld.js --closure 1
node helloworld.js
```
Teardown of compilation command:
|part|description|
|---|---|
|`docker run`| A standard command to run a command in a container|
|`--rm`|remove a container after execution|
|`-v $(pwd):/src`|Mounting current folder from the host system, into `/src` of the image|
|`-u emscripten`|(1.37.23+) Run a container as a non-root user `emscripten`, hence all files produced by this are accessible to non-root users|
|`trzeci/emscripten`|Get the latest tag of this container|
|`emcc helloworld.cpp -o helloworld.js --closure 1`|Execute emcc command with following arguments inside container|
## How to compile?
0. Pull the latest https://github.com/trzecieu/emscripten-docker
0. [Optional] To be extra accurate, you can check which version of [EMSDK](https://github.com/juj/emsdk) was used in a particular image. For older images you can check [a file](https://github.com/trzecieu/emscripten-docker/blob/master/emscripten_to_emsdk_map.md) otherwise for images 1.38.9+ execute a command `docker run --rm -it trzeci/emscripten:sdk-tag-1.38.9-64bit bash -c "git -C /emsdk_portable rev-parse HEAD"`
0. Compile [Dockerfile](https://github.com/trzecieu/emscripten-docker/blob/master/docker/trzeci/emscripten/Dockerfile)
Helper command: `./build compile trzeci/emscripten:sdk-tag-1.37.17-64bit` (where `sdk-tag-1.37.17-64bit` is an arbitrary tag)
## Support
* **GitHub / Issue tracker**: https://github.com/trzecieu/emscripten-docker
* **Docker: emscripten**: https://hub.docker.com/r/trzeci/emscripten/
* **Docker: emscripten-slim**: https://hub.docker.com/r/trzeci/emscripten-slim/
## History
* **1.38.30** [#40](https://github.com/trzecieu/emscripten-docker/issues/40) Fixed image compilation problem caused by JRE backport package
* **1.38.22** [#35](https://github.com/trzecieu/emscripten-docker/issues/35) upgrade to `cmake` 3.12.2
* **1.38.17** Version ignored due problems with [Emscripten]
* **1.38.9** `/emsdk_portable` will be preserved as a git repos (with valid version of changeset)
* **1.38.7** Version removed due problems with [emsdk](https://github.com/juj/emsdk/pull/156)
* **1.37.29** upgrade to `cmake` 3.7.2
* **1.37.23** Added `curl`, `zip`, `unzip`, upgrade to openjdk-jre-8
* **1.37.21** Fixed missing `ctest` command
* **1.37.21** image includes `ssh` and cache of libc libcxx is fixed.
* **1.37.19** image doesn't use entrypoint from the base image.
* **1.37.18** it contains `perl` and `git` package
* **1.37.16** images are compiled from singe [Dockerfile](https://github.com/trzecieu/emscripten-docker/blob/master/docker/trzeci/emscripten/Dockerfile).
* **1.37.10** images are bundled with `java`
* **1.36.7** images are bundled with `make` and `nodejs`
* **1.36.7** images are bundled with `cmake` 3.6.3, images are build from generated [Dockerfiles](https://github.com/trzecieu/emscripten-docker/tree/f738f061c8068ec24124c37286eafec01d54a6ef/configs)
* **1.35.0** images base on Debian
* **1.34.X** images base on Ubuntu:15.10
### License
MIT
|
asRIA/emscripten-docker
|
emscripten.md
|
Markdown
|
mit
| 5,518
|
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Key | picturepark-sdk-v1-pickers API</title>
<meta name="description" content="Documentation for picturepark-sdk-v1-pickers API">
<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.json" 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">picturepark-sdk-v1-pickers API</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="../modules/_readline_.html">"readline"</a>
</li>
<li>
<a href="_readline_.key.html">Key</a>
</li>
</ul>
<h1>Interface Key</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">Key</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="_readline_.key.html#ctrl" class="tsd-kind-icon">ctrl</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_readline_.key.html#meta" class="tsd-kind-icon">meta</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_readline_.key.html#name" class="tsd-kind-icon">name</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_readline_.key.html#sequence" class="tsd-kind-icon">sequence</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface tsd-is-external"><a href="_readline_.key.html#shift" class="tsd-kind-icon">shift</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="ctrl" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> ctrl</h3>
<div class="tsd-signature tsd-kind-icon">ctrl<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/readline.d.ts:8</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="meta" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> meta</h3>
<div class="tsd-signature tsd-kind-icon">meta<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/readline.d.ts:9</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="name" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> name</h3>
<div class="tsd-signature tsd-kind-icon">name<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/readline.d.ts:7</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="sequence" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> sequence</h3>
<div class="tsd-signature tsd-kind-icon">sequence<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/readline.d.ts:6</li>
</ul>
</aside>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a name="shift" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> shift</h3>
<div class="tsd-signature tsd-kind-icon">shift<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in node_modules/@types/node/readline.d.ts:10</li>
</ul>
</aside>
</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>
<li class="current tsd-kind-module tsd-is-external">
<a href="../modules/_readline_.html">"readline"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_readline_.interface.html" class="tsd-kind-icon">Interface</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="_readline_.cursorpos.html" class="tsd-kind-icon">Cursor<wbr>Pos</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="_readline_.key.html" class="tsd-kind-icon">Key</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_readline_.key.html#ctrl" class="tsd-kind-icon">ctrl</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_readline_.key.html#meta" class="tsd-kind-icon">meta</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_readline_.key.html#name" class="tsd-kind-icon">name</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_readline_.key.html#sequence" class="tsd-kind-icon">sequence</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface tsd-is-external">
<a href="_readline_.key.html#shift" class="tsd-kind-icon">shift</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="_readline_.readlineoptions.html" class="tsd-kind-icon">Read<wbr>Line<wbr>Options</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#asynccompleter" class="tsd-kind-icon">Async<wbr>Completer</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#completer" class="tsd-kind-icon">Completer</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#completerresult" class="tsd-kind-icon">Completer<wbr>Result</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#direction" class="tsd-kind-icon">Direction</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#readline" class="tsd-kind-icon">Read<wbr>Line</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#clearline" class="tsd-kind-icon">clear<wbr>Line</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#clearscreendown" class="tsd-kind-icon">clear<wbr>Screen<wbr>Down</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#createinterface" class="tsd-kind-icon">create<wbr>Interface</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#cursorto" class="tsd-kind-icon">cursor<wbr>To</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#emitkeypressevents" class="tsd-kind-icon">emit<wbr>Keypress<wbr>Events</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="../modules/_readline_.html#movecursor" class="tsd-kind-icon">move<wbr>Cursor</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
</body>
</html>
|
Picturepark/Picturepark.SDK.TypeScript
|
docs/picturepark-sdk-v1-pickers/api/interfaces/_readline_.key.html
|
HTML
|
mit
| 11,435
|
# system detection
platform='unknown'
unamestr=`uname`
if [[ "$unamestr" == 'Linux' ]]; then
platform='linux'
elif [[ "$unamestr" == 'Darwin' ]]; then
platform='mac'
fi
###################################
# PATH
###################################
if [[ "$platform" == 'mac' ]]; then
export PATH=~/bin:/usr/local/sbin:$PATH
else
export PATH=~/bin:/opt/fiji:$PATH:~/.local/bin
export LD_LIBRARY_PATH=/opt/cuda/lib64:/opt/cuda/lib:$LD_LIBRARY_PATH
fi
# bibinputs
export BIBINPUTS="~/Dropbox/bibliography/"
# IDL
#export IDL_PATH=+~/lib/idl:$IDL_PATH
export IDL_STARTUP=~/lib/idl/idlstartup.pro
# MATLAB
# export MATLABPATH=$MATLABPATH:~/lib/matlab:~/lib/matlab/linac:~/lib/matlab/export_fig:~/lib/matlab/matlab2tikz/src
export MATLABPATH=$MATLABPATH:~/devel/matlab
# Anaconda
# export PATH=~/miniconda3/bin:"$PATH"
# pdflatex
export PDFLATEX="pdflatex --shell-escape"
# plantuml
export GRAPHVIZ_DOT="/usr/bin/dot"
# ruby
PATH="$(ruby -e 'print Gem.user_dir')/bin:$PATH"
###################################
# virtualenv
###################################
# pyenv-virtual env
# export PYENV_VIRTUALENV_DISABLE_PROMPT=1
# use the same directory for virtualenvs as virtualenvwrapper
# export PIP_VIRTUALENV_BASE=$WORKON_HOME
# makes pip detect an active virtualenv and install to it
export PIP_RESPECT_VIRTUALENV=true
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/devel
# if [[ "$platform" == 'mac' ]]; then
# export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python
# source /usr/local/bin/virtualenvwrapper.sh
# else
# source ~/.local/bin/virtualenvwrapper.sh
# fi
###################################
# CUDA
###################################
# CUDA (only linux for now)
if [[ "$platform" == 'linux' ]]; then
# core dumps
export CUDA_ENABLE_COREDUMP_ON_EXCEPTION=1
fi
# # CUDA (only linux for now)
# if [[ "$platform" == 'linux' ]]; then
# # core dumps
# export CUDA_ENABLE_COREDUMP_ON_EXCEPTION=1
# fi
###################################
# emacs
###################################
# Editor config
export EDITOR=emacsclient
#export ALTERNATE_EDITOR=vim
export VISUAL=emacsclient
# Emacs Environment
###################################
# mail
###################################
export MAILDIR=~/.mail
###################################
# music
###################################
# export XDG_MUSIC_DIR=~/music
|
reconmaster/dotfiles
|
bash/env.sh
|
Shell
|
mit
| 2,387
|
//
// AppDelegate.h
// CleverRoad
//
// Created by Admin on 1/25/15.
// Copyright (c) 2015 leonidkokhnovych. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;
@end
|
LeonidKokhnovich/CleverRoadTestApp
|
CleverRoad/CleverRoad/AppDelegate.h
|
C
|
mit
| 642
|
IF OBJECT_ID('dbo.usp_bcpTableUnload', 'P') IS NULL EXECUTE ('CREATE PROCEDURE dbo.usp_bcpTableUnload AS SELECT 1');
go
ALTER PROCEDURE dbo.usp_bcpTableUnload (
@path NVARCHAR(900)
, @serverName SYSNAME = @@SERVERNAME
, @databaseName SYSNAME
, @schemaName SYSNAME
, @tableName SYSNAME
, @field_term NVARCHAR(10) = '|'
, @row_term NVARCHAR(10) = '\n'
, @fileExtension NVARCHAR(10) = 'txt'
, @codePage NVARCHAR(10) = 'C1251'
, @excludeColumns NVARCHAR(MAX) = ''
, @orderByColumns NVARCHAR(MAX) = ''
, @outputColumnHeaders BIT = 1
, @debug BIT = 0
)
AS
/*
bcp docs: https://msdn.microsoft.com/ru-ru/library/ms162802.aspx
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1;
GO
-- To update the currently configured value for advanced options.
RECONFIGURE;
GO
-- To enable the feature.
EXEC sp_configure 'xp_cmdshell', 1;
GO
-- To update the currently configured value for this feature.
RECONFIGURE;
GO
EXECUTE [dbo].[usp_bcpTableUnload]
@path = 'd:\'
, @databaseName = 'DatabaseName'
, @schemaName = 'dbo'
, @tableName = 'TableName'
, @field_term = '|'
, @row_term = '\n'
, @fileExtension = 'txt'
, @excludeColumns = '[CreatedDate],[ModifiedDate],[UserID]'
, @orderByColumns = 'TableNameID'
, @outputColumnHeaders = 1
, @debug = 0;
*/
BEGIN
BEGIN TRY
IF @debug = 0 SET NOCOUNT ON;
DECLARE @tsqlCommand NVARCHAR(MAX) = '';
DECLARE @cmdCommand VARCHAR(8000) = '';
DECLARE @ParmDefinition NVARCHAR(500) = '@object_idIN INTEGER, @ColumnsOUT VARCHAR(MAX) OUTPUT';
DECLARE @tableFullName SYSNAME = QUOTENAME(@databaseName) + '.' + QUOTENAME(@schemaName) + '.' + QUOTENAME(@tableName);
DECLARE @object_id INTEGER = OBJECT_ID(@tableFullName);
DECLARE @Columns NVARCHAR(MAX) = '';
DECLARE @filePath NVARCHAR(900) = @path + @tableFullName + '.' + @fileExtension;
DECLARE @crlf NVARCHAR(10) = CHAR(13);
DECLARE @orderByColumns_term NVARCHAR(10) = ',';
DECLARE @TROW50000 NVARCHAR(MAX) = 'Table ' + @tableFullName + ' is not exists in database ' + QUOTENAME(@databaseName) + '!!!';
DECLARE @TROW50001 NVARCHAR(MAX) = 'Some columns in @orderByColumns = {' + @orderByColumns + '} not exists in table ' + @tableFullName + '!!!';
IF @debug = 1 PRINT ISNULL('/******* Start Debug' + @crlf + '@tableFullName = {' + CAST(@tableFullName AS NVARCHAR(MAX)) + '}', '@tableFullName = {Null}');
IF @debug = 1 PRINT ISNULL('@object_id = {' + CAST(@object_id AS NVARCHAR(MAX)) + '}', '@object_id = {Null}');
IF @object_id IS NULL THROW 50000, @TROW50000, 1
IF @orderByColumns <> ''
BEGIN
SET @tsqlCommand = N'USE ' + @databaseName + ';' + @crlf +
N'SELECT @ColumnsOUT = COUNT(*)' + @crlf +
N'FROM sys.columns sac ' + @crlf +
N'WHERE sac.object_id = @object_idIN' + @crlf +
N' AND QUOTENAME(Name) IN (''[' + REPLACE(@orderByColumns, ',', ']'',''[') + ']'');' + @crlf;
IF @debug = 1 PRINT ISNULL(N'@tsqlCommand = {' + @crlf + @tsqlCommand + @crlf + N'}', N'@tsqlCommand = {Null}');
EXECUTE sp_executesql @tsqlCommand, @ParmDefinition, @object_idIN = @object_id, @ColumnsOUT = @Columns OUTPUT SELECT @Columns;
IF @Columns <> (DATALENGTH(@orderByColumns) - DATALENGTH(Replace(@orderByColumns, @orderByColumns_term, ''))) / DATALENGTH(@orderByColumns_term) + 1
THROW 50001, @TROW50001, 1;
SET @Columns = '';
END;
SET @tsqlCommand = N'USE ' + @databaseName + ';' + @crlf +
N'SELECT @ColumnsOUT = @ColumnsOUT + QUOTENAME(Name) + '',''' + @crlf +
N'FROM sys.columns sac ' + @crlf +
N'WHERE sac.object_id = @object_idIN' + @crlf +
N' AND QUOTENAME(Name) NOT IN (''' + REPLACE(@excludeColumns, ',', ''',''') + ''')' + @crlf +
N'ORDER BY Name;';
IF @debug = 1 PRINT ISNULL(N'@tsqlCommand = {' + @crlf + @tsqlCommand + @crlf + N'}', N'@tsqlCommand = {Null}');
EXECUTE sp_executesql @tsqlCommand, @ParmDefinition, @object_idIN = @object_id, @ColumnsOUT = @Columns OUTPUT SELECT @Columns;
IF @debug = 1 PRINT ISNULL('@Columns = {' + @crlf + @Columns + @crlf + '}', '@Columns = {Null}');
SET @Columns = CASE WHEN LEN(@Columns) > 0 THEN LEFT(@Columns, LEN(@Columns) - 1) END;
IF @debug = 1 PRINT CAST(ISNULL('@Columns = {' + @Columns + '}', '@Columns = {Null}') AS TEXT);
SET @tsqlCommand = 'EXECUTE xp_cmdshell ' + '''bcp "SELECT ' + @Columns + ' FROM ' + @tableFullName +
CASE WHEN @orderByColumns <> '' THEN ' ORDER BY ' + @orderByColumns ELSE '' END +
'" queryout "' + @filePath + '" -T -S ' + @serverName +' -c -' + @codePage +
' -t"' + @field_term + '"' + ' -r"' + @row_term + '"''' + @crlf;
IF @debug = 1 PRINT CAST(ISNULL('@tsqlCommand = {' + @crlf + @tsqlCommand + @crlf + '}', '@tsqlCommand = {Null}' + @crlf) AS TEXT);
ELSE EXECUTE sp_executesql @tsqlCommand;
IF @outputColumnHeaders = 1
BEGIN
SET @tsqlCommand = 'EXECUTE xp_cmdshell ' + '''bcp "SELECT ''''' + REPLACE(@Columns, ',', @field_term) +
'''''" queryout "' + @path + @tableFullName + '_headers.txt' + '" -T -S ' +
@serverName + ' -c -' + @codePage + ' -t"' + @field_term + '"' +
' -r"' + @row_term + '"''' + @crlf;
IF @debug = 1 PRINT CAST(ISNULL('@tsqlCommand = {' + @crlf + @tsqlCommand + @crlf + '}',
'@tsqlCommand = {Null}' + @crlf) AS TEXT);
ELSE EXECUTE sp_executesql @tsqlCommand;
SET @cmdCommand = 'copy /b ' + @path + @tableFullName + '_headers.' + @fileExtension + ' + ' +
@filePath + ' ' + @path + @tableFullName + '_headers.' + @fileExtension;
IF @debug = 1 PRINT CAST(ISNULL('@cmdCommand = {' + @crlf + @cmdCommand + @crlf + '}', '@cmdCommand = {Null}' + @crlf) AS TEXT)
ELSE EXECUTE xp_cmdshell @cmdCommand;
SET @cmdCommand = 'del ' + @filePath;
IF @debug = 1 PRINT CAST(ISNULL('@cmdCommand = {' + @crlf + @cmdCommand + @crlf + '}', '@cmdCommand = {Null}' + @crlf) AS TEXT)
ELSE EXECUTE xp_cmdshell @cmdCommand;
END
IF @debug = 1 PRINT '--End Deubg*********/';
ELSE SET NOCOUNT OFF;
END TRY
BEGIN CATCH
EXECUTE dbo.usp_LogError;
EXECUTE dbo.usp_PrintError;
END CATCH
END;
|
amanrajbits/sql
|
Stored_Procedure/usp_bcpTableUnload.sql
|
SQL
|
mit
| 7,476
|
<!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_45) on Tue May 12 14:55:49 CEST 2015 -->
<title>All Classes</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="service/adaptation/effectors/AbstractEffector.html" title="class in service.adaptation.effectors">AbstractEffector</a></li>
<li><a href="service/auxiliary/AbstractMessage.html" title="class in service.auxiliary">AbstractMessage</a></li>
<li><a href="service/adaptation/probes/AbstractProbe.html" title="class in service.adaptation.probes">AbstractProbe</a></li>
<li><a href="service/workflow/AbstractQoSRequirement.html" title="interface in service.workflow"><span class="interfaceName">AbstractQoSRequirement</span></a></li>
<li><a href="service/auxiliary/AbstractService.html" title="class in service.auxiliary">AbstractService</a></li>
<li><a href="service/client/AbstractServiceClient.html" title="class in service.client">AbstractServiceClient</a></li>
<li><a href="service/workflow/ast/ASTNode.html" title="class in service.workflow.ast">ASTNode</a></li>
<li><a href="service/workflow/ast/ASTNode.AndOp.html" title="class in service.workflow.ast">ASTNode.AndOp</a></li>
<li><a href="service/workflow/ast/ASTNode.ArgumentList.html" title="class in service.workflow.ast">ASTNode.ArgumentList</a></li>
<li><a href="service/workflow/ast/ASTNode.ArrayAccess.html" title="class in service.workflow.ast">ASTNode.ArrayAccess</a></li>
<li><a href="service/workflow/ast/ASTNode.AssignmentStmt.html" title="class in service.workflow.ast">ASTNode.AssignmentStmt</a></li>
<li><a href="service/workflow/ast/ASTNode.AssignOp.html" title="class in service.workflow.ast">ASTNode.AssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.ASTList.html" title="class in service.workflow.ast">ASTNode.ASTList</a></li>
<li><a href="service/workflow/ast/ASTNode.BinaryOperator.html" title="class in service.workflow.ast">ASTNode.BinaryOperator</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseAndAssignOp.html" title="class in service.workflow.ast">ASTNode.BitwiseAndAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseAndOp.html" title="class in service.workflow.ast">ASTNode.BitwiseAndOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseExclOrOp.html" title="class in service.workflow.ast">ASTNode.BitwiseExclOrOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseInclOrOp.html" title="class in service.workflow.ast">ASTNode.BitwiseInclOrOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseOrAssignOp.html" title="class in service.workflow.ast">ASTNode.BitwiseOrAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BitwiseXorAssignOp.html" title="class in service.workflow.ast">ASTNode.BitwiseXorAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.BooleanLiteral.html" title="class in service.workflow.ast">ASTNode.BooleanLiteral</a></li>
<li><a href="service/workflow/ast/ASTNode.DivideAssignOp.html" title="class in service.workflow.ast">ASTNode.DivideAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.DivisionOp.html" title="class in service.workflow.ast">ASTNode.DivisionOp</a></li>
<li><a href="service/workflow/ast/ASTNode.DoWhile.html" title="class in service.workflow.ast">ASTNode.DoWhile</a></li>
<li><a href="service/workflow/ast/ASTNode.EqualOp.html" title="class in service.workflow.ast">ASTNode.EqualOp</a></li>
<li><a href="service/workflow/ast/ASTNode.Expression.html" title="class in service.workflow.ast">ASTNode.Expression</a></li>
<li><a href="service/workflow/ast/ASTNode.ExprList.html" title="class in service.workflow.ast">ASTNode.ExprList</a></li>
<li><a href="service/workflow/ast/ASTNode.ForLoop.html" title="class in service.workflow.ast">ASTNode.ForLoop</a></li>
<li><a href="service/workflow/ast/ASTNode.GtEqualOp.html" title="class in service.workflow.ast">ASTNode.GtEqualOp</a></li>
<li><a href="service/workflow/ast/ASTNode.GtOp.html" title="class in service.workflow.ast">ASTNode.GtOp</a></li>
<li><a href="service/workflow/ast/ASTNode.If.html" title="class in service.workflow.ast">ASTNode.If</a></li>
<li><a href="service/workflow/ast/ASTNode.ImplyOp.html" title="class in service.workflow.ast">ASTNode.ImplyOp</a></li>
<li><a href="service/workflow/ast/ASTNode.IntegerLiteral.html" title="class in service.workflow.ast">ASTNode.IntegerLiteral</a></li>
<li><a href="service/workflow/ast/ASTNode.LeftShiftAssignOp.html" title="class in service.workflow.ast">ASTNode.LeftShiftAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.LeftShiftOp.html" title="class in service.workflow.ast">ASTNode.LeftShiftOp</a></li>
<li><a href="service/workflow/ast/ASTNode.LogicalAndOp.html" title="class in service.workflow.ast">ASTNode.LogicalAndOp</a></li>
<li><a href="service/workflow/ast/ASTNode.LogicOrOp.html" title="class in service.workflow.ast">ASTNode.LogicOrOp</a></li>
<li><a href="service/workflow/ast/ASTNode.LtEqualOp.html" title="class in service.workflow.ast">ASTNode.LtEqualOp</a></li>
<li><a href="service/workflow/ast/ASTNode.LtOp.html" title="class in service.workflow.ast">ASTNode.LtOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MaxOp.html" title="class in service.workflow.ast">ASTNode.MaxOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MethodRef.html" title="class in service.workflow.ast">ASTNode.MethodRef</a></li>
<li><a href="service/workflow/ast/ASTNode.MinOp.html" title="class in service.workflow.ast">ASTNode.MinOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MinusAssignOp.html" title="class in service.workflow.ast">ASTNode.MinusAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MinusOp.html" title="class in service.workflow.ast">ASTNode.MinusOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MultAssignOp.html" title="class in service.workflow.ast">ASTNode.MultAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.MultOp.html" title="class in service.workflow.ast">ASTNode.MultOp</a></li>
<li><a href="service/workflow/ast/ASTNode.NotEqualOp.html" title="class in service.workflow.ast">ASTNode.NotEqualOp</a></li>
<li><a href="service/workflow/ast/ASTNode.NullLiteral.html" title="class in service.workflow.ast">ASTNode.NullLiteral</a></li>
<li><a href="service/workflow/ast/ASTNode.OrOp.html" title="class in service.workflow.ast">ASTNode.OrOp</a></li>
<li><a href="service/workflow/ast/ASTNode.Parallel.html" title="class in service.workflow.ast">ASTNode.Parallel</a></li>
<li><a href="service/workflow/ast/ASTNode.Param.html" title="class in service.workflow.ast">ASTNode.Param</a></li>
<li><a href="service/workflow/ast/ASTNode.ParamList.html" title="class in service.workflow.ast">ASTNode.ParamList</a></li>
<li><a href="service/workflow/ast/ASTNode.PlusAssignOp.html" title="class in service.workflow.ast">ASTNode.PlusAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.PlusOp.html" title="class in service.workflow.ast">ASTNode.PlusOp</a></li>
<li><a href="service/workflow/ast/ASTNode.PostDecrement.html" title="class in service.workflow.ast">ASTNode.PostDecrement</a></li>
<li><a href="service/workflow/ast/ASTNode.PostIncrement.html" title="class in service.workflow.ast">ASTNode.PostIncrement</a></li>
<li><a href="service/workflow/ast/ASTNode.PreDecrementOp.html" title="class in service.workflow.ast">ASTNode.PreDecrementOp</a></li>
<li><a href="service/workflow/ast/ASTNode.PreIncrementOp.html" title="class in service.workflow.ast">ASTNode.PreIncrementOp</a></li>
<li><a href="service/workflow/ast/ASTNode.Prime.html" title="class in service.workflow.ast">ASTNode.Prime</a></li>
<li><a href="service/workflow/ast/ASTNode.QualifiedAcess.html" title="class in service.workflow.ast">ASTNode.QualifiedAcess</a></li>
<li><a href="service/workflow/ast/ASTNode.RemainderAssignOp.html" title="class in service.workflow.ast">ASTNode.RemainderAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.RemainderOp.html" title="class in service.workflow.ast">ASTNode.RemainderOp</a></li>
<li><a href="service/workflow/ast/ASTNode.Return.html" title="class in service.workflow.ast">ASTNode.Return</a></li>
<li><a href="service/workflow/ast/ASTNode.RightShiftAssignOp.html" title="class in service.workflow.ast">ASTNode.RightShiftAssignOp</a></li>
<li><a href="service/workflow/ast/ASTNode.RightShiftOp.html" title="class in service.workflow.ast">ASTNode.RightShiftOp</a></li>
<li><a href="service/workflow/ast/ASTNode.Start.html" title="class in service.workflow.ast">ASTNode.Start</a></li>
<li><a href="service/workflow/ast/ASTNode.Stmnt.html" title="class in service.workflow.ast">ASTNode.Stmnt</a></li>
<li><a href="service/workflow/ast/ASTNode.StmntList.html" title="class in service.workflow.ast">ASTNode.StmntList</a></li>
<li><a href="service/workflow/ast/ASTNode.TaskList.html" title="class in service.workflow.ast">ASTNode.TaskList</a></li>
<li><a href="service/workflow/ast/ASTNode.TernaryOp.html" title="class in service.workflow.ast">ASTNode.TernaryOp</a></li>
<li><a href="service/workflow/ast/ASTNode.UnaryMinusOp.html" title="class in service.workflow.ast">ASTNode.UnaryMinusOp</a></li>
<li><a href="service/workflow/ast/ASTNode.UnaryNotOp.html" title="class in service.workflow.ast">ASTNode.UnaryNotOp</a></li>
<li><a href="service/workflow/ast/ASTNode.UnaryOperator.html" title="class in service.workflow.ast">ASTNode.UnaryOperator</a></li>
<li><a href="service/workflow/ast/ASTNode.UnaryPlusOp.html" title="class in service.workflow.ast">ASTNode.UnaryPlusOp</a></li>
<li><a href="service/workflow/ast/ASTNode.VarRef.html" title="class in service.workflow.ast">ASTNode.VarRef</a></li>
<li><a href="service/workflow/ast/ASTNode.While.html" title="class in service.workflow.ast">ASTNode.While</a></li>
<li><a href="tools/ASTSymTabVisualizer.html" title="class in tools">ASTSymTabVisualizer</a></li>
<li><a href="service/atomic/AtomicService.html" title="class in service.atomic">AtomicService</a></li>
<li><a href="service/auxiliary/AtomicServiceConfiguration.html" title="annotation in service.auxiliary">AtomicServiceConfiguration</a></li>
<li><a href="service/adaptation/effectors/CacheEffector.html" title="class in service.adaptation.effectors">CacheEffector</a></li>
<li><a href="service/composite/CompositeService.html" title="class in service.composite">CompositeService</a></li>
<li><a href="service/composite/CompositeServiceClient.html" title="class in service.composite">CompositeServiceClient</a></li>
<li><a href="service/auxiliary/CompositeServiceConfiguration.html" title="annotation in service.auxiliary">CompositeServiceConfiguration</a></li>
<li><a href="service/auxiliary/Configuration.html" title="class in service.auxiliary">Configuration</a></li>
<li><a href="service/adaptation/effectors/ConfigurationEffector.html" title="class in service.adaptation.effectors">ConfigurationEffector</a></li>
<li><a href="service/adaptation/probes/CostProbe.html" title="class in service.adaptation.probes">CostProbe</a></li>
<li><a href="service/adaptation/probes/interfaces/CostProbeInterface.html" title="interface in service.adaptation.probes.interfaces"><span class="interfaceName">CostProbeInterface</span></a></li>
<li><a href="tools/GMLExporter.html" title="class in tools">GMLExporter</a></li>
<li><a href="tools/GMLHelper.html" title="class in tools">GMLHelper</a></li>
<li><a href="profile/InputProfile.html" title="class in profile">InputProfile</a></li>
<li><a href="profile/InputProfileValue.html" title="class in profile">InputProfileValue</a></li>
<li><a href="profile/InputProfileVariable.html" title="class in profile">InputProfileVariable</a></li>
<li><a href="service/auxiliary/LocalOperation.html" title="annotation in service.auxiliary">LocalOperation</a></li>
<li><a href="service/utility/LogAtomicService.html" title="class in service.utility">LogAtomicService</a></li>
<li><a href="service/provider/MessageReceiver.html" title="interface in service.provider"><span class="interfaceName">MessageReceiver</span></a></li>
<li><a href="service/messagingservice/MessagingService.html" title="class in service.messagingservice">MessagingService</a></li>
<li><a href="service/messagingservice/MessagingServiceProvider.html" title="class in service.messagingservice">MessagingServiceProvider</a></li>
<li><a href="service/auxiliary/Operation.html" title="class in service.auxiliary">Operation</a></li>
<li><a href="service/auxiliary/OperationAborted.html" title="class in service.auxiliary">OperationAborted</a></li>
<li><a href="service/auxiliary/Param.html" title="class in service.auxiliary">Param</a></li>
<li><a href="profile/ProfileExecutor.html" title="class in profile">ProfileExecutor</a></li>
<li><a href="service/auxiliary/Request.html" title="class in service.auxiliary">Request</a></li>
<li><a href="service/auxiliary/Response.html" title="class in service.auxiliary">Response</a></li>
<li><a href="service/workflow/ast/rspLexer.html" title="class in service.workflow.ast">rspLexer</a></li>
<li><a href="service/workflow/ast/rspParser.html" title="class in service.workflow.ast">rspParser</a></li>
<li><a href="service/workflow/ast/rspParser.additive_expression_return.html" title="class in service.workflow.ast">rspParser.additive_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.and_expression_return.html" title="class in service.workflow.ast">rspParser.and_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.arguments_return.html" title="class in service.workflow.ast">rspParser.arguments_return</a></li>
<li><a href="service/workflow/ast/rspParser.assignment_operator_return.html" title="class in service.workflow.ast">rspParser.assignment_operator_return</a></li>
<li><a href="service/workflow/ast/rspParser.bitwise_and_expression_return.html" title="class in service.workflow.ast">rspParser.bitwise_and_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.block_return.html" title="class in service.workflow.ast">rspParser.block_return</a></li>
<li><a href="service/workflow/ast/rspParser.doWhileLoop_return.html" title="class in service.workflow.ast">rspParser.doWhileLoop_return</a></li>
<li><a href="service/workflow/ast/rspParser.equality_expression_return.html" title="class in service.workflow.ast">rspParser.equality_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.exclusive_or_expression_return.html" title="class in service.workflow.ast">rspParser.exclusive_or_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.expression_list_return.html" title="class in service.workflow.ast">rspParser.expression_list_return</a></li>
<li><a href="service/workflow/ast/rspParser.expression_return.html" title="class in service.workflow.ast">rspParser.expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.forLoop_return.html" title="class in service.workflow.ast">rspParser.forLoop_return</a></li>
<li><a href="service/workflow/ast/rspParser.ifStatement_return.html" title="class in service.workflow.ast">rspParser.ifStatement_return</a></li>
<li><a href="service/workflow/ast/rspParser.imply_expression_return.html" title="class in service.workflow.ast">rspParser.imply_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.inclusive_or_expression_return.html" title="class in service.workflow.ast">rspParser.inclusive_or_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.logical_and_expression_return.html" title="class in service.workflow.ast">rspParser.logical_and_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.logical_or_expression_return.html" title="class in service.workflow.ast">rspParser.logical_or_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.min_max_expression_return.html" title="class in service.workflow.ast">rspParser.min_max_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.multiplicative_expression_return.html" title="class in service.workflow.ast">rspParser.multiplicative_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.or_expression_return.html" title="class in service.workflow.ast">rspParser.or_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.parallelStatement_return.html" title="class in service.workflow.ast">rspParser.parallelStatement_return</a></li>
<li><a href="service/workflow/ast/rspParser.parameter_return.html" title="class in service.workflow.ast">rspParser.parameter_return</a></li>
<li><a href="service/workflow/ast/rspParser.parameters_return.html" title="class in service.workflow.ast">rspParser.parameters_return</a></li>
<li><a href="service/workflow/ast/rspParser.postfix_expression_return.html" title="class in service.workflow.ast">rspParser.postfix_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.primary_expression_return.html" title="class in service.workflow.ast">rspParser.primary_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.relational_expression_return.html" title="class in service.workflow.ast">rspParser.relational_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.returnStatement_return.html" title="class in service.workflow.ast">rspParser.returnStatement_return</a></li>
<li><a href="service/workflow/ast/rspParser.shift_expression_return.html" title="class in service.workflow.ast">rspParser.shift_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.start_return.html" title="class in service.workflow.ast">rspParser.start_return</a></li>
<li><a href="service/workflow/ast/rspParser.statement_return.html" title="class in service.workflow.ast">rspParser.statement_return</a></li>
<li><a href="service/workflow/ast/rspParser.ternary_expression_return.html" title="class in service.workflow.ast">rspParser.ternary_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.unary_expression_return.html" title="class in service.workflow.ast">rspParser.unary_expression_return</a></li>
<li><a href="service/workflow/ast/rspParser.whileLoop_return.html" title="class in service.workflow.ast">rspParser.whileLoop_return</a></li>
<li><a href="service/composite/SDCache.html" title="class in service.composite">SDCache</a></li>
<li><a href="service/auxiliary/ServiceDescription.html" title="class in service.auxiliary">ServiceDescription</a></li>
<li><a href="service/auxiliary/ServiceOperation.html" title="annotation in service.auxiliary">ServiceOperation</a></li>
<li><a href="service/atomic/ServiceProfile.html" title="class in service.atomic">ServiceProfile</a></li>
<li><a href="service/atomic/ServiceProfileAttribute.html" title="annotation in service.atomic">ServiceProfileAttribute</a></li>
<li><a href="service/provider/ServiceProvider.html" title="interface in service.provider"><span class="interfaceName">ServiceProvider</span></a></li>
<li><a href="service/provider/ServiceProviderFactory.html" title="class in service.provider">ServiceProviderFactory</a></li>
<li><a href="service/registry/ServiceRegistry.html" title="class in service.registry">ServiceRegistry</a></li>
<li><a href="service/auxiliary/ServiceRegistryInterface.html" title="interface in service.auxiliary"><span class="interfaceName">ServiceRegistryInterface</span></a></li>
<li><a href="taskgraph/TaskGraph.html" title="class in taskgraph">TaskGraph</a></li>
<li><a href="taskgraph/TaskGraph.ALLOC.html" title="class in taskgraph">TaskGraph.ALLOC</a></li>
<li><a href="taskgraph/TaskGraph.ARRAY_ACCESS.html" title="class in taskgraph">TaskGraph.ARRAY_ACCESS</a></li>
<li><a href="taskgraph/TaskGraph.BinaryOp.html" title="class in taskgraph">TaskGraph.BinaryOp</a></li>
<li><a href="taskgraph/TaskGraph.BooleanLiteral.html" title="class in taskgraph">TaskGraph.BooleanLiteral</a></li>
<li><a href="taskgraph/TaskGraph.CALL.html" title="class in taskgraph">TaskGraph.CALL</a></li>
<li><a href="taskgraph/TaskGraph.DECL.html" title="class in taskgraph">TaskGraph.DECL</a></li>
<li><a href="taskgraph/TaskGraph.EAssignOp.html" title="enum in taskgraph">TaskGraph.EAssignOp</a></li>
<li><a href="taskgraph/TaskGraph.EBinaryOp.html" title="enum in taskgraph">TaskGraph.EBinaryOp</a></li>
<li><a href="taskgraph/TaskGraph.End.html" title="class in taskgraph">TaskGraph.End</a></li>
<li><a href="taskgraph/TaskGraph.ETaskType.html" title="enum in taskgraph">TaskGraph.ETaskType</a></li>
<li><a href="taskgraph/TaskGraph.EUnaryOp.html" title="enum in taskgraph">TaskGraph.EUnaryOp</a></li>
<li><a href="taskgraph/TaskGraph.Expression.html" title="class in taskgraph">TaskGraph.Expression</a></li>
<li><a href="taskgraph/TaskGraph.IF.html" title="class in taskgraph">TaskGraph.IF</a></li>
<li><a href="taskgraph/TaskGraph.INSTANTIATE.html" title="class in taskgraph">TaskGraph.INSTANTIATE</a></li>
<li><a href="taskgraph/TaskGraph.IntLiteral.html" title="class in taskgraph">TaskGraph.IntLiteral</a></li>
<li><a href="taskgraph/TaskGraph.LIST_END.html" title="class in taskgraph">TaskGraph.LIST_END</a></li>
<li><a href="taskgraph/TaskGraph.LIST_ITEM.html" title="class in taskgraph">TaskGraph.LIST_ITEM</a></li>
<li><a href="taskgraph/TaskGraph.LIST_START.html" title="class in taskgraph">TaskGraph.LIST_START</a></li>
<li><a href="taskgraph/TaskGraph.Literal.html" title="class in taskgraph">TaskGraph.Literal</a></li>
<li><a href="taskgraph/TaskGraph.Load.html" title="class in taskgraph">TaskGraph.Load</a></li>
<li><a href="taskgraph/TaskGraph.MemoryOperation.html" title="class in taskgraph">TaskGraph.MemoryOperation</a></li>
<li><a href="taskgraph/TaskGraph.PARALLEL.html" title="class in taskgraph">TaskGraph.PARALLEL</a></li>
<li><a href="taskgraph/TaskGraph.PARAM.html" title="class in taskgraph">TaskGraph.PARAM</a></li>
<li><a href="taskgraph/TaskGraph.PUSH.html" title="class in taskgraph">TaskGraph.PUSH</a></li>
<li><a href="taskgraph/TaskGraph.QUALIFIED_ACCESS.html" title="class in taskgraph">TaskGraph.QUALIFIED_ACCESS</a></li>
<li><a href="taskgraph/TaskGraph.RANGE.html" title="class in taskgraph">TaskGraph.RANGE</a></li>
<li><a href="taskgraph/TaskGraph.RATE.html" title="class in taskgraph">TaskGraph.RATE</a></li>
<li><a href="taskgraph/TaskGraph.RETURN.html" title="class in taskgraph">TaskGraph.RETURN</a></li>
<li><a href="taskgraph/TaskGraph.START.html" title="class in taskgraph">TaskGraph.START</a></li>
<li><a href="taskgraph/TaskGraph.Store.html" title="class in taskgraph">TaskGraph.Store</a></li>
<li><a href="taskgraph/TaskGraph.TernaryOp.html" title="class in taskgraph">TaskGraph.TernaryOp</a></li>
<li><a href="taskgraph/TaskGraph.UnaryOp.html" title="class in taskgraph">TaskGraph.UnaryOp</a></li>
<li><a href="taskgraph/TaskGraphInterpreter.html" title="class in taskgraph">TaskGraphInterpreter</a></li>
<li><a href="tools/TaskGraphVisualizer.html" title="class in tools">TaskGraphVisualizer</a></li>
<li><a href="service/utility/Time.html" title="class in service.utility">Time</a></li>
<li><a href="service/auxiliary/TimeOutError.html" title="class in service.auxiliary">TimeOutError</a></li>
<li><a href="service/adaptation/effectors/WorkflowEffector.html" title="class in service.adaptation.effectors">WorkflowEffector</a></li>
<li><a href="service/workflow/WorkflowEngine.html" title="class in service.workflow">WorkflowEngine</a></li>
<li><a href="service/adaptation/probes/WorkflowProbe.html" title="class in service.adaptation.probes">WorkflowProbe</a></li>
<li><a href="service/adaptation/probes/interfaces/WorkflowProbeInterface.html" title="interface in service.adaptation.probes.interfaces"><span class="interfaceName">WorkflowProbeInterface</span></a></li>
<li><a href="service/auxiliary/XMLBuilder.html" title="class in service.auxiliary">XMLBuilder</a></li>
</ul>
</div>
</body>
</html>
|
musman/RSP
|
ResearchServicePlatform/doc/allclasses-noframe.html
|
HTML
|
mit
| 23,994
|
# Scenarios - TFS 2017 Deployment
INSERT TEXT HERE
```powershell
New-LabDefinition -Name TFS2017 -DefaultVirtualizationEngine HyperV
$PSDefaultParameterValues = @{
'Add-LabMachineDefinition:OperatingSystem' = 'Windows Server 2016 Datacenter (Desktop Experience)'
'Add-LabMachineDefinition:DomainName' = 'contoso.com'
'Add-LabMachineDefinition:Memory' = 2GB
'Add-LabMachineDefinition:Tools' = "$labsources\Tools"
}
Add-LabDomainDefinition -Name contoso.com -AdminUser Install -AdminPassword Somepass1
Set-LabInstallationCredential -Username Install -Password Somepass1
# As usual, use the role name as the ISO image definition name
Add-LabIsoImageDefinition -Name Tfs2017 -Path $labsources\ISOs\en_team_foundation_server_2017_update_3_x64_dvd_11697950.iso
Add-LabIsoImageDefinition -Name SQLServer2016 -Path $labsources\ISOs\en_sql_server_2016_standard_with_service_pack_1_x64_dvd_9540929.iso
Add-LabMachineDefinition -Name tfs2DC1 -Roles RootDC -Memory 1GB
Add-LabMachineDefinition -Name tfs2SQL1 -ROles SQLServer2016
# If no properties are used, we automatically select a SQL server, use port 8080 and name the initial
# Collection AutomatedLab
$role = Get-LabMachineRoleDefinition -Role Tfs2017 -Properties @{
Port = '8081'
DbServer = "tfs1SQL1"
InitialCollection = 'CustomCollection'
}
Add-LabMachineDefinition -Name tfs2Srv1 -Roles $role -Memory 4GB
# If no properties are used, we automatically bind to the first TFS Server in the lab, use port 9090 and 2 build agents
# If a TFS server is used, the fitting installation (TFS2015 or 2017) will be used for the build agent
Add-LabMachineDefinition -Name tfs2Build1 -Roles TfsBuildWorker
Install-Lab
Show-LabDeploymentSummary -Detailed
```
|
AutomatedLab/AutomatedLab
|
Help/Wiki/SampleScripts/Scenarios/en-us/TFS 2017 Deployment.md
|
Markdown
|
mit
| 1,754
|
import React from 'react'
import { renderRoutes } from 'react-router-config'
import { Header } from '../containers/Header'
const App = ({ route }) => (
<div>
<Header
title="reSolve Styled-Components Example"
name="Styled-Components Example"
favicon="/favicon.png"
css={['/bootstrap.min.css']}
/>
{renderRoutes(route.routes)}
</div>
)
export default App
|
reimagined/resolve
|
templates/js/styled-components/client/components/App.js
|
JavaScript
|
mit
| 393
|
# -*- coding: utf-8 -*-
import unittest
import mock
class DynamicFieldsMixinTestCase(unittest.TestCase):
"""Test functionality of the DynamicFieldsMixin class."""
def test_restrict_dynamic_fields(self):
|
chewse/djangorestframework-dynamic-fields
|
test_dynamicfields.py
|
Python
|
mit
| 218
|
#lay_content a.readon:hover, .button:hover,
tr:hover td.sectiontableheader,
#gloss:hover {
background : url(../../images/gloss/bar-ice.gif) repeat-x;
}
.menu_tabs ul li a:hover,
#lay_main .moduletable h3:hover,
.moduletable_text h3:hover,
.moduletable_menu h3:hover {
background : url(../../images/gloss/title-ice.gif) no-repeat;
}
.moduletable_menu ul.menu li:hover,
.moduletable_menu ul.menu li li:hover {
background : url(../../images/gloss/item-ice.gif) no-repeat;
}
.breadcrumbs:hover a,
.moduletable_menu ul.menu li:hover a,
.moduletable_menu ul.menu li li:hover a { color : #884; }
|
epsi-rns/AlumniBook-SF
|
plugins/sfThemeOriclonePlugin/web/css/hover/ice.css
|
CSS
|
mit
| 597
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.