code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
package Flood; import java.awt.Font; import java.awt.FontFormatException; import java.io.FileInputStream; import java.io.IOException; /** * * @author Left & Right * @version 1.0 * @date APR/12/2016 */ public class Pregunta { private String sPregunta; private String sRespuesta; private int iPuntos; /** * * @param sPregunta * @param sRespuesta * @param iPuntos * @throws FontFormatException * @throws IOException */ public Pregunta(String sPregunta, String sRespuesta, int iPuntos) throws FontFormatException, IOException { this.sPregunta = sPregunta; this.sRespuesta = sRespuesta; this.iPuntos = iPuntos; } /** * * * @return */ public String getPregunta() { return sPregunta; } /** * * @return */ public String getRespuesta() { return sRespuesta; } /** * * @return */ public int getPuntos() { return iPuntos; } }
humberto-garza/VideoJuegos
Proyecto_Final/Flood/src/Flood/Pregunta.java
Java
bsd-3-clause
1,024
<?php declare(strict_types=1); namespace hiqdev\php\merchant\card; use DateTimeImmutable; final class CardInformation { public string $last4; public ?string $brand; public ?string $fingerprint; public DateTimeImmutable $expirationTime; }
hiqdev/php-merchant
src/card/CardInformation.php
PHP
bsd-3-clause
260
/* ljm3103 - Luke Matarazzo * CSCI-243 -- Project 1 - Scanner * filename: matrix.c * File containing source code of functions of the matrix "module". These are * functions to help create and print transition matrices. */ #include "matrix.h" #include <string.h> #include <ctype.h> /* Function: strToInt * Parameters: str - array of characters that needs to be converted. * Purpose: Take in a C string assuming that it is or contains integer values, * and convert it to an integer. * Returns: An int which is the converted value from the C string. */ int strToInt(char str[]) { int ret = 0; for(unsigned int i = 0; i < strlen(str); i++) { if(isdigit(str[i])) ret = ret * 10 + str[i] - '0'; else break; } return ret; } /* Function: initMatrix * Parameters: fp - file pointer to read from. * tempTm - 2d array of indexStructs * numStates - number of states in the 2d array * Purpose: Take a transition matrix file and create a 2d array containing * that information. * Returns: Nothing. */ void initMatrix(FILE *fp, indexStruct tempTm[][N_CC], int numStates) { for(int i = 0; i < numStates; i++) //initialize to default values { for(int j = 0; j < N_CC; j++) { tempTm[i][j].nextState = 99; tempTm[i][j].action = 'd'; } } char *ptr, buf[256]; //pointer from fgets, buffer for fgets //read and parse the rest of the lines in the file while((ptr = fgets(buf, 256, fp)) != NULL) { char *temp; temp = strtok(buf, " "); //split by spaces int stateNum = 0; stateNum = strToInt(temp); //get state number of the line temp = strtok(NULL, " "); while(temp != NULL) //split by spaces until no more spaces { int col = 0, next = 0; char c = ' '; //get next state and action and add to the tm sscanf(temp, "%d/%d%c ", &col, &next, &c); tempTm[stateNum][col].nextState = next; tempTm[stateNum][col].action = c; temp = strtok(NULL, " "); } } } /* Function: printMatrix * Parameters: tempTm - 2d array of indexStructs * numStates - number of states of the 2d array given * Purpose: Print a given 2d array of indexStructs. * Returns: Nothing. */ void printMatrix(indexStruct tempTm[][N_CC], int numStates) { for(int i = 0; i < numStates; i++) { printf("\n%2d", i); for(int j = 0; j < N_CC; j++) printf(" %2d%c", tempTm[i][j].nextState, tempTm[i][j].action); } putchar('\n'); }
bigshebang/cs_projects
project1/matrix.c
C
bsd-3-clause
2,427
package DBIx::Class::Schema::Config; use 5.005; use warnings; use strict; use base 'DBIx::Class::Schema'; use File::HomeDir; use Storable qw( dclone ); use Hash::Merge qw( merge ); use namespace::clean; use URI; our $VERSION = '0.001014'; # 0.1.14 $VERSION = eval $VERSION; sub connection { my ( $class, @info ) = @_; if ( ref($info[0]) eq 'CODE' ) { return $class->next::method( @info ); } my $attrs = $class->_make_connect_attrs(@info); # We will not load credentials for someone who uses dbh_maker, # however we will pass their request through. return $class->next::method( $attrs ) if defined $attrs->{dbh_maker}; # Take responsibility for passing through normal-looking # credentials. $attrs = $class->load_credentials($attrs) unless $attrs->{dsn} =~ /^dbi:/i; return $class->next::method( $attrs ); } sub coerce_credentials_from_mojolike { my ( $class, $attrs ) = @_; (my $in = $attrs->{dsn}) =~ s/^postgresql/http/; my $url = URI->new( $in ); my $db = ($url->path_segments)[1]; my $dsn = defined $db ? "dbi:Pg:dbname=$db" : 'dbi:Pg:'; $dsn .= ";host=" . $url->host if $url->host; $dsn .= ";port=" . $url->port if $url->port and $url->port != 80; $attrs->{dsn} = $dsn; # Set user & password, default to '', # then use $url->userinfo, like so: # # user@ -> username, '' # user:@ -> username, '' # :password@ -> '', password ($attrs->{user}, $attrs->{password}) = ('', ''); if ( $url->userinfo ) { my ( $user, $password ) = split /:/, $url->userinfo, 2; $attrs->{user} = $user; $attrs->{password} = $password || ''; } return $attrs; } # Normalize arguments into a single hash. If we get a single hashref, # return it. # Check if $user and $pass are hashes to support things like # ->connect( 'CONFIG_FILE', { hostname => 'db.foo.com' } ); sub _make_connect_attrs { my ( $class, $dsn, $user, $pass, $dbi_attr, $extra_attr ) = @_; return $dsn if ref $dsn eq 'HASH'; return { dsn => $dsn, %{ref $user eq 'HASH' ? $user : { user => $user }}, %{ref $pass eq 'HASH' ? $pass : { password => $pass }}, %{$dbi_attr || {} }, %{ $extra_attr || {} } }; } # Cache the loaded configuration. sub config { my ( $class ) = @_; if ( ! $class->_config ) { $class->_config( $class->_load_config ); } return dclone( $class->_config ); } sub _load_config { my ( $class ) = @_; require Config::Any; # Only loaded if we need to load credentials. # If we have ->config_files, we'll use those and load_files # instead of the default load_stems. my %cf_opts = ( use_ext => 1 ); return @{$class->config_files} ? Config::Any->load_files({ files => $class->config_files, %cf_opts }) : Config::Any->load_stems({ stems => $class->config_paths, %cf_opts }); } sub load_credentials { my ( $class, $connect_args ) = @_; # Handle mojo-like postgres:// urls return $class->coerce_credentials_from_mojolike($connect_args) if $connect_args->{dsn} =~ /^postgresql:/i; # While ->connect is responsible for returning normal-looking # credential information, we do it here as well so that it can be # independently unit tested. return $connect_args if $connect_args->{dsn} =~ /^dbi:/i; return $class->filter_loaded_credentials( $class->_find_credentials( $connect_args, $class->config ), $connect_args ); } # This will look through the data structure returned by Config::Any # and return the first instance of the database credentials it can # find. sub _find_credentials { my ( $class, $connect_args, $ConfigAny ) = @_; for my $cfile ( @$ConfigAny ) { for my $filename ( keys %$cfile ) { for my $database ( keys %{$cfile->{$filename}} ) { if ( $database eq $connect_args->{dsn} ) { return $cfile->{$filename}->{$database}; } } } } } sub get_env_vars { return $ENV{DBIX_CONFIG_DIR} . "/dbic" if exists $ENV{DBIX_CONFIG_DIR}; return (); } # Intended to be sub-classed, the default behavior is to # overwrite the loaded configuration with any specified # configuration from the connect() call, with the exception # of the DSN itself. sub filter_loaded_credentials { my ( $class, $new, $old ) = @_; local $old->{password}, delete $old->{password} unless $old->{password}; local $old->{user}, delete $old->{user} unless $old->{user}; local $old->{dsn}, delete $old->{dsn}; return merge( $old, $new ); }; __PACKAGE__->mk_classaccessor('config_paths'); __PACKAGE__->mk_classaccessor('config_files'); __PACKAGE__->mk_classaccessor('_config'); __PACKAGE__->config_paths([( get_env_vars(), './dbic', File::HomeDir->my_home . '/.dbic', '/etc/dbic')]); __PACKAGE__->config_files([ ] ); 1; =encoding UTF-8 =head1 NAME DBIx::Class::Schema::Config - Credential Management for DBIx::Class =head1 DESCRIPTION DBIx::Class::Schema::Config is a subclass of DBIx::Class::Schema that allows the loading of credentials & configuration from a file. The actual code itself would only need to know about the name used in the configuration file. This aims to make it simpler for operations teams to manage database credentials. A simple tutorial that compliments this documentation and explains converting an existing DBIx::Class Schema to use this software to manage credentials can be found at L<http://www.symkat.com/credential-management-in-dbix-class> =head1 SYNOPSIS /etc/dbic.yaml MY_DATABASE: dsn: "dbi:Pg:host=localhost;database=blog" user: "TheDoctor" password: "dnoPydoleM" TraceLevel: 1 package My::Schema use warnings; use strict; use base 'DBIx::Class::Schema::Config'; __PACKAGE__->load_namespaces; package My::Code; use warnings; use strict; use My::Schema; my $schema = My::Schema->connect('MY_DATABASE'); # arbitrary config access from anywhere in your $app my $level = My::Schema->config->{TraceLevel}; =head1 CONFIG FILES This module will load the files in the following order if they exist: =over 4 =item * C<$ENV{DBIX_CONFIG_DIR}> . '/dbic', C<$ENV{DBIX_CONFIG_DIR}> can be configured at run-time, for instance: DBIX_CONFIG_DIR="/var/local/" ./my_program.pl =item * ./dbic.* =item * ~/.dbic.* =item * /etc/dbic.* =back The files should have an extension that L<Config::Any> recognizes, for example /etc/dbic.B<yaml>. NOTE: The first available credential will be used. Therefore I<DATABASE> in ~/.dbic.yaml will only be looked at if it was not found in ./dbic.yaml. If there are duplicates in one file (such that DATABASE is listed twice in ~/.dbic.yaml,) the first configuration will be used. =head1 CHANGE CONFIG PATH Use C<__PACKAGE__-E<gt>config_paths([( '/file/stub', '/var/www/etc/dbic')]);> to change the paths that are searched. For example: package My::Schema use warnings; use strict; use base 'DBIx::Class::Schema::Config'; __PACKAGE__->config_paths([( '/var/www/secret/dbic', '/opt/database' )]); The above code would have I</var/www/secret/dbic.*> and I</opt/database.*> searched, in that order. As above, the first credentials found would be used. This will replace the files originally searched for, not add to them. =head1 USE SPECIFIC CONFIG FILES If you would rather explicitly state the configuration files you want loaded, you can use the class accessor C<config_files> instead. package My::Schema use warnings; use strict; use base 'DBIx::Class::Schema::Config'; __PACKAGE__->config_files([( '/var/www/secret/dbic.yaml', '/opt/database.yaml' )]); This will check the files, C</var/www/secret/dbic.yaml>, and C</opt/database.yaml> in the same way as C<config_paths>, however it will only check the specific files, instead of checking for each extension that L<Config::Any> supports. You MUST use the extension that corresponds to the file type you are loading. See L<Config::Any> for information on supported file types and extension mapping. =head1 ACCESSING THE CONFIG FILE The config file is stored via the C<__PACKAGE__-E<gt>config> accessor, which can be called as both a class and instance method. =head1 OVERRIDING The API has been designed to be simple to override if you have additional needs in loading DBIC configurations. =head2 Mojo::Pg-Like Connection Strings Calls to connect with L<Mojo::Pg>-like URIs are supported. my $schema = My::Schema->connect( 'postgresql://username:password@localhost/dbname' ); =head2 Overriding Connection Configuration Simple cases where one wants to replace specific configuration tokens can be given as extra parameters in the ->connect call. For example, suppose we have the database MY_DATABASE from above: MY_DATABASE: dsn: "dbi:Pg:host=localhost;database=blog" user: "TheDoctor" password: "dnoPydoleM" TraceLevel: 1 If you’d like to replace the username with “Eccleston” and we’d like to turn PrintError off. The following connect line would achieve this: $Schema->connect(“MY_DATABASE”, “Eccleston”, undef, { PrintError => 0 } ); The name of the connection to load from the configuration file is still given as the first argument, while other arguments may be given exactly as you would for any other call to C<connect>. Historical Note: This class accepts numerous ways to connect to DBIC that would otherwise not be valid. These connection methods are discouraged but tested for and kept for compatibility with earlier versions. For valid ways of connecting to DBIC please see L<https://metacpan.org/pod/DBIx::Class::Storage::DBI#connect_info> =head2 filter_loaded_credentials Override this function if you want to change the loaded credentials before they are passed to DBIC. This is useful for use-cases that include decrypting encrypted passwords or making programmatic changes to the configuration before using it. sub filter_loaded_credentials { my ( $class, $loaded_credentials, $connect_args ) = @_; ... return $loaded_credentials; } C<$loaded_credentials> is the structure after it has been loaded from the configuration file. In this case, C<$loaded_credentials-E<gt>{user}> eq B<WalterWhite> and C<$loaded_credentials-E<gt>{dsn}> eq B<DBI:mysql:database=students;host=%s;port=3306>. C<$connect_args> is the structure originally passed on C<-E<gt>connect()> after it has been turned into a hash. For instance, C<-E<gt>connect('DATABASE', 'USERNAME')> will result in C<$connect_args-E<gt>{dsn}> eq B<DATABASE> and C<$connect_args-E<gt>{user}> eq B<USERNAME>. Additional parameters can be added by appending a hashref, to the connection call, as an example, C<-E<gt>connect( 'CONFIG', { hostname =E<gt> "db.foo.com" } );> will give C<$connect_args> a structure like C<{ dsn =E<gt> 'CONFIG', hostname =E<gt> "db.foo.com" }>. For instance, if you want to use hostnames when you make the initial connection to DBIC and are using the configuration primarily for usernames, passwords and other configuration data, you can create a config like the following: DATABASE: dsn: "DBI:mysql:database=students;host=%s;port=3306" user: "WalterWhite" password: "relykS" In your Schema class, you could include the following: package My::Schema use warnings; use strict; use base 'DBIx::Class::Schema::Config'; sub filter_loaded_credentials { my ( $class, $loaded_credentials, $connect_args ) = @_; if ( $loaded_credentials->{dsn} =~ /\%s/ ) { $loaded_credentials->{dsn} = sprintf( $loaded_credentials->{dsn}, $connect_args->{hostname}); } } __PACKAGE__->load_classes; 1; Then the connection could be done with C<$Schema-E<gt>connect('DATABASE', { hostname => 'my.hostname.com' });> See L</load_credentials> for more complex changes that require changing how the configuration itself is loaded. =head2 load_credentials Override this function to change the way that L<DBIx::Class::Schema::Config> loads credentials. The function takes the class name, as well as a hashref. If you take the route of having C<-E<gt>connect('DATABASE')> used as a key for whatever configuration you are loading, I<DATABASE> would be C<$config-E<gt>{dsn}> Some::Schema->connect( "SomeTarget", "Yuri", "Yawny", { TraceLevel => 1 } ); Would result in the following data structure as $config in C<load_credentials($class, $config)>: { dsn => "SomeTarget", user => "Yuri", password => "Yawny", TraceLevel => 1, } Currently, load_credentials will NOT be called if the first argument to C<-E<gt>connect()> looks like a valid DSN. This is determined by match the DSN with C</^dbi:/i>. The function should return the same structure. For instance: package My::Schema use warnings; use strict; use base 'DBIx::Class::Schema::Config'; use LWP::Simple; use JSON # Load credentials from internal web server. sub load_credentials { my ( $class, $config ) = @_; return decode_json( get( "http://someserver.com/v1.0/database?key=somesecret&db=" . $config->{dsn} )); } __PACKAGE__->load_classes; =head1 AUTHOR Kaitlyn Parkhurst (SymKat) I<E<lt>[email protected]<gt>> ( Blog: L<http://symkat.com/> ) =head1 CONTRIBUTORS =over 4 =item * Matt S. Trout (mst) I<E<lt>[email protected]<gt>> =item * Peter Rabbitson (ribasushi) I<E<lt>[email protected]<gt>> =item * Christian Walde (Mihtaldu) I<E<lt>[email protected]<gt>> =item * Dagfinn Ilmari Mannsåker (ilmari) I<E<lt>[email protected]<gt>> =item * Matthew Phillips (mattp) I<E<lt>[email protected]<gt>> =back =head1 COPYRIGHT AND LICENSE This library is free software and may be distributed under the same terms as perl itself. =head1 AVAILABILITY The latest version of this software is available at L<https://github.com/symkat/DBIx-Class-Schema-Config> =cut
symkat/DBIx-Class-Schema-Config
lib/DBIx/Class/Schema/Config.pm
Perl
bsd-3-clause
14,323
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Bodegas; /** * BodegasSearch represents the model behind the search form about `app\models\Bodegas`. */ class BodegasSearch extends Bodegas { /** * @inheritdoc */ public function rules() { return [ [['BO_ID', 'BO_CANTIDADHERRAMIENTAS', 'BO_CANTIDADMATERIALES'], 'integer'], [['BO_NOMBRE', 'BO_DIRECCION'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = Bodegas::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'BO_ID' => $this->BO_ID, 'BO_CANTIDADHERRAMIENTAS' => $this->BO_CANTIDADHERRAMIENTAS, 'BO_CANTIDADMATERIALES' => $this->BO_CANTIDADMATERIALES, ]); $query->andFilterWhere(['like', 'BO_NOMBRE', $this->BO_NOMBRE]) ->andFilterWhere(['like', 'BO_DIRECCION', $this->BO_DIRECCION]); return $dataProvider; } }
malikeox/mymltda2
models/BodegasSearch.php
PHP
bsd-3-clause
1,670
# Load the rails application require File.expand_path('../mailjet', __FILE__) require File.expand_path('../application', __FILE__) require 'rails_rinku' module Kaminari module Helpers class Tag def page_url_for(page) @template.url_for @template.params.merge(@param_name => (page < 1 ? nil : page)) end end end end # Predefined roles for CanCan ROLES = %w( admin buyer seller ) class String def role? ROLES.include?(self) end def to_role role? ? 2 ** ROLES.index(self) : 0 end end DEFAULT_ROLE = 'buyer'.to_role # Generate a slug suitable for permalinks # See http://stackoverflow.com/questions/1302022/best-way-to-generate-slugs-human-readable-ids-in-rails # and https://github.com/ludo/to_slug/ class String def to_slug slug = self.mb_chars.normalize :kd # Normalize mutlibyte characters slug.gsub! /[^\x00-\x7F]/n, '' # Strip ugly non-ASCII stuff slug.gsub! /['`]/, '' # Remove quotes slug.gsub! '@', ' at ' # Preserve meaning of the at symbol slug.gsub! '&', ' and ' # ...and the ampersand slug.gsub! /\W+/, ' ' # Convert non-word characters to spaces slug.strip! # Strip leading and trailing spaces slug.gsub! /\s+/, '-' # Convert whitespace to dashes slug.downcase # Oh yeah, and lowercase end end # Run a string through the Markdown filter and return for output class String def markdown sanitized_self = ActionController::Base.helpers.sanitize self, :tags => %w( a p strong b em i strike u sub sup ol ul li blockquote caption div span code pre samp tt var address h1 h2 h3 h4 h5 h6 hr br dd dl dt cite abbr acronym dfn q ), :attributes => %w( href title type compact cite ) Rinku.auto_link(RDiscount.new(sanitized_self, :filter_styles, :no_image, :no_tables, :strict, :safelink, :no_pseudo_protocols).to_html).html_safe end end CATEGORIES = [ ['Apartments', 'Apartments'], ['Subleases', 'Subleases'], ['Appliances', 'Appliances'], ['Bikes', 'Bikes'], ['Books', 'Hardbacks, paperbacks, textbooks'], ['Cars', 'Cars, motorcycles'], ['Electronics', 'Computers, TVs, personal electronics'], ['Employment', 'Job opportunities'], ['Furniture', 'Couches, chairs, bookshelves'], ['Miscellaneous', 'Catch-all'], ['Services', 'Odd jobs, advertisements'], ['Wanted', 'Looking for...'] ] # Add custom date formatters Time::DATE_FORMATS.merge!({ :default => '%b %d, %Y at %H:%M' }) # Unfortunate but useful contstants SITE_NAME = 'Marketplace' APP_RESOURCES = %w( listings users categories ) STATIC_PAGES = %w( terms-privacy safety about ) STATIC_PAGE_LINKS = [ ['About Marketplace', 'about'], ['Safety & Security', 'safety'], ['Terms & Privacy', 'terms-privacy'] ] OTHER_LINKS = [ ['Atom Feeds', 'feeds'] ] DEVISE_PAGES = %w( register login logout ) RESERVED_PATHS = CATEGORIES.map(&:first).map(&:downcase) + STATIC_PAGES + DEVISE_PAGES + \ %w( admin faqs status welcome issues terms privacy versions browse search users categories listings starred dashboard index show new create edit update delete ) # Special routes # Wrap errors in <span>s instead of <div>s ActionView::Base.field_error_proc = Proc.new { |html_tag, instance| "<span class='field_with_errors'>#{html_tag}</span>".html_safe } # Initialize the rails application Dhaka::Application.initialize!
jiamaozheng/Dhaka
config/environment.rb
Ruby
bsd-3-clause
3,486
/* SORT command and helper functions. * * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Redis nor the names of its contributors may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "server.h" #include "pqsort.h" /* Partial qsort for SORT+LIMIT */ #include <math.h> /* isnan() */ zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank); redisSortOperation *createSortOperation(int type, robj *pattern) { redisSortOperation *so = zmalloc(sizeof(*so)); so->type = type; so->pattern = pattern; return so; } /* Return the value associated to the key with a name obtained using * the following rules: * * 1) The first occurrence of '*' in 'pattern' is substituted with 'subst'. * * 2) If 'pattern' matches the "->" string, everything on the left of * the arrow is treated as the name of a hash field, and the part on the * left as the key name containing a hash. The value of the specified * field is returned. * * 3) If 'pattern' equals "#", the function simply returns 'subst' itself so * that the SORT command can be used like: SORT key GET # to retrieve * the Set/List elements directly. * * The returned object will always have its refcount increased by 1 * when it is non-NULL. */ robj *lookupKeyByPattern(redisDb *db, robj *pattern, robj *subst, int writeflag) { char *p, *f, *k; sds spat, ssub; robj *keyobj, *fieldobj = NULL, *o; int prefixlen, sublen, postfixlen, fieldlen; /* If the pattern is "#" return the substitution object itself in order * to implement the "SORT ... GET #" feature. */ spat = pattern->ptr; if (spat[0] == '#' && spat[1] == '\0') { incrRefCount(subst); return subst; } /* The substitution object may be specially encoded. If so we create * a decoded object on the fly. Otherwise getDecodedObject will just * increment the ref count, that we'll decrement later. */ subst = getDecodedObject(subst); ssub = subst->ptr; /* If we can't find '*' in the pattern we return NULL as to GET a * fixed key does not make sense. */ p = strchr(spat,'*'); if (!p) { decrRefCount(subst); return NULL; } /* Find out if we're dealing with a hash dereference. */ if ((f = strstr(p+1, "->")) != NULL && *(f+2) != '\0') { fieldlen = sdslen(spat)-(f-spat)-2; fieldobj = createStringObject(f+2,fieldlen); } else { fieldlen = 0; } /* Perform the '*' substitution. */ prefixlen = p-spat; sublen = sdslen(ssub); postfixlen = sdslen(spat)-(prefixlen+1)-(fieldlen ? fieldlen+2 : 0); keyobj = createStringObject(NULL,prefixlen+sublen+postfixlen); k = keyobj->ptr; memcpy(k,spat,prefixlen); memcpy(k+prefixlen,ssub,sublen); memcpy(k+prefixlen+sublen,p+1,postfixlen); decrRefCount(subst); /* Incremented by decodeObject() */ /* Lookup substituted key */ if (!writeflag) o = lookupKeyRead(db,keyobj); else o = lookupKeyWrite(db,keyobj); if (o == NULL) goto noobj; if (fieldobj) { if (o->type != OBJ_HASH) goto noobj; /* Retrieve value from hash by the field name. The returned object * is a new object with refcount already incremented. */ o = hashTypeGetValueObject(o, fieldobj->ptr); } else { if (o->type != OBJ_STRING) goto noobj; /* Every object that this function returns needs to have its refcount * increased. sortCommand decreases it again. */ incrRefCount(o); } decrRefCount(keyobj); if (fieldobj) decrRefCount(fieldobj); return o; noobj: decrRefCount(keyobj); if (fieldlen) decrRefCount(fieldobj); return NULL; } /* sortCompare() is used by qsort in sortCommand(). Given that qsort_r with * the additional parameter is not standard but a BSD-specific we have to * pass sorting parameters via the global 'server' structure */ int sortCompare(const void *s1, const void *s2) { const redisSortObject *so1 = s1, *so2 = s2; int cmp; if (!server.sort_alpha) { /* Numeric sorting. Here it's trivial as we precomputed scores */ if (so1->u.score > so2->u.score) { cmp = 1; } else if (so1->u.score < so2->u.score) { cmp = -1; } else { /* Objects have the same score, but we don't want the comparison * to be undefined, so we compare objects lexicographically. * This way the result of SORT is deterministic. */ cmp = compareStringObjects(so1->obj,so2->obj); } } else { /* Alphanumeric sorting */ if (server.sort_bypattern) { if (!so1->u.cmpobj || !so2->u.cmpobj) { /* At least one compare object is NULL */ if (so1->u.cmpobj == so2->u.cmpobj) cmp = 0; else if (so1->u.cmpobj == NULL) cmp = -1; else cmp = 1; } else { /* We have both the objects, compare them. */ if (server.sort_store) { cmp = compareStringObjects(so1->u.cmpobj,so2->u.cmpobj); } else { /* Here we can use strcoll() directly as we are sure that * the objects are decoded string objects. */ cmp = strcoll(so1->u.cmpobj->ptr,so2->u.cmpobj->ptr); } } } else { /* Compare elements directly. */ if (server.sort_store) { cmp = compareStringObjects(so1->obj,so2->obj); } else { cmp = collateStringObjects(so1->obj,so2->obj); } } } return server.sort_desc ? -cmp : cmp; } /* The SORT command is the most complex command in Redis. Warning: this code * is optimized for speed and a bit less for readability */ void sortCommandGeneric(client *c, int readonly) { list *operations; unsigned int outputlen = 0; int desc = 0, alpha = 0; long limit_start = 0, limit_count = -1, start, end; int j, dontsort = 0, vectorlen; int getop = 0; /* GET operation counter */ int int_conversion_error = 0; int syntax_error = 0; robj *sortval, *sortby = NULL, *storekey = NULL; redisSortObject *vector; /* Resulting vector to sort */ /* Create a list of operations to perform for every sorted element. * Operations can be GET */ operations = listCreate(); listSetFreeMethod(operations,zfree); j = 2; /* options start at argv[2] */ /* The SORT command has an SQL-alike syntax, parse it */ while(j < c->argc) { int leftargs = c->argc-j-1; if (!strcasecmp(c->argv[j]->ptr,"asc")) { desc = 0; } else if (!strcasecmp(c->argv[j]->ptr,"desc")) { desc = 1; } else if (!strcasecmp(c->argv[j]->ptr,"alpha")) { alpha = 1; } else if (!strcasecmp(c->argv[j]->ptr,"limit") && leftargs >= 2) { if ((getLongFromObjectOrReply(c, c->argv[j+1], &limit_start, NULL) != C_OK) || (getLongFromObjectOrReply(c, c->argv[j+2], &limit_count, NULL) != C_OK)) { syntax_error++; break; } j+=2; } else if (readonly == 0 && !strcasecmp(c->argv[j]->ptr,"store") && leftargs >= 1) { storekey = c->argv[j+1]; j++; } else if (!strcasecmp(c->argv[j]->ptr,"by") && leftargs >= 1) { sortby = c->argv[j+1]; /* If the BY pattern does not contain '*', i.e. it is constant, * we don't need to sort nor to lookup the weight keys. */ if (strchr(c->argv[j+1]->ptr,'*') == NULL) { dontsort = 1; } else { /* If BY is specified with a real patter, we can't accept * it in cluster mode. */ if (server.cluster_enabled) { addReplyError(c,"BY option of SORT denied in Cluster mode."); syntax_error++; break; } } j++; } else if (!strcasecmp(c->argv[j]->ptr,"get") && leftargs >= 1) { if (server.cluster_enabled) { addReplyError(c,"GET option of SORT denied in Cluster mode."); syntax_error++; break; } listAddNodeTail(operations,createSortOperation( SORT_OP_GET,c->argv[j+1])); getop++; j++; } else { addReplyErrorObject(c,shared.syntaxerr); syntax_error++; break; } j++; } /* Handle syntax errors set during options parsing. */ if (syntax_error) { listRelease(operations); return; } /* Lookup the key to sort. It must be of the right types */ if (!storekey) sortval = lookupKeyRead(c->db,c->argv[1]); else sortval = lookupKeyWrite(c->db,c->argv[1]); if (sortval && sortval->type != OBJ_SET && sortval->type != OBJ_LIST && sortval->type != OBJ_ZSET) { listRelease(operations); addReplyErrorObject(c,shared.wrongtypeerr); return; } /* Now we need to protect sortval incrementing its count, in the future * SORT may have options able to overwrite/delete keys during the sorting * and the sorted key itself may get destroyed */ if (sortval) incrRefCount(sortval); else sortval = createQuicklistObject(); /* When sorting a set with no sort specified, we must sort the output * so the result is consistent across scripting and replication. * * The other types (list, sorted set) will retain their native order * even if no sort order is requested, so they remain stable across * scripting and replication. */ if (dontsort && sortval->type == OBJ_SET && (storekey || c->flags & CLIENT_LUA)) { /* Force ALPHA sorting */ dontsort = 0; alpha = 1; sortby = NULL; } /* Destructively convert encoded sorted sets for SORT. */ if (sortval->type == OBJ_ZSET) zsetConvert(sortval, OBJ_ENCODING_SKIPLIST); /* Obtain the length of the object to sort. */ switch(sortval->type) { case OBJ_LIST: vectorlen = listTypeLength(sortval); break; case OBJ_SET: vectorlen = setTypeSize(sortval); break; case OBJ_ZSET: vectorlen = dictSize(((zset*)sortval->ptr)->dict); break; default: vectorlen = 0; serverPanic("Bad SORT type"); /* Avoid GCC warning */ } /* Perform LIMIT start,count sanity checking. */ start = (limit_start < 0) ? 0 : limit_start; end = (limit_count < 0) ? vectorlen-1 : start+limit_count-1; if (start >= vectorlen) { start = vectorlen-1; end = vectorlen-2; } if (end >= vectorlen) end = vectorlen-1; /* Whenever possible, we load elements into the output array in a more * direct way. This is possible if: * * 1) The object to sort is a sorted set or a list (internally sorted). * 2) There is nothing to sort as dontsort is true (BY <constant string>). * * In this special case, if we have a LIMIT option that actually reduces * the number of elements to fetch, we also optimize to just load the * range we are interested in and allocating a vector that is big enough * for the selected range length. */ if ((sortval->type == OBJ_ZSET || sortval->type == OBJ_LIST) && dontsort && (start != 0 || end != vectorlen-1)) { vectorlen = end-start+1; } /* Load the sorting vector with all the objects to sort */ vector = zmalloc(sizeof(redisSortObject)*vectorlen); j = 0; if (sortval->type == OBJ_LIST && dontsort) { /* Special handling for a list, if 'dontsort' is true. * This makes sure we return elements in the list original * ordering, accordingly to DESC / ASC options. * * Note that in this case we also handle LIMIT here in a direct * way, just getting the required range, as an optimization. */ if (end >= start) { listTypeIterator *li; listTypeEntry entry; li = listTypeInitIterator(sortval, desc ? (long)(listTypeLength(sortval) - start - 1) : start, desc ? LIST_HEAD : LIST_TAIL); while(j < vectorlen && listTypeNext(li,&entry)) { vector[j].obj = listTypeGet(&entry); vector[j].u.score = 0; vector[j].u.cmpobj = NULL; j++; } listTypeReleaseIterator(li); /* Fix start/end: output code is not aware of this optimization. */ end -= start; start = 0; } } else if (sortval->type == OBJ_LIST) { listTypeIterator *li = listTypeInitIterator(sortval,0,LIST_TAIL); listTypeEntry entry; while(listTypeNext(li,&entry)) { vector[j].obj = listTypeGet(&entry); vector[j].u.score = 0; vector[j].u.cmpobj = NULL; j++; } listTypeReleaseIterator(li); } else if (sortval->type == OBJ_SET) { setTypeIterator *si = setTypeInitIterator(sortval); sds sdsele; while((sdsele = setTypeNextObject(si)) != NULL) { vector[j].obj = createObject(OBJ_STRING,sdsele); vector[j].u.score = 0; vector[j].u.cmpobj = NULL; j++; } setTypeReleaseIterator(si); } else if (sortval->type == OBJ_ZSET && dontsort) { /* Special handling for a sorted set, if 'dontsort' is true. * This makes sure we return elements in the sorted set original * ordering, accordingly to DESC / ASC options. * * Note that in this case we also handle LIMIT here in a direct * way, just getting the required range, as an optimization. */ zset *zs = sortval->ptr; zskiplist *zsl = zs->zsl; zskiplistNode *ln; sds sdsele; int rangelen = vectorlen; /* Check if starting point is trivial, before doing log(N) lookup. */ if (desc) { long zsetlen = dictSize(((zset*)sortval->ptr)->dict); ln = zsl->tail; if (start > 0) ln = zslGetElementByRank(zsl,zsetlen-start); } else { ln = zsl->header->level[0].forward; if (start > 0) ln = zslGetElementByRank(zsl,start+1); } while(rangelen--) { serverAssertWithInfo(c,sortval,ln != NULL); sdsele = ln->ele; vector[j].obj = createStringObject(sdsele,sdslen(sdsele)); vector[j].u.score = 0; vector[j].u.cmpobj = NULL; j++; ln = desc ? ln->backward : ln->level[0].forward; } /* Fix start/end: output code is not aware of this optimization. */ end -= start; start = 0; } else if (sortval->type == OBJ_ZSET) { dict *set = ((zset*)sortval->ptr)->dict; dictIterator *di; dictEntry *setele; sds sdsele; di = dictGetIterator(set); while((setele = dictNext(di)) != NULL) { sdsele = dictGetKey(setele); vector[j].obj = createStringObject(sdsele,sdslen(sdsele)); vector[j].u.score = 0; vector[j].u.cmpobj = NULL; j++; } dictReleaseIterator(di); } else { serverPanic("Unknown type"); } serverAssertWithInfo(c,sortval,j == vectorlen); /* Now it's time to load the right scores in the sorting vector */ if (!dontsort) { for (j = 0; j < vectorlen; j++) { robj *byval; if (sortby) { /* lookup value to sort by */ byval = lookupKeyByPattern(c->db,sortby,vector[j].obj,storekey!=NULL); if (!byval) continue; } else { /* use object itself to sort by */ byval = vector[j].obj; } if (alpha) { if (sortby) vector[j].u.cmpobj = getDecodedObject(byval); } else { if (sdsEncodedObject(byval)) { char *eptr; vector[j].u.score = strtod(byval->ptr,&eptr); if (eptr[0] != '\0' || errno == ERANGE || isnan(vector[j].u.score)) { int_conversion_error = 1; } } else if (byval->encoding == OBJ_ENCODING_INT) { /* Don't need to decode the object if it's * integer-encoded (the only encoding supported) so * far. We can just cast it */ vector[j].u.score = (long)byval->ptr; } else { serverAssertWithInfo(c,sortval,1 != 1); } } /* when the object was retrieved using lookupKeyByPattern, * its refcount needs to be decreased. */ if (sortby) { decrRefCount(byval); } } server.sort_desc = desc; server.sort_alpha = alpha; server.sort_bypattern = sortby ? 1 : 0; server.sort_store = storekey ? 1 : 0; if (sortby && (start != 0 || end != vectorlen-1)) pqsort(vector,vectorlen,sizeof(redisSortObject),sortCompare, start,end); else qsort(vector,vectorlen,sizeof(redisSortObject),sortCompare); } /* Send command output to the output buffer, performing the specified * GET/DEL/INCR/DECR operations if any. */ outputlen = getop ? getop*(end-start+1) : end-start+1; if (int_conversion_error) { addReplyError(c,"One or more scores can't be converted into double"); } else if (storekey == NULL) { /* STORE option not specified, sent the sorting result to client */ addReplyArrayLen(c,outputlen); for (j = start; j <= end; j++) { listNode *ln; listIter li; if (!getop) addReplyBulk(c,vector[j].obj); listRewind(operations,&li); while((ln = listNext(&li))) { redisSortOperation *sop = ln->value; robj *val = lookupKeyByPattern(c->db,sop->pattern, vector[j].obj,storekey!=NULL); if (sop->type == SORT_OP_GET) { if (!val) { addReplyNull(c); } else { addReplyBulk(c,val); decrRefCount(val); } } else { /* Always fails */ serverAssertWithInfo(c,sortval,sop->type == SORT_OP_GET); } } } } else { robj *sobj = createQuicklistObject(); /* STORE option specified, set the sorting result as a List object */ for (j = start; j <= end; j++) { listNode *ln; listIter li; if (!getop) { listTypePush(sobj,vector[j].obj,LIST_TAIL); } else { listRewind(operations,&li); while((ln = listNext(&li))) { redisSortOperation *sop = ln->value; robj *val = lookupKeyByPattern(c->db,sop->pattern, vector[j].obj,storekey!=NULL); if (sop->type == SORT_OP_GET) { if (!val) val = createStringObject("",0); /* listTypePush does an incrRefCount, so we should take care * care of the incremented refcount caused by either * lookupKeyByPattern or createStringObject("",0) */ listTypePush(sobj,val,LIST_TAIL); decrRefCount(val); } else { /* Always fails */ serverAssertWithInfo(c,sortval,sop->type == SORT_OP_GET); } } } } if (outputlen) { setKey(c,c->db,storekey,sobj,0); notifyKeyspaceEvent(NOTIFY_LIST,"sortstore",storekey, c->db->id); server.dirty += outputlen; } else if (dbDelete(c->db,storekey)) { signalModifiedKey(c,c->db,storekey); notifyKeyspaceEvent(NOTIFY_GENERIC,"del",storekey,c->db->id); server.dirty++; } decrRefCount(sobj); addReplyLongLong(c,outputlen); } /* Cleanup */ for (j = 0; j < vectorlen; j++) decrRefCount(vector[j].obj); decrRefCount(sortval); listRelease(operations); for (j = 0; j < vectorlen; j++) { if (alpha && vector[j].u.cmpobj) decrRefCount(vector[j].u.cmpobj); } zfree(vector); } /* SORT wrapper function for read-only mode. */ void sortroCommand(client *c) { sortCommandGeneric(c, 1); } void sortCommand(client *c) { sortCommandGeneric(c, 0); }
ofirluzon/redis
src/sort.c
C
bsd-3-clause
22,806
/*L * Copyright Washington University in St.Louis * Copyright Information Management Services, Inc. * Copyright Sapient * Copyright Booz Allen Hamilton * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/common-biorepository-model/LICENSE.txt for details. */ /** * DataServiceResourceProperties.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2RC2 Apr 28, 2006 (12:42:00 EDT) WSDL2Java emitter. */ package gov.nih.nci.cagrid.data; public class DataServiceResourceProperties implements java.io.Serializable { public DataServiceResourceProperties() { } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof DataServiceResourceProperties)) return false; DataServiceResourceProperties other = (DataServiceResourceProperties) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true; __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(DataServiceResourceProperties.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://gov.nih.nci.cagrid.data/DataService", ">DataServiceResourceProperties")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
NCIP/common-biorepository-model
CBMservice/build/stubs-CBM/src/gov/nih/nci/cagrid/data/DataServiceResourceProperties.java
Java
bsd-3-clause
2,823
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2022, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------------------------------------- import qiime2 # Artifacts and parameters. def concatenate_ints(ints1: list, ints2: list, ints3: list, int1: int, int2: int) -> list: return ints1 + ints2 + ints3 + [int1] + [int2] # Multiple output artifacts. def split_ints(ints: list) -> (list, list): middle = int(len(ints) / 2) left = ints[:middle] right = ints[middle:] return left, right # No parameters, only artifacts. def merge_mappings(mapping1: dict, mapping2: dict) -> dict: merged = mapping1.copy() for key, value in mapping2.items(): if key in merged and merged[key] != value: raise ValueError( "Key %r exists in `mapping1` and `mapping2` with conflicting " "values: %r != %r" % (key, merged[key], value)) merged[key] = value return merged # No input artifacts, only parameters. def params_only_method(name: str, age: int) -> dict: return {name: age} # Unioned primitives def unioned_primitives(foo: int, bar: str = 'auto_bar') -> dict: return {'foo': foo, 'bar': bar} # No input artifacts or parameters. def no_input_method() -> dict: return {'foo': 42} def deprecated_method() -> dict: return {'foo': 43} def long_description_method(mapping1: dict, name: str, age: int) -> dict: return {name: age} def docstring_order_method(req_input: dict, req_param: str, opt_input: dict = None, opt_param: int = None) -> dict: return {req_param: opt_param} def identity_with_metadata(ints: list, metadata: qiime2.Metadata) -> list: assert isinstance(metadata, qiime2.Metadata) return ints # TODO unit tests (test_method.py) for 3 variations of MetadataColumn methods # below def identity_with_metadata_column(ints: list, metadata: qiime2.MetadataColumn) -> list: assert isinstance(metadata, (qiime2.CategoricalMetadataColumn, qiime2.NumericMetadataColumn)) return ints def identity_with_categorical_metadata_column( ints: list, metadata: qiime2.CategoricalMetadataColumn) -> list: assert isinstance(metadata, qiime2.CategoricalMetadataColumn) return ints def identity_with_numeric_metadata_column( ints: list, metadata: qiime2.NumericMetadataColumn) -> list: assert isinstance(metadata, qiime2.NumericMetadataColumn) return ints def identity_with_optional_metadata(ints: list, metadata: qiime2.Metadata = None) -> list: assert isinstance(metadata, (qiime2.Metadata, type(None))) return ints def identity_with_optional_metadata_column( ints: list, metadata: qiime2.MetadataColumn = None) -> list: assert isinstance(metadata, (qiime2.CategoricalMetadataColumn, qiime2.NumericMetadataColumn, type(None))) return ints def optional_artifacts_method(ints: list, num1: int, optional1: list = None, optional2: list = None, num2: int = None) -> list: result = ints + [num1] if optional1 is not None: result += optional1 if optional2 is not None: result += optional2 if num2 is not None: result += [num2] return result def variadic_input_method(ints: list, int_set: int, nums: int, opt_nums: int = None) -> list: results = [] for int_list in ints: results += int_list results += sorted(int_set) results += nums if opt_nums: results += opt_nums return results def type_match_list_and_set(ints: list, strs1: list, strs2: set) -> list: return [0]
qiime2/qiime2
qiime2/core/testing/method.py
Python
bsd-3-clause
4,080
//================================================================================================= /*! // \file blaze/math/traits/TDVecImagExprTrait.h // \brief Header file for the TDVecImagExprTrait class template // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_TRAITS_TDVECIMAGEXPRTRAIT_H_ #define _BLAZE_MATH_TRAITS_TDVECIMAGEXPRTRAIT_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/math/expressions/Forward.h> #include <blaze/math/typetraits/IsDenseVector.h> #include <blaze/math/typetraits/IsRowVector.h> #include <blaze/math/typetraits/UnderlyingNumeric.h> #include <blaze/util/InvalidType.h> #include <blaze/util/mpl/And.h> #include <blaze/util/mpl/If.h> #include <blaze/util/mpl/Or.h> #include <blaze/util/typetraits/IsBuiltin.h> #include <blaze/util/typetraits/IsConst.h> #include <blaze/util/typetraits/IsReference.h> #include <blaze/util/typetraits/IsVolatile.h> #include <blaze/util/typetraits/RemoveCV.h> #include <blaze/util/typetraits/RemoveReference.h> namespace blaze { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*!\brief Evaluation of the expression type of a dense vector imaginary part operation. // \ingroup math_traits // // Via this type trait it is possible to evaluate the resulting expression type of a dense // vector imaginary part operation. Given the transpose dense vector type \a VT, the nested // type \a Type corresponds to the resulting expression type. In case \a VT is not a transpose // dense vector type, the resulting \a Type is set to \a INVALID_TYPE. */ template< typename VT > // Type of the dense vector struct TDVecImagExprTrait { private: //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ typedef typename UnderlyingNumeric<VT>::Type NET; typedef If< And< IsDenseVector<VT>, IsRowVector<VT> > , typename If< IsBuiltin<NET>, const VT&, DVecImagExpr<VT,true> >::Type , INVALID_TYPE > Tmp; typedef typename RemoveReference< typename RemoveCV<VT>::Type >::Type Type1; /*! \endcond */ //********************************************************************************************** public: //********************************************************************************************** /*! \cond BLAZE_INTERNAL */ typedef typename If< Or< IsConst<VT>, IsVolatile<VT>, IsReference<VT> > , TDVecImagExprTrait<Type1>, Tmp >::Type::Type Type; /*! \endcond */ //********************************************************************************************** }; //************************************************************************************************* } // namespace blaze #endif
byzhang/blaze
blaze/math/traits/TDVecImagExprTrait.h
C
bsd-3-clause
4,989
# -*-coding:Utf-8 -* # Copyright (c) 2010-2017 LE GOFF Vincent # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT # OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """Fichier contenant la fonction oui_ou_non.""" from primaires.format.fonctions import oui_ou_non from primaires.scripting.fonction import Fonction from primaires.scripting.instruction import ErreurExecution class ClasseFonction(Fonction): """Retourne la chaîne "oui" ou "non".""" @classmethod def init_types(cls): cls.ajouter_types(cls.oui_ou_non, "object") @staticmethod def oui_ou_non(valeur): """Retourne "oui" si la valeur est vraie, "non" sinon. 0 est toujours faux. 1 ou n'importe quel nombre est toujours vrai. Une valeur nulle est fausse. Une liste vide est fausse. Une information quelconque est toujours vraie (voir les exemples ci-dessous). Paramètres à préciser : * valeur : la valeur, sous la forme d'un nombre ou autre. Exemples d'utilisation : retour = oui_ou_non(1) # retour contient "oui" retour = oui_ou_non(0) # retour contient "non" retour = oui_ou_non(liste()) # retour contient "non" """ return oui_ou_non(bool(valeur))
vlegoff/tsunami
src/primaires/scripting/fonctions/oui_ou_non.py
Python
bsd-3-clause
2,695
# First-Bitbucket-Add-On Displays word cloud of all file types in the repository.
batrashubham/First-Bitbucket-Add-On
README.md
Markdown
bsd-3-clause
82
<?php /* mod/db/reg.php * @author: Carlos Thompson * * Entry points for database module. */ switch($obj['db']['engine']) { case 'mysql': require_once 'mod/db/mysql.php'; function db_open() { global $obj; $db = $obj['db']['handler'] = new db_mysql( $obj['db']['server'], $obj['db']['username'], $obj['db']['password'], $obj['db']['database'], $obj['db']['prefix'] ); db_obj::set_db($db); return $db; } function db_close() { global $obj; return $obj['db']['handler']->close(); } break; case 'sqlite': default: require_once 'mod/db/sqlite.php'; function db_open() { global $obj; $db = $obj['db']['handler'] = new db_sqlite( $obj['db']['filename'] ); db_obj::set_db($db); return $db; } function db_close() { global $obj; return $obj['db']['handler']->close(); } break; } ?>
Interlecto/proho
dist/mod/db/reg.php
PHP
bsd-3-clause
840
// Copyright 2014 The gofsh Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "flag" "log" "net/http" ) var ( addr = flag.String("addr", ":6060", "listening address") root = flag.String("root", ".", "root folder") ) func main() { flag.Parse() log.Printf("Listening on %s (root=%s)\n", *addr, *root) fileHandler := http.FileServer(http.Dir(*root)) if err := http.ListenAndServe(*addr, logHandler(fileHandler)); err != nil { log.Fatalln("Error:", err) } } func logHandler(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Printf("%s - %s %s\n", r.RemoteAddr, r.Method, r.RequestURI) handler.ServeHTTP(w, r) }) }
jroimartin/gofsh
main.go
GO
bsd-3-clause
801
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <!-- required because all the links are pseudo-absolute --> <base href="../.."> <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="static-assets/prettify.css"> <link rel="stylesheet" href="static-assets/css/bootstrap.min.css"> <link rel="stylesheet" href="static-assets/styles.css"> <meta name="description" content=""> <link rel="icon" href="static-assets/favicon.png"> <!-- Do not remove placeholder --> <!-- Header Placeholder --> </head> <body> <div id="overlay-under-drawer"></div> <header class="container-fluid" id="title"> <nav class="navbar navbar-fixed-top"> <div class="container"> <button id="sidenav-left-toggle" type="button">&nbsp;</button> <ol class="breadcrumbs gt-separated hidden-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html">ButtonInputElement</a></li> <li class="self-crumb">ButtonInputElement</li> </ol> <div class="self-name">ButtonInputElement</div> </div> </nav> <div class="container masthead"> <ol class="breadcrumbs gt-separated visible-xs"> <li><a href="index.html">polymer_app_layout_template</a></li> <li><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></li> <li><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html">ButtonInputElement</a></li> <li class="self-crumb">ButtonInputElement</li> </ol> <div class="title-description"> <h1 class="title"> <div class="kind">constructor</div> ButtonInputElement </h1> <!-- p class="subtitle"> </p --> </div> <ul class="subnav"> </ul> </div> </header> <div class="container body"> <div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left"> <h5><a href="index.html">polymer_app_layout_template</a></h5> <h5><a href="polymer_app_layout.behaviors/polymer_app_layout.behaviors-library.html">polymer_app_layout.behaviors</a></h5> <h5><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html">ButtonInputElement</a></h5> <ol> <li class="section-title"><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html#constructors">Constructors</a></li> <li><a href="polymer_app_layout.behaviors/ButtonInputElement/ButtonInputElement.html">ButtonInputElement</a></li> <li class="section-title"><a href="polymer_app_layout.behaviors/ButtonInputElement-class.html#methods">Methods</a></li> <li>addEventListener </li> <li>animate </li> <li>append </li> <li>appendHtml </li> <li>appendText </li> <li>attached </li> <li>attributeChanged </li> <li>blur </li> <li>checkValidity </li> <li>click </li> <li>clone </li> <li>contains </li> <li>createFragment </li> <li>createShadowRoot </li> <li>detached </li> <li>dispatchEvent </li> <li>enteredView </li> <li>focus </li> <li>getAnimationPlayers </li> <li>getAttribute </li> <li>getAttributeNS </li> <li>getBoundingClientRect </li> <li>getClientRects </li> <li>getComputedStyle </li> <li>getDestinationInsertionPoints </li> <li>getElementsByClassName </li> <li>getNamespacedAttributes </li> <li>hasChildNodes </li> <li>insertAdjacentElement </li> <li>insertAdjacentHtml </li> <li>insertAdjacentText </li> <li>insertAllBefore </li> <li>insertBefore </li> <li>leftView </li> <li>matches </li> <li>matchesWithAncestors </li> <li>offsetTo </li> <li>query </li> <li>queryAll </li> <li>querySelector </li> <li>querySelectorAll </li> <li>remove </li> <li>removeEventListener </li> <li>replaceWith </li> <li>requestFullscreen </li> <li>requestPointerLock </li> <li>scrollIntoView </li> <li>setAttribute </li> <li>setAttributeNS </li> <li>setCustomValidity </li> <li>setInnerHtml </li> </ol> </div><!--/.sidebar-offcanvas-left--> <div class="col-xs-12 col-sm-9 col-md-6 main-content"> <section class="multi-line-signature"> <span class="name ">ButtonInputElement</span>() </section> <section class="desc markdown"> <p class="no-docs">Not documented.</p> </section> </div> <!-- /.main-content --> </div> <!-- container --> <footer> <div class="container-fluid"> <div class="container"> <p class="text-center"> <span class="no-break"> polymer_app_layout_template 0.1.0 api docs </span> &bull; <span class="copyright no-break"> <a href="https://www.dartlang.org"> <img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16"> </a> </span> &bull; <span class="copyright no-break"> <a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a> </span> </p> </div> </div> </footer> <script src="static-assets/prettify.js"></script> <script src="static-assets/script.js"></script> <!-- Do not remove placeholder --> <!-- Footer Placeholder --> </body> </html>
lejard-h/polymer_app_layout_templates
doc/api/polymer_app_layout.behaviors/ButtonInputElement/ButtonInputElement.html
HTML
bsd-3-clause
6,115
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Form\View\Helper; use Zend\Form\ElementInterface; use Zend\Form\Element\MultiCheckbox as MultiCheckboxElement; use Zend\Form\Exception; class FormMultiCheckbox extends FormInput { const LABEL_APPEND = 'append'; const LABEL_PREPEND = 'prepend'; /** * The attributes applied to option label * * @var array */ protected $labelAttributes; /** * Where will be label rendered? * * @var string */ protected $labelPosition = self::LABEL_APPEND; /** * Separator for checkbox elements * * @var string */ protected $separator = ''; /** * Prefixing the element with a hidden element for the unset value? * * @var bool */ protected $useHiddenElement = false; /** * The unchecked value used when "UseHiddenElement" is turned on * * @var string */ protected $uncheckedValue = ''; /** * Form input helper instance * * @var FormInput */ protected $inputHelper; /** * Form label helper instance * * @var FormLabel */ protected $labelHelper; /** * Invoke helper as functor * * Proxies to {@link render()}. * * @param ElementInterface|null $element * @param null|string $labelPosition * @return string|FormMultiCheckbox */ public function __invoke(ElementInterface $element = null, $labelPosition = null) { if (!$element) { return $this; } if ($labelPosition !== null) { $this->setLabelPosition($labelPosition); } return $this->render($element); } /** * Render a form <input> element from the provided $element * * @param ElementInterface $element * @throws Exception\InvalidArgumentException * @throws Exception\DomainException * @return string */ public function render(ElementInterface $element) { if (!$element instanceof MultiCheckboxElement) { throw new Exception\InvalidArgumentException(sprintf( '%s requires that the element is of type Zend\Form\Element\MultiCheckbox', __METHOD__ )); } $name = static::getName($element); $options = $element->getValueOptions(); if (empty($options)) { throw new Exception\DomainException(sprintf( '%s requires that the element has "value_options"; none found', __METHOD__ )); } $attributes = $element->getAttributes(); $attributes['name'] = $name; $attributes['type'] = $this->getInputType(); $selectedOptions = (array) $element->getValue(); $rendered = $this->renderOptions($element, $options, $selectedOptions, $attributes); // Render hidden element $useHiddenElement = method_exists($element, 'useHiddenElement') && $element->useHiddenElement() ? $element->useHiddenElement() : $this->useHiddenElement; if ($useHiddenElement) { $rendered = $this->renderHiddenElement($element, $attributes) . $rendered; } return $rendered; } /** * Render options * * @param MultiCheckboxElement $element * @param array $options * @param array $selectedOptions * @param array $attributes * @return string */ protected function renderOptions(MultiCheckboxElement $element, array $options, array $selectedOptions, array $attributes) { $escapeHtmlHelper = $this->getEscapeHtmlHelper(); $labelOptions = $element->getLabelOptions(); $labelHelper = $this->getLabelHelper(); $labelClose = $labelHelper->closeTag(); $labelPosition = $this->getLabelPosition(); $globalLabelAttributes = $element->getLabelAttributes(); $closingBracket = $this->getInlineClosingBracket(); if (empty($globalLabelAttributes)) { $globalLabelAttributes = $this->labelAttributes; } $combinedMarkup = array(); $count = 0; foreach ($options as $key => $optionSpec) { $count++; if ($count > 1 && array_key_exists('id', $attributes)) { unset($attributes['id']); } $value = ''; $label = ''; $inputAttributes = $attributes; $labelAttributes = $globalLabelAttributes; $selected = isset($inputAttributes['selected']) && $inputAttributes['type'] != 'radio' && $inputAttributes['selected'] != false ? true : false; $disabled = isset($inputAttributes['disabled']) && $inputAttributes['disabled'] != false ? true : false; if (is_scalar($optionSpec)) { $optionSpec = array( 'label' => $optionSpec, 'value' => $key ); } if (isset($optionSpec['value'])) { $value = $optionSpec['value']; } if (isset($optionSpec['label'])) { $label = $optionSpec['label']; } if (isset($optionSpec['selected'])) { $selected = $optionSpec['selected']; } if (isset($optionSpec['disabled'])) { $disabled = $optionSpec['disabled']; } if (isset($optionSpec['label_attributes'])) { $labelAttributes = (isset($labelAttributes)) ? array_merge($labelAttributes, $optionSpec['label_attributes']) : $optionSpec['label_attributes']; } if (isset($optionSpec['attributes'])) { $inputAttributes = array_merge($inputAttributes, $optionSpec['attributes']); } if (in_array($value, $selectedOptions)) { $selected = true; } $inputAttributes['value'] = $value; $inputAttributes['checked'] = $selected; $inputAttributes['disabled'] = $disabled; $input = sprintf( '<input %s%s', $this->createAttributesString($inputAttributes), $closingBracket ); if (null !== ($translator = $this->getTranslator())) { $label = $translator->translate( $label, $this->getTranslatorTextDomain() ); } if (empty($labelOptions) || $labelOptions['disable_html_escape'] == false) { $label = $escapeHtmlHelper($label); } $labelOpen = $labelHelper->openTag($labelAttributes); $template = $labelOpen . '%s%s' . $labelClose; switch ($labelPosition) { case self::LABEL_PREPEND: $markup = sprintf($template, $label, $input); break; case self::LABEL_APPEND: default: $markup = sprintf($template, $input, $label); break; } $combinedMarkup[] = $markup; } return implode($this->getSeparator(), $combinedMarkup); } /** * Render a hidden element for empty/unchecked value * * @param MultiCheckboxElement $element * @param array $attributes * @return string */ protected function renderHiddenElement(MultiCheckboxElement $element, array $attributes) { $closingBracket = $this->getInlineClosingBracket(); $uncheckedValue = $element->getUncheckedValue() ? $element->getUncheckedValue() : $this->uncheckedValue; $hiddenAttributes = array( 'name' => $element->getName(), 'value' => $uncheckedValue, ); return sprintf( '<input type="hidden" %s%s', $this->createAttributesString($hiddenAttributes), $closingBracket ); } /** * Sets the attributes applied to option label. * * @param array|null $attributes * @return FormMultiCheckbox */ public function setLabelAttributes($attributes) { $this->labelAttributes = $attributes; return $this; } /** * Returns the attributes applied to each option label. * * @return array|null */ public function getLabelAttributes() { return $this->labelAttributes; } /** * Set value for labelPosition * * @param mixed $labelPosition * @throws Exception\InvalidArgumentException * @return FormMultiCheckbox */ public function setLabelPosition($labelPosition) { $labelPosition = strtolower($labelPosition); if (!in_array($labelPosition, array(self::LABEL_APPEND, self::LABEL_PREPEND))) { throw new Exception\InvalidArgumentException(sprintf( '%s expects either %s::LABEL_APPEND or %s::LABEL_PREPEND; received "%s"', __METHOD__, __CLASS__, __CLASS__, (string) $labelPosition )); } $this->labelPosition = $labelPosition; return $this; } /** * Get position of label * * @return string */ public function getLabelPosition() { return $this->labelPosition; } /** * Set separator string for checkbox elements * * @param string $separator * @return FormMultiCheckbox */ public function setSeparator($separator) { $this->separator = (string) $separator; return $this; } /** * Get separator for checkbox elements * * @return string */ public function getSeparator() { return $this->separator; } /** * Sets the option for prefixing the element with a hidden element * for the unset value. * * @param bool $useHiddenElement * @return FormMultiCheckbox */ public function setUseHiddenElement($useHiddenElement) { $this->useHiddenElement = (bool) $useHiddenElement; return $this; } /** * Returns the option for prefixing the element with a hidden element * for the unset value. * * @return bool */ public function getUseHiddenElement() { return $this->useHiddenElement; } /** * Sets the unchecked value used when "UseHiddenElement" is turned on. * * @param bool $value * @return FormMultiCheckbox */ public function setUncheckedValue($value) { $this->uncheckedValue = $value; return $this; } /** * Returns the unchecked value used when "UseHiddenElement" is turned on. * * @return string */ public function getUncheckedValue() { return $this->uncheckedValue; } /** * Return input type * * @return string */ protected function getInputType() { return 'checkbox'; } /** * Get element name * * @param ElementInterface $element * @throws Exception\DomainException * @return string */ protected static function getName(ElementInterface $element) { $name = $element->getName(); if ($name === null || $name === '') { throw new Exception\DomainException(sprintf( '%s requires that the element has an assigned name; none discovered', __METHOD__ )); } return $name . '[]'; } /** * Retrieve the FormInput helper * * @return FormInput */ protected function getInputHelper() { if ($this->inputHelper) { return $this->inputHelper; } if (method_exists($this->view, 'plugin')) { $this->inputHelper = $this->view->plugin('form_input'); } if (!$this->inputHelper instanceof FormInput) { $this->inputHelper = new FormInput(); } return $this->inputHelper; } /** * Retrieve the FormLabel helper * * @return FormLabel */ protected function getLabelHelper() { if ($this->labelHelper) { return $this->labelHelper; } if (method_exists($this->view, 'plugin')) { $this->labelHelper = $this->view->plugin('form_label'); } if (!$this->labelHelper instanceof FormLabel) { $this->labelHelper = new FormLabel(); } return $this->labelHelper; } }
mowema/verano
vendor/zendframework/zendframework/library/Zend/Form/View/Helper/FormMultiCheckbox.php
PHP
bsd-3-clause
13,572
#!/bin/bash list=./encode65.list data=./encode65/ mkdir -p $data for x in `cat $list` do id=`echo $x | cut -f 1 -d ":"` url="https://www.encodeproject.org/files/$id/@@download/$id.bam" wget $url -O $data/$id.bam done
Kingsford-Group/scalloptest
data/download.encode65.sh
Shell
bsd-3-clause
223
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleContexts #-} -- -- Maybe.hs --- Optional Ivory values. -- -- Copyright (C) 2013, Galois, Inc. -- All Rights Reserved. -- -- This software is released under the "BSD3" license. Read the file -- "LICENSE" for more information. -- -- | This module provides an interface for a nullable Ivory type. -- -- To define a type like Haskell's @Maybe Float@, define an -- Ivory structure type, and make the structure an instance -- of 'MaybeType'. -- -- > [ivory| -- > struct maybe_float -- > { mf_valid :: Stored IBool -- > ; mf_value :: Stored IFloat -- > } -- > |] -- > -- > instance MaybeType "maybe_float" IFloat where -- > maybeValidLabel = mf_valid -- > maybeValueLabel = mf_value -- -- With this definition in place, any of the functions in this -- module will accept a @Struct \"maybe_float\"@. -- -- These structure types must be defined in an Ivory module as -- usual, and it is recommended to make them private unless they -- are necessary as part of the module's public interface. module Ivory.Stdlib.Maybe ( -- * Interface MaybeType(..) -- * Initialization , initJust, initNothing -- * Getting , getMaybe -- * Setting , setJust, setNothing , setDefault, setDefault_ -- * Modifying , mapMaybe , mapMaybeM, mapMaybeM_ , forMaybeM, forMaybeM_ ) where import GHC.TypeLits import Ivory.Language class (IvoryStruct sym, IvoryExpr t, IvoryStore t, IvoryInit t) => MaybeType (sym :: Symbol) t | sym -> t where -- | Return a boolean field indicating whether the value is valid. maybeValidLabel :: Label sym (Stored IBool) -- | Return the field containing a value, if it is valid. maybeValueLabel :: Label sym (Stored t) -- | Return an initializer for a maybe type with a valid value. initJust :: MaybeType sym a => a -> Init (Struct sym) initJust x = istruct [ maybeValidLabel .= ival true , maybeValueLabel .= ival x ] -- | Return an initializer for a maybe type with no value. initNothing :: MaybeType sym a => Init (Struct sym) initNothing = istruct [ maybeValidLabel .= ival false ] -- | Retrieve a maybe's value given a default if it is nothing. getMaybe :: MaybeType sym a => ConstRef s1 (Struct sym) -> a -> Ivory eff a getMaybe ref def = do valid <- deref (ref ~> maybeValidLabel) value <- deref (ref ~> maybeValueLabel) assign (valid ? (value, def)) -- | Set a maybe's value to a default if it is nothing, returning -- the current value. setDefault :: MaybeType sym a => Ref s1 (Struct sym) -> a -> Ivory eff a setDefault ref def = do setDefault_ ref def deref (ref ~> maybeValueLabel) -- | Set a maybe's value to a default value if it is nothing. setDefault_ :: MaybeType sym a => Ref s1 (Struct sym) -> a -> Ivory eff () setDefault_ ref def = do valid <- deref (ref ~> maybeValidLabel) ifte_ (iNot valid) (do store (ref ~> maybeValidLabel) true store (ref ~> maybeValueLabel) def) (return ()) -- | Modify a maybe value by an expression if it is not nothing. mapMaybe :: MaybeType sym a => (a -> a) -> Ref s1 (Struct sym) -> Ivory eff () mapMaybe f ref = mapMaybeM (return . f) ref -- | Modify a maybe value by an action if it is not nothing. mapMaybeM :: MaybeType sym a => (a -> Ivory eff a) -> Ref s1 (Struct sym) -> Ivory eff () mapMaybeM f ref = do valid <- deref (ref ~> maybeValidLabel) ifte_ valid (do value <- deref (ref ~> maybeValueLabel) value' <- f value store (ref ~> maybeValueLabel) value') (return ()) -- | Flipped version of 'mapMaybeM'. forMaybeM :: MaybeType sym a => Ref s1 (Struct sym) -> (a -> Ivory eff a) -> Ivory eff () forMaybeM = flip mapMaybeM -- | Call an action with a maybe value if it is not nothing. mapMaybeM_ :: MaybeType sym a => (a -> Ivory eff ()) -> Ref s1 (Struct sym) -> Ivory eff () mapMaybeM_ f ref = do valid <- deref (ref ~> maybeValidLabel) ifte_ valid (do value <- deref (ref ~> maybeValueLabel) f value) (return ()) -- | Flipped version of 'mapMaybeM_'. forMaybeM_ :: MaybeType sym a => Ref s1 (Struct sym) -> (a -> Ivory eff ()) -> Ivory eff () forMaybeM_ = flip mapMaybeM_ -- | Set a maybe value to a valid value. setJust :: MaybeType sym a => Ref s1 (Struct sym) -> a -> Ivory eff () setJust ref x = do store (ref ~> maybeValidLabel) true store (ref ~> maybeValueLabel) x -- | Set a maybe value to an invalid value. setNothing :: MaybeType sym a => Ref s1 (Struct sym) -> Ivory eff () setNothing ref = store (ref ~> maybeValidLabel) false
Hodapp87/ivory
ivory-stdlib/src/Ivory/Stdlib/Maybe.hs
Haskell
bsd-3-clause
4,931
package net.carriercommander.ui.hud.walrus; import com.jme3.app.Application; import net.carriercommander.ui.WindowState; import net.carriercommander.ui.hud.widgets.Window; public class StateStatus extends WindowState { @Override protected void initialize(Application app) { window = new Window(); scaleAndPosition(app.getCamera(), 0.5f, 0.5f); } @Override protected void cleanup(Application app) { } }
neuweiler/CarrierCommander
src/main/java/net/carriercommander/ui/hud/walrus/StateStatus.java
Java
bsd-3-clause
417
#pragma once //=====================================================================// /*! @file @brief DDS 画像を扱うクラス(ヘッダー) @author 平松邦仁 ([email protected]) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE */ //=====================================================================// #include "img_io/i_img_io.hpp" #include "img_io/img_idx8.hpp" #include "img_io/img_rgba8.hpp" namespace img { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief DDS 画像クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class dds_io : public i_img_io { shared_img img_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// dds_io() { } //-----------------------------------------------------------------// /*! @brief デストラクター */ //-----------------------------------------------------------------// virtual ~dds_io() { } //-----------------------------------------------------------------// /*! @brief ファイル拡張子を返す @return ファイル拡張子の文字列 */ //-----------------------------------------------------------------// const char* get_file_ext() const override { return "dds"; } //-----------------------------------------------------------------// /*! @brief DDS ファイルか確認する @param[in] fin file_io クラス @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool probe(utils::file_io& fin) override; //-----------------------------------------------------------------// /*! @brief 画像ファイルの情報を取得する @param[in] fin file_io クラス @param[in] fo 情報を受け取る構造体 @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool info(utils::file_io& fin, img::img_info& fo) override; //-----------------------------------------------------------------// /*! @brief DDS ファイル、ロード(utils::file_io) @param[in] fin ファイル I/O クラス @param[in] ext フォーマット固有の設定文字列 @return エラーなら「false」を返す */ //-----------------------------------------------------------------// bool load(utils::file_io& fin, const std::string& ext = "") override; //-----------------------------------------------------------------// /*! @brief DDS ファイルをセーブする @param[in] fout ファイル I/O クラス @param[in] ext フォーマット固有の設定文字列 @return エラーがあれば「false」 */ //-----------------------------------------------------------------// bool save(utils::file_io& fout, const std::string& ext = "") override; //-----------------------------------------------------------------// /*! @brief イメージインターフェースを取得 @return イメージインターフェース */ //-----------------------------------------------------------------// const shared_img get_image() const override { return img_; } //-----------------------------------------------------------------// /*! @brief イメージインターフェースの登録 @param[in] imf イメージインターフェース */ //-----------------------------------------------------------------// void set_image(shared_img img) override { img_ = img; } }; }
hirakuni45/glfw3_app
glfw3_app/common/img_io/dds_io.hpp
C++
bsd-3-clause
3,880
<ol class="breadcrumb"> <li><a href="/post/index">首页</a></li> <li><a href="/interest/index">景点管理</a></li> <li class="active">新增景点</li> </ol> <div class="panel panel-primary"> <!-- Default panel contents --> <div class="panel-heading">增加景点</div> <!-- Table --> <table class="table" id="schedule"> <tr> <td >相关港口</td> <td><select class="selectpicker port" name="port" id="port"> <?php if($port){ ?> <?php for($i =0 ;$i< count($port) ; $i++){?> <option><?php echo $port[$i]->name ?> </option> <?php }?> <?php }?> </select> </td> </tr> <tr> <td >景点标题</td> <td> <input type="text" style="width:400px"name="title" id="title" > </td> </tr> <tr> <td>景点内容</td> <td> <div class="summernote" id="summernote"></div> </td> </tr> </table> <div> <button class="btn btn-success " onclick="save()">保存</button> </div> </div> <script type="text/javascript"> $(document).ready(function() { $('#summernote').summernote({ height: 400, // set editor height onImageUpload: function(files, editor, welEditable) { sendFile(files[0], editor, welEditable); } }); // $('.summernote').destroy(); }); function sendFile(file, editor, welEditable) { data = new FormData(); data.append("file", file); $.ajax({ data: data, type: "POST", url: "/schedule/upload_image", cache: false, contentType: false, processData: false, success: function(url) { // alert(url); editor.insertImage(welEditable, url); } }); } var save = function() { var aHTML = $('.summernote').code(); //save HTML If you need(aHTML: array). var port = $('.port').val(); var title = document.getElementById("title").value; $.ajax({ dataType: "json", data:{ "title":title, "port":port, "content":aHTML }, type: "post", url: "/interest/add_interest", success: function() { alert('success'); // editor.insertImage(welEditable, url); } }); // $('.summernote').destroy(); }; </script>
garydai/yii2
demos/backend/protected/views/interest/add.php
PHP
bsd-3-clause
2,716
#ifndef I_DEFINITION_MANAGER_HPP #define I_DEFINITION_MANAGER_HPP #include <string> #include <vector> #include <memory> #include "mutable_vector.hpp" #include "core_serialization/i_datastream.hpp" #include "reflected_object.hpp" #include "object_handle.hpp" namespace wgt { class IClassDefinitionModifier; class IClassDefinitionDetails; class IClassDefinition; class IDefinitionHelper; class IObjectManager; class PropertyAccessorListener; class ISerializer; /** * IDefinitionManager */ class IDefinitionManager { public: virtual ~IDefinitionManager() {} typedef MutableVector< std::weak_ptr< PropertyAccessorListener > > PropertyAccessorListeners; /** * Get a definition for the type represented by 'name'. */ virtual IClassDefinition * getDefinition( const char * name ) const = 0; /** * Get a definition for an object instance. Will fall back to object type if no definition can be found for the specific instance */ virtual IClassDefinition * getObjectDefinition( const ObjectHandle & object ) const = 0; virtual std::unique_ptr<IClassDefinitionDetails> createGenericDefinition( const char * name ) const = 0; virtual void getDefinitionsOfType( const IClassDefinition * definition, std::vector< IClassDefinition * > & o_Definitions ) const = 0; virtual void getDefinitionsOfType( const std::string & type, std::vector< IClassDefinition * > & o_Definitions ) const = 0; virtual IObjectManager * getObjectManager() const = 0; virtual IClassDefinition * registerDefinition( std::unique_ptr<IClassDefinitionDetails> definition ) = 0; virtual bool deregisterDefinition( const IClassDefinition * definition ) = 0; virtual void registerDefinitionHelper( const IDefinitionHelper & helper ) = 0; virtual void deregisterDefinitionHelper( const IDefinitionHelper & helper ) = 0; virtual void registerPropertyAccessorListener( std::shared_ptr< PropertyAccessorListener > & listener ) = 0; virtual void deregisterPropertyAccessorListener( std::shared_ptr< PropertyAccessorListener > & listener ) = 0; virtual const PropertyAccessorListeners & getPropertyAccessorListeners() const = 0; virtual bool serializeDefinitions( ISerializer & serializer ) = 0; virtual bool deserializeDefinitions( ISerializer & serializer ) = 0; template< typename TargetType > IClassDefinition * getDefinition() const { const char * defName = getClassIdentifier< TargetType >(); return getDefinition( defName ); } template< class T > ObjectHandleT< T > create( bool managed = true ) const { auto definition = getDefinition< T >(); if (definition == nullptr) { return ObjectHandleT< T >(); } auto object = managed ? definition->createManagedObject() : definition->create(); return safeCast< T >( object ); } template< class TDefinition > IClassDefinition* registerDefinition() { return registerDefinition( std::unique_ptr<IClassDefinitionDetails>( new TDefinition() ) ); } }; } // end namespace wgt #endif // I_DEFINITION_MANAGER_HPP
dava/wgtf
src/core/lib/core_reflection/i_definition_manager.hpp
C++
bsd-3-clause
2,988
/*- * Copyright (c) 2001 Atsushi Onoe * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: releng/9.3/sys/net80211/ieee80211_output.c 266507 2014-05-21 17:02:21Z hselasky $"); #include "opt_inet.h" #include "opt_inet6.h" #include "opt_wlan.h" #include <sys/param.h> #include <sys/systm.h> #include <sys/mbuf.h> #include <sys/kernel.h> #include <sys/endian.h> #include <sys/socket.h> #include <net/bpf.h> #include <net/ethernet.h> #include <net/if.h> #include <net/if_llc.h> #include <net/if_media.h> #include <net/if_vlan_var.h> #include <net80211/ieee80211_var.h> #include <net80211/ieee80211_regdomain.h> #ifdef IEEE80211_SUPPORT_SUPERG #include <net80211/ieee80211_superg.h> #endif #ifdef IEEE80211_SUPPORT_TDMA #include <net80211/ieee80211_tdma.h> #endif #include <net80211/ieee80211_wds.h> #include <net80211/ieee80211_mesh.h> #if defined(INET) || defined(INET6) #include <netinet/in.h> #endif #ifdef INET #include <netinet/if_ether.h> #include <netinet/in_systm.h> #include <netinet/ip.h> #endif #ifdef INET6 #include <netinet/ip6.h> #endif #include <security/mac/mac_framework.h> #define ETHER_HEADER_COPY(dst, src) \ memcpy(dst, src, sizeof(struct ether_header)) /* unalligned little endian access */ #define LE_WRITE_2(p, v) do { \ ((uint8_t *)(p))[0] = (v) & 0xff; \ ((uint8_t *)(p))[1] = ((v) >> 8) & 0xff; \ } while (0) #define LE_WRITE_4(p, v) do { \ ((uint8_t *)(p))[0] = (v) & 0xff; \ ((uint8_t *)(p))[1] = ((v) >> 8) & 0xff; \ ((uint8_t *)(p))[2] = ((v) >> 16) & 0xff; \ ((uint8_t *)(p))[3] = ((v) >> 24) & 0xff; \ } while (0) static int ieee80211_fragment(struct ieee80211vap *, struct mbuf *, u_int hdrsize, u_int ciphdrsize, u_int mtu); static void ieee80211_tx_mgt_cb(struct ieee80211_node *, void *, int); #ifdef IEEE80211_DEBUG /* * Decide if an outbound management frame should be * printed when debugging is enabled. This filters some * of the less interesting frames that come frequently * (e.g. beacons). */ static __inline int doprint(struct ieee80211vap *vap, int subtype) { switch (subtype) { case IEEE80211_FC0_SUBTYPE_PROBE_RESP: return (vap->iv_opmode == IEEE80211_M_IBSS); } return 1; } #endif /* * Start method for vap's. All packets from the stack come * through here. We handle common processing of the packets * before dispatching them to the underlying device. */ void ieee80211_start(struct ifnet *ifp) { #define IS_DWDS(vap) \ (vap->iv_opmode == IEEE80211_M_WDS && \ (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY) == 0) struct ieee80211vap *vap = ifp->if_softc; struct ieee80211com *ic = vap->iv_ic; struct ifnet *parent = ic->ic_ifp; struct ieee80211_node *ni; struct mbuf *m; struct ether_header *eh; int error; /* NB: parent must be up and running */ if (!IFNET_IS_UP_RUNNING(parent)) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT, "%s: ignore queue, parent %s not up+running\n", __func__, parent->if_xname); /* XXX stat */ return; } if (vap->iv_state == IEEE80211_S_SLEEP) { /* * In power save, wakeup device for transmit. */ ieee80211_new_state(vap, IEEE80211_S_RUN, 0); return; } /* * No data frames go out unless we're running. * Note in particular this covers CAC and CSA * states (though maybe we should check muting * for CSA). */ if (vap->iv_state != IEEE80211_S_RUN) { IEEE80211_LOCK(ic); /* re-check under the com lock to avoid races */ if (vap->iv_state != IEEE80211_S_RUN) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT, "%s: ignore queue, in %s state\n", __func__, ieee80211_state_name[vap->iv_state]); vap->iv_stats.is_tx_badstate++; ifp->if_drv_flags |= IFF_DRV_OACTIVE; IEEE80211_UNLOCK(ic); return; } IEEE80211_UNLOCK(ic); } for (;;) { IFQ_DEQUEUE(&ifp->if_snd, m); if (m == NULL) break; /* * Sanitize mbuf flags for net80211 use. We cannot * clear M_PWR_SAV or M_MORE_DATA because these may * be set for frames that are re-submitted from the * power save queue. * * NB: This must be done before ieee80211_classify as * it marks EAPOL in frames with M_EAPOL. */ m->m_flags &= ~(M_80211_TX - M_PWR_SAV - M_MORE_DATA); /* * Cancel any background scan. */ if (ic->ic_flags & IEEE80211_F_SCAN) ieee80211_cancel_anyscan(vap); /* * Find the node for the destination so we can do * things like power save and fast frames aggregation. * * NB: past this point various code assumes the first * mbuf has the 802.3 header present (and contiguous). */ ni = NULL; if (m->m_len < sizeof(struct ether_header) && (m = m_pullup(m, sizeof(struct ether_header))) == NULL) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT, "discard frame, %s\n", "m_pullup failed"); vap->iv_stats.is_tx_nobuf++; /* XXX */ ifp->if_oerrors++; continue; } eh = mtod(m, struct ether_header *); if (ETHER_IS_MULTICAST(eh->ether_dhost)) { if (IS_DWDS(vap)) { /* * Only unicast frames from the above go out * DWDS vaps; multicast frames are handled by * dispatching the frame as it comes through * the AP vap (see below). */ IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_WDS, eh->ether_dhost, "mcast", "%s", "on DWDS"); vap->iv_stats.is_dwds_mcast++; m_freem(m); continue; } if (vap->iv_opmode == IEEE80211_M_HOSTAP) { /* * Spam DWDS vap's w/ multicast traffic. */ /* XXX only if dwds in use? */ ieee80211_dwds_mcast(vap, m); } } #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode != IEEE80211_M_MBSS) { #endif ni = ieee80211_find_txnode(vap, eh->ether_dhost); if (ni == NULL) { /* NB: ieee80211_find_txnode does stat+msg */ ifp->if_oerrors++; m_freem(m); continue; } if (ni->ni_associd == 0 && (ni->ni_flags & IEEE80211_NODE_ASSOCID)) { IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT, eh->ether_dhost, NULL, "sta not associated (type 0x%04x)", htons(eh->ether_type)); vap->iv_stats.is_tx_notassoc++; ifp->if_oerrors++; m_freem(m); ieee80211_free_node(ni); continue; } #ifdef IEEE80211_SUPPORT_MESH } else { if (!IEEE80211_ADDR_EQ(eh->ether_shost, vap->iv_myaddr)) { /* * Proxy station only if configured. */ if (!ieee80211_mesh_isproxyena(vap)) { IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_MESH, eh->ether_dhost, NULL, "%s", "proxy not enabled"); vap->iv_stats.is_mesh_notproxy++; ifp->if_oerrors++; m_freem(m); continue; } ieee80211_mesh_proxy_check(vap, eh->ether_shost); } ni = ieee80211_mesh_discover(vap, eh->ether_dhost, m); if (ni == NULL) { /* * NB: ieee80211_mesh_discover holds/disposes * frame (e.g. queueing on path discovery). */ ifp->if_oerrors++; continue; } } #endif if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) && (m->m_flags & M_PWR_SAV) == 0) { /* * Station in power save mode; pass the frame * to the 802.11 layer and continue. We'll get * the frame back when the time is right. * XXX lose WDS vap linkage? */ (void) ieee80211_pwrsave(ni, m); ieee80211_free_node(ni); continue; } /* calculate priority so drivers can find the tx queue */ if (ieee80211_classify(ni, m)) { IEEE80211_DISCARD_MAC(vap, IEEE80211_MSG_OUTPUT, eh->ether_dhost, NULL, "%s", "classification failure"); vap->iv_stats.is_tx_classify++; ifp->if_oerrors++; m_freem(m); ieee80211_free_node(ni); continue; } /* * Stash the node pointer. Note that we do this after * any call to ieee80211_dwds_mcast because that code * uses any existing value for rcvif to identify the * interface it (might have been) received on. */ m->m_pkthdr.rcvif = (void *)ni; BPF_MTAP(ifp, m); /* 802.3 tx */ /* * Check if A-MPDU tx aggregation is setup or if we * should try to enable it. The sta must be associated * with HT and A-MPDU enabled for use. When the policy * routine decides we should enable A-MPDU we issue an * ADDBA request and wait for a reply. The frame being * encapsulated will go out w/o using A-MPDU, or possibly * it might be collected by the driver and held/retransmit. * The default ic_ampdu_enable routine handles staggering * ADDBA requests in case the receiver NAK's us or we are * otherwise unable to establish a BA stream. */ if ((ni->ni_flags & IEEE80211_NODE_AMPDU_TX) && (vap->iv_flags_ht & IEEE80211_FHT_AMPDU_TX) && (m->m_flags & M_EAPOL) == 0) { const int ac = M_WME_GETAC(m); struct ieee80211_tx_ampdu *tap = &ni->ni_tx_ampdu[ac]; ieee80211_txampdu_count_packet(tap); if (IEEE80211_AMPDU_RUNNING(tap)) { /* * Operational, mark frame for aggregation. * * XXX do tx aggregation here */ m->m_flags |= M_AMPDU_MPDU; } else if (!IEEE80211_AMPDU_REQUESTED(tap) && ic->ic_ampdu_enable(ni, tap)) { /* * Not negotiated yet, request service. */ ieee80211_ampdu_request(ni, tap); /* XXX hold frame for reply? */ } } #ifdef IEEE80211_SUPPORT_SUPERG else if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_NODE_FF)) { m = ieee80211_ff_check(ni, m); if (m == NULL) { /* NB: any ni ref held on stageq */ continue; } } #endif /* IEEE80211_SUPPORT_SUPERG */ if (__predict_true((vap->iv_caps & IEEE80211_C_8023ENCAP) == 0)) { /* * Encapsulate the packet in prep for transmission. */ m = ieee80211_encap(vap, ni, m); if (m == NULL) { /* NB: stat+msg handled in ieee80211_encap */ ieee80211_free_node(ni); continue; } } error = parent->if_transmit(parent, m); if (error != 0) { /* NB: IFQ_HANDOFF reclaims mbuf */ ieee80211_free_node(ni); } else { ifp->if_opackets++; } ic->ic_lastdata = ticks; } #undef IS_DWDS } /* * 802.11 output routine. This is (currently) used only to * connect bpf write calls to the 802.11 layer for injecting * raw 802.11 frames. */ int ieee80211_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst, struct route *ro) { #define senderr(e) do { error = (e); goto bad;} while (0) struct ieee80211_node *ni = NULL; struct ieee80211vap *vap; struct ieee80211_frame *wh; int error; if (ifp->if_drv_flags & IFF_DRV_OACTIVE) { /* * Short-circuit requests if the vap is marked OACTIVE * as this can happen because a packet came down through * ieee80211_start before the vap entered RUN state in * which case it's ok to just drop the frame. This * should not be necessary but callers of if_output don't * check OACTIVE. */ senderr(ENETDOWN); } vap = ifp->if_softc; /* * Hand to the 802.3 code if not tagged as * a raw 802.11 frame. */ if (dst->sa_family != AF_IEEE80211) return vap->iv_output(ifp, m, dst, ro); #ifdef MAC error = mac_ifnet_check_transmit(ifp, m); if (error) senderr(error); #endif if (ifp->if_flags & IFF_MONITOR) senderr(ENETDOWN); if (!IFNET_IS_UP_RUNNING(ifp)) senderr(ENETDOWN); if (vap->iv_state == IEEE80211_S_CAC) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH, "block %s frame in CAC state\n", "raw data"); vap->iv_stats.is_tx_badstate++; senderr(EIO); /* XXX */ } else if (vap->iv_state == IEEE80211_S_SCAN) senderr(EIO); /* XXX bypass bridge, pfil, carp, etc. */ if (m->m_pkthdr.len < sizeof(struct ieee80211_frame_ack)) senderr(EIO); /* XXX */ wh = mtod(m, struct ieee80211_frame *); if ((wh->i_fc[0] & IEEE80211_FC0_VERSION_MASK) != IEEE80211_FC0_VERSION_0) senderr(EIO); /* XXX */ /* locate destination node */ switch (wh->i_fc[1] & IEEE80211_FC1_DIR_MASK) { case IEEE80211_FC1_DIR_NODS: case IEEE80211_FC1_DIR_FROMDS: ni = ieee80211_find_txnode(vap, wh->i_addr1); break; case IEEE80211_FC1_DIR_TODS: case IEEE80211_FC1_DIR_DSTODS: if (m->m_pkthdr.len < sizeof(struct ieee80211_frame)) senderr(EIO); /* XXX */ ni = ieee80211_find_txnode(vap, wh->i_addr3); break; default: senderr(EIO); /* XXX */ } if (ni == NULL) { /* * Permit packets w/ bpf params through regardless * (see below about sa_len). */ if (dst->sa_len == 0) senderr(EHOSTUNREACH); ni = ieee80211_ref_node(vap->iv_bss); } /* * Sanitize mbuf for net80211 flags leaked from above. * * NB: This must be done before ieee80211_classify as * it marks EAPOL in frames with M_EAPOL. */ m->m_flags &= ~M_80211_TX; /* calculate priority so drivers can find the tx queue */ /* XXX assumes an 802.3 frame */ if (ieee80211_classify(ni, m)) senderr(EIO); /* XXX */ ifp->if_opackets++; IEEE80211_NODE_STAT(ni, tx_data); if (IEEE80211_IS_MULTICAST(wh->i_addr1)) { IEEE80211_NODE_STAT(ni, tx_mcast); m->m_flags |= M_MCAST; } else IEEE80211_NODE_STAT(ni, tx_ucast); /* NB: ieee80211_encap does not include 802.11 header */ IEEE80211_NODE_STAT_ADD(ni, tx_bytes, m->m_pkthdr.len); /* * NB: DLT_IEEE802_11_RADIO identifies the parameters are * present by setting the sa_len field of the sockaddr (yes, * this is a hack). * NB: we assume sa_data is suitably aligned to cast. */ return vap->iv_ic->ic_raw_xmit(ni, m, (const struct ieee80211_bpf_params *)(dst->sa_len ? dst->sa_data : NULL)); bad: if (m != NULL) m_freem(m); if (ni != NULL) ieee80211_free_node(ni); ifp->if_oerrors++; return error; #undef senderr } /* * Set the direction field and address fields of an outgoing * frame. Note this should be called early on in constructing * a frame as it sets i_fc[1]; other bits can then be or'd in. */ void ieee80211_send_setup( struct ieee80211_node *ni, struct mbuf *m, int type, int tid, const uint8_t sa[IEEE80211_ADDR_LEN], const uint8_t da[IEEE80211_ADDR_LEN], const uint8_t bssid[IEEE80211_ADDR_LEN]) { #define WH4(wh) ((struct ieee80211_frame_addr4 *)wh) struct ieee80211vap *vap = ni->ni_vap; struct ieee80211_tx_ampdu *tap; struct ieee80211_frame *wh = mtod(m, struct ieee80211_frame *); ieee80211_seq seqno; wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | type; if ((type & IEEE80211_FC0_TYPE_MASK) == IEEE80211_FC0_TYPE_DATA) { switch (vap->iv_opmode) { case IEEE80211_M_STA: wh->i_fc[1] = IEEE80211_FC1_DIR_TODS; IEEE80211_ADDR_COPY(wh->i_addr1, bssid); IEEE80211_ADDR_COPY(wh->i_addr2, sa); IEEE80211_ADDR_COPY(wh->i_addr3, da); break; case IEEE80211_M_IBSS: case IEEE80211_M_AHDEMO: wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, sa); IEEE80211_ADDR_COPY(wh->i_addr3, bssid); break; case IEEE80211_M_HOSTAP: wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS; IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, bssid); IEEE80211_ADDR_COPY(wh->i_addr3, sa); break; case IEEE80211_M_WDS: wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS; IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, da); IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa); break; case IEEE80211_M_MBSS: #ifdef IEEE80211_SUPPORT_MESH /* XXX add support for proxied addresses */ if (IEEE80211_IS_MULTICAST(da)) { wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS; /* XXX next hop */ IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); } else { wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS; IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, da); IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, sa); } #endif break; case IEEE80211_M_MONITOR: /* NB: to quiet compiler */ break; } } else { wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; IEEE80211_ADDR_COPY(wh->i_addr1, da); IEEE80211_ADDR_COPY(wh->i_addr2, sa); #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode == IEEE80211_M_MBSS) IEEE80211_ADDR_COPY(wh->i_addr3, sa); else #endif IEEE80211_ADDR_COPY(wh->i_addr3, bssid); } *(uint16_t *)&wh->i_dur[0] = 0; tap = &ni->ni_tx_ampdu[TID_TO_WME_AC(tid)]; if (tid != IEEE80211_NONQOS_TID && IEEE80211_AMPDU_RUNNING(tap)) m->m_flags |= M_AMPDU_MPDU; else { seqno = ni->ni_txseqs[tid]++; *(uint16_t *)&wh->i_seq[0] = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT); M_SEQNO_SET(m, seqno); } if (IEEE80211_IS_MULTICAST(wh->i_addr1)) m->m_flags |= M_MCAST; #undef WH4 } /* * Send a management frame to the specified node. The node pointer * must have a reference as the pointer will be passed to the driver * and potentially held for a long time. If the frame is successfully * dispatched to the driver, then it is responsible for freeing the * reference (and potentially free'ing up any associated storage); * otherwise deal with reclaiming any reference (on error). */ int ieee80211_mgmt_output(struct ieee80211_node *ni, struct mbuf *m, int type, struct ieee80211_bpf_params *params) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ieee80211_frame *wh; KASSERT(ni != NULL, ("null node")); if (vap->iv_state == IEEE80211_S_CAC) { IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH, ni, "block %s frame in CAC state", ieee80211_mgt_subtype_name[ (type & IEEE80211_FC0_SUBTYPE_MASK) >> IEEE80211_FC0_SUBTYPE_SHIFT]); vap->iv_stats.is_tx_badstate++; ieee80211_free_node(ni); m_freem(m); return EIO; /* XXX */ } M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT); if (m == NULL) { ieee80211_free_node(ni); return ENOMEM; } wh = mtod(m, struct ieee80211_frame *); ieee80211_send_setup(ni, m, IEEE80211_FC0_TYPE_MGT | type, IEEE80211_NONQOS_TID, vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid); if (params->ibp_flags & IEEE80211_BPF_CRYPTO) { IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_AUTH, wh->i_addr1, "encrypting frame (%s)", __func__); wh->i_fc[1] |= IEEE80211_FC1_WEP; } m->m_flags |= M_ENCAP; /* mark encapsulated */ KASSERT(type != IEEE80211_FC0_SUBTYPE_PROBE_RESP, ("probe response?")); M_WME_SETAC(m, params->ibp_pri); #ifdef IEEE80211_DEBUG /* avoid printing too many frames */ if ((ieee80211_msg_debug(vap) && doprint(vap, type)) || ieee80211_msg_dumppkts(vap)) { printf("[%s] send %s on channel %u\n", ether_sprintf(wh->i_addr1), ieee80211_mgt_subtype_name[ (type & IEEE80211_FC0_SUBTYPE_MASK) >> IEEE80211_FC0_SUBTYPE_SHIFT], ieee80211_chan2ieee(ic, ic->ic_curchan)); } #endif IEEE80211_NODE_STAT(ni, tx_mgmt); return ic->ic_raw_xmit(ni, m, params); } /* * Send a null data frame to the specified node. If the station * is setup for QoS then a QoS Null Data frame is constructed. * If this is a WDS station then a 4-address frame is constructed. * * NB: the caller is assumed to have setup a node reference * for use; this is necessary to deal with a race condition * when probing for inactive stations. Like ieee80211_mgmt_output * we must cleanup any node reference on error; however we * can safely just unref it as we know it will never be the * last reference to the node. */ int ieee80211_send_nulldata(struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct mbuf *m; struct ieee80211_frame *wh; int hdrlen; uint8_t *frm; if (vap->iv_state == IEEE80211_S_CAC) { IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT | IEEE80211_MSG_DOTH, ni, "block %s frame in CAC state", "null data"); ieee80211_unref_node(&ni); vap->iv_stats.is_tx_badstate++; return EIO; /* XXX */ } if (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) hdrlen = sizeof(struct ieee80211_qosframe); else hdrlen = sizeof(struct ieee80211_frame); /* NB: only WDS vap's get 4-address frames */ if (vap->iv_opmode == IEEE80211_M_WDS) hdrlen += IEEE80211_ADDR_LEN; if (ic->ic_flags & IEEE80211_F_DATAPAD) hdrlen = roundup(hdrlen, sizeof(uint32_t)); m = ieee80211_getmgtframe(&frm, ic->ic_headroom + hdrlen, 0); if (m == NULL) { /* XXX debug msg */ ieee80211_unref_node(&ni); vap->iv_stats.is_tx_nobuf++; return ENOMEM; } KASSERT(M_LEADINGSPACE(m) >= hdrlen, ("leading space %zd", M_LEADINGSPACE(m))); M_PREPEND(m, hdrlen, M_DONTWAIT); if (m == NULL) { /* NB: cannot happen */ ieee80211_free_node(ni); return ENOMEM; } wh = mtod(m, struct ieee80211_frame *); /* NB: a little lie */ if (ni->ni_flags & IEEE80211_NODE_QOS) { const int tid = WME_AC_TO_TID(WME_AC_BE); uint8_t *qos; ieee80211_send_setup(ni, m, IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_QOS_NULL, tid, vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid); if (vap->iv_opmode == IEEE80211_M_WDS) qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos; else qos = ((struct ieee80211_qosframe *) wh)->i_qos; qos[0] = tid & IEEE80211_QOS_TID; if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[WME_AC_BE].wmep_noackPolicy) qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK; qos[1] = 0; } else { ieee80211_send_setup(ni, m, IEEE80211_FC0_TYPE_DATA | IEEE80211_FC0_SUBTYPE_NODATA, IEEE80211_NONQOS_TID, vap->iv_myaddr, ni->ni_macaddr, ni->ni_bssid); } if (vap->iv_opmode != IEEE80211_M_WDS) { /* NB: power management bit is never sent by an AP */ if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) && vap->iv_opmode != IEEE80211_M_HOSTAP) wh->i_fc[1] |= IEEE80211_FC1_PWR_MGT; } m->m_len = m->m_pkthdr.len = hdrlen; m->m_flags |= M_ENCAP; /* mark encapsulated */ M_WME_SETAC(m, WME_AC_BE); IEEE80211_NODE_STAT(ni, tx_data); IEEE80211_NOTE(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, ni, "send %snull data frame on channel %u, pwr mgt %s", ni->ni_flags & IEEE80211_NODE_QOS ? "QoS " : "", ieee80211_chan2ieee(ic, ic->ic_curchan), wh->i_fc[1] & IEEE80211_FC1_PWR_MGT ? "ena" : "dis"); return ic->ic_raw_xmit(ni, m, NULL); } /* * Assign priority to a frame based on any vlan tag assigned * to the station and/or any Diffserv setting in an IP header. * Finally, if an ACM policy is setup (in station mode) it's * applied. */ int ieee80211_classify(struct ieee80211_node *ni, struct mbuf *m) { const struct ether_header *eh = mtod(m, struct ether_header *); int v_wme_ac, d_wme_ac, ac; /* * Always promote PAE/EAPOL frames to high priority. */ if (eh->ether_type == htons(ETHERTYPE_PAE)) { /* NB: mark so others don't need to check header */ m->m_flags |= M_EAPOL; ac = WME_AC_VO; goto done; } /* * Non-qos traffic goes to BE. */ if ((ni->ni_flags & IEEE80211_NODE_QOS) == 0) { ac = WME_AC_BE; goto done; } /* * If node has a vlan tag then all traffic * to it must have a matching tag. */ v_wme_ac = 0; if (ni->ni_vlan != 0) { if ((m->m_flags & M_VLANTAG) == 0) { IEEE80211_NODE_STAT(ni, tx_novlantag); return 1; } if (EVL_VLANOFTAG(m->m_pkthdr.ether_vtag) != EVL_VLANOFTAG(ni->ni_vlan)) { IEEE80211_NODE_STAT(ni, tx_vlanmismatch); return 1; } /* map vlan priority to AC */ v_wme_ac = TID_TO_WME_AC(EVL_PRIOFTAG(ni->ni_vlan)); } /* XXX m_copydata may be too slow for fast path */ #ifdef INET if (eh->ether_type == htons(ETHERTYPE_IP)) { uint8_t tos; /* * IP frame, map the DSCP bits from the TOS field. */ /* NB: ip header may not be in first mbuf */ m_copydata(m, sizeof(struct ether_header) + offsetof(struct ip, ip_tos), sizeof(tos), &tos); tos >>= 5; /* NB: ECN + low 3 bits of DSCP */ d_wme_ac = TID_TO_WME_AC(tos); } else { #endif /* INET */ #ifdef INET6 if (eh->ether_type == htons(ETHERTYPE_IPV6)) { uint32_t flow; uint8_t tos; /* * IPv6 frame, map the DSCP bits from the traffic class field. */ m_copydata(m, sizeof(struct ether_header) + offsetof(struct ip6_hdr, ip6_flow), sizeof(flow), (caddr_t) &flow); tos = (uint8_t)(ntohl(flow) >> 20); tos >>= 5; /* NB: ECN + low 3 bits of DSCP */ d_wme_ac = TID_TO_WME_AC(tos); } else { #endif /* INET6 */ d_wme_ac = WME_AC_BE; #ifdef INET6 } #endif #ifdef INET } #endif /* * Use highest priority AC. */ if (v_wme_ac > d_wme_ac) ac = v_wme_ac; else ac = d_wme_ac; /* * Apply ACM policy. */ if (ni->ni_vap->iv_opmode == IEEE80211_M_STA) { static const int acmap[4] = { WME_AC_BK, /* WME_AC_BE */ WME_AC_BK, /* WME_AC_BK */ WME_AC_BE, /* WME_AC_VI */ WME_AC_VI, /* WME_AC_VO */ }; struct ieee80211com *ic = ni->ni_ic; while (ac != WME_AC_BK && ic->ic_wme.wme_wmeBssChanParams.cap_wmeParams[ac].wmep_acm) ac = acmap[ac]; } done: M_WME_SETAC(m, ac); return 0; } /* * Insure there is sufficient contiguous space to encapsulate the * 802.11 data frame. If room isn't already there, arrange for it. * Drivers and cipher modules assume we have done the necessary work * and fail rudely if they don't find the space they need. */ struct mbuf * ieee80211_mbuf_adjust(struct ieee80211vap *vap, int hdrsize, struct ieee80211_key *key, struct mbuf *m) { #define TO_BE_RECLAIMED (sizeof(struct ether_header) - sizeof(struct llc)) int needed_space = vap->iv_ic->ic_headroom + hdrsize; if (key != NULL) { /* XXX belongs in crypto code? */ needed_space += key->wk_cipher->ic_header; /* XXX frags */ /* * When crypto is being done in the host we must insure * the data are writable for the cipher routines; clone * a writable mbuf chain. * XXX handle SWMIC specially */ if (key->wk_flags & (IEEE80211_KEY_SWENCRYPT|IEEE80211_KEY_SWENMIC)) { m = m_unshare(m, M_NOWAIT); if (m == NULL) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT, "%s: cannot get writable mbuf\n", __func__); vap->iv_stats.is_tx_nobuf++; /* XXX new stat */ return NULL; } } } /* * We know we are called just before stripping an Ethernet * header and prepending an LLC header. This means we know * there will be * sizeof(struct ether_header) - sizeof(struct llc) * bytes recovered to which we need additional space for the * 802.11 header and any crypto header. */ /* XXX check trailing space and copy instead? */ if (M_LEADINGSPACE(m) < needed_space - TO_BE_RECLAIMED) { struct mbuf *n = m_gethdr(M_NOWAIT, m->m_type); if (n == NULL) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_OUTPUT, "%s: cannot expand storage\n", __func__); vap->iv_stats.is_tx_nobuf++; m_freem(m); return NULL; } KASSERT(needed_space <= MHLEN, ("not enough room, need %u got %zu\n", needed_space, MHLEN)); /* * Setup new mbuf to have leading space to prepend the * 802.11 header and any crypto header bits that are * required (the latter are added when the driver calls * back to ieee80211_crypto_encap to do crypto encapsulation). */ /* NB: must be first 'cuz it clobbers m_data */ m_move_pkthdr(n, m); n->m_len = 0; /* NB: m_gethdr does not set */ n->m_data += needed_space; /* * Pull up Ethernet header to create the expected layout. * We could use m_pullup but that's overkill (i.e. we don't * need the actual data) and it cannot fail so do it inline * for speed. */ /* NB: struct ether_header is known to be contiguous */ n->m_len += sizeof(struct ether_header); m->m_len -= sizeof(struct ether_header); m->m_data += sizeof(struct ether_header); /* * Replace the head of the chain. */ n->m_next = m; m = n; } return m; #undef TO_BE_RECLAIMED } /* * Return the transmit key to use in sending a unicast frame. * If a unicast key is set we use that. When no unicast key is set * we fall back to the default transmit key. */ static __inline struct ieee80211_key * ieee80211_crypto_getucastkey(struct ieee80211vap *vap, struct ieee80211_node *ni) { if (IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)) { if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE || IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey])) return NULL; return &vap->iv_nw_keys[vap->iv_def_txkey]; } else { return &ni->ni_ucastkey; } } /* * Return the transmit key to use in sending a multicast frame. * Multicast traffic always uses the group key which is installed as * the default tx key. */ static __inline struct ieee80211_key * ieee80211_crypto_getmcastkey(struct ieee80211vap *vap, struct ieee80211_node *ni) { if (vap->iv_def_txkey == IEEE80211_KEYIX_NONE || IEEE80211_KEY_UNDEFINED(&vap->iv_nw_keys[vap->iv_def_txkey])) return NULL; return &vap->iv_nw_keys[vap->iv_def_txkey]; } /* * Encapsulate an outbound data frame. The mbuf chain is updated. * If an error is encountered NULL is returned. The caller is required * to provide a node reference and pullup the ethernet header in the * first mbuf. * * NB: Packet is assumed to be processed by ieee80211_classify which * marked EAPOL frames w/ M_EAPOL. */ struct mbuf * ieee80211_encap(struct ieee80211vap *vap, struct ieee80211_node *ni, struct mbuf *m) { #define WH4(wh) ((struct ieee80211_frame_addr4 *)(wh)) struct ieee80211com *ic = ni->ni_ic; #ifdef IEEE80211_SUPPORT_MESH struct ieee80211_mesh_state *ms = vap->iv_mesh; struct ieee80211_meshcntl_ae10 *mc; #endif struct ether_header eh; struct ieee80211_frame *wh; struct ieee80211_key *key; struct llc *llc; int hdrsize, hdrspace, datalen, addqos, txfrag, is4addr; ieee80211_seq seqno; int meshhdrsize, meshae; uint8_t *qos; /* * Copy existing Ethernet header to a safe place. The * rest of the code assumes it's ok to strip it when * reorganizing state for the final encapsulation. */ KASSERT(m->m_len >= sizeof(eh), ("no ethernet header!")); ETHER_HEADER_COPY(&eh, mtod(m, caddr_t)); /* * Insure space for additional headers. First identify * transmit key to use in calculating any buffer adjustments * required. This is also used below to do privacy * encapsulation work. Then calculate the 802.11 header * size and any padding required by the driver. * * Note key may be NULL if we fall back to the default * transmit key and that is not set. In that case the * buffer may not be expanded as needed by the cipher * routines, but they will/should discard it. */ if (vap->iv_flags & IEEE80211_F_PRIVACY) { if (vap->iv_opmode == IEEE80211_M_STA || !IEEE80211_IS_MULTICAST(eh.ether_dhost) || (vap->iv_opmode == IEEE80211_M_WDS && (vap->iv_flags_ext & IEEE80211_FEXT_WDSLEGACY))) key = ieee80211_crypto_getucastkey(vap, ni); else key = ieee80211_crypto_getmcastkey(vap, ni); if (key == NULL && (m->m_flags & M_EAPOL) == 0) { IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_CRYPTO, eh.ether_dhost, "no default transmit key (%s) deftxkey %u", __func__, vap->iv_def_txkey); vap->iv_stats.is_tx_nodefkey++; goto bad; } } else key = NULL; /* * XXX Some ap's don't handle QoS-encapsulated EAPOL * frames so suppress use. This may be an issue if other * ap's require all data frames to be QoS-encapsulated * once negotiated in which case we'll need to make this * configurable. */ addqos = (ni->ni_flags & (IEEE80211_NODE_QOS|IEEE80211_NODE_HT)) && (m->m_flags & M_EAPOL) == 0; if (addqos) hdrsize = sizeof(struct ieee80211_qosframe); else hdrsize = sizeof(struct ieee80211_frame); #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode == IEEE80211_M_MBSS) { /* * Mesh data frames are encapsulated according to the * rules of Section 11B.8.5 (p.139 of D3.0 spec). * o Group Addressed data (aka multicast) originating * at the local sta are sent w/ 3-address format and * address extension mode 00 * o Individually Addressed data (aka unicast) originating * at the local sta are sent w/ 4-address format and * address extension mode 00 * o Group Addressed data forwarded from a non-mesh sta are * sent w/ 3-address format and address extension mode 01 * o Individually Address data from another sta are sent * w/ 4-address format and address extension mode 10 */ is4addr = 0; /* NB: don't use, disable */ if (!IEEE80211_IS_MULTICAST(eh.ether_dhost)) hdrsize += IEEE80211_ADDR_LEN; /* unicast are 4-addr */ meshhdrsize = sizeof(struct ieee80211_meshcntl); /* XXX defines for AE modes */ if (IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr)) { if (!IEEE80211_IS_MULTICAST(eh.ether_dhost)) meshae = 0; else meshae = 4; /* NB: pseudo */ } else if (IEEE80211_IS_MULTICAST(eh.ether_dhost)) { meshae = 1; meshhdrsize += 1*IEEE80211_ADDR_LEN; } else { meshae = 2; meshhdrsize += 2*IEEE80211_ADDR_LEN; } } else { #endif /* * 4-address frames need to be generated for: * o packets sent through a WDS vap (IEEE80211_M_WDS) * o packets sent through a vap marked for relaying * (e.g. a station operating with dynamic WDS) */ is4addr = vap->iv_opmode == IEEE80211_M_WDS || ((vap->iv_flags_ext & IEEE80211_FEXT_4ADDR) && !IEEE80211_ADDR_EQ(eh.ether_shost, vap->iv_myaddr)); if (is4addr) hdrsize += IEEE80211_ADDR_LEN; meshhdrsize = meshae = 0; #ifdef IEEE80211_SUPPORT_MESH } #endif /* * Honor driver DATAPAD requirement. */ if (ic->ic_flags & IEEE80211_F_DATAPAD) hdrspace = roundup(hdrsize, sizeof(uint32_t)); else hdrspace = hdrsize; if (__predict_true((m->m_flags & M_FF) == 0)) { /* * Normal frame. */ m = ieee80211_mbuf_adjust(vap, hdrspace + meshhdrsize, key, m); if (m == NULL) { /* NB: ieee80211_mbuf_adjust handles msgs+statistics */ goto bad; } /* NB: this could be optimized 'cuz of ieee80211_mbuf_adjust */ m_adj(m, sizeof(struct ether_header) - sizeof(struct llc)); llc = mtod(m, struct llc *); llc->llc_dsap = llc->llc_ssap = LLC_SNAP_LSAP; llc->llc_control = LLC_UI; llc->llc_snap.org_code[0] = 0; llc->llc_snap.org_code[1] = 0; llc->llc_snap.org_code[2] = 0; llc->llc_snap.ether_type = eh.ether_type; } else { #ifdef IEEE80211_SUPPORT_SUPERG /* * Aggregated frame. */ m = ieee80211_ff_encap(vap, m, hdrspace + meshhdrsize, key); if (m == NULL) #endif goto bad; } datalen = m->m_pkthdr.len; /* NB: w/o 802.11 header */ M_PREPEND(m, hdrspace + meshhdrsize, M_DONTWAIT); if (m == NULL) { vap->iv_stats.is_tx_nobuf++; goto bad; } wh = mtod(m, struct ieee80211_frame *); wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_DATA; *(uint16_t *)wh->i_dur = 0; qos = NULL; /* NB: quiet compiler */ if (is4addr) { wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS; IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost); IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost); } else switch (vap->iv_opmode) { case IEEE80211_M_STA: wh->i_fc[1] = IEEE80211_FC1_DIR_TODS; IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_bssid); IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost); IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost); break; case IEEE80211_M_IBSS: case IEEE80211_M_AHDEMO: wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost); IEEE80211_ADDR_COPY(wh->i_addr2, eh.ether_shost); /* * NB: always use the bssid from iv_bss as the * neighbor's may be stale after an ibss merge */ IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_bss->ni_bssid); break; case IEEE80211_M_HOSTAP: wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS; IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost); IEEE80211_ADDR_COPY(wh->i_addr2, ni->ni_bssid); IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost); break; #ifdef IEEE80211_SUPPORT_MESH case IEEE80211_M_MBSS: /* NB: offset by hdrspace to deal with DATAPAD */ mc = (struct ieee80211_meshcntl_ae10 *) (mtod(m, uint8_t *) + hdrspace); switch (meshae) { case 0: /* ucast, no proxy */ wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS; IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost); IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, eh.ether_shost); mc->mc_flags = 0; qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos; break; case 4: /* mcast, no proxy */ wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS; IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_shost); mc->mc_flags = 0; /* NB: AE is really 0 */ qos = ((struct ieee80211_qosframe *) wh)->i_qos; break; case 1: /* mcast, proxy */ wh->i_fc[1] = IEEE80211_FC1_DIR_FROMDS; IEEE80211_ADDR_COPY(wh->i_addr1, eh.ether_dhost); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, vap->iv_myaddr); mc->mc_flags = 1; IEEE80211_ADDR_COPY(mc->mc_addr4, eh.ether_shost); qos = ((struct ieee80211_qosframe *) wh)->i_qos; break; case 2: /* ucast, proxy */ wh->i_fc[1] = IEEE80211_FC1_DIR_DSTODS; IEEE80211_ADDR_COPY(wh->i_addr1, ni->ni_macaddr); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); /* XXX not right, need MeshDA */ IEEE80211_ADDR_COPY(wh->i_addr3, eh.ether_dhost); /* XXX assume are MeshSA */ IEEE80211_ADDR_COPY(WH4(wh)->i_addr4, vap->iv_myaddr); mc->mc_flags = 2; IEEE80211_ADDR_COPY(mc->mc_addr4, eh.ether_dhost); IEEE80211_ADDR_COPY(mc->mc_addr5, eh.ether_shost); qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos; break; default: KASSERT(0, ("meshae %d", meshae)); break; } mc->mc_ttl = ms->ms_ttl; ms->ms_seq++; LE_WRITE_4(mc->mc_seq, ms->ms_seq); break; #endif case IEEE80211_M_WDS: /* NB: is4addr should always be true */ default: goto bad; } if (m->m_flags & M_MORE_DATA) wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA; if (addqos) { int ac, tid; if (is4addr) { qos = ((struct ieee80211_qosframe_addr4 *) wh)->i_qos; /* NB: mesh case handled earlier */ } else if (vap->iv_opmode != IEEE80211_M_MBSS) qos = ((struct ieee80211_qosframe *) wh)->i_qos; ac = M_WME_GETAC(m); /* map from access class/queue to 11e header priorty value */ tid = WME_AC_TO_TID(ac); qos[0] = tid & IEEE80211_QOS_TID; if (ic->ic_wme.wme_wmeChanParams.cap_wmeParams[ac].wmep_noackPolicy) qos[0] |= IEEE80211_QOS_ACKPOLICY_NOACK; qos[1] = 0; wh->i_fc[0] |= IEEE80211_FC0_SUBTYPE_QOS; if ((m->m_flags & M_AMPDU_MPDU) == 0) { /* * NB: don't assign a sequence # to potential * aggregates; we expect this happens at the * point the frame comes off any aggregation q * as otherwise we may introduce holes in the * BA sequence space and/or make window accouting * more difficult. * * XXX may want to control this with a driver * capability; this may also change when we pull * aggregation up into net80211 */ seqno = ni->ni_txseqs[tid]++; *(uint16_t *)wh->i_seq = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT); M_SEQNO_SET(m, seqno); } } else { seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++; *(uint16_t *)wh->i_seq = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT); M_SEQNO_SET(m, seqno); } /* check if xmit fragmentation is required */ txfrag = (m->m_pkthdr.len > vap->iv_fragthreshold && !IEEE80211_IS_MULTICAST(wh->i_addr1) && (vap->iv_caps & IEEE80211_C_TXFRAG) && (m->m_flags & (M_FF | M_AMPDU_MPDU)) == 0); if (key != NULL) { /* * IEEE 802.1X: send EAPOL frames always in the clear. * WPA/WPA2: encrypt EAPOL keys when pairwise keys are set. */ if ((m->m_flags & M_EAPOL) == 0 || ((vap->iv_flags & IEEE80211_F_WPA) && (vap->iv_opmode == IEEE80211_M_STA ? !IEEE80211_KEY_UNDEFINED(key) : !IEEE80211_KEY_UNDEFINED(&ni->ni_ucastkey)))) { wh->i_fc[1] |= IEEE80211_FC1_WEP; if (!ieee80211_crypto_enmic(vap, key, m, txfrag)) { IEEE80211_NOTE_MAC(vap, IEEE80211_MSG_OUTPUT, eh.ether_dhost, "%s", "enmic failed, discard frame"); vap->iv_stats.is_crypto_enmicfail++; goto bad; } } } if (txfrag && !ieee80211_fragment(vap, m, hdrsize, key != NULL ? key->wk_cipher->ic_header : 0, vap->iv_fragthreshold)) goto bad; m->m_flags |= M_ENCAP; /* mark encapsulated */ IEEE80211_NODE_STAT(ni, tx_data); if (IEEE80211_IS_MULTICAST(wh->i_addr1)) { IEEE80211_NODE_STAT(ni, tx_mcast); m->m_flags |= M_MCAST; } else IEEE80211_NODE_STAT(ni, tx_ucast); IEEE80211_NODE_STAT_ADD(ni, tx_bytes, datalen); return m; bad: if (m != NULL) m_freem(m); return NULL; #undef WH4 } /* * Fragment the frame according to the specified mtu. * The size of the 802.11 header (w/o padding) is provided * so we don't need to recalculate it. We create a new * mbuf for each fragment and chain it through m_nextpkt; * we might be able to optimize this by reusing the original * packet's mbufs but that is significantly more complicated. */ static int ieee80211_fragment(struct ieee80211vap *vap, struct mbuf *m0, u_int hdrsize, u_int ciphdrsize, u_int mtu) { struct ieee80211_frame *wh, *whf; struct mbuf *m, *prev, *next; u_int totalhdrsize, fragno, fragsize, off, remainder, payload; KASSERT(m0->m_nextpkt == NULL, ("mbuf already chained?")); KASSERT(m0->m_pkthdr.len > mtu, ("pktlen %u mtu %u", m0->m_pkthdr.len, mtu)); wh = mtod(m0, struct ieee80211_frame *); /* NB: mark the first frag; it will be propagated below */ wh->i_fc[1] |= IEEE80211_FC1_MORE_FRAG; totalhdrsize = hdrsize + ciphdrsize; fragno = 1; off = mtu - ciphdrsize; remainder = m0->m_pkthdr.len - off; prev = m0; do { fragsize = totalhdrsize + remainder; if (fragsize > mtu) fragsize = mtu; /* XXX fragsize can be >2048! */ KASSERT(fragsize < MCLBYTES, ("fragment size %u too big!", fragsize)); if (fragsize > MHLEN) m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR); else m = m_gethdr(M_DONTWAIT, MT_DATA); if (m == NULL) goto bad; /* leave room to prepend any cipher header */ m_align(m, fragsize - ciphdrsize); /* * Form the header in the fragment. Note that since * we mark the first fragment with the MORE_FRAG bit * it automatically is propagated to each fragment; we * need only clear it on the last fragment (done below). */ whf = mtod(m, struct ieee80211_frame *); memcpy(whf, wh, hdrsize); *(uint16_t *)&whf->i_seq[0] |= htole16( (fragno & IEEE80211_SEQ_FRAG_MASK) << IEEE80211_SEQ_FRAG_SHIFT); fragno++; payload = fragsize - totalhdrsize; /* NB: destination is known to be contiguous */ m_copydata(m0, off, payload, mtod(m, uint8_t *) + hdrsize); m->m_len = hdrsize + payload; m->m_pkthdr.len = hdrsize + payload; m->m_flags |= M_FRAG; /* chain up the fragment */ prev->m_nextpkt = m; prev = m; /* deduct fragment just formed */ remainder -= payload; off += payload; } while (remainder != 0); /* set the last fragment */ m->m_flags |= M_LASTFRAG; whf->i_fc[1] &= ~IEEE80211_FC1_MORE_FRAG; /* strip first mbuf now that everything has been copied */ m_adj(m0, -(m0->m_pkthdr.len - (mtu - ciphdrsize))); m0->m_flags |= M_FIRSTFRAG | M_FRAG; vap->iv_stats.is_tx_fragframes++; vap->iv_stats.is_tx_frags += fragno-1; return 1; bad: /* reclaim fragments but leave original frame for caller to free */ for (m = m0->m_nextpkt; m != NULL; m = next) { next = m->m_nextpkt; m->m_nextpkt = NULL; /* XXX paranoid */ m_freem(m); } m0->m_nextpkt = NULL; return 0; } /* * Add a supported rates element id to a frame. */ uint8_t * ieee80211_add_rates(uint8_t *frm, const struct ieee80211_rateset *rs) { int nrates; *frm++ = IEEE80211_ELEMID_RATES; nrates = rs->rs_nrates; if (nrates > IEEE80211_RATE_SIZE) nrates = IEEE80211_RATE_SIZE; *frm++ = nrates; memcpy(frm, rs->rs_rates, nrates); return frm + nrates; } /* * Add an extended supported rates element id to a frame. */ uint8_t * ieee80211_add_xrates(uint8_t *frm, const struct ieee80211_rateset *rs) { /* * Add an extended supported rates element if operating in 11g mode. */ if (rs->rs_nrates > IEEE80211_RATE_SIZE) { int nrates = rs->rs_nrates - IEEE80211_RATE_SIZE; *frm++ = IEEE80211_ELEMID_XRATES; *frm++ = nrates; memcpy(frm, rs->rs_rates + IEEE80211_RATE_SIZE, nrates); frm += nrates; } return frm; } /* * Add an ssid element to a frame. */ static uint8_t * ieee80211_add_ssid(uint8_t *frm, const uint8_t *ssid, u_int len) { *frm++ = IEEE80211_ELEMID_SSID; *frm++ = len; memcpy(frm, ssid, len); return frm + len; } /* * Add an erp element to a frame. */ static uint8_t * ieee80211_add_erp(uint8_t *frm, struct ieee80211com *ic) { uint8_t erp; *frm++ = IEEE80211_ELEMID_ERP; *frm++ = 1; erp = 0; if (ic->ic_nonerpsta != 0) erp |= IEEE80211_ERP_NON_ERP_PRESENT; if (ic->ic_flags & IEEE80211_F_USEPROT) erp |= IEEE80211_ERP_USE_PROTECTION; if (ic->ic_flags & IEEE80211_F_USEBARKER) erp |= IEEE80211_ERP_LONG_PREAMBLE; *frm++ = erp; return frm; } /* * Add a CFParams element to a frame. */ static uint8_t * ieee80211_add_cfparms(uint8_t *frm, struct ieee80211com *ic) { #define ADDSHORT(frm, v) do { \ LE_WRITE_2(frm, v); \ frm += 2; \ } while (0) *frm++ = IEEE80211_ELEMID_CFPARMS; *frm++ = 6; *frm++ = 0; /* CFP count */ *frm++ = 2; /* CFP period */ ADDSHORT(frm, 0); /* CFP MaxDuration (TU) */ ADDSHORT(frm, 0); /* CFP CurRemaining (TU) */ return frm; #undef ADDSHORT } static __inline uint8_t * add_appie(uint8_t *frm, const struct ieee80211_appie *ie) { memcpy(frm, ie->ie_data, ie->ie_len); return frm + ie->ie_len; } static __inline uint8_t * add_ie(uint8_t *frm, const uint8_t *ie) { memcpy(frm, ie, 2 + ie[1]); return frm + 2 + ie[1]; } #define WME_OUI_BYTES 0x00, 0x50, 0xf2 /* * Add a WME information element to a frame. */ static uint8_t * ieee80211_add_wme_info(uint8_t *frm, struct ieee80211_wme_state *wme) { static const struct ieee80211_wme_info info = { .wme_id = IEEE80211_ELEMID_VENDOR, .wme_len = sizeof(struct ieee80211_wme_info) - 2, .wme_oui = { WME_OUI_BYTES }, .wme_type = WME_OUI_TYPE, .wme_subtype = WME_INFO_OUI_SUBTYPE, .wme_version = WME_VERSION, .wme_info = 0, }; memcpy(frm, &info, sizeof(info)); return frm + sizeof(info); } /* * Add a WME parameters element to a frame. */ static uint8_t * ieee80211_add_wme_param(uint8_t *frm, struct ieee80211_wme_state *wme) { #define SM(_v, _f) (((_v) << _f##_S) & _f) #define ADDSHORT(frm, v) do { \ LE_WRITE_2(frm, v); \ frm += 2; \ } while (0) /* NB: this works 'cuz a param has an info at the front */ static const struct ieee80211_wme_info param = { .wme_id = IEEE80211_ELEMID_VENDOR, .wme_len = sizeof(struct ieee80211_wme_param) - 2, .wme_oui = { WME_OUI_BYTES }, .wme_type = WME_OUI_TYPE, .wme_subtype = WME_PARAM_OUI_SUBTYPE, .wme_version = WME_VERSION, }; int i; memcpy(frm, &param, sizeof(param)); frm += __offsetof(struct ieee80211_wme_info, wme_info); *frm++ = wme->wme_bssChanParams.cap_info; /* AC info */ *frm++ = 0; /* reserved field */ for (i = 0; i < WME_NUM_AC; i++) { const struct wmeParams *ac = &wme->wme_bssChanParams.cap_wmeParams[i]; *frm++ = SM(i, WME_PARAM_ACI) | SM(ac->wmep_acm, WME_PARAM_ACM) | SM(ac->wmep_aifsn, WME_PARAM_AIFSN) ; *frm++ = SM(ac->wmep_logcwmax, WME_PARAM_LOGCWMAX) | SM(ac->wmep_logcwmin, WME_PARAM_LOGCWMIN) ; ADDSHORT(frm, ac->wmep_txopLimit); } return frm; #undef SM #undef ADDSHORT } #undef WME_OUI_BYTES /* * Add an 11h Power Constraint element to a frame. */ static uint8_t * ieee80211_add_powerconstraint(uint8_t *frm, struct ieee80211vap *vap) { const struct ieee80211_channel *c = vap->iv_bss->ni_chan; /* XXX per-vap tx power limit? */ int8_t limit = vap->iv_ic->ic_txpowlimit / 2; frm[0] = IEEE80211_ELEMID_PWRCNSTR; frm[1] = 1; frm[2] = c->ic_maxregpower > limit ? c->ic_maxregpower - limit : 0; return frm + 3; } /* * Add an 11h Power Capability element to a frame. */ static uint8_t * ieee80211_add_powercapability(uint8_t *frm, const struct ieee80211_channel *c) { frm[0] = IEEE80211_ELEMID_PWRCAP; frm[1] = 2; frm[2] = c->ic_minpower; frm[3] = c->ic_maxpower; return frm + 4; } /* * Add an 11h Supported Channels element to a frame. */ static uint8_t * ieee80211_add_supportedchannels(uint8_t *frm, struct ieee80211com *ic) { static const int ielen = 26; frm[0] = IEEE80211_ELEMID_SUPPCHAN; frm[1] = ielen; /* XXX not correct */ memcpy(frm+2, ic->ic_chan_avail, ielen); return frm + 2 + ielen; } /* * Add an 11h Channel Switch Announcement element to a frame. * Note that we use the per-vap CSA count to adjust the global * counter so we can use this routine to form probe response * frames and get the current count. */ static uint8_t * ieee80211_add_csa(uint8_t *frm, struct ieee80211vap *vap) { struct ieee80211com *ic = vap->iv_ic; struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) frm; csa->csa_ie = IEEE80211_ELEMID_CSA; csa->csa_len = 3; csa->csa_mode = 1; /* XXX force quiet on channel */ csa->csa_newchan = ieee80211_chan2ieee(ic, ic->ic_csa_newchan); csa->csa_count = ic->ic_csa_count - vap->iv_csa_count; return frm + sizeof(*csa); } /* * Add an 11h country information element to a frame. */ static uint8_t * ieee80211_add_countryie(uint8_t *frm, struct ieee80211com *ic) { if (ic->ic_countryie == NULL || ic->ic_countryie_chan != ic->ic_bsschan) { /* * Handle lazy construction of ie. This is done on * first use and after a channel change that requires * re-calculation. */ if (ic->ic_countryie != NULL) free(ic->ic_countryie, M_80211_NODE_IE); ic->ic_countryie = ieee80211_alloc_countryie(ic); if (ic->ic_countryie == NULL) return frm; ic->ic_countryie_chan = ic->ic_bsschan; } return add_appie(frm, ic->ic_countryie); } uint8_t * ieee80211_add_wpa(uint8_t *frm, const struct ieee80211vap *vap) { if (vap->iv_flags & IEEE80211_F_WPA1 && vap->iv_wpa_ie != NULL) return (add_ie(frm, vap->iv_wpa_ie)); else { /* XXX else complain? */ return (frm); } } uint8_t * ieee80211_add_rsn(uint8_t *frm, const struct ieee80211vap *vap) { if (vap->iv_flags & IEEE80211_F_WPA2 && vap->iv_rsn_ie != NULL) return (add_ie(frm, vap->iv_rsn_ie)); else { /* XXX else complain? */ return (frm); } } uint8_t * ieee80211_add_qos(uint8_t *frm, const struct ieee80211_node *ni) { if (ni->ni_flags & IEEE80211_NODE_QOS) { *frm++ = IEEE80211_ELEMID_QOS; *frm++ = 1; *frm++ = 0; } return (frm); } /* * Send a probe request frame with the specified ssid * and any optional information element data. */ int ieee80211_send_probereq(struct ieee80211_node *ni, const uint8_t sa[IEEE80211_ADDR_LEN], const uint8_t da[IEEE80211_ADDR_LEN], const uint8_t bssid[IEEE80211_ADDR_LEN], const uint8_t *ssid, size_t ssidlen) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; const struct ieee80211_txparam *tp; struct ieee80211_bpf_params params; struct ieee80211_frame *wh; const struct ieee80211_rateset *rs; struct mbuf *m; uint8_t *frm; if (vap->iv_state == IEEE80211_S_CAC) { IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, ni, "block %s frame in CAC state", "probe request"); vap->iv_stats.is_tx_badstate++; return EIO; /* XXX */ } /* * Hold a reference on the node so it doesn't go away until after * the xmit is complete all the way in the driver. On error we * will remove our reference. */ IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE, "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__, ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1); ieee80211_ref_node(ni); /* * prreq frame format * [tlv] ssid * [tlv] supported rates * [tlv] RSN (optional) * [tlv] extended supported rates * [tlv] WPA (optional) * [tlv] user-specified ie's */ m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), 2 + IEEE80211_NWID_LEN + 2 + IEEE80211_RATE_SIZE + sizeof(struct ieee80211_ie_wpa) + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE) + sizeof(struct ieee80211_ie_wpa) + (vap->iv_appie_probereq != NULL ? vap->iv_appie_probereq->ie_len : 0) ); if (m == NULL) { vap->iv_stats.is_tx_nobuf++; ieee80211_free_node(ni); return ENOMEM; } frm = ieee80211_add_ssid(frm, ssid, ssidlen); rs = ieee80211_get_suprates(ic, ic->ic_curchan); frm = ieee80211_add_rates(frm, rs); frm = ieee80211_add_rsn(frm, vap); frm = ieee80211_add_xrates(frm, rs); frm = ieee80211_add_wpa(frm, vap); if (vap->iv_appie_probereq != NULL) frm = add_appie(frm, vap->iv_appie_probereq); m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *); KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ieee80211_frame), ("leading space %zd", M_LEADINGSPACE(m))); M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT); if (m == NULL) { /* NB: cannot happen */ ieee80211_free_node(ni); return ENOMEM; } wh = mtod(m, struct ieee80211_frame *); ieee80211_send_setup(ni, m, IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_REQ, IEEE80211_NONQOS_TID, sa, da, bssid); /* XXX power management? */ m->m_flags |= M_ENCAP; /* mark encapsulated */ M_WME_SETAC(m, WME_AC_BE); IEEE80211_NODE_STAT(ni, tx_probereq); IEEE80211_NODE_STAT(ni, tx_mgmt); IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, "send probe req on channel %u bssid %s ssid \"%.*s\"\n", ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(bssid), ssidlen, ssid); memset(&params, 0, sizeof(params)); params.ibp_pri = M_WME_GETAC(m); tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)]; params.ibp_rate0 = tp->mgmtrate; if (IEEE80211_IS_MULTICAST(da)) { params.ibp_flags |= IEEE80211_BPF_NOACK; params.ibp_try0 = 1; } else params.ibp_try0 = tp->maxretry; params.ibp_power = ni->ni_txpower; return ic->ic_raw_xmit(ni, m, &params); } /* * Calculate capability information for mgt frames. */ uint16_t ieee80211_getcapinfo(struct ieee80211vap *vap, struct ieee80211_channel *chan) { struct ieee80211com *ic = vap->iv_ic; uint16_t capinfo; KASSERT(vap->iv_opmode != IEEE80211_M_STA, ("station mode")); if (vap->iv_opmode == IEEE80211_M_HOSTAP) capinfo = IEEE80211_CAPINFO_ESS; else if (vap->iv_opmode == IEEE80211_M_IBSS) capinfo = IEEE80211_CAPINFO_IBSS; else capinfo = 0; if (vap->iv_flags & IEEE80211_F_PRIVACY) capinfo |= IEEE80211_CAPINFO_PRIVACY; if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) && IEEE80211_IS_CHAN_2GHZ(chan)) capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE; if (ic->ic_flags & IEEE80211_F_SHSLOT) capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME; if (IEEE80211_IS_CHAN_5GHZ(chan) && (vap->iv_flags & IEEE80211_F_DOTH)) capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT; return capinfo; } /* * Send a management frame. The node is for the destination (or ic_bss * when in station mode). Nodes other than ic_bss have their reference * count bumped to reflect our use for an indeterminant time. */ int ieee80211_send_mgmt(struct ieee80211_node *ni, int type, int arg) { #define HTFLAGS (IEEE80211_NODE_HT | IEEE80211_NODE_HTCOMPAT) #define senderr(_x, _v) do { vap->iv_stats._v++; ret = _x; goto bad; } while (0) struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ieee80211_node *bss = vap->iv_bss; struct ieee80211_bpf_params params; struct mbuf *m; uint8_t *frm; uint16_t capinfo; int has_challenge, is_shared_key, ret, status; KASSERT(ni != NULL, ("null node")); /* * Hold a reference on the node so it doesn't go away until after * the xmit is complete all the way in the driver. On error we * will remove our reference. */ IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE, "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__, ni, ether_sprintf(ni->ni_macaddr), ieee80211_node_refcnt(ni)+1); ieee80211_ref_node(ni); memset(&params, 0, sizeof(params)); switch (type) { case IEEE80211_FC0_SUBTYPE_AUTH: status = arg >> 16; arg &= 0xffff; has_challenge = ((arg == IEEE80211_AUTH_SHARED_CHALLENGE || arg == IEEE80211_AUTH_SHARED_RESPONSE) && ni->ni_challenge != NULL); /* * Deduce whether we're doing open authentication or * shared key authentication. We do the latter if * we're in the middle of a shared key authentication * handshake or if we're initiating an authentication * request and configured to use shared key. */ is_shared_key = has_challenge || arg >= IEEE80211_AUTH_SHARED_RESPONSE || (arg == IEEE80211_AUTH_SHARED_REQUEST && bss->ni_authmode == IEEE80211_AUTH_SHARED); m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), 3 * sizeof(uint16_t) + (has_challenge && status == IEEE80211_STATUS_SUCCESS ? sizeof(uint16_t)+IEEE80211_CHALLENGE_LEN : 0) ); if (m == NULL) senderr(ENOMEM, is_tx_nobuf); ((uint16_t *)frm)[0] = (is_shared_key) ? htole16(IEEE80211_AUTH_ALG_SHARED) : htole16(IEEE80211_AUTH_ALG_OPEN); ((uint16_t *)frm)[1] = htole16(arg); /* sequence number */ ((uint16_t *)frm)[2] = htole16(status);/* status */ if (has_challenge && status == IEEE80211_STATUS_SUCCESS) { ((uint16_t *)frm)[3] = htole16((IEEE80211_CHALLENGE_LEN << 8) | IEEE80211_ELEMID_CHALLENGE); memcpy(&((uint16_t *)frm)[4], ni->ni_challenge, IEEE80211_CHALLENGE_LEN); m->m_pkthdr.len = m->m_len = 4 * sizeof(uint16_t) + IEEE80211_CHALLENGE_LEN; if (arg == IEEE80211_AUTH_SHARED_RESPONSE) { IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni, "request encrypt frame (%s)", __func__); /* mark frame for encryption */ params.ibp_flags |= IEEE80211_BPF_CRYPTO; } } else m->m_pkthdr.len = m->m_len = 3 * sizeof(uint16_t); /* XXX not right for shared key */ if (status == IEEE80211_STATUS_SUCCESS) IEEE80211_NODE_STAT(ni, tx_auth); else IEEE80211_NODE_STAT(ni, tx_auth_fail); if (vap->iv_opmode == IEEE80211_M_STA) ieee80211_add_callback(m, ieee80211_tx_mgt_cb, (void *) vap->iv_state); break; case IEEE80211_FC0_SUBTYPE_DEAUTH: IEEE80211_NOTE(vap, IEEE80211_MSG_AUTH, ni, "send station deauthenticate (reason %d)", arg); m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), sizeof(uint16_t)); if (m == NULL) senderr(ENOMEM, is_tx_nobuf); *(uint16_t *)frm = htole16(arg); /* reason */ m->m_pkthdr.len = m->m_len = sizeof(uint16_t); IEEE80211_NODE_STAT(ni, tx_deauth); IEEE80211_NODE_STAT_SET(ni, tx_deauth_code, arg); ieee80211_node_unauthorize(ni); /* port closed */ break; case IEEE80211_FC0_SUBTYPE_ASSOC_REQ: case IEEE80211_FC0_SUBTYPE_REASSOC_REQ: /* * asreq frame format * [2] capability information * [2] listen interval * [6*] current AP address (reassoc only) * [tlv] ssid * [tlv] supported rates * [tlv] extended supported rates * [4] power capability (optional) * [28] supported channels (optional) * [tlv] HT capabilities * [tlv] WME (optional) * [tlv] Vendor OUI HT capabilities (optional) * [tlv] Atheros capabilities (if negotiated) * [tlv] AppIE's (optional) */ m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), sizeof(uint16_t) + sizeof(uint16_t) + IEEE80211_ADDR_LEN + 2 + IEEE80211_NWID_LEN + 2 + IEEE80211_RATE_SIZE + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE) + 4 + 2 + 26 + sizeof(struct ieee80211_wme_info) + sizeof(struct ieee80211_ie_htcap) + 4 + sizeof(struct ieee80211_ie_htcap) #ifdef IEEE80211_SUPPORT_SUPERG + sizeof(struct ieee80211_ath_ie) #endif + (vap->iv_appie_wpa != NULL ? vap->iv_appie_wpa->ie_len : 0) + (vap->iv_appie_assocreq != NULL ? vap->iv_appie_assocreq->ie_len : 0) ); if (m == NULL) senderr(ENOMEM, is_tx_nobuf); KASSERT(vap->iv_opmode == IEEE80211_M_STA, ("wrong mode %u", vap->iv_opmode)); capinfo = IEEE80211_CAPINFO_ESS; if (vap->iv_flags & IEEE80211_F_PRIVACY) capinfo |= IEEE80211_CAPINFO_PRIVACY; /* * NB: Some 11a AP's reject the request when * short premable is set. */ if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) && IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE; if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan) && (ic->ic_caps & IEEE80211_C_SHSLOT)) capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME; if ((ni->ni_capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) && (vap->iv_flags & IEEE80211_F_DOTH)) capinfo |= IEEE80211_CAPINFO_SPECTRUM_MGMT; *(uint16_t *)frm = htole16(capinfo); frm += 2; KASSERT(bss->ni_intval != 0, ("beacon interval is zero!")); *(uint16_t *)frm = htole16(howmany(ic->ic_lintval, bss->ni_intval)); frm += 2; if (type == IEEE80211_FC0_SUBTYPE_REASSOC_REQ) { IEEE80211_ADDR_COPY(frm, bss->ni_bssid); frm += IEEE80211_ADDR_LEN; } frm = ieee80211_add_ssid(frm, ni->ni_essid, ni->ni_esslen); frm = ieee80211_add_rates(frm, &ni->ni_rates); frm = ieee80211_add_rsn(frm, vap); frm = ieee80211_add_xrates(frm, &ni->ni_rates); if (capinfo & IEEE80211_CAPINFO_SPECTRUM_MGMT) { frm = ieee80211_add_powercapability(frm, ic->ic_curchan); frm = ieee80211_add_supportedchannels(frm, ic); } if ((vap->iv_flags_ht & IEEE80211_FHT_HT) && ni->ni_ies.htcap_ie != NULL && ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_HTCAP) frm = ieee80211_add_htcap(frm, ni); frm = ieee80211_add_wpa(frm, vap); if ((ic->ic_flags & IEEE80211_F_WME) && ni->ni_ies.wme_ie != NULL) frm = ieee80211_add_wme_info(frm, &ic->ic_wme); if ((vap->iv_flags_ht & IEEE80211_FHT_HT) && ni->ni_ies.htcap_ie != NULL && ni->ni_ies.htcap_ie[0] == IEEE80211_ELEMID_VENDOR) frm = ieee80211_add_htcap_vendor(frm, ni); #ifdef IEEE80211_SUPPORT_SUPERG if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) { frm = ieee80211_add_ath(frm, IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS), ((vap->iv_flags & IEEE80211_F_WPA) == 0 && ni->ni_authmode != IEEE80211_AUTH_8021X) ? vap->iv_def_txkey : IEEE80211_KEYIX_NONE); } #endif /* IEEE80211_SUPPORT_SUPERG */ if (vap->iv_appie_assocreq != NULL) frm = add_appie(frm, vap->iv_appie_assocreq); m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *); ieee80211_add_callback(m, ieee80211_tx_mgt_cb, (void *) vap->iv_state); break; case IEEE80211_FC0_SUBTYPE_ASSOC_RESP: case IEEE80211_FC0_SUBTYPE_REASSOC_RESP: /* * asresp frame format * [2] capability information * [2] status * [2] association ID * [tlv] supported rates * [tlv] extended supported rates * [tlv] HT capabilities (standard, if STA enabled) * [tlv] HT information (standard, if STA enabled) * [tlv] WME (if configured and STA enabled) * [tlv] HT capabilities (vendor OUI, if STA enabled) * [tlv] HT information (vendor OUI, if STA enabled) * [tlv] Atheros capabilities (if STA enabled) * [tlv] AppIE's (optional) */ m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint16_t) + 2 + IEEE80211_RATE_SIZE + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE) + sizeof(struct ieee80211_ie_htcap) + 4 + sizeof(struct ieee80211_ie_htinfo) + 4 + sizeof(struct ieee80211_wme_param) #ifdef IEEE80211_SUPPORT_SUPERG + sizeof(struct ieee80211_ath_ie) #endif + (vap->iv_appie_assocresp != NULL ? vap->iv_appie_assocresp->ie_len : 0) ); if (m == NULL) senderr(ENOMEM, is_tx_nobuf); capinfo = ieee80211_getcapinfo(vap, bss->ni_chan); *(uint16_t *)frm = htole16(capinfo); frm += 2; *(uint16_t *)frm = htole16(arg); /* status */ frm += 2; if (arg == IEEE80211_STATUS_SUCCESS) { *(uint16_t *)frm = htole16(ni->ni_associd); IEEE80211_NODE_STAT(ni, tx_assoc); } else IEEE80211_NODE_STAT(ni, tx_assoc_fail); frm += 2; frm = ieee80211_add_rates(frm, &ni->ni_rates); frm = ieee80211_add_xrates(frm, &ni->ni_rates); /* NB: respond according to what we received */ if ((ni->ni_flags & HTFLAGS) == IEEE80211_NODE_HT) { frm = ieee80211_add_htcap(frm, ni); frm = ieee80211_add_htinfo(frm, ni); } if ((vap->iv_flags & IEEE80211_F_WME) && ni->ni_ies.wme_ie != NULL) frm = ieee80211_add_wme_param(frm, &ic->ic_wme); if ((ni->ni_flags & HTFLAGS) == HTFLAGS) { frm = ieee80211_add_htcap_vendor(frm, ni); frm = ieee80211_add_htinfo_vendor(frm, ni); } #ifdef IEEE80211_SUPPORT_SUPERG if (IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS)) frm = ieee80211_add_ath(frm, IEEE80211_ATH_CAP(vap, ni, IEEE80211_F_ATHEROS), ((vap->iv_flags & IEEE80211_F_WPA) == 0 && ni->ni_authmode != IEEE80211_AUTH_8021X) ? vap->iv_def_txkey : IEEE80211_KEYIX_NONE); #endif /* IEEE80211_SUPPORT_SUPERG */ if (vap->iv_appie_assocresp != NULL) frm = add_appie(frm, vap->iv_appie_assocresp); m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *); break; case IEEE80211_FC0_SUBTYPE_DISASSOC: IEEE80211_NOTE(vap, IEEE80211_MSG_ASSOC, ni, "send station disassociate (reason %d)", arg); m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), sizeof(uint16_t)); if (m == NULL) senderr(ENOMEM, is_tx_nobuf); *(uint16_t *)frm = htole16(arg); /* reason */ m->m_pkthdr.len = m->m_len = sizeof(uint16_t); IEEE80211_NODE_STAT(ni, tx_disassoc); IEEE80211_NODE_STAT_SET(ni, tx_disassoc_code, arg); break; default: IEEE80211_NOTE(vap, IEEE80211_MSG_ANY, ni, "invalid mgmt frame type %u", type); senderr(EINVAL, is_tx_unknownmgt); /* NOTREACHED */ } /* NB: force non-ProbeResp frames to the highest queue */ params.ibp_pri = WME_AC_VO; params.ibp_rate0 = bss->ni_txparms->mgmtrate; /* NB: we know all frames are unicast */ params.ibp_try0 = bss->ni_txparms->maxretry; params.ibp_power = bss->ni_txpower; return ieee80211_mgmt_output(ni, m, type, &params); bad: ieee80211_free_node(ni); return ret; #undef senderr #undef HTFLAGS } /* * Return an mbuf with a probe response frame in it. * Space is left to prepend and 802.11 header at the * front but it's left to the caller to fill in. */ struct mbuf * ieee80211_alloc_proberesp(struct ieee80211_node *bss, int legacy) { struct ieee80211vap *vap = bss->ni_vap; struct ieee80211com *ic = bss->ni_ic; const struct ieee80211_rateset *rs; struct mbuf *m; uint16_t capinfo; uint8_t *frm; /* * probe response frame format * [8] time stamp * [2] beacon interval * [2] cabability information * [tlv] ssid * [tlv] supported rates * [tlv] parameter set (FH/DS) * [tlv] parameter set (IBSS) * [tlv] country (optional) * [3] power control (optional) * [5] channel switch announcement (CSA) (optional) * [tlv] extended rate phy (ERP) * [tlv] extended supported rates * [tlv] RSN (optional) * [tlv] HT capabilities * [tlv] HT information * [tlv] WPA (optional) * [tlv] WME (optional) * [tlv] Vendor OUI HT capabilities (optional) * [tlv] Vendor OUI HT information (optional) * [tlv] Atheros capabilities * [tlv] AppIE's (optional) * [tlv] Mesh ID (MBSS) * [tlv] Mesh Conf (MBSS) */ m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), 8 + sizeof(uint16_t) + sizeof(uint16_t) + 2 + IEEE80211_NWID_LEN + 2 + IEEE80211_RATE_SIZE + 7 /* max(7,3) */ + IEEE80211_COUNTRY_MAX_SIZE + 3 + sizeof(struct ieee80211_csa_ie) + 3 + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE) + sizeof(struct ieee80211_ie_wpa) + sizeof(struct ieee80211_ie_htcap) + sizeof(struct ieee80211_ie_htinfo) + sizeof(struct ieee80211_ie_wpa) + sizeof(struct ieee80211_wme_param) + 4 + sizeof(struct ieee80211_ie_htcap) + 4 + sizeof(struct ieee80211_ie_htinfo) #ifdef IEEE80211_SUPPORT_SUPERG + sizeof(struct ieee80211_ath_ie) #endif #ifdef IEEE80211_SUPPORT_MESH + 2 + IEEE80211_MESHID_LEN + sizeof(struct ieee80211_meshconf_ie) #endif + (vap->iv_appie_proberesp != NULL ? vap->iv_appie_proberesp->ie_len : 0) ); if (m == NULL) { vap->iv_stats.is_tx_nobuf++; return NULL; } memset(frm, 0, 8); /* timestamp should be filled later */ frm += 8; *(uint16_t *)frm = htole16(bss->ni_intval); frm += 2; capinfo = ieee80211_getcapinfo(vap, bss->ni_chan); *(uint16_t *)frm = htole16(capinfo); frm += 2; frm = ieee80211_add_ssid(frm, bss->ni_essid, bss->ni_esslen); rs = ieee80211_get_suprates(ic, bss->ni_chan); frm = ieee80211_add_rates(frm, rs); if (IEEE80211_IS_CHAN_FHSS(bss->ni_chan)) { *frm++ = IEEE80211_ELEMID_FHPARMS; *frm++ = 5; *frm++ = bss->ni_fhdwell & 0x00ff; *frm++ = (bss->ni_fhdwell >> 8) & 0x00ff; *frm++ = IEEE80211_FH_CHANSET( ieee80211_chan2ieee(ic, bss->ni_chan)); *frm++ = IEEE80211_FH_CHANPAT( ieee80211_chan2ieee(ic, bss->ni_chan)); *frm++ = bss->ni_fhindex; } else { *frm++ = IEEE80211_ELEMID_DSPARMS; *frm++ = 1; *frm++ = ieee80211_chan2ieee(ic, bss->ni_chan); } if (vap->iv_opmode == IEEE80211_M_IBSS) { *frm++ = IEEE80211_ELEMID_IBSSPARMS; *frm++ = 2; *frm++ = 0; *frm++ = 0; /* TODO: ATIM window */ } if ((vap->iv_flags & IEEE80211_F_DOTH) || (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) frm = ieee80211_add_countryie(frm, ic); if (vap->iv_flags & IEEE80211_F_DOTH) { if (IEEE80211_IS_CHAN_5GHZ(bss->ni_chan)) frm = ieee80211_add_powerconstraint(frm, vap); if (ic->ic_flags & IEEE80211_F_CSAPENDING) frm = ieee80211_add_csa(frm, vap); } if (IEEE80211_IS_CHAN_ANYG(bss->ni_chan)) frm = ieee80211_add_erp(frm, ic); frm = ieee80211_add_xrates(frm, rs); frm = ieee80211_add_rsn(frm, vap); /* * NB: legacy 11b clients do not get certain ie's. * The caller identifies such clients by passing * a token in legacy to us. Could expand this to be * any legacy client for stuff like HT ie's. */ if (IEEE80211_IS_CHAN_HT(bss->ni_chan) && legacy != IEEE80211_SEND_LEGACY_11B) { frm = ieee80211_add_htcap(frm, bss); frm = ieee80211_add_htinfo(frm, bss); } frm = ieee80211_add_wpa(frm, vap); if (vap->iv_flags & IEEE80211_F_WME) frm = ieee80211_add_wme_param(frm, &ic->ic_wme); if (IEEE80211_IS_CHAN_HT(bss->ni_chan) && (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT) && legacy != IEEE80211_SEND_LEGACY_11B) { frm = ieee80211_add_htcap_vendor(frm, bss); frm = ieee80211_add_htinfo_vendor(frm, bss); } #ifdef IEEE80211_SUPPORT_SUPERG if ((vap->iv_flags & IEEE80211_F_ATHEROS) && legacy != IEEE80211_SEND_LEGACY_11B) frm = ieee80211_add_athcaps(frm, bss); #endif if (vap->iv_appie_proberesp != NULL) frm = add_appie(frm, vap->iv_appie_proberesp); #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode == IEEE80211_M_MBSS) { frm = ieee80211_add_meshid(frm, vap); frm = ieee80211_add_meshconf(frm, vap); } #endif m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *); return m; } /* * Send a probe response frame to the specified mac address. * This does not go through the normal mgt frame api so we * can specify the destination address and re-use the bss node * for the sta reference. */ int ieee80211_send_proberesp(struct ieee80211vap *vap, const uint8_t da[IEEE80211_ADDR_LEN], int legacy) { struct ieee80211_node *bss = vap->iv_bss; struct ieee80211com *ic = vap->iv_ic; struct ieee80211_frame *wh; struct mbuf *m; if (vap->iv_state == IEEE80211_S_CAC) { IEEE80211_NOTE(vap, IEEE80211_MSG_OUTPUT, bss, "block %s frame in CAC state", "probe response"); vap->iv_stats.is_tx_badstate++; return EIO; /* XXX */ } /* * Hold a reference on the node so it doesn't go away until after * the xmit is complete all the way in the driver. On error we * will remove our reference. */ IEEE80211_DPRINTF(vap, IEEE80211_MSG_NODE, "ieee80211_ref_node (%s:%u) %p<%s> refcnt %d\n", __func__, __LINE__, bss, ether_sprintf(bss->ni_macaddr), ieee80211_node_refcnt(bss)+1); ieee80211_ref_node(bss); m = ieee80211_alloc_proberesp(bss, legacy); if (m == NULL) { ieee80211_free_node(bss); return ENOMEM; } M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT); KASSERT(m != NULL, ("no room for header")); wh = mtod(m, struct ieee80211_frame *); ieee80211_send_setup(bss, m, IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP, IEEE80211_NONQOS_TID, vap->iv_myaddr, da, bss->ni_bssid); /* XXX power management? */ m->m_flags |= M_ENCAP; /* mark encapsulated */ M_WME_SETAC(m, WME_AC_BE); IEEE80211_DPRINTF(vap, IEEE80211_MSG_DEBUG | IEEE80211_MSG_DUMPPKTS, "send probe resp on channel %u to %s%s\n", ieee80211_chan2ieee(ic, ic->ic_curchan), ether_sprintf(da), legacy ? " <legacy>" : ""); IEEE80211_NODE_STAT(bss, tx_mgmt); return ic->ic_raw_xmit(bss, m, NULL); } /* * Allocate and build a RTS (Request To Send) control frame. */ struct mbuf * ieee80211_alloc_rts(struct ieee80211com *ic, const uint8_t ra[IEEE80211_ADDR_LEN], const uint8_t ta[IEEE80211_ADDR_LEN], uint16_t dur) { struct ieee80211_frame_rts *rts; struct mbuf *m; /* XXX honor ic_headroom */ m = m_gethdr(M_DONTWAIT, MT_DATA); if (m != NULL) { rts = mtod(m, struct ieee80211_frame_rts *); rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_RTS; rts->i_fc[1] = IEEE80211_FC1_DIR_NODS; *(u_int16_t *)rts->i_dur = htole16(dur); IEEE80211_ADDR_COPY(rts->i_ra, ra); IEEE80211_ADDR_COPY(rts->i_ta, ta); m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_rts); } return m; } /* * Allocate and build a CTS (Clear To Send) control frame. */ struct mbuf * ieee80211_alloc_cts(struct ieee80211com *ic, const uint8_t ra[IEEE80211_ADDR_LEN], uint16_t dur) { struct ieee80211_frame_cts *cts; struct mbuf *m; /* XXX honor ic_headroom */ m = m_gethdr(M_DONTWAIT, MT_DATA); if (m != NULL) { cts = mtod(m, struct ieee80211_frame_cts *); cts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL | IEEE80211_FC0_SUBTYPE_CTS; cts->i_fc[1] = IEEE80211_FC1_DIR_NODS; *(u_int16_t *)cts->i_dur = htole16(dur); IEEE80211_ADDR_COPY(cts->i_ra, ra); m->m_pkthdr.len = m->m_len = sizeof(struct ieee80211_frame_cts); } return m; } static void ieee80211_tx_mgt_timeout(void *arg) { struct ieee80211_node *ni = arg; struct ieee80211vap *vap = ni->ni_vap; if (vap->iv_state != IEEE80211_S_INIT && (vap->iv_ic->ic_flags & IEEE80211_F_SCAN) == 0) { /* * NB: it's safe to specify a timeout as the reason here; * it'll only be used in the right state. */ ieee80211_new_state(vap, IEEE80211_S_SCAN, IEEE80211_SCAN_FAIL_TIMEOUT); } } static void ieee80211_tx_mgt_cb(struct ieee80211_node *ni, void *arg, int status) { struct ieee80211vap *vap = ni->ni_vap; enum ieee80211_state ostate = (enum ieee80211_state) arg; /* * Frame transmit completed; arrange timer callback. If * transmit was successfuly we wait for response. Otherwise * we arrange an immediate callback instead of doing the * callback directly since we don't know what state the driver * is in (e.g. what locks it is holding). This work should * not be too time-critical and not happen too often so the * added overhead is acceptable. * * XXX what happens if !acked but response shows up before callback? */ if (vap->iv_state == ostate) callout_reset(&vap->iv_mgtsend, status == 0 ? IEEE80211_TRANS_WAIT*hz : 0, ieee80211_tx_mgt_timeout, ni); } static void ieee80211_beacon_construct(struct mbuf *m, uint8_t *frm, struct ieee80211_beacon_offsets *bo, struct ieee80211_node *ni) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ieee80211_rateset *rs = &ni->ni_rates; uint16_t capinfo; /* * beacon frame format * [8] time stamp * [2] beacon interval * [2] cabability information * [tlv] ssid * [tlv] supported rates * [3] parameter set (DS) * [8] CF parameter set (optional) * [tlv] parameter set (IBSS/TIM) * [tlv] country (optional) * [3] power control (optional) * [5] channel switch announcement (CSA) (optional) * [tlv] extended rate phy (ERP) * [tlv] extended supported rates * [tlv] RSN parameters * [tlv] HT capabilities * [tlv] HT information * XXX Vendor-specific OIDs (e.g. Atheros) * [tlv] WPA parameters * [tlv] WME parameters * [tlv] Vendor OUI HT capabilities (optional) * [tlv] Vendor OUI HT information (optional) * [tlv] Atheros capabilities (optional) * [tlv] TDMA parameters (optional) * [tlv] Mesh ID (MBSS) * [tlv] Mesh Conf (MBSS) * [tlv] application data (optional) */ memset(bo, 0, sizeof(*bo)); memset(frm, 0, 8); /* XXX timestamp is set by hardware/driver */ frm += 8; *(uint16_t *)frm = htole16(ni->ni_intval); frm += 2; capinfo = ieee80211_getcapinfo(vap, ni->ni_chan); bo->bo_caps = (uint16_t *)frm; *(uint16_t *)frm = htole16(capinfo); frm += 2; *frm++ = IEEE80211_ELEMID_SSID; if ((vap->iv_flags & IEEE80211_F_HIDESSID) == 0) { *frm++ = ni->ni_esslen; memcpy(frm, ni->ni_essid, ni->ni_esslen); frm += ni->ni_esslen; } else *frm++ = 0; frm = ieee80211_add_rates(frm, rs); if (!IEEE80211_IS_CHAN_FHSS(ni->ni_chan)) { *frm++ = IEEE80211_ELEMID_DSPARMS; *frm++ = 1; *frm++ = ieee80211_chan2ieee(ic, ni->ni_chan); } if (ic->ic_flags & IEEE80211_F_PCF) { bo->bo_cfp = frm; frm = ieee80211_add_cfparms(frm, ic); } bo->bo_tim = frm; if (vap->iv_opmode == IEEE80211_M_IBSS) { *frm++ = IEEE80211_ELEMID_IBSSPARMS; *frm++ = 2; *frm++ = 0; *frm++ = 0; /* TODO: ATIM window */ bo->bo_tim_len = 0; } else if (vap->iv_opmode == IEEE80211_M_HOSTAP || vap->iv_opmode == IEEE80211_M_MBSS) { /* TIM IE is the same for Mesh and Hostap */ struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) frm; tie->tim_ie = IEEE80211_ELEMID_TIM; tie->tim_len = 4; /* length */ tie->tim_count = 0; /* DTIM count */ tie->tim_period = vap->iv_dtim_period; /* DTIM period */ tie->tim_bitctl = 0; /* bitmap control */ tie->tim_bitmap[0] = 0; /* Partial Virtual Bitmap */ frm += sizeof(struct ieee80211_tim_ie); bo->bo_tim_len = 1; } bo->bo_tim_trailer = frm; if ((vap->iv_flags & IEEE80211_F_DOTH) || (vap->iv_flags_ext & IEEE80211_FEXT_DOTD)) frm = ieee80211_add_countryie(frm, ic); if (vap->iv_flags & IEEE80211_F_DOTH) { if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan)) frm = ieee80211_add_powerconstraint(frm, vap); bo->bo_csa = frm; if (ic->ic_flags & IEEE80211_F_CSAPENDING) frm = ieee80211_add_csa(frm, vap); } else bo->bo_csa = frm; if (IEEE80211_IS_CHAN_ANYG(ni->ni_chan)) { bo->bo_erp = frm; frm = ieee80211_add_erp(frm, ic); } frm = ieee80211_add_xrates(frm, rs); frm = ieee80211_add_rsn(frm, vap); if (IEEE80211_IS_CHAN_HT(ni->ni_chan)) { frm = ieee80211_add_htcap(frm, ni); bo->bo_htinfo = frm; frm = ieee80211_add_htinfo(frm, ni); } frm = ieee80211_add_wpa(frm, vap); if (vap->iv_flags & IEEE80211_F_WME) { bo->bo_wme = frm; frm = ieee80211_add_wme_param(frm, &ic->ic_wme); } if (IEEE80211_IS_CHAN_HT(ni->ni_chan) && (vap->iv_flags_ht & IEEE80211_FHT_HTCOMPAT)) { frm = ieee80211_add_htcap_vendor(frm, ni); frm = ieee80211_add_htinfo_vendor(frm, ni); } #ifdef IEEE80211_SUPPORT_SUPERG if (vap->iv_flags & IEEE80211_F_ATHEROS) { bo->bo_ath = frm; frm = ieee80211_add_athcaps(frm, ni); } #endif #ifdef IEEE80211_SUPPORT_TDMA if (vap->iv_caps & IEEE80211_C_TDMA) { bo->bo_tdma = frm; frm = ieee80211_add_tdma(frm, vap); } #endif if (vap->iv_appie_beacon != NULL) { bo->bo_appie = frm; bo->bo_appie_len = vap->iv_appie_beacon->ie_len; frm = add_appie(frm, vap->iv_appie_beacon); } #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode == IEEE80211_M_MBSS) { frm = ieee80211_add_meshid(frm, vap); bo->bo_meshconf = frm; frm = ieee80211_add_meshconf(frm, vap); } #endif bo->bo_tim_trailer_len = frm - bo->bo_tim_trailer; bo->bo_csa_trailer_len = frm - bo->bo_csa; m->m_pkthdr.len = m->m_len = frm - mtod(m, uint8_t *); } /* * Allocate a beacon frame and fillin the appropriate bits. */ struct mbuf * ieee80211_beacon_alloc(struct ieee80211_node *ni, struct ieee80211_beacon_offsets *bo) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; struct ifnet *ifp = vap->iv_ifp; struct ieee80211_frame *wh; struct mbuf *m; int pktlen; uint8_t *frm; /* * beacon frame format * [8] time stamp * [2] beacon interval * [2] cabability information * [tlv] ssid * [tlv] supported rates * [3] parameter set (DS) * [8] CF parameter set (optional) * [tlv] parameter set (IBSS/TIM) * [tlv] country (optional) * [3] power control (optional) * [5] channel switch announcement (CSA) (optional) * [tlv] extended rate phy (ERP) * [tlv] extended supported rates * [tlv] RSN parameters * [tlv] HT capabilities * [tlv] HT information * [tlv] Vendor OUI HT capabilities (optional) * [tlv] Vendor OUI HT information (optional) * XXX Vendor-specific OIDs (e.g. Atheros) * [tlv] WPA parameters * [tlv] WME parameters * [tlv] TDMA parameters (optional) * [tlv] Mesh ID (MBSS) * [tlv] Mesh Conf (MBSS) * [tlv] application data (optional) * NB: we allocate the max space required for the TIM bitmap. * XXX how big is this? */ pktlen = 8 /* time stamp */ + sizeof(uint16_t) /* beacon interval */ + sizeof(uint16_t) /* capabilities */ + 2 + ni->ni_esslen /* ssid */ + 2 + IEEE80211_RATE_SIZE /* supported rates */ + 2 + 1 /* DS parameters */ + 2 + 6 /* CF parameters */ + 2 + 4 + vap->iv_tim_len /* DTIM/IBSSPARMS */ + IEEE80211_COUNTRY_MAX_SIZE /* country */ + 2 + 1 /* power control */ + sizeof(struct ieee80211_csa_ie) /* CSA */ + 2 + 1 /* ERP */ + 2 + (IEEE80211_RATE_MAXSIZE - IEEE80211_RATE_SIZE) + (vap->iv_caps & IEEE80211_C_WPA ? /* WPA 1+2 */ 2*sizeof(struct ieee80211_ie_wpa) : 0) /* XXX conditional? */ + 4+2*sizeof(struct ieee80211_ie_htcap)/* HT caps */ + 4+2*sizeof(struct ieee80211_ie_htinfo)/* HT info */ + (vap->iv_caps & IEEE80211_C_WME ? /* WME */ sizeof(struct ieee80211_wme_param) : 0) #ifdef IEEE80211_SUPPORT_SUPERG + sizeof(struct ieee80211_ath_ie) /* ATH */ #endif #ifdef IEEE80211_SUPPORT_TDMA + (vap->iv_caps & IEEE80211_C_TDMA ? /* TDMA */ sizeof(struct ieee80211_tdma_param) : 0) #endif #ifdef IEEE80211_SUPPORT_MESH + 2 + ni->ni_meshidlen + sizeof(struct ieee80211_meshconf_ie) #endif + IEEE80211_MAX_APPIE ; m = ieee80211_getmgtframe(&frm, ic->ic_headroom + sizeof(struct ieee80211_frame), pktlen); if (m == NULL) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_ANY, "%s: cannot get buf; size %u\n", __func__, pktlen); vap->iv_stats.is_tx_nobuf++; return NULL; } ieee80211_beacon_construct(m, frm, bo, ni); M_PREPEND(m, sizeof(struct ieee80211_frame), M_DONTWAIT); KASSERT(m != NULL, ("no space for 802.11 header?")); wh = mtod(m, struct ieee80211_frame *); wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_BEACON; wh->i_fc[1] = IEEE80211_FC1_DIR_NODS; *(uint16_t *)wh->i_dur = 0; IEEE80211_ADDR_COPY(wh->i_addr1, ifp->if_broadcastaddr); IEEE80211_ADDR_COPY(wh->i_addr2, vap->iv_myaddr); IEEE80211_ADDR_COPY(wh->i_addr3, ni->ni_bssid); *(uint16_t *)wh->i_seq = 0; return m; } /* * Update the dynamic parts of a beacon frame based on the current state. */ int ieee80211_beacon_update(struct ieee80211_node *ni, struct ieee80211_beacon_offsets *bo, struct mbuf *m, int mcast) { struct ieee80211vap *vap = ni->ni_vap; struct ieee80211com *ic = ni->ni_ic; int len_changed = 0; uint16_t capinfo; struct ieee80211_frame *wh; ieee80211_seq seqno; IEEE80211_LOCK(ic); /* * Handle 11h channel change when we've reached the count. * We must recalculate the beacon frame contents to account * for the new channel. Note we do this only for the first * vap that reaches this point; subsequent vaps just update * their beacon state to reflect the recalculated channel. */ if (isset(bo->bo_flags, IEEE80211_BEACON_CSA) && vap->iv_csa_count == ic->ic_csa_count) { vap->iv_csa_count = 0; /* * Effect channel change before reconstructing the beacon * frame contents as many places reference ni_chan. */ if (ic->ic_csa_newchan != NULL) ieee80211_csa_completeswitch(ic); /* * NB: ieee80211_beacon_construct clears all pending * updates in bo_flags so we don't need to explicitly * clear IEEE80211_BEACON_CSA. */ ieee80211_beacon_construct(m, mtod(m, uint8_t*) + sizeof(struct ieee80211_frame), bo, ni); /* XXX do WME aggressive mode processing? */ IEEE80211_UNLOCK(ic); return 1; /* just assume length changed */ } wh = mtod(m, struct ieee80211_frame *); seqno = ni->ni_txseqs[IEEE80211_NONQOS_TID]++; *(uint16_t *)&wh->i_seq[0] = htole16(seqno << IEEE80211_SEQ_SEQ_SHIFT); M_SEQNO_SET(m, seqno); /* XXX faster to recalculate entirely or just changes? */ capinfo = ieee80211_getcapinfo(vap, ni->ni_chan); *bo->bo_caps = htole16(capinfo); if (vap->iv_flags & IEEE80211_F_WME) { struct ieee80211_wme_state *wme = &ic->ic_wme; /* * Check for agressive mode change. When there is * significant high priority traffic in the BSS * throttle back BE traffic by using conservative * parameters. Otherwise BE uses agressive params * to optimize performance of legacy/non-QoS traffic. */ if (wme->wme_flags & WME_F_AGGRMODE) { if (wme->wme_hipri_traffic > wme->wme_hipri_switch_thresh) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME, "%s: traffic %u, disable aggressive mode\n", __func__, wme->wme_hipri_traffic); wme->wme_flags &= ~WME_F_AGGRMODE; ieee80211_wme_updateparams_locked(vap); wme->wme_hipri_traffic = wme->wme_hipri_switch_hysteresis; } else wme->wme_hipri_traffic = 0; } else { if (wme->wme_hipri_traffic <= wme->wme_hipri_switch_thresh) { IEEE80211_DPRINTF(vap, IEEE80211_MSG_WME, "%s: traffic %u, enable aggressive mode\n", __func__, wme->wme_hipri_traffic); wme->wme_flags |= WME_F_AGGRMODE; ieee80211_wme_updateparams_locked(vap); wme->wme_hipri_traffic = 0; } else wme->wme_hipri_traffic = wme->wme_hipri_switch_hysteresis; } if (isset(bo->bo_flags, IEEE80211_BEACON_WME)) { (void) ieee80211_add_wme_param(bo->bo_wme, wme); clrbit(bo->bo_flags, IEEE80211_BEACON_WME); } } if (isset(bo->bo_flags, IEEE80211_BEACON_HTINFO)) { ieee80211_ht_update_beacon(vap, bo); clrbit(bo->bo_flags, IEEE80211_BEACON_HTINFO); } #ifdef IEEE80211_SUPPORT_TDMA if (vap->iv_caps & IEEE80211_C_TDMA) { /* * NB: the beacon is potentially updated every TBTT. */ ieee80211_tdma_update_beacon(vap, bo); } #endif #ifdef IEEE80211_SUPPORT_MESH if (vap->iv_opmode == IEEE80211_M_MBSS) ieee80211_mesh_update_beacon(vap, bo); #endif if (vap->iv_opmode == IEEE80211_M_HOSTAP || vap->iv_opmode == IEEE80211_M_MBSS) { /* NB: no IBSS support*/ struct ieee80211_tim_ie *tie = (struct ieee80211_tim_ie *) bo->bo_tim; if (isset(bo->bo_flags, IEEE80211_BEACON_TIM)) { u_int timlen, timoff, i; /* * ATIM/DTIM needs updating. If it fits in the * current space allocated then just copy in the * new bits. Otherwise we need to move any trailing * data to make room. Note that we know there is * contiguous space because ieee80211_beacon_allocate * insures there is space in the mbuf to write a * maximal-size virtual bitmap (based on iv_max_aid). */ /* * Calculate the bitmap size and offset, copy any * trailer out of the way, and then copy in the * new bitmap and update the information element. * Note that the tim bitmap must contain at least * one byte and any offset must be even. */ if (vap->iv_ps_pending != 0) { timoff = 128; /* impossibly large */ for (i = 0; i < vap->iv_tim_len; i++) if (vap->iv_tim_bitmap[i]) { timoff = i &~ 1; break; } KASSERT(timoff != 128, ("tim bitmap empty!")); for (i = vap->iv_tim_len-1; i >= timoff; i--) if (vap->iv_tim_bitmap[i]) break; timlen = 1 + (i - timoff); } else { timoff = 0; timlen = 1; } if (timlen != bo->bo_tim_len) { /* copy up/down trailer */ int adjust = tie->tim_bitmap+timlen - bo->bo_tim_trailer; ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust, bo->bo_tim_trailer_len); bo->bo_tim_trailer += adjust; bo->bo_erp += adjust; bo->bo_htinfo += adjust; #ifdef IEEE80211_SUPPORT_SUPERG bo->bo_ath += adjust; #endif #ifdef IEEE80211_SUPPORT_TDMA bo->bo_tdma += adjust; #endif #ifdef IEEE80211_SUPPORT_MESH bo->bo_meshconf += adjust; #endif bo->bo_appie += adjust; bo->bo_wme += adjust; bo->bo_csa += adjust; bo->bo_tim_len = timlen; /* update information element */ tie->tim_len = 3 + timlen; tie->tim_bitctl = timoff; len_changed = 1; } memcpy(tie->tim_bitmap, vap->iv_tim_bitmap + timoff, bo->bo_tim_len); clrbit(bo->bo_flags, IEEE80211_BEACON_TIM); IEEE80211_DPRINTF(vap, IEEE80211_MSG_POWER, "%s: TIM updated, pending %u, off %u, len %u\n", __func__, vap->iv_ps_pending, timoff, timlen); } /* count down DTIM period */ if (tie->tim_count == 0) tie->tim_count = tie->tim_period - 1; else tie->tim_count--; /* update state for buffered multicast frames on DTIM */ if (mcast && tie->tim_count == 0) tie->tim_bitctl |= 1; else tie->tim_bitctl &= ~1; if (isset(bo->bo_flags, IEEE80211_BEACON_CSA)) { struct ieee80211_csa_ie *csa = (struct ieee80211_csa_ie *) bo->bo_csa; /* * Insert or update CSA ie. If we're just starting * to count down to the channel switch then we need * to insert the CSA ie. Otherwise we just need to * drop the count. The actual change happens above * when the vap's count reaches the target count. */ if (vap->iv_csa_count == 0) { memmove(&csa[1], csa, bo->bo_csa_trailer_len); bo->bo_erp += sizeof(*csa); bo->bo_htinfo += sizeof(*csa); bo->bo_wme += sizeof(*csa); #ifdef IEEE80211_SUPPORT_SUPERG bo->bo_ath += sizeof(*csa); #endif #ifdef IEEE80211_SUPPORT_TDMA bo->bo_tdma += sizeof(*csa); #endif #ifdef IEEE80211_SUPPORT_MESH bo->bo_meshconf += sizeof(*csa); #endif bo->bo_appie += sizeof(*csa); bo->bo_csa_trailer_len += sizeof(*csa); bo->bo_tim_trailer_len += sizeof(*csa); m->m_len += sizeof(*csa); m->m_pkthdr.len += sizeof(*csa); ieee80211_add_csa(bo->bo_csa, vap); } else csa->csa_count--; vap->iv_csa_count++; /* NB: don't clear IEEE80211_BEACON_CSA */ } if (isset(bo->bo_flags, IEEE80211_BEACON_ERP)) { /* * ERP element needs updating. */ (void) ieee80211_add_erp(bo->bo_erp, ic); clrbit(bo->bo_flags, IEEE80211_BEACON_ERP); } #ifdef IEEE80211_SUPPORT_SUPERG if (isset(bo->bo_flags, IEEE80211_BEACON_ATH)) { ieee80211_add_athcaps(bo->bo_ath, ni); clrbit(bo->bo_flags, IEEE80211_BEACON_ATH); } #endif } if (isset(bo->bo_flags, IEEE80211_BEACON_APPIE)) { const struct ieee80211_appie *aie = vap->iv_appie_beacon; int aielen; uint8_t *frm; aielen = 0; if (aie != NULL) aielen += aie->ie_len; if (aielen != bo->bo_appie_len) { /* copy up/down trailer */ int adjust = aielen - bo->bo_appie_len; ovbcopy(bo->bo_tim_trailer, bo->bo_tim_trailer+adjust, bo->bo_tim_trailer_len); bo->bo_tim_trailer += adjust; bo->bo_appie += adjust; bo->bo_appie_len = aielen; len_changed = 1; } frm = bo->bo_appie; if (aie != NULL) frm = add_appie(frm, aie); clrbit(bo->bo_flags, IEEE80211_BEACON_APPIE); } IEEE80211_UNLOCK(ic); return len_changed; }
dcui/FreeBSD-9.3_kernel
sys/net80211/ieee80211_output.c
C
bsd-3-clause
93,287
module Main ( main ) where import qualified Data.Foldable as F import Data.Map ( Map ) import qualified Data.Map as M import Data.Maybe ( fromMaybe, mapMaybe ) import Data.Monoid import Data.Set ( Set ) import qualified Data.Set as S import System.Environment ( getArgs, withArgs ) import System.FilePath ( (<.>) ) import Test.HUnit ( assertEqual ) import LLVM.Analysis import LLVM.Analysis.Util.Testing import LLVM.Parse import Foreign.Inference.Interface import Foreign.Inference.Preprocessing import Foreign.Inference.Analysis.ErrorHandling import Foreign.Inference.Analysis.IndirectCallResolver import Foreign.Inference.Analysis.Util.CompositeSummary main :: IO () main = do args <- getArgs let pattern = case args of [] -> "tests/error-handling/*.c" [infile] -> infile ds <- loadDependencies ["tests/error-handling"] [] let testDescriptors = [ TestDescriptor { testPattern = pattern , testExpectedMapping = (<.> "expected") , testResultBuilder = analyzeErrors ds , testResultComparator = assertEqual } ] withArgs [] $ testAgainstExpected requiredOptimizations bcParser testDescriptors where bcParser = parseLLVMFile defaultParserOptions type TestFormat = Map String (Set String, ErrorReturn) analyzeErrors :: DependencySummary -> Module -> TestFormat analyzeErrors ds m = toTestFormat eres fs where pta = identifyIndirectCallTargets m fs = moduleDefinedFunctions m funcLikes :: [FunctionMetadata] funcLikes = map fromFunction (moduleDefinedFunctions m) eres = identifyErrorHandling funcLikes ds pta toTestFormat :: ErrorSummary -> [Function] -> TestFormat toTestFormat eres = foldr checkSummary mempty where checkSummary f acc = fromMaybe acc $ do let s = summarizeFunction f eres (FAReportsErrors acts rcs, _) <- F.find isErrRetAnnot s let fname = identifierAsString (functionName f) return $ M.insert fname (errorFuncs acts, rcs) acc isErrRetAnnot :: (FuncAnnotation, a) -> Bool isErrRetAnnot (a, _) = case a of FAReportsErrors _ _ -> True _ -> False errorFuncs :: Set ErrorAction -> Set String errorFuncs = S.fromList . mapMaybe toErrFunc . S.toList where toErrFunc a = case a of FunctionCall fname _ -> return fname _ -> Nothing
travitch/foreign-inference
tests/ErrorHandlingTests.hs
Haskell
bsd-3-clause
2,456
/* * Copyright (c) 2015 Dmitry V. Levin <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <sys/syscall.h> #ifdef __NR_ftruncate #include <errno.h> #include <stdio.h> #include <unistd.h> #include "kernel_types.h" int main(void) { const kernel_ulong_t len = (kernel_ulong_t) 0xdefaced0badc0deULL; int rc; if (sizeof(len) > sizeof(long)) rc = ftruncate(-1, len); else rc = syscall(__NR_ftruncate, -1L, len); if (rc != -1 || EBADF != errno) return 77; printf("ftruncate(-1, %llu) = -1 EBADF (Bad file descriptor)\n", (unsigned long long) len); puts("+++ exited with 0 +++"); return 0; } #else int main(void) { return 77; } #endif
Distrotech/strace
tests/ftruncate.c
C
bsd-3-clause
2,120
var searchData= [ ['fabric',['fabric',['../classMapper.html#a56537d34f84fee8e18d0a2831e8d11d9',1,'Mapper\fabric()'],['../classStudentAdapter.html#a56537d34f84fee8e18d0a2831e8d11d9',1,'StudentAdapter\fabric()']]], ['fetch',['fetch',['../classRequest.html#ab1bf1d22d758cdf223986502814901bb',1,'Request']]], ['fillmodel',['fillModel',['../classMapper.html#a2d20aa8a3541ee321480f000dc9cd82b',1,'Mapper']]], ['front_2ddoc_2ephp',['front-doc.php',['../front-doc_8php.html',1,'']]] ];
lovasoa/trpo-dz
doc/html/search/all_6.js
JavaScript
bsd-3-clause
486
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "commands/CCreateShape.h" #include "items/VCommentDiagram.h" #include "nodes/CommentDiagram.h" #include "nodes/CommentDiagramShape.h" namespace Comments { CCreateShape::CCreateShape() : Interaction::CreateNamedObjectWithAttributes("shape", {{"ellipse", "diamond", "rectangle"}}) { } Interaction::CommandResult* CCreateShape::create(Visualization::Item*, Visualization::Item* target, const QString&, const QStringList& attributes) { auto vdiagram = dynamic_cast<VCommentDiagram*>(target); auto last = vdiagram->lastRightClick(); int x = std::max(0, last.x()-50), y = std::max(0, last.y()-50); auto diagram = dynamic_cast<CommentDiagram*> (target->node()); auto shape = new CommentDiagramShape(x, y, 100, 100, CommentDiagramShape::ShapeType::Rectangle); // what kind of shape? if(attributes.first() == "ellipse") shape->setShapeType(CommentDiagramShape::ShapeType::Ellipse); else if(attributes.first() == "diamond") shape->setShapeType(CommentDiagramShape::ShapeType::Diamond); diagram->model()->beginModification(diagram, "create shape"); diagram->shapes()->append(shape); diagram->model()->endModification(); target->setUpdateNeeded(Visualization::Item::StandardUpdate); return new Interaction::CommandResult(); } } /* namespace OOInteraction */
patrick-luethi/Envision
Comments/src/commands/CCreateShape.cpp
C++
bsd-3-clause
3,109
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} module Sigym4.Geometry.Types ( Geometry (..) , LineString (..) , MultiLineString (..) , LinearRing (..) , Vertex , Point (..) , MultiPoint (..) , Polygon (..) , MultiPolygon (..) , Triangle (..) , TIN (..) , PolyhedralSurface (..) , GeometryCollection (..) , Feature , FeatureCollection , FeatureT (..) , FeatureCollectionT (..) , VectorSpace (..) , HasOffset (..) , Pixel (..) , Size (..) , Offset (..) , RowMajor , ColumnMajor , Extent (..) , GeoTransform (..) , Raster (..) , indexRaster , northUpGeoTransform , GeoReference (..) , mkGeoReference , pointOffset , grScalarSize , scalarSize , grForward , grBackward , mkLineString , mkLinearRing , mkPolygon , mkTriangle , pointCoordinates , lineStringCoordinates , polygonCoordinates , polygonRings , triangleCoordinates , convertRasterOffsetType , gSrid , hasSrid , withSrid , eSize -- lenses & prisms , pVertex , fGeom , fData , fcFeatures , mpPoints , lrPoints , lsPoints , mlLineStrings , pOuterRing , pRings , mpPolygons , psPolygons , tinTriangles , gcGeometries , _GeoPoint , _GeoMultiPoint , _GeoLineString , _GeoMultiLineString , _GeoPolygon , _GeoMultiPolygon , _GeoTriangle , _GeoPolyhedralSurface , _GeoTIN , _GeoCollection , NoSrid -- re-exports , KnownNat , Nat , module V2 , module V3 ) where import Control.Lens import Data.Foldable (product) import Data.Proxy (Proxy (..)) import qualified Data.Semigroup as SG import qualified Data.Vector as V import qualified Data.Vector.Generic as GV import qualified Data.Vector.Unboxed as U import Data.Vector.Unboxed.Deriving (derivingUnbox) import GHC.TypeLits import Linear.Matrix (inv22, inv33, (!*), (*!)) import Linear.Metric (Metric) import Linear.V2 as V2 import Linear.V3 as V3 import Prelude hiding (product) -- | A vertex type Vertex v = v Double -- | A square Matrix type SqMatrix v = v (Vertex v) -- | A vector space class ( Num (Vertex v), Fractional (Vertex v) , Show (Vertex v), Eq (Vertex v), U.Unbox (Vertex v) , Show (v Int), Eq (v Int), Eq (v Bool) , Num (SqMatrix v), Show (SqMatrix v), Eq (SqMatrix v) , Metric v, Applicative v, Foldable v) => VectorSpace v where inv :: SqMatrix v -> SqMatrix v dim :: Proxy v -> Int coords :: Vertex v -> [Double] fromCoords :: [Double] -> Maybe (Vertex v) instance VectorSpace V2 where inv = inv22 dim _ = 2 coords (V2 u v) = [u, v] fromCoords [u, v] = Just $ V2 u v fromCoords _ = Nothing {-# INLINE dim #-} {-# INLINE fromCoords #-} {-# INLINE coords #-} instance VectorSpace V3 where inv = inv33 dim _ = 3 coords (V3 u v z) = [u, v, z] fromCoords [u, v, z] = Just $ V3 u v z fromCoords _ = Nothing {-# INLINE dim #-} {-# INLINE fromCoords #-} {-# INLINE coords #-} newtype Offset (t :: OffsetType) = Offset {unOff :: Int} deriving (Eq, Show, Ord, Num) data OffsetType = RowMajor | ColumnMajor type RowMajor = 'RowMajor type ColumnMajor = 'ColumnMajor class HasOffset v (t :: OffsetType) where toOffset :: Size v -> Pixel v -> Maybe (Offset t) fromOffset :: Size v -> Offset t -> Maybe (Pixel v) unsafeToOffset :: Size v -> Pixel v -> Offset t unsafeFromOffset :: Size v -> Offset t -> Pixel v instance HasOffset V2 RowMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy = Just (unsafeToOffset s p) | otherwise = Nothing where V2 sx sy = unSize s V2 px py = fmap floor $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ py * sx + px where V2 sx _ = unSize s V2 px py = fmap floor $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V2 sx sy)) o@(Offset o') | 0<=o' && o'<sx*sy = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V2 sx _)) (Offset o) = Pixel (V2 (fromIntegral px) (fromIntegral py)) where (py,px) = o `divMod` sx {-# INLINE unsafeFromOffset #-} instance HasOffset V2 ColumnMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy = Just (unsafeToOffset s p) | otherwise = Nothing where V2 sx sy = unSize s V2 px py = fmap floor $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ px * sy + py where V2 _ sy = unSize s V2 px py = fmap floor $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V2 sx sy)) o@(Offset o') | 0<=o' && o'<sx*sy = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V2 _ sy)) (Offset o) = Pixel (V2 (fromIntegral px) (fromIntegral py)) where (px,py) = o `divMod` sy {-# INLINE unsafeFromOffset #-} instance HasOffset V3 RowMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy , 0<=pz && pz < sz = Just (unsafeToOffset s p) | otherwise = Nothing where V3 sx sy sz = unSize s V3 px py pz = fmap floor $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ (pz * sx * sy) + (py * sx) + px where V3 sx sy _ = unSize s V3 px py pz = fmap floor $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V3 sx sy sz)) o@(Offset o') | 0<=o' && o'<sx*sy*sz = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V3 sx sy _)) (Offset o) = Pixel (V3 (fromIntegral px) (fromIntegral py) (fromIntegral pz)) where (pz, r) = o `divMod` (sx*sy) (py,px) = r `divMod` sx {-# INLINE unsafeFromOffset #-} instance HasOffset V3 ColumnMajor where toOffset s p | 0<=px && px < sx , 0<=py && py < sy , 0<=pz && pz < sz = Just (unsafeToOffset s p) | otherwise = Nothing where V3 sx sy sz = unSize s V3 px py pz = fmap floor $ unPx p {-# INLINE toOffset #-} unsafeToOffset s p = Offset $ (px * sz * sy) + (py * sz) + pz where V3 _ sy sz = unSize s V3 px py pz = fmap floor $ unPx p {-# INLINE unsafeToOffset #-} fromOffset s@(Size (V3 sx sy sz)) o@(Offset o') | 0<=o' && o'<sx*sy*sz = Just (unsafeFromOffset s o) | otherwise = Nothing {-# INLINE fromOffset #-} unsafeFromOffset (Size (V3 _ sy sz)) (Offset o) = Pixel (V3 (fromIntegral px) (fromIntegral py) (fromIntegral pz)) where (px, r) = o `divMod` (sz*sy) (py,pz) = r `divMod` sz {-# INLINE unsafeFromOffset #-} type NoSrid = 0 -- | An extent in v space is a pair of minimum and maximum vertices data Extent v (srid :: Nat) = Extent {eMin :: !(Vertex v), eMax :: !(Vertex v)} deriving instance VectorSpace v => Eq (Extent v srid) deriving instance VectorSpace v => Show (Extent v srid) eSize :: VectorSpace v => Extent v srid -> Vertex v eSize e = eMax e - eMin e instance VectorSpace v => SG.Semigroup (Extent v srid) where Extent a0 a1 <> Extent b0 b1 = Extent (min <$> a0 <*> b0) (max <$> a1 <*> b1) -- | A pixel is a newtype around a vertex newtype Pixel v = Pixel {unPx :: Vertex v} deriving instance VectorSpace v => Show (Pixel v) deriving instance VectorSpace v => Eq (Pixel v) newtype Size v = Size {unSize :: v Int} deriving instance VectorSpace v => Eq (Size v) deriving instance VectorSpace v => Show (Size v) scalarSize :: VectorSpace v => Size v -> Int scalarSize = product . unSize -- A GeoTransform defines how we translate from geographic 'Vertex'es to -- 'Pixel' coordinates and back. gtMatrix *must* be inversible so smart -- constructors are provided data GeoTransform v (srid :: Nat) = GeoTransform { gtMatrix :: !(SqMatrix v) , gtOrigin :: !(Vertex v) } deriving instance VectorSpace v => Eq (GeoTransform v srid) deriving instance VectorSpace v => Show (GeoTransform v srid) northUpGeoTransform :: Extent V2 srid -> Size V2 -> Either String (GeoTransform V2 srid) northUpGeoTransform e s | not isValidBox = Left "northUpGeoTransform: invalid extent" | not isValidSize = Left "northUpGeoTransform: invalid size" | otherwise = Right $ GeoTransform matrix origin where isValidBox = fmap (> 0) (eMax e - eMin e) == pure True isValidSize = fmap (> 0) s' == pure True V2 x0 _ = eMin e V2 _ y1 = eMax e origin = V2 x0 y1 s' = fmap fromIntegral $ unSize s V2 dx dy = (eMax e - eMin e)/s' matrix = V2 (V2 dx 0) (V2 0 (-dy)) gtForward :: VectorSpace v => GeoTransform v srid -> Point v srid -> Pixel v gtForward gt (Point v) = Pixel $ m !* (v-v0) where m = inv $ gtMatrix gt v0 = gtOrigin gt gtBackward :: VectorSpace v => GeoTransform v srid -> Pixel v -> Point v srid gtBackward gt p = Point $ v0 + (unPx p) *! m where m = gtMatrix gt v0 = gtOrigin gt data GeoReference v srid = GeoReference { grTransform :: GeoTransform v srid , grSize :: Size v } deriving instance VectorSpace v => Eq (GeoReference v srid) deriving instance VectorSpace v => Show (GeoReference v srid) grScalarSize :: VectorSpace v => GeoReference v srid -> Int grScalarSize = scalarSize . grSize pointOffset :: (HasOffset v t, VectorSpace v) => GeoReference v srid -> Point v srid -> Maybe (Offset t) pointOffset gr = toOffset (grSize gr) . grForward gr {-# INLINEABLE pointOffset #-} grForward :: VectorSpace v => GeoReference v srid -> Point v srid -> Pixel v grForward gr = gtForward (grTransform gr) {-# INLINE grForward #-} grBackward :: VectorSpace v => GeoReference v srid -> Pixel v -> Point v srid grBackward gr = gtBackward (grTransform gr) {-# INLINE grBackward #-} mkGeoReference :: Extent V2 srid -> Size V2 -> Either String (GeoReference V2 srid) mkGeoReference e s = fmap (\gt -> GeoReference gt s) (northUpGeoTransform e s) newtype Point v (srid :: Nat) = Point {_pVertex:: Vertex v} deriving instance VectorSpace v => Show (Point v srid) deriving instance VectorSpace v => Eq (Point v srid) pVertex :: VectorSpace v => Lens' (Point v srid) (Vertex v) pVertex = lens _pVertex (\point v -> point { _pVertex = v }) {-# INLINE pVertex #-} derivingUnbox "Point" [t| forall v srid. VectorSpace v => Point v srid -> Vertex v |] [| \(Point v) -> v |] [| \v -> Point v|] derivingUnbox "Pixel" [t| forall v. VectorSpace v => Pixel v -> Vertex v |] [| \(Pixel v) -> v |] [| \v -> Pixel v|] derivingUnbox "Offset" [t| forall t. Offset (t :: OffsetType) -> Int |] [| \(Offset o) -> o |] [| \o -> Offset o|] newtype MultiPoint v srid = MultiPoint { _mpPoints :: V.Vector (Point v srid) } deriving (Eq, Show) makeLenses ''MultiPoint newtype LinearRing v srid = LinearRing {_lrPoints :: U.Vector (Point v srid)} deriving (Eq, Show) makeLenses ''LinearRing newtype LineString v srid = LineString {_lsPoints :: U.Vector (Point v srid)} deriving (Eq, Show) makeLenses ''LineString newtype MultiLineString v srid = MultiLineString { _mlLineStrings :: V.Vector (LineString v srid) } deriving (Eq, Show) makeLenses ''MultiLineString data Triangle v srid = Triangle !(Point v srid) !(Point v srid) !(Point v srid) deriving (Eq, Show) derivingUnbox "Triangle" [t| forall v srid. VectorSpace v => Triangle v srid -> (Point v srid, Point v srid, Point v srid) |] [| \(Triangle a b c) -> (a, b, c) |] [| \(a, b, c) -> Triangle a b c|] data Polygon v srid = Polygon { _pOuterRing :: LinearRing v srid , _pRings :: V.Vector (LinearRing v srid) } deriving (Eq, Show) makeLenses ''Polygon newtype MultiPolygon v srid = MultiPolygon { _mpPolygons :: V.Vector (Polygon v srid) } deriving (Eq, Show) makeLenses ''MultiPolygon newtype PolyhedralSurface v srid = PolyhedralSurface { _psPolygons :: V.Vector (Polygon v srid) } deriving (Eq, Show) makeLenses ''PolyhedralSurface newtype TIN v srid = TIN { _tinTriangles :: U.Vector (Triangle v srid) } deriving (Eq, Show) makeLenses ''TIN data Geometry v (srid::Nat) = GeoPoint (Point v srid) | GeoMultiPoint (MultiPoint v srid) | GeoLineString (LineString v srid) | GeoMultiLineString (MultiLineString v srid) | GeoPolygon (Polygon v srid) | GeoMultiPolygon (MultiPolygon v srid) | GeoTriangle (Triangle v srid) | GeoPolyhedralSurface (PolyhedralSurface v srid) | GeoTIN (TIN v srid) | GeoCollection (GeometryCollection v srid) deriving (Eq, Show) newtype GeometryCollection v srid = GeometryCollection { _gcGeometries :: V.Vector (Geometry v srid) } deriving (Eq, Show) makeLenses ''GeometryCollection makePrisms ''Geometry gSrid :: KnownNat srid => proxy srid -> Integer gSrid = natVal withSrid :: Integer -> (forall srid. KnownNat srid => Proxy srid -> a) -> Maybe a withSrid srid f = case someNatVal srid of Just (SomeNat a) -> Just (f a) Nothing -> Nothing hasSrid :: KnownNat srid => Geometry v srid -> Bool hasSrid = (/= 0) . gSrid mkLineString :: VectorSpace v => [Point v srid] -> Maybe (LineString v srid) mkLineString ls | U.length v >= 2 = Just $ LineString v | otherwise = Nothing where v = U.fromList ls mkLinearRing :: VectorSpace v => [Point v srid] -> Maybe (LinearRing v srid) mkLinearRing ls | U.length v >= 4, U.last v == U.head v = Just $ LinearRing v | otherwise = Nothing where v = U.fromList ls mkPolygon :: [LinearRing v srid] -> Maybe (Polygon v srid) mkPolygon (oRing:rings) = Just $ Polygon oRing $ V.fromList rings mkPolygon _ = Nothing mkTriangle :: VectorSpace v => Point v srid -> Point v srid -> Point v srid -> Maybe (Triangle v srid) mkTriangle a b c | a/=b, b/=c, a/=c = Just $ Triangle a b c | otherwise = Nothing pointCoordinates :: VectorSpace v => Point v srid -> [Double] pointCoordinates = views pVertex coords lineStringCoordinates :: VectorSpace v => LineString v srid -> [[Double]] lineStringCoordinates = vectorCoordinates . _lsPoints linearRingCoordinates :: VectorSpace v => LinearRing v srid -> [[Double]] linearRingCoordinates = vectorCoordinates . _lrPoints polygonCoordinates :: VectorSpace v => Polygon v srid -> [[[Double]]] polygonCoordinates = V.toList . V.map linearRingCoordinates . polygonRings polygonRings :: Polygon v srid -> V.Vector (LinearRing v srid) polygonRings (Polygon ir rs) = V.cons ir rs triangleCoordinates :: VectorSpace v => Triangle v srid -> [[Double]] triangleCoordinates (Triangle a b c) = map pointCoordinates [a, b, c, a] vectorCoordinates :: VectorSpace v => U.Vector (Point v srid) -> [[Double]] vectorCoordinates = V.toList . V.map pointCoordinates . V.convert -- | A feature of 'GeometryType' t, vertex type 'v' and associated data 'd' data FeatureT (g :: (* -> *) -> Nat -> *) v (srid::Nat) d = Feature { _fGeom :: g v srid , _fData :: d } deriving (Eq, Show, Functor) makeLenses ''FeatureT type Feature = FeatureT Geometry newtype FeatureCollectionT (g :: (* -> *) -> Nat -> *) v (srid::Nat) d = FeatureCollection { _fcFeatures :: [FeatureT g v srid d] } deriving (Eq, Show, Functor) makeLenses ''FeatureCollectionT type FeatureCollection = FeatureCollectionT Geometry instance Monoid (FeatureCollectionT g v srid d) where mempty = FeatureCollection mempty (FeatureCollection as) `mappend` (FeatureCollection bs) = FeatureCollection $ as `mappend` bs data Raster vs (t :: OffsetType) srid v a = Raster { rGeoReference :: !(GeoReference vs srid) , rData :: !(v a) } deriving (Eq, Show) indexRaster :: forall vs t srid v a. (GV.Vector v a, HasOffset vs t) => Raster vs t srid v a -> Pixel vs -> Maybe a indexRaster raster px = fmap (GV.unsafeIndex arr . unOff) offset where offset :: Maybe (Offset t) offset = toOffset (grSize (rGeoReference raster)) px arr = rData raster {-# INLINE indexRaster #-} convertRasterOffsetType :: forall vs t1 t2 srid v a. (GV.Vector v a, HasOffset vs t1, HasOffset vs t2) => Raster vs t1 srid v a -> Raster vs t2 srid v a convertRasterOffsetType r = r {rData = GV.generate n go} where go i = let px = unsafeFromOffset s (Offset i :: Offset t2) Offset i' = unsafeToOffset s px :: Offset t1 in rd `GV.unsafeIndex` i' s = grSize (rGeoReference r) rd = rData r n = GV.length rd
krisajenkins/sigym4-geometry
Sigym4/Geometry/Types.hs
Haskell
bsd-3-clause
17,424
package com.game.client; import java.net.InetSocketAddress; import java.net.URL; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoHandler; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.game.client.handlers.PacketHandler; import com.game.common.codec.Packet; import com.game.common.codec.PacketBuilder; import com.game.common.codec.PacketCodecFactory; import com.game.common.util.ISAACAlgorithm; import com.game.common.util.PersistenceManager; public class Connection implements IoHandler { private static final Logger log = LoggerFactory.getLogger(Connection.class); public static final int PING_DELAY = 30000; public static final int PACKET_PROCESSING_DELAY = 100; protected final Client client; protected final NioSocketConnector connector; protected final Map<Packet.Type, PacketHandler> packetHandlers; protected final Queue<Packet> packets; protected IoSession session; protected long lastPingUpdate, lastPacketUpdate; public Connection(Client client) { this.client = client; packetHandlers = this.loadPacketHandlers(); packets = new LinkedList<Packet>(); connector = new NioSocketConnector(); connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new PacketCodecFactory())); connector.setHandler(this); lastPingUpdate = 0; lastPacketUpdate = 0; } private Map<Packet.Type, PacketHandler> loadPacketHandlers() { Map<Packet.Type, PacketHandler> handlers = new HashMap<Packet.Type, PacketHandler>(); URL path = PacketHandler.class.getResource("packethandlers.xml"); if (path == null) { // fatal error throw new RuntimeException("Unable to find packethandlers.xml resource"); } PersistenceManager.PacketHandler[] definitions = (PersistenceManager.PacketHandler[]) PersistenceManager.load(path); for (PersistenceManager.PacketHandler definition : definitions) { try { PacketHandler handler = (PacketHandler) definition.handler.newInstance(); for (Packet.Type type : definition.types) handlers.put(type, handler); } catch (Exception e) { // fatal error throw new RuntimeException("Error loading packet handlers: " + e.getMessage()); } } if (log.isDebugEnabled()) log.debug("Loaded " + handlers.size() + " packet handlers"); return handlers; } public void open(String hostname, int port) throws RuntimeIoException { if (session != null) return; InetSocketAddress address = new InetSocketAddress(hostname, port); ConnectFuture future = connector.connect(address); future.awaitUninterruptibly(); session = future.getSession(); log.info("Connected to server: " + address.getHostName() + ":" + address.getPort()); } public void enableEncryption(long encryptionSeed, long decryptionSeed) { session.setAttribute("encrypter", new ISAACAlgorithm(encryptionSeed)); session.setAttribute("decrypter", new ISAACAlgorithm(decryptionSeed)); } public void close() { if (session == null) return; IoSession session = this.session; this.session = null; if (session.isConnected()) session.close(true).awaitUninterruptibly(); } public void destroy() { this.close(); connector.dispose(); } public void update(long now) { // Process the queued packets if (now - lastPacketUpdate > PACKET_PROCESSING_DELAY) { lastPacketUpdate = now; synchronized (packets) { for (Packet message : packets) this.processPacket(message); packets.clear(); } } // If we aren't logged in, ignore the rest... if (!client.isLoggedIn()) return; // Send a ping to keep the connection alive if (now - lastPingUpdate > PING_DELAY) { lastPingUpdate = now; PacketBuilder builder = new PacketBuilder(Packet.Type.PING_SEND); this.write(builder); } } private boolean processPacket(Packet message) { if (session == null) return true; if (!client.isLoggedIn() && !session.containsAttribute("pending")) return true; PacketHandler handler = packetHandlers.get(message.getType()); // If there's no handler then close the session (forcefully) if (handler == null) { log.error("Unhandled packet: " + message); session.close(true); return false; } try { handler.handlePacket(client, client.getWorldManager(), message); return true; } // Something went wrong (malformed packet?), close the session (forcefully) catch (Exception e) { log.warn("Error decoding packet: " + e.getMessage()); session.close(true); return false; } } public void write(PacketBuilder packet) { session.write(packet); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { log.warn("Error from server connection: " + cause.getMessage()); cause.printStackTrace(); // Close the session (forcefully) session.close(true); } @Override public void messageReceived(IoSession session, Object o) throws Exception { Packet message = (Packet) o; // We should only process 1 packet from a session at a time synchronized (session) { // If logged in queue the packet for processing if (client.isLoggedIn() || session.containsAttribute("pending")) { synchronized (packets) { packets.add(message); } } // If we aren't logged in then this must be the login response else if (message.getType() == Packet.Type.LOGIN_RESPONSE) { // Mark this session as pending login session.setAttribute("pending"); // Queue the packet synchronized (packets) { packets.add(message); } } // Otherwise this packet shouldn't be here! else { log.error("Client isn't logged in, but received a packet: " + message); session.close(true); } } } @Override public void messageSent(IoSession session, Object o) throws Exception { lastPingUpdate = System.currentTimeMillis(); } @Override public void sessionClosed(IoSession session) throws Exception { if (this.session == null) return; client.handleLogout(); } @Override public void sessionCreated(IoSession session) throws Exception { } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { // When a session becomes idle, close it (gracefully) session.close(false); } @Override public void sessionOpened(IoSession session) throws Exception { } }
reines/game
game-client/src/main/java/com/game/client/Connection.java
Java
bsd-3-clause
6,682
/* * Copyright (c) 2011-2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Copyright (c) 2003-2006 The Regents of The University of Michigan * Copyright (c) 2011 Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Steve Reinhardt * Lisa Hsu * Nathan Binkert * Ali Saidi * Rick Strong */ #include "arch/isa_traits.hh" #include "arch/remote_gdb.hh" #include "arch/utility.hh" #include "arch/vtophys.hh" #include "base/loader/object_file.hh" #include "base/loader/symtab.hh" #include "base/str.hh" #include "base/trace.hh" #include "config/the_isa.hh" #include "cpu/thread_context.hh" #include "debug/Loader.hh" #include "debug/WorkItems.hh" #include "kern/kernel_stats.hh" #include "mem/physical.hh" #include "params/System.hh" #include "sim/byteswap.hh" #include "sim/debug.hh" #include "sim/full_system.hh" #include "sim/system.hh" using namespace std; using namespace TheISA; vector<System *> System::systemList; int System::numSystemsRunning = 0; System::System(Params *p) : MemObject(p), _systemPort("system_port", this), _numContexts(0), pagePtr(0), init_param(p->init_param), physProxy(_systemPort), virtProxy(_systemPort), loadAddrMask(p->load_addr_mask), nextPID(0), physmem(p->memories), memoryMode(p->mem_mode), workItemsBegin(0), workItemsEnd(0), numWorkIds(p->num_work_ids), _params(p), totalNumInsts(0), instEventQueue("system instruction-based event queue") { // add self to global system list systemList.push_back(this); if (FullSystem) { kernelSymtab = new SymbolTable; if (!debugSymbolTable) debugSymbolTable = new SymbolTable; } // Get the generic system master IDs MasterID tmp_id M5_VAR_USED; tmp_id = getMasterId("writebacks"); assert(tmp_id == Request::wbMasterId); tmp_id = getMasterId("functional"); assert(tmp_id == Request::funcMasterId); tmp_id = getMasterId("interrupt"); assert(tmp_id == Request::intMasterId); if (FullSystem) { if (params()->kernel == "") { inform("No kernel set for full system simulation. " "Assuming you know what you're doing\n"); kernel = NULL; } else { // Get the kernel code kernel = createObjectFile(params()->kernel); inform("kernel located at: %s", params()->kernel); if (kernel == NULL) fatal("Could not load kernel file %s", params()->kernel); // setup entry points kernelStart = kernel->textBase(); kernelEnd = kernel->bssBase() + kernel->bssSize(); kernelEntry = kernel->entryPoint(); // load symbols if (!kernel->loadGlobalSymbols(kernelSymtab)) fatal("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(kernelSymtab)) fatal("could not load kernel local symbols\n"); if (!kernel->loadGlobalSymbols(debugSymbolTable)) fatal("could not load kernel symbols\n"); if (!kernel->loadLocalSymbols(debugSymbolTable)) fatal("could not load kernel local symbols\n"); // Loading only needs to happen once and after memory system is // connected so it will happen in initState() } } // increment the number of running systms numSystemsRunning++; // Set back pointers to the system in all memories for (int x = 0; x < params()->memories.size(); x++) params()->memories[x]->system(this); } System::~System() { delete kernelSymtab; delete kernel; for (uint32_t j = 0; j < numWorkIds; j++) delete workItemStats[j]; } void System::init() { // check that the system port is connected if (!_systemPort.isConnected()) panic("System port on %s is not connected.\n", name()); } MasterPort& System::getMasterPort(const std::string &if_name, int idx) { // no need to distinguish at the moment (besides checking) return _systemPort; } void System::setMemoryMode(Enums::MemoryMode mode) { assert(getState() == Drained); memoryMode = mode; } bool System::breakpoint() { if (remoteGDB.size()) return remoteGDB[0]->breakpoint(); return false; } /** * Setting rgdb_wait to a positive integer waits for a remote debugger to * connect to that context ID before continuing. This should really be a parameter on the CPU object or something... */ int rgdb_wait = -1; int System::registerThreadContext(ThreadContext *tc, int assigned) { int id; if (assigned == -1) { for (id = 0; id < threadContexts.size(); id++) { if (!threadContexts[id]) break; } if (threadContexts.size() <= id) threadContexts.resize(id + 1); } else { if (threadContexts.size() <= assigned) threadContexts.resize(assigned + 1); id = assigned; } if (threadContexts[id]) fatal("Cannot have two CPUs with the same id (%d)\n", id); threadContexts[id] = tc; _numContexts++; int port = getRemoteGDBPort(); if (port) { RemoteGDB *rgdb = new RemoteGDB(this, tc); GDBListener *gdbl = new GDBListener(rgdb, port + id); gdbl->listen(); if (rgdb_wait != -1 && rgdb_wait == id) gdbl->accept(); if (remoteGDB.size() <= id) { remoteGDB.resize(id + 1); } remoteGDB[id] = rgdb; } activeCpus.push_back(false); return id; } int System::numRunningContexts() { int running = 0; for (int i = 0; i < _numContexts; ++i) { if (threadContexts[i]->status() != ThreadContext::Halted) ++running; } return running; } void System::initState() { if (FullSystem) { for (int i = 0; i < threadContexts.size(); i++) TheISA::startupCPU(threadContexts[i], i); // Moved from the constructor to here since it relies on the // address map being resolved in the interconnect /** * Load the kernel code into memory */ if (params()->kernel != "") { // Validate kernel mapping before loading binary if (!(isMemAddr(kernelStart & loadAddrMask) && isMemAddr(kernelEnd & loadAddrMask))) { fatal("Kernel is mapped to invalid location (not memory). " "kernelStart 0x(%x) - kernelEnd 0x(%x)\n", kernelStart, kernelEnd); } // Load program sections into memory kernel->loadSections(physProxy, loadAddrMask); DPRINTF(Loader, "Kernel start = %#x\n", kernelStart); DPRINTF(Loader, "Kernel end = %#x\n", kernelEnd); DPRINTF(Loader, "Kernel entry = %#x\n", kernelEntry); DPRINTF(Loader, "Kernel loaded...\n"); } } activeCpus.clear(); } void System::replaceThreadContext(ThreadContext *tc, int context_id) { if (context_id >= threadContexts.size()) { panic("replaceThreadContext: bad id, %d >= %d\n", context_id, threadContexts.size()); } threadContexts[context_id] = tc; if (context_id < remoteGDB.size()) remoteGDB[context_id]->replaceThreadContext(tc); } Addr System::allocPhysPages(int npages) { Addr return_addr = pagePtr << LogVMPageSize; pagePtr += npages; if ((pagePtr << LogVMPageSize) > physmem.totalSize()) fatal("Out of memory, please increase size of physical memory."); return return_addr; } Addr System::memSize() const { return physmem.totalSize(); } Addr System::freeMemSize() const { return physmem.totalSize() - (pagePtr << LogVMPageSize); } bool System::isMemAddr(Addr addr) const { return physmem.isMemAddr(addr); } void System::resume() { SimObject::resume(); totalNumInsts = 0; } void System::serialize(ostream &os) { if (FullSystem) kernelSymtab->serialize("kernel_symtab", os); SERIALIZE_SCALAR(pagePtr); SERIALIZE_SCALAR(nextPID); } void System::unserialize(Checkpoint *cp, const string &section) { if (FullSystem) kernelSymtab->unserialize("kernel_symtab", cp, section); UNSERIALIZE_SCALAR(pagePtr); UNSERIALIZE_SCALAR(nextPID); } void System::regStats() { for (uint32_t j = 0; j < numWorkIds ; j++) { workItemStats[j] = new Stats::Histogram(); stringstream namestr; ccprintf(namestr, "work_item_type%d", j); workItemStats[j]->init(20) .name(name() + "." + namestr.str()) .desc("Run time stat for" + namestr.str()) .prereq(*workItemStats[j]); } } void System::workItemEnd(uint32_t tid, uint32_t workid) { std::pair<uint32_t,uint32_t> p(tid, workid); if (!lastWorkItemStarted.count(p)) return; Tick samp = curTick() - lastWorkItemStarted[p]; DPRINTF(WorkItems, "Work item end: %d\t%d\t%lld\n", tid, workid, samp); if (workid >= numWorkIds) fatal("Got workid greater than specified in system configuration\n"); workItemStats[workid]->sample(samp); lastWorkItemStarted.erase(p); } void System::printSystems() { vector<System *>::iterator i = systemList.begin(); vector<System *>::iterator end = systemList.end(); for (; i != end; ++i) { System *sys = *i; cerr << "System " << sys->name() << ": " << hex << sys << endl; } } void printSystems() { System::printSystems(); } MasterID System::getMasterId(std::string master_name) { // strip off system name if the string starts with it if (startswith(master_name, name())) master_name = master_name.erase(0, name().size() + 1); // CPUs in switch_cpus ask for ids again after switching for (int i = 0; i < masterIds.size(); i++) { if (masterIds[i] == master_name) { return i; } } // Verify that the statistics haven't been enabled yet // Otherwise objects will have sized their stat buckets and // they will be too small if (Stats::enabled()) fatal("Can't request a masterId after regStats(). \ You must do so in init().\n"); masterIds.push_back(master_name); return masterIds.size() - 1; } std::string System::getMasterName(MasterID master_id) { if (master_id >= masterIds.size()) fatal("Invalid master_id passed to getMasterName()\n"); return masterIds[master_id]; } const char *System::MemoryModeStrings[3] = {"invalid", "atomic", "timing"}; System * SystemParams::create() { return new System(this); }
lastweek/gem5
src/sim/system.cc
C++
bsd-3-clause
12,809
#ifndef __gl3platform_h_ #define __gl3platform_h_ /* $Revision: 23328 $ on $Date:: 2013-10-02 02:28:28 -0700 #$ */ /* * This document is licensed under the SGI Free Software B License Version * 2.0. For details, see http://oss.sgi.com/projects/FreeB/ . */ /* Platform-specific types and definitions for OpenGL ES 3.X gl3.h * * Adopters may modify khrplatform.h and this file to suit their platform. * You are encouraged to submit all modifications to the Khronos group so that * they can be included in future versions of this file. Please submit changes * by sending them to the public Khronos Bugzilla (http://khronos.org/bugzilla) * by filing a bug against product "OpenGL-ES" component "Registry". */ #include <KHR/khrplatform.h> #ifndef GL_APICALL #define GL_APICALL KHRONOS_APICALL #endif #ifndef GL_APIENTRY #define GL_APIENTRY KHRONOS_APIENTRY #endif #endif /* __gl3platform_h_ */
youtube/cobalt
glimp/include/GLES3/gl3platform.h
C
bsd-3-clause
908
# -*- coding: utf-8 -*- # # Copyright (C) 2016 Andi Albrecht, [email protected] # # This module is part of python-sqlparse and is released under # the BSD License: http://www.opensource.org/licenses/bsd-license.php import re from sqlparse import tokens def is_keyword(value): val = value.upper() return (KEYWORDS_COMMON.get(val) or KEYWORDS_ORACLE.get(val) or KEYWORDS.get(val, tokens.Name)), value SQL_REGEX = { 'root': [ (r'(--|# )\+.*?(\r\n|\r|\n|$)', tokens.Comment.Single.Hint), (r'/\*\+[\s\S]*?\*/', tokens.Comment.Multiline.Hint), (r'/\*\![\s\S]*?\*/', tokens.Comment.Multiline.Code), (r'(--|# ).*?(\r\n|\r|\n|$)', tokens.Comment.Single), (r'/\*[\s\S]*?\*/', tokens.Comment.Multiline), (r'(\r\n|\r|\n)', tokens.Newline), (r'\s+', tokens.Whitespace), (r':=', tokens.Assignment), (r'::', tokens.Punctuation), (r'\*', tokens.Wildcard), (r"`(``|[^`])*`", tokens.Name), (r"´(´´|[^´])*´", tokens.Name), (r'\$([_A-Z]\w*)?\$', tokens.Name.Builtin), (r'\?', tokens.Name.Placeholder), (r'%(\(\w+\))?s', tokens.Name.Placeholder), (r'[$:?]\w+', tokens.Name.Placeholder), # FIXME(andi): VALUES shouldn't be listed here # see https://github.com/andialbrecht/sqlparse/pull/64 # IN is special, it may be followed by a parenthesis, but # is never a functino, see issue183 (r'(CASE|IN|VALUES|USING)\b', tokens.Keyword), (r'(@|##|#)[A-Z]\w+', tokens.Name), # see issue #39 # Spaces around period `schema . name` are valid identifier # TODO: Spaces before period not implemented (r'[A-Z]\w*(?=\s*\.)', tokens.Name), # 'Name' . (r'(?<=\.)[A-Z]\w*', tokens.Name), # .'Name' (r'[A-Z]\w*(?=\()', tokens.Name), # side effect: change kw to func # TODO: `1.` and `.1` are valid numbers (r'-?0x[\dA-F]+', tokens.Number.Hexadecimal), (r'-?\d*(\.\d+)?E-?\d+', tokens.Number.Float), (r'-?\d*\.\d+', tokens.Number.Float), (r'-?\d+', tokens.Number.Integer), (r"'(''|\\\\|\\'|[^'])*'", tokens.String.Single), # not a real string literal in ANSI SQL: (r'(""|".*?[^\\]")', tokens.String.Symbol), # sqlite names can be escaped with [square brackets]. left bracket # cannot be preceded by word character or a right bracket -- # otherwise it's probably an array index (r'(?<![\w\])])(\[[^\]]+\])', tokens.Name), (r'((LEFT\s+|RIGHT\s+|FULL\s+)?(INNER\s+|OUTER\s+|STRAIGHT\s+)?' r'|(CROSS\s+|NATURAL\s+)?)?JOIN\b', tokens.Keyword.Join), # Combine 2 work tokens into 1? Not Implemented # (r'(CONNECT|GROUP|ORDER|PARTITION)\s+BY\b', tokens.Keyword), (r'END(\s+IF|\s+LOOP|\s+WHILE)?\b', tokens.Keyword), (r'NOT\s+(NULL|LIKE|IN)\b', tokens.Operator.Comparison), (r'CREATE(\s+OR\s+REPLACE)?\b', tokens.Keyword.DDL), (r'DOUBLE\s+PRECISION\b', tokens.Name.Builtin), (r'[_A-Z]\w*', is_keyword), (r'[;:()\[\],\.]', tokens.Punctuation), (r'(!=|<>)', tokens.Operator.Comparison), (r'[<>=~!]+', tokens.Operator.Comparison), (r'[+/@#%^&|`?^-]+', tokens.Operator), ]} FLAGS = re.IGNORECASE | re.UNICODE SQL_REGEX = [(re.compile(rx, FLAGS).match, tt) for rx, tt in SQL_REGEX['root']] KEYWORDS = { 'ABORT': tokens.Keyword, 'ABS': tokens.Keyword, 'ABSOLUTE': tokens.Keyword, 'ACCESS': tokens.Keyword, 'ADA': tokens.Keyword, 'ADD': tokens.Keyword, 'ADMIN': tokens.Keyword, 'AFTER': tokens.Keyword, 'AGGREGATE': tokens.Keyword, 'ALIAS': tokens.Keyword, 'ALL': tokens.Keyword, 'ALLOCATE': tokens.Keyword, 'ANALYSE': tokens.Keyword, 'ANALYZE': tokens.Keyword, 'ANY': tokens.Keyword, 'ARRAYLEN': tokens.Keyword, 'ARE': tokens.Keyword, 'ASC': tokens.Keyword.Order, 'ASENSITIVE': tokens.Keyword, 'ASSERTION': tokens.Keyword, 'ASSIGNMENT': tokens.Keyword, 'ASYMMETRIC': tokens.Keyword, 'AT': tokens.Keyword, 'ATOMIC': tokens.Keyword, 'AUDIT': tokens.Keyword, 'AUTHORIZATION': tokens.Keyword, 'AVG': tokens.Keyword, 'BACKWARD': tokens.Keyword, 'BEFORE': tokens.Keyword, 'BEGIN': tokens.Keyword, 'BETWEEN': tokens.Keyword, 'BITVAR': tokens.Keyword, 'BIT_LENGTH': tokens.Keyword, 'BOTH': tokens.Keyword, 'BREADTH': tokens.Keyword, # 'C': tokens.Keyword, # most likely this is an alias 'CACHE': tokens.Keyword, 'CALL': tokens.Keyword, 'CALLED': tokens.Keyword, 'CARDINALITY': tokens.Keyword, 'CASCADE': tokens.Keyword, 'CASCADED': tokens.Keyword, 'CAST': tokens.Keyword, 'CATALOG': tokens.Keyword, 'CATALOG_NAME': tokens.Keyword, 'CHAIN': tokens.Keyword, 'CHARACTERISTICS': tokens.Keyword, 'CHARACTER_LENGTH': tokens.Keyword, 'CHARACTER_SET_CATALOG': tokens.Keyword, 'CHARACTER_SET_NAME': tokens.Keyword, 'CHARACTER_SET_SCHEMA': tokens.Keyword, 'CHAR_LENGTH': tokens.Keyword, 'CHECK': tokens.Keyword, 'CHECKED': tokens.Keyword, 'CHECKPOINT': tokens.Keyword, 'CLASS': tokens.Keyword, 'CLASS_ORIGIN': tokens.Keyword, 'CLOB': tokens.Keyword, 'CLOSE': tokens.Keyword, 'CLUSTER': tokens.Keyword, 'COALESCE': tokens.Keyword, 'COBOL': tokens.Keyword, 'COLLATE': tokens.Keyword, 'COLLATION': tokens.Keyword, 'COLLATION_CATALOG': tokens.Keyword, 'COLLATION_NAME': tokens.Keyword, 'COLLATION_SCHEMA': tokens.Keyword, 'COLLECT': tokens.Keyword, 'COLUMN': tokens.Keyword, 'COLUMN_NAME': tokens.Keyword, 'COMPRESS': tokens.Keyword, 'COMMAND_FUNCTION': tokens.Keyword, 'COMMAND_FUNCTION_CODE': tokens.Keyword, 'COMMENT': tokens.Keyword, 'COMMIT': tokens.Keyword.DML, 'COMMITTED': tokens.Keyword, 'COMPLETION': tokens.Keyword, 'CONDITION_NUMBER': tokens.Keyword, 'CONNECT': tokens.Keyword, 'CONNECTION': tokens.Keyword, 'CONNECTION_NAME': tokens.Keyword, 'CONSTRAINT': tokens.Keyword, 'CONSTRAINTS': tokens.Keyword, 'CONSTRAINT_CATALOG': tokens.Keyword, 'CONSTRAINT_NAME': tokens.Keyword, 'CONSTRAINT_SCHEMA': tokens.Keyword, 'CONSTRUCTOR': tokens.Keyword, 'CONTAINS': tokens.Keyword, 'CONTINUE': tokens.Keyword, 'CONVERSION': tokens.Keyword, 'CONVERT': tokens.Keyword, 'COPY': tokens.Keyword, 'CORRESPONTING': tokens.Keyword, 'COUNT': tokens.Keyword, 'CREATEDB': tokens.Keyword, 'CREATEUSER': tokens.Keyword, 'CROSS': tokens.Keyword, 'CUBE': tokens.Keyword, 'CURRENT': tokens.Keyword, 'CURRENT_DATE': tokens.Keyword, 'CURRENT_PATH': tokens.Keyword, 'CURRENT_ROLE': tokens.Keyword, 'CURRENT_TIME': tokens.Keyword, 'CURRENT_TIMESTAMP': tokens.Keyword, 'CURRENT_USER': tokens.Keyword, 'CURSOR': tokens.Keyword, 'CURSOR_NAME': tokens.Keyword, 'CYCLE': tokens.Keyword, 'DATA': tokens.Keyword, 'DATABASE': tokens.Keyword, 'DATETIME_INTERVAL_CODE': tokens.Keyword, 'DATETIME_INTERVAL_PRECISION': tokens.Keyword, 'DAY': tokens.Keyword, 'DEALLOCATE': tokens.Keyword, 'DECLARE': tokens.Keyword, 'DEFAULT': tokens.Keyword, 'DEFAULTS': tokens.Keyword, 'DEFERRABLE': tokens.Keyword, 'DEFERRED': tokens.Keyword, 'DEFINED': tokens.Keyword, 'DEFINER': tokens.Keyword, 'DELIMITER': tokens.Keyword, 'DELIMITERS': tokens.Keyword, 'DEREF': tokens.Keyword, 'DESC': tokens.Keyword.Order, 'DESCRIBE': tokens.Keyword, 'DESCRIPTOR': tokens.Keyword, 'DESTROY': tokens.Keyword, 'DESTRUCTOR': tokens.Keyword, 'DETERMINISTIC': tokens.Keyword, 'DIAGNOSTICS': tokens.Keyword, 'DICTIONARY': tokens.Keyword, 'DISABLE': tokens.Keyword, 'DISCONNECT': tokens.Keyword, 'DISPATCH': tokens.Keyword, 'DO': tokens.Keyword, 'DOMAIN': tokens.Keyword, 'DYNAMIC': tokens.Keyword, 'DYNAMIC_FUNCTION': tokens.Keyword, 'DYNAMIC_FUNCTION_CODE': tokens.Keyword, 'EACH': tokens.Keyword, 'ENABLE': tokens.Keyword, 'ENCODING': tokens.Keyword, 'ENCRYPTED': tokens.Keyword, 'END-EXEC': tokens.Keyword, 'EQUALS': tokens.Keyword, 'ESCAPE': tokens.Keyword, 'EVERY': tokens.Keyword, 'EXCEPT': tokens.Keyword, 'EXCEPTION': tokens.Keyword, 'EXCLUDING': tokens.Keyword, 'EXCLUSIVE': tokens.Keyword, 'EXEC': tokens.Keyword, 'EXECUTE': tokens.Keyword, 'EXISTING': tokens.Keyword, 'EXISTS': tokens.Keyword, 'EXTERNAL': tokens.Keyword, 'EXTRACT': tokens.Keyword, 'FALSE': tokens.Keyword, 'FETCH': tokens.Keyword, 'FILE': tokens.Keyword, 'FINAL': tokens.Keyword, 'FIRST': tokens.Keyword, 'FORCE': tokens.Keyword, 'FOREACH': tokens.Keyword, 'FOREIGN': tokens.Keyword, 'FORTRAN': tokens.Keyword, 'FORWARD': tokens.Keyword, 'FOUND': tokens.Keyword, 'FREE': tokens.Keyword, 'FREEZE': tokens.Keyword, 'FULL': tokens.Keyword, 'FUNCTION': tokens.Keyword, # 'G': tokens.Keyword, 'GENERAL': tokens.Keyword, 'GENERATED': tokens.Keyword, 'GET': tokens.Keyword, 'GLOBAL': tokens.Keyword, 'GO': tokens.Keyword, 'GOTO': tokens.Keyword, 'GRANT': tokens.Keyword, 'GRANTED': tokens.Keyword, 'GROUPING': tokens.Keyword, 'HANDLER': tokens.Keyword, 'HAVING': tokens.Keyword, 'HIERARCHY': tokens.Keyword, 'HOLD': tokens.Keyword, 'HOST': tokens.Keyword, 'IDENTIFIED': tokens.Keyword, 'IDENTITY': tokens.Keyword, 'IGNORE': tokens.Keyword, 'ILIKE': tokens.Keyword, 'IMMEDIATE': tokens.Keyword, 'IMMUTABLE': tokens.Keyword, 'IMPLEMENTATION': tokens.Keyword, 'IMPLICIT': tokens.Keyword, 'INCLUDING': tokens.Keyword, 'INCREMENT': tokens.Keyword, 'INDEX': tokens.Keyword, 'INDITCATOR': tokens.Keyword, 'INFIX': tokens.Keyword, 'INHERITS': tokens.Keyword, 'INITIAL': tokens.Keyword, 'INITIALIZE': tokens.Keyword, 'INITIALLY': tokens.Keyword, 'INOUT': tokens.Keyword, 'INPUT': tokens.Keyword, 'INSENSITIVE': tokens.Keyword, 'INSTANTIABLE': tokens.Keyword, 'INSTEAD': tokens.Keyword, 'INTERSECT': tokens.Keyword, 'INTO': tokens.Keyword, 'INVOKER': tokens.Keyword, 'IS': tokens.Keyword, 'ISNULL': tokens.Keyword, 'ISOLATION': tokens.Keyword, 'ITERATE': tokens.Keyword, # 'K': tokens.Keyword, 'KEY': tokens.Keyword, 'KEY_MEMBER': tokens.Keyword, 'KEY_TYPE': tokens.Keyword, 'LANCOMPILER': tokens.Keyword, 'LANGUAGE': tokens.Keyword, 'LARGE': tokens.Keyword, 'LAST': tokens.Keyword, 'LATERAL': tokens.Keyword, 'LEADING': tokens.Keyword, 'LENGTH': tokens.Keyword, 'LESS': tokens.Keyword, 'LEVEL': tokens.Keyword, 'LIMIT': tokens.Keyword, 'LISTEN': tokens.Keyword, 'LOAD': tokens.Keyword, 'LOCAL': tokens.Keyword, 'LOCALTIME': tokens.Keyword, 'LOCALTIMESTAMP': tokens.Keyword, 'LOCATION': tokens.Keyword, 'LOCATOR': tokens.Keyword, 'LOCK': tokens.Keyword, 'LOWER': tokens.Keyword, # 'M': tokens.Keyword, 'MAP': tokens.Keyword, 'MATCH': tokens.Keyword, 'MAXEXTENTS': tokens.Keyword, 'MAXVALUE': tokens.Keyword, 'MESSAGE_LENGTH': tokens.Keyword, 'MESSAGE_OCTET_LENGTH': tokens.Keyword, 'MESSAGE_TEXT': tokens.Keyword, 'METHOD': tokens.Keyword, 'MINUTE': tokens.Keyword, 'MINUS': tokens.Keyword, 'MINVALUE': tokens.Keyword, 'MOD': tokens.Keyword, 'MODE': tokens.Keyword, 'MODIFIES': tokens.Keyword, 'MODIFY': tokens.Keyword, 'MONTH': tokens.Keyword, 'MORE': tokens.Keyword, 'MOVE': tokens.Keyword, 'MUMPS': tokens.Keyword, 'NAMES': tokens.Keyword, 'NATIONAL': tokens.Keyword, 'NATURAL': tokens.Keyword, 'NCHAR': tokens.Keyword, 'NCLOB': tokens.Keyword, 'NEW': tokens.Keyword, 'NEXT': tokens.Keyword, 'NO': tokens.Keyword, 'NOAUDIT': tokens.Keyword, 'NOCOMPRESS': tokens.Keyword, 'NOCREATEDB': tokens.Keyword, 'NOCREATEUSER': tokens.Keyword, 'NONE': tokens.Keyword, 'NOT': tokens.Keyword, 'NOTFOUND': tokens.Keyword, 'NOTHING': tokens.Keyword, 'NOTIFY': tokens.Keyword, 'NOTNULL': tokens.Keyword, 'NOWAIT': tokens.Keyword, 'NULL': tokens.Keyword, 'NULLABLE': tokens.Keyword, 'NULLIF': tokens.Keyword, 'OBJECT': tokens.Keyword, 'OCTET_LENGTH': tokens.Keyword, 'OF': tokens.Keyword, 'OFF': tokens.Keyword, 'OFFLINE': tokens.Keyword, 'OFFSET': tokens.Keyword, 'OIDS': tokens.Keyword, 'OLD': tokens.Keyword, 'ONLINE': tokens.Keyword, 'ONLY': tokens.Keyword, 'OPEN': tokens.Keyword, 'OPERATION': tokens.Keyword, 'OPERATOR': tokens.Keyword, 'OPTION': tokens.Keyword, 'OPTIONS': tokens.Keyword, 'ORDINALITY': tokens.Keyword, 'OUT': tokens.Keyword, 'OUTPUT': tokens.Keyword, 'OVER': tokens.Keyword, 'OVERLAPS': tokens.Keyword, 'OVERLAY': tokens.Keyword, 'OVERRIDING': tokens.Keyword, 'OWNER': tokens.Keyword, 'PAD': tokens.Keyword, 'PARAMETER': tokens.Keyword, 'PARAMETERS': tokens.Keyword, 'PARAMETER_MODE': tokens.Keyword, 'PARAMATER_NAME': tokens.Keyword, 'PARAMATER_ORDINAL_POSITION': tokens.Keyword, 'PARAMETER_SPECIFIC_CATALOG': tokens.Keyword, 'PARAMETER_SPECIFIC_NAME': tokens.Keyword, 'PARAMATER_SPECIFIC_SCHEMA': tokens.Keyword, 'PARTIAL': tokens.Keyword, 'PASCAL': tokens.Keyword, 'PCTFREE': tokens.Keyword, 'PENDANT': tokens.Keyword, 'PLACING': tokens.Keyword, 'PLI': tokens.Keyword, 'POSITION': tokens.Keyword, 'POSTFIX': tokens.Keyword, 'PRECISION': tokens.Keyword, 'PREFIX': tokens.Keyword, 'PREORDER': tokens.Keyword, 'PREPARE': tokens.Keyword, 'PRESERVE': tokens.Keyword, 'PRIMARY': tokens.Keyword, 'PRIOR': tokens.Keyword, 'PRIVILEGES': tokens.Keyword, 'PROCEDURAL': tokens.Keyword, 'PROCEDURE': tokens.Keyword, 'PUBLIC': tokens.Keyword, 'RAISE': tokens.Keyword, 'RAW': tokens.Keyword, 'READ': tokens.Keyword, 'READS': tokens.Keyword, 'RECHECK': tokens.Keyword, 'RECURSIVE': tokens.Keyword, 'REF': tokens.Keyword, 'REFERENCES': tokens.Keyword, 'REFERENCING': tokens.Keyword, 'REINDEX': tokens.Keyword, 'RELATIVE': tokens.Keyword, 'RENAME': tokens.Keyword, 'REPEATABLE': tokens.Keyword, 'RESET': tokens.Keyword, 'RESOURCE': tokens.Keyword, 'RESTART': tokens.Keyword, 'RESTRICT': tokens.Keyword, 'RESULT': tokens.Keyword, 'RETURN': tokens.Keyword, 'RETURNED_LENGTH': tokens.Keyword, 'RETURNED_OCTET_LENGTH': tokens.Keyword, 'RETURNED_SQLSTATE': tokens.Keyword, 'RETURNING': tokens.Keyword, 'RETURNS': tokens.Keyword, 'REVOKE': tokens.Keyword, 'RIGHT': tokens.Keyword, 'ROLE': tokens.Keyword, 'ROLLBACK': tokens.Keyword.DML, 'ROLLUP': tokens.Keyword, 'ROUTINE': tokens.Keyword, 'ROUTINE_CATALOG': tokens.Keyword, 'ROUTINE_NAME': tokens.Keyword, 'ROUTINE_SCHEMA': tokens.Keyword, 'ROW': tokens.Keyword, 'ROWS': tokens.Keyword, 'ROW_COUNT': tokens.Keyword, 'RULE': tokens.Keyword, 'SAVE_POINT': tokens.Keyword, 'SCALE': tokens.Keyword, 'SCHEMA': tokens.Keyword, 'SCHEMA_NAME': tokens.Keyword, 'SCOPE': tokens.Keyword, 'SCROLL': tokens.Keyword, 'SEARCH': tokens.Keyword, 'SECOND': tokens.Keyword, 'SECURITY': tokens.Keyword, 'SELF': tokens.Keyword, 'SENSITIVE': tokens.Keyword, 'SEQUENCE': tokens.Keyword, 'SERIALIZABLE': tokens.Keyword, 'SERVER_NAME': tokens.Keyword, 'SESSION': tokens.Keyword, 'SESSION_USER': tokens.Keyword, 'SETOF': tokens.Keyword, 'SETS': tokens.Keyword, 'SHARE': tokens.Keyword, 'SHOW': tokens.Keyword, 'SIMILAR': tokens.Keyword, 'SIMPLE': tokens.Keyword, 'SIZE': tokens.Keyword, 'SOME': tokens.Keyword, 'SOURCE': tokens.Keyword, 'SPACE': tokens.Keyword, 'SPECIFIC': tokens.Keyword, 'SPECIFICTYPE': tokens.Keyword, 'SPECIFIC_NAME': tokens.Keyword, 'SQL': tokens.Keyword, 'SQLBUF': tokens.Keyword, 'SQLCODE': tokens.Keyword, 'SQLERROR': tokens.Keyword, 'SQLEXCEPTION': tokens.Keyword, 'SQLSTATE': tokens.Keyword, 'SQLWARNING': tokens.Keyword, 'STABLE': tokens.Keyword, 'START': tokens.Keyword.DML, 'STATE': tokens.Keyword, 'STATEMENT': tokens.Keyword, 'STATIC': tokens.Keyword, 'STATISTICS': tokens.Keyword, 'STDIN': tokens.Keyword, 'STDOUT': tokens.Keyword, 'STORAGE': tokens.Keyword, 'STRICT': tokens.Keyword, 'STRUCTURE': tokens.Keyword, 'STYPE': tokens.Keyword, 'SUBCLASS_ORIGIN': tokens.Keyword, 'SUBLIST': tokens.Keyword, 'SUBSTRING': tokens.Keyword, 'SUCCESSFUL': tokens.Keyword, 'SUM': tokens.Keyword, 'SYMMETRIC': tokens.Keyword, 'SYNONYM': tokens.Keyword, 'SYSID': tokens.Keyword, 'SYSTEM': tokens.Keyword, 'SYSTEM_USER': tokens.Keyword, 'TABLE': tokens.Keyword, 'TABLE_NAME': tokens.Keyword, 'TEMP': tokens.Keyword, 'TEMPLATE': tokens.Keyword, 'TEMPORARY': tokens.Keyword, 'TERMINATE': tokens.Keyword, 'THAN': tokens.Keyword, 'TIMESTAMP': tokens.Keyword, 'TIMEZONE_HOUR': tokens.Keyword, 'TIMEZONE_MINUTE': tokens.Keyword, 'TO': tokens.Keyword, 'TOAST': tokens.Keyword, 'TRAILING': tokens.Keyword, 'TRANSATION': tokens.Keyword, 'TRANSACTIONS_COMMITTED': tokens.Keyword, 'TRANSACTIONS_ROLLED_BACK': tokens.Keyword, 'TRANSATION_ACTIVE': tokens.Keyword, 'TRANSFORM': tokens.Keyword, 'TRANSFORMS': tokens.Keyword, 'TRANSLATE': tokens.Keyword, 'TRANSLATION': tokens.Keyword, 'TREAT': tokens.Keyword, 'TRIGGER': tokens.Keyword, 'TRIGGER_CATALOG': tokens.Keyword, 'TRIGGER_NAME': tokens.Keyword, 'TRIGGER_SCHEMA': tokens.Keyword, 'TRIM': tokens.Keyword, 'TRUE': tokens.Keyword, 'TRUNCATE': tokens.Keyword, 'TRUSTED': tokens.Keyword, 'TYPE': tokens.Keyword, 'UID': tokens.Keyword, 'UNCOMMITTED': tokens.Keyword, 'UNDER': tokens.Keyword, 'UNENCRYPTED': tokens.Keyword, 'UNION': tokens.Keyword, 'UNIQUE': tokens.Keyword, 'UNKNOWN': tokens.Keyword, 'UNLISTEN': tokens.Keyword, 'UNNAMED': tokens.Keyword, 'UNNEST': tokens.Keyword, 'UNTIL': tokens.Keyword, 'UPPER': tokens.Keyword, 'USAGE': tokens.Keyword, 'USE': tokens.Keyword, 'USER': tokens.Keyword, 'USER_DEFINED_TYPE_CATALOG': tokens.Keyword, 'USER_DEFINED_TYPE_NAME': tokens.Keyword, 'USER_DEFINED_TYPE_SCHEMA': tokens.Keyword, 'USING': tokens.Keyword, 'VACUUM': tokens.Keyword, 'VALID': tokens.Keyword, 'VALIDATE': tokens.Keyword, 'VALIDATOR': tokens.Keyword, 'VALUES': tokens.Keyword, 'VARIABLE': tokens.Keyword, 'VERBOSE': tokens.Keyword, 'VERSION': tokens.Keyword, 'VIEW': tokens.Keyword, 'VOLATILE': tokens.Keyword, 'WHENEVER': tokens.Keyword, 'WITH': tokens.Keyword.CTE, 'WITHOUT': tokens.Keyword, 'WORK': tokens.Keyword, 'WRITE': tokens.Keyword, 'YEAR': tokens.Keyword, 'ZONE': tokens.Keyword, # Name.Builtin 'ARRAY': tokens.Name.Builtin, 'BIGINT': tokens.Name.Builtin, 'BINARY': tokens.Name.Builtin, 'BIT': tokens.Name.Builtin, 'BLOB': tokens.Name.Builtin, 'BOOLEAN': tokens.Name.Builtin, 'CHAR': tokens.Name.Builtin, 'CHARACTER': tokens.Name.Builtin, 'DATE': tokens.Name.Builtin, 'DEC': tokens.Name.Builtin, 'DECIMAL': tokens.Name.Builtin, 'FLOAT': tokens.Name.Builtin, 'INT': tokens.Name.Builtin, 'INT8': tokens.Name.Builtin, 'INTEGER': tokens.Name.Builtin, 'INTERVAL': tokens.Name.Builtin, 'LONG': tokens.Name.Builtin, 'NUMBER': tokens.Name.Builtin, 'NUMERIC': tokens.Name.Builtin, 'REAL': tokens.Name.Builtin, 'ROWID': tokens.Name.Builtin, 'ROWLABEL': tokens.Name.Builtin, 'ROWNUM': tokens.Name.Builtin, 'SERIAL': tokens.Name.Builtin, 'SERIAL8': tokens.Name.Builtin, 'SIGNED': tokens.Name.Builtin, 'SMALLINT': tokens.Name.Builtin, 'SYSDATE': tokens.Name.Builtin, 'TEXT': tokens.Name.Builtin, 'TINYINT': tokens.Name.Builtin, 'UNSIGNED': tokens.Name.Builtin, 'VARCHAR': tokens.Name.Builtin, 'VARCHAR2': tokens.Name.Builtin, 'VARYING': tokens.Name.Builtin, } KEYWORDS_COMMON = { 'SELECT': tokens.Keyword.DML, 'INSERT': tokens.Keyword.DML, 'DELETE': tokens.Keyword.DML, 'UPDATE': tokens.Keyword.DML, 'REPLACE': tokens.Keyword.DML, 'MERGE': tokens.Keyword.DML, 'DROP': tokens.Keyword.DDL, 'CREATE': tokens.Keyword.DDL, 'ALTER': tokens.Keyword.DDL, 'WHERE': tokens.Keyword, 'FROM': tokens.Keyword, 'INNER': tokens.Keyword, 'JOIN': tokens.Keyword.Join, 'STRAIGHT_JOIN': tokens.Keyword.Join, 'AND': tokens.Keyword, 'OR': tokens.Keyword, 'LIKE': tokens.Operator.Comparison, 'ON': tokens.Keyword, 'IN': tokens.Operator.Comparison, 'SET': tokens.Keyword, 'BY': tokens.Keyword, 'GROUP': tokens.Keyword, 'ORDER': tokens.Keyword, 'LEFT': tokens.Keyword, 'OUTER': tokens.Keyword, 'FULL': tokens.Keyword, 'IF': tokens.Keyword, 'END': tokens.Keyword, 'THEN': tokens.Keyword, 'LOOP': tokens.Keyword, 'AS': tokens.Keyword, 'ELSE': tokens.Keyword, 'FOR': tokens.Keyword, 'WHILE': tokens.Keyword, 'CASE': tokens.Keyword, 'WHEN': tokens.Keyword, 'MIN': tokens.Keyword, 'MAX': tokens.Keyword, 'DISTINCT': tokens.Keyword, } KEYWORDS_ORACLE = { 'ARCHIVE': tokens.Keyword, 'ARCHIVELOG': tokens.Keyword, 'BACKUP': tokens.Keyword, 'BECOME': tokens.Keyword, 'BLOCK': tokens.Keyword, 'BODY': tokens.Keyword, 'CANCEL': tokens.Keyword, 'CHANGE': tokens.Keyword, 'COMPILE': tokens.Keyword, 'CONTENTS': tokens.Keyword, 'CONTROLFILE': tokens.Keyword, 'DATAFILE': tokens.Keyword, 'DBA': tokens.Keyword, 'DISMOUNT': tokens.Keyword, 'DOUBLE': tokens.Keyword, 'DUMP': tokens.Keyword, 'EVENTS': tokens.Keyword, 'EXCEPTIONS': tokens.Keyword, 'EXPLAIN': tokens.Keyword, 'EXTENT': tokens.Keyword, 'EXTERNALLY': tokens.Keyword, 'FLUSH': tokens.Keyword, 'FREELIST': tokens.Keyword, 'FREELISTS': tokens.Keyword, 'GROUPS': tokens.Keyword, 'INDICATOR': tokens.Keyword, 'INITRANS': tokens.Keyword, 'INSTANCE': tokens.Keyword, 'LAYER': tokens.Keyword, 'LINK': tokens.Keyword, 'LISTS': tokens.Keyword, 'LOGFILE': tokens.Keyword, 'MANAGE': tokens.Keyword, 'MANUAL': tokens.Keyword, 'MAXDATAFILES': tokens.Keyword, 'MAXINSTANCES': tokens.Keyword, 'MAXLOGFILES': tokens.Keyword, 'MAXLOGHISTORY': tokens.Keyword, 'MAXLOGMEMBERS': tokens.Keyword, 'MAXTRANS': tokens.Keyword, 'MINEXTENTS': tokens.Keyword, 'MODULE': tokens.Keyword, 'MOUNT': tokens.Keyword, 'NOARCHIVELOG': tokens.Keyword, 'NOCACHE': tokens.Keyword, 'NOCYCLE': tokens.Keyword, 'NOMAXVALUE': tokens.Keyword, 'NOMINVALUE': tokens.Keyword, 'NOORDER': tokens.Keyword, 'NORESETLOGS': tokens.Keyword, 'NORMAL': tokens.Keyword, 'NOSORT': tokens.Keyword, 'OPTIMAL': tokens.Keyword, 'OWN': tokens.Keyword, 'PACKAGE': tokens.Keyword, 'PARALLEL': tokens.Keyword, 'PCTINCREASE': tokens.Keyword, 'PCTUSED': tokens.Keyword, 'PLAN': tokens.Keyword, 'PRIVATE': tokens.Keyword, 'PROFILE': tokens.Keyword, 'QUOTA': tokens.Keyword, 'RECOVER': tokens.Keyword, 'RESETLOGS': tokens.Keyword, 'RESTRICTED': tokens.Keyword, 'REUSE': tokens.Keyword, 'ROLES': tokens.Keyword, 'SAVEPOINT': tokens.Keyword, 'SCN': tokens.Keyword, 'SECTION': tokens.Keyword, 'SEGMENT': tokens.Keyword, 'SHARED': tokens.Keyword, 'SNAPSHOT': tokens.Keyword, 'SORT': tokens.Keyword, 'STATEMENT_ID': tokens.Keyword, 'STOP': tokens.Keyword, 'SWITCH': tokens.Keyword, 'TABLES': tokens.Keyword, 'TABLESPACE': tokens.Keyword, 'THREAD': tokens.Keyword, 'TIME': tokens.Keyword, 'TRACING': tokens.Keyword, 'TRANSACTION': tokens.Keyword, 'TRIGGERS': tokens.Keyword, 'UNLIMITED': tokens.Keyword, }
vmuriart/sqlparse
sqlparse/keywords.py
Python
bsd-3-clause
24,425
package ode_test import ( "fmt" "testing" "github.com/sj14/ode" ) // PopulationGrowthSimple Start Values var yStartPop = []float64{10} func populationGrowthSimple(t float64, y []float64) []float64 { result := make([]float64, 1) result[0] = 0.008 * y[0] return result } // SIR Start Values var yStartSIR = []float64{700, 400, 100} func sir(t float64, y []float64) []float64 { result := make([]float64, 3) result[0] = -0.0001 * y[1] * y[0] result[1] = 0.0001*y[1]*y[0] - 0.005*y[1] result[2] = 0.005 * y[1] return result } func BenchmarkEulerForwardPopulation(b *testing.B) { ode.EulerForward(0, 0.1, 10000, yStartPop, populationGrowthSimple) } func BenchmarkRungeKuttaPopulation(b *testing.B) { ode.RungeKutta4(0, 0.1, 10000, yStartPop, populationGrowthSimple) } func BenchmarkEulerForwardSIR(b *testing.B) { ode.EulerForward(0, 0.1, 10000, yStartSIR, sir) } func BenchmarkRungeKuttaSIR(b *testing.B) { ode.RungeKutta4(0, 0.1, 10000, yStartSIR, sir) } func ExampleEulerForward_population() { y := ode.EulerForward(0, 10, 100, yStartPop, populationGrowthSimple) for _, val := range y { fmt.Println(val) } // Output: // [0 10] // [10 10.8] // [20 11.664000000000001] // [30 12.597120000000002] // [40 13.604889600000002] // [50 14.693280768000001] // [60 15.868743229440001] // [70 17.138242687795202] // [80 18.50930210281882] // [90 19.990046271044324] // [100 21.58924997272787] } func ExampleEulerForward_sir() { y := ode.EulerForward(0, 10, 100, yStartSIR, sir) for _, val := range y { fmt.Println(val) } // Output: // [0 700 400 100] // [10 420 660 120] // [20 142.79999999999995 904.2 153] // [30 13.68023999999997 988.10976 198.21] // [40 0.16266133685759776 952.2218506631424 247.61548800000003] // [50 0.00777165764371518 904.7656478091992 295.2265805331572] // [60 0.0007401287811479003 859.5343969476019 340.46486292361715] // [70 0.00010396263558037628 816.5583132663673 383.44158277099723] // [80 1.9071081228138196e-05 775.7304824946034 424.2694984343156] // [90 4.277062185340778e-06 736.9439731638922 463.0560225590458] // [100 1.1251069850067054e-06 700.0967776576529 499.9032212172404] } func ExampleRungeKutta4_population() { yz := ode.RungeKutta4(0, 10, 100, yStartPop, populationGrowthSimple) for _, value := range yz { fmt.Println(value) } // Output: // [0 10] // [10 10.832870400000001] // [20 11.735108110319617] // [30 12.71249052890813] // [40 13.771276236088923] // [50 14.91824507081511] // [60 16.16074154475789] // [70 17.506721872225803] // [80 18.96480491706675] // [90 20.544327382786687] // [100 22.255403599289938] } func ExampleRungeKutta4_sir() { y := ode.RungeKutta4(0, 10, 100, yStartSIR, sir) for _, val := range y { fmt.Println(val) } // Output: // [0 700 400 100] // [10 410.90567125203955 662.4382350812937 126.65609366666666] // [20 191.97505869594923 843.2048493089754 164.82009199507524] // [30 79.86753851144415 911.0287568497188 209.10370463883703] // [40 32.32376388920436 912.7706547315336 254.90558137926206] // [50 13.263171694988241 886.7634313299168 299.973396975095] // [60 5.607931908716353 850.9501619076912 343.4419061835925] // [70 2.4571403113927808 812.5094770189563 385.03338266965085] // [80 1.1171479813071248 774.1848647682339 424.697987250459] // [90 0.5268422655752388 737.0010917960352 462.4720659383895] // [100 0.2574396186972187 701.3189883896745 498.4235719916282] }
sj14/ode
ode_test.go
GO
bsd-3-clause
3,438
// vim:filetype=java:ts=4 /* Copyright (c) 2004-2007 Conor McDermottroe. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the author nor the names of any contributors to the software may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mcdermottroe.exemplar.model; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mcdermottroe.exemplar.Copyable; import com.mcdermottroe.exemplar.DBC; import com.mcdermottroe.exemplar.Utils; import static com.mcdermottroe.exemplar.Constants.Character.LEFT_PAREN; import static com.mcdermottroe.exemplar.Constants.Character.RIGHT_PAREN; /** A class representing an XML DTD/Schema of some sort. @author Conor McDermottroe @since 0.1 */ public class XMLDocumentType implements Comparable<XMLDocumentType>, Copyable<XMLDocumentType> { /** A map of all the elements in this DTD/Schema. */ private final Map<String, XMLElement> elements; /** A map of all the attribute lists in this DTD/Schema. */ private final Map<String, XMLAttributeList> attlists; /** A map of all the entities in this DTD/Schema. */ private final Map<String, XMLEntity> entities; /** A map of all the notations in this DTD/Schema. */ private final Map<String, XMLNotation> notations; /** Make an {@link XMLDocumentType} out of a {@link Collection} of markup declarations. @param markup A {@link Collection} of markup declarations. */ public XMLDocumentType(Collection<XMLNamedObject<?>> markup) { DBC.REQUIRE(markup != null); // Allocate storage for the various hashes int markupSize = 0; if (markup != null) { markupSize = markup.size(); } attlists = new HashMap<String, XMLAttributeList>(markupSize); elements = new HashMap<String, XMLElement>(markupSize); entities = new HashMap<String, XMLEntity>(markupSize); notations = new HashMap<String, XMLNotation>(markupSize); // Go through the list of markup declarations and put the objects in // the correct hashes. if (markup != null) { for (XMLNamedObject<?> xmlObject : markup) { if (xmlObject == null) { continue; } Class<? extends XMLNamedObject> c = xmlObject.getClass(); if (XMLAttributeList.class.isAssignableFrom(c)) { attlists.put( xmlObject.getName(), XMLAttributeList.class.cast(xmlObject) ); } else if (XMLElement.class.isAssignableFrom(c)) { elements.put( xmlObject.getName(), XMLElement.class.cast(xmlObject) ); } else if (XMLEntity.class.isAssignableFrom(c)) { entities.put( xmlObject.getName(), XMLEntity.class.cast(xmlObject) ); } else if (XMLNotation.class.isAssignableFrom(c)) { notations.put( xmlObject.getName(), XMLNotation.class.cast(xmlObject) ); } } } // Associate attributes with their elements. for (String name : attlists.keySet()) { // Get the XMLAttributeList and corresponding XMLElement XMLAttributeList attlist = attlists.get(name); XMLElement element = elements.get(name); // Associate the two if (element != null) { element.setAttlist(attlist); elements.put(name, element); } } } /** Shorthand for finding out if the current document type declares any attribute lists. @return True if the document type declares attribute lists and false in every other case, including if errors occur. */ public boolean hasAttlists() { return attlists != null && !attlists.isEmpty(); } /** Accessor for elements. @return A {@link Map} (keyed on the names) of the elements declared in this {@link XMLDocumentType}. */ public Map<String, XMLElement> elements() { return new HashMap<String, XMLElement>(elements); } /** Accessor for attribute lists. @return A {@link Map} (keyed on the names) of the attribute lists declared in this {@link XMLDocumentType} */ public Map<String, XMLAttributeList> attlists() { return new HashMap<String, XMLAttributeList>(attlists); } /** Accessor for entities. @return A {@link Map} (keyed on the names) of the general entities declared in this {@link XMLDocumentType}. */ public Map<String, XMLEntity> entities() { return new HashMap<String, XMLEntity>(entities); } /** Accessor for notations. @return A {@link Map} (keyed on the names) of the notations declared in this {@link XMLDocumentType}. */ public Map<String, XMLNotation> notations() { return new HashMap<String, XMLNotation>(notations); } /** Implement {@link Comparable#compareTo(Object)}. @param other The {@link XMLDocumentType} to compare with. @return A result as defined by {@link Comparable#compareTo(Object)}. */ public int compareTo(XMLDocumentType other) { int elementsCmp = Utils.compare(elements, other.elements()); if (elementsCmp != 0) { return elementsCmp; } int attlistsCmp = Utils.compare(attlists, other.attlists()); if (attlistsCmp != 0) { return attlistsCmp; } int entitiesCmp = Utils.compare(entities, other.entities()); if (entitiesCmp != 0) { return entitiesCmp; } return Utils.compare(notations, other.notations()); } /** {@inheritDoc} */ public XMLDocumentType getCopy() { List<XMLNamedObject<?>> all; all = new ArrayList<XMLNamedObject<?>>(); all.addAll(attlists.values()); all.addAll(elements.values()); all.addAll(entities.values()); all.addAll(notations.values()); return new XMLDocumentType(all); } /** See {@link Object#equals(Object)}. @param o The object to compare against. @return True if <code>this</code> is equal to <code>o</code>. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || !(o instanceof XMLDocumentType)) { return false; } XMLDocumentType other = (XMLDocumentType)o; Object[] thisFields = { attlists, elements, entities, notations, }; Object[] otherFields = { other.attlists(), other.elements(), other.entities(), other.notations(), }; return Utils.areAllDeeplyEqual(thisFields, otherFields); } /** See {@link Object#hashCode()}. @return A hash code. */ @Override public int hashCode() { return Utils.genericHashCode(attlists, elements, entities, notations); } /** See {@link Object#toString()}. @return A descriptive {@link String}. */ @Override public String toString() { StringBuilder description = new StringBuilder(); description.append(getClass().getName()); description.append(LEFT_PAREN); description.append(hashCode()); description.append(RIGHT_PAREN); return description.toString(); } }
conormcd/exemplar
src/com/mcdermottroe/exemplar/model/XMLDocumentType.java
Java
bsd-3-clause
7,960
""" byceps.services.newsletter.types ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from enum import Enum SubscriptionState = Enum('SubscriptionState', ['requested', 'declined'])
homeworkprod/byceps
byceps/services/newsletter/types.py
Python
bsd-3-clause
271
# # Copyright 2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # CXX = g++ CPPFLAGS += -I/usr/local/include -pthread CXXFLAGS += -std=c++11 LDFLAGS += -L/usr/local/lib `pkg-config --libs grpc++ grpc` -lprotobuf -lpthread -ldl PROTOC = protoc GRPC_CPP_PLUGIN = grpc_cpp_plugin GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)` PROTOS_PATH = ../../protos vpath %.proto $(PROTOS_PATH) all: system-check greeter_client greeter_server greeter_async_client greeter_async_client2 greeter_async_server greeter_client: helloworld.pb.o helloworld.grpc.pb.o greeter_client.o $(CXX) $^ $(LDFLAGS) -o $@ greeter_server: helloworld.pb.o helloworld.grpc.pb.o greeter_server.o $(CXX) $^ $(LDFLAGS) -o $@ greeter_async_client: helloworld.pb.o helloworld.grpc.pb.o greeter_async_client.o $(CXX) $^ $(LDFLAGS) -o $@ greeter_async_client2: helloworld.pb.o helloworld.grpc.pb.o greeter_async_client2.o $(CXX) $^ $(LDFLAGS) -o $@ greeter_async_server: helloworld.pb.o helloworld.grpc.pb.o greeter_async_server.o $(CXX) $^ $(LDFLAGS) -o $@ .PRECIOUS: %.grpc.pb.cc %.grpc.pb.cc: %.proto $(PROTOC) -I $(PROTOS_PATH) --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $< .PRECIOUS: %.pb.cc %.pb.cc: %.proto $(PROTOC) -I $(PROTOS_PATH) --cpp_out=. $< clean: rm -f *.o *.pb.cc *.pb.h greeter_client greeter_server greeter_async_client greeter_async_client2 greeter_async_server # The following is to test your system and ensure a smoother experience. # They are by no means necessary to actually compile a grpc-enabled software. PROTOC_CMD = which $(PROTOC) PROTOC_CHECK_CMD = $(PROTOC) --version | grep -q libprotoc.3 PLUGIN_CHECK_CMD = which $(GRPC_CPP_PLUGIN) HAS_PROTOC = $(shell $(PROTOC_CMD) > /dev/null && echo true || echo false) ifeq ($(HAS_PROTOC),true) HAS_VALID_PROTOC = $(shell $(PROTOC_CHECK_CMD) 2> /dev/null && echo true || echo false) endif HAS_PLUGIN = $(shell $(PLUGIN_CHECK_CMD) > /dev/null && echo true || echo false) SYSTEM_OK = false ifeq ($(HAS_VALID_PROTOC),true) ifeq ($(HAS_PLUGIN),true) SYSTEM_OK = true endif endif system-check: ifneq ($(HAS_VALID_PROTOC),true) @echo " DEPENDENCY ERROR" @echo @echo "You don't have protoc 3.0.0 installed in your path." @echo "Please install Google protocol buffers 3.0.0 and its compiler." @echo "You can find it here:" @echo @echo " https://github.com/google/protobuf/releases/tag/v3.0.0-beta-2" @echo @echo "Here is what I get when trying to evaluate your version of protoc:" @echo -$(PROTOC) --version @echo @echo endif ifneq ($(HAS_PLUGIN),true) @echo " DEPENDENCY ERROR" @echo @echo "You don't have the grpc c++ protobuf plugin installed in your path." @echo "Please install grpc. You can find it here:" @echo @echo " https://github.com/grpc/grpc" @echo @echo "Here is what I get when trying to detect if you have the plugin:" @echo -which $(GRPC_CPP_PLUGIN) @echo @echo endif ifneq ($(SYSTEM_OK),true) @false endif
leifurhauks/grpc
examples/cpp/helloworld/Makefile
Makefile
bsd-3-clause
4,391
Semilla is a web presentation engine to manage software projects we developped and use at fortylines. Based on our [philosophy](https://fortylines.com/reps/whitepapers/doc/rationale.book) and [organization](https://fortylines.com/reps/whitepapers/doc/organization.book), instead of building a tower of babel made of various remote resources (repositories, wikis, issue tracking systems, etc.) and dealing with the associated IT nightmare, we keep code, documentation and todo items in a single git repository. Semilla is a straightforward presentation engine we use to navigate that information through a web browser.
djaodjin/tero
README.md
Markdown
bsd-3-clause
620
module Leadspend module Parser end end
justindossey/leadspend
lib/leadspend/parser.rb
Ruby
bsd-3-clause
43
spawn-fcgi-1.6.3 ================ spawn-fcgi-1.6.3代码小注释
kulv2012/spawn-fcgi-1.6.3
README.md
Markdown
bsd-3-clause
67
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H__ #define CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H__ #include <libudev.h> #include <string> #include "update_engine/file_descriptor.h" #include "update_engine/udev_interface.h" namespace chromeos_update_engine { // An abstract GPIO handler interface. Serves as basic for both concrete and // mock implementations. class GpioHandler { public: GpioHandler() {} virtual ~GpioHandler() {}; // ensure virtual destruction // Returns true iff GPIOs have been used to signal an automated test case. // This call may trigger a (deferred) GPIO discovery step prior to engaging in // the signaling protocol; if discovery did not reveal GPIO devices, or the // protocol has terminated prematurely, it will conservatively default to // false. virtual bool IsTestModeSignaled() = 0; private: DISALLOW_COPY_AND_ASSIGN(GpioHandler); }; // Concrete implementation of GPIO signal handling. Currently, it only utilizes // the two Chromebook-specific GPIOs (aka 'dut_flaga' and 'dut_flagb') in // deciding whether a lab test mode has been signaled. Internal logic includes // detection, setup and reading from / writing to GPIOs. Detection is done via // libudev calls. This class should be instantiated at most once to avoid race // conditions in communicating over GPIO signals; instantiating a second // object will actually cause a runtime error. class StandardGpioHandler : public GpioHandler { public: // This constructor accepts a udev interface |udev_iface| and a reusable file // descriptor |fd|. The value of |is_defer_discovery| determines whether GPIO // discovery should be attempted right away (false) or done lazily, when // necessitated by other calls (true). If |is_cache_test_mode| is true, // checking for test mode signal is done only once and further queries return // the cached result. StandardGpioHandler(UdevInterface* udev_iface, FileDescriptor* fd, bool is_defer_discovery, bool is_cache_test_mode); // Free all resources, allow to reinstantiate. virtual ~StandardGpioHandler(); // Returns true iff GPIOs have been used to signal an automated test case. The // check is performed at most once and the result is cached and returned on // subsequent calls, unless |is_force| is true. This call may trigger a // delayed GPIO discovery prior to engaging in the signaling protocol; if the // delay period has not elapsed, it will conservatively default to false. virtual bool IsTestModeSignaled(); private: // GPIO identifiers, currently includes only the two dutflags. enum GpioId { kGpioIdDutflaga = 0, kGpioIdDutflagb, kGpioIdMax // marker, do not remove! }; // GPIO direction specifier. enum GpioDir { kGpioDirIn = 0, kGpioDirOut, kGpioDirMax // marker, do not remove! }; // GPIO value. enum GpioVal { kGpioValUp = 0, kGpioValDown, kGpioValMax // marker, do not remove! }; // GPIO definition data. struct GpioDef { const char* name; // referential name of this GPIO const char* udev_property; // udev property containing the device id }; // GPIO runtime control structure. struct Gpio { std::string descriptor; // unique GPIO descriptor std::string dev_path; // sysfs device name }; // The number of seconds we wait before flipping the output signal (aka, // producing the "challenge" signal). Assuming a 1 second sampling frequency // on the servo side, a two second wait should be enough. static const int kServoOutputResponseWaitInSecs = 2; // The total number of seconds we wait for a servo response from the point we // flip the output signal. Assuming a 1 second sampling frequency on the servo // side, a two second wait should suffice. We add one more second for grace // (servod / hardware processing delays, etc). static const int kServoInputResponseTimeoutInSecs = 3; // The number of times per second we check for a servo response. Five seems // like a reasonable value. static const int kServoInputNumChecksPerSec = 5; // GPIO value/direction conversion tables. static const char* gpio_dirs_[kGpioDirMax]; static const char* gpio_vals_[kGpioValMax]; // GPIO definitions. static const GpioDef gpio_defs_[kGpioIdMax]; // Udev device enumeration helper classes. First here is an interface // definition, which provides callbacks for enumeration setup and processing. class UdevEnumHelper { public: UdevEnumHelper(StandardGpioHandler* gpio_handler) : gpio_handler_(gpio_handler) {} // Setup the enumeration filters. virtual bool SetupEnumFilters(udev_enumerate* udev_enum) = 0; // Processes an enumerated device. Returns true upon success, false // otherwise. virtual bool ProcessDev(udev_device* dev) = 0; // Finalize the enumeration. virtual bool Finalize() = 0; protected: StandardGpioHandler* gpio_handler_; private: DISALLOW_COPY_AND_ASSIGN(UdevEnumHelper); }; // Specialized udev enumerate helper for extracting GPIO descriptors from the // GPIO chip device. class GpioChipUdevEnumHelper : public UdevEnumHelper { public: GpioChipUdevEnumHelper(StandardGpioHandler* gpio_handler) : UdevEnumHelper(gpio_handler), num_gpio_chips_(0) {} virtual bool SetupEnumFilters(udev_enumerate* udev_enum); virtual bool ProcessDev(udev_device* dev); virtual bool Finalize(); private: // Records the number of times a GPIO chip has been enumerated (should not // exceed 1). int num_gpio_chips_; DISALLOW_COPY_AND_ASSIGN(GpioChipUdevEnumHelper); }; // Specialized udev enumerate helper for extracting a sysfs device path from a // GPIO device. class GpioUdevEnumHelper : public UdevEnumHelper { public: GpioUdevEnumHelper(StandardGpioHandler* gpio_handler, GpioId id) : UdevEnumHelper(gpio_handler), num_gpios_(0), id_(id) {} virtual bool SetupEnumFilters(udev_enumerate* udev_enum); virtual bool ProcessDev(udev_device* dev); virtual bool Finalize(); private: // Records the number of times a GPIO has been enumerated with a given // descriptor (should not exceed 1). int num_gpios_; // The enumerated GPIO identifier. GpioId id_; DISALLOW_COPY_AND_ASSIGN(GpioUdevEnumHelper); }; // Helper class for resetting a GPIO direction. class GpioDirResetter { public: GpioDirResetter(StandardGpioHandler* handler, GpioId id, GpioDir dir); ~GpioDirResetter(); bool do_reset() const { return do_reset_; } bool set_do_reset(bool do_reset) { return (do_reset_ = do_reset); } private: // Determines whether or not the GPIO direction should be reset to the // initial value. bool do_reset_; // The GPIO handler to use for changing the GPIO direction. StandardGpioHandler* handler_; // The GPIO identifier and initial direction. GpioId id_; GpioDir dir_; }; // An initialization helper performing udev enumeration. |enum_helper| // implements an enumeration initialization and processing methods. Returns // true upon success, false otherwise. bool InitUdevEnum(struct udev* udev, UdevEnumHelper* enum_helper); // Resets the object's flags which determine the status of test mode // signaling. void ResetTestModeSignalingFlags(); // Attempt GPIO discovery, at most once. Returns true if discovery process was // successfully completed, false otherwise. bool DiscoverGpios(); // Assigns a copy of the device name of GPIO |id| to |dev_path_p|. Assumes // initialization. Returns true upon success, false otherwise. bool GetGpioDevName(GpioId id, std::string* dev_path_p); // Open a sysfs file device |dev_name| of GPIO |id|, for either reading or // writing depending on |is_write|. Uses the internal file descriptor for // this purpose, which can be reused as long as it is closed between // successive opens. Returns true upon success, false otherwise (optionally, // with errno set accordingly). bool OpenGpioFd(GpioId id, const char* dev_name, bool is_write); // Writes a value to device |dev_name| of GPIO |id|. The index |output| is // used to index the corresponding string to be written from the list // |entries| of length |num_entries|. Returns true upon success, false // otherwise. bool SetGpio(GpioId id, const char* dev_name, const char* entries[], const int num_entries, int output); // Reads a value from device |dev_name| of GPIO |id|. The list |entries| of // length |num_entries| is used to convert the read string into an index, // which is written to |input_p|. The call will fail if the value being read // is not listed in |entries|. Returns true upon success, false otherwise. bool GetGpio(GpioId id, const char* dev_name, const char* entries[], const int num_entries, int* input_p); // Sets GPIO |id| to to operate in a given |direction|. Assumes // initialization. Returns true on success, false otherwise. bool SetGpioDirection(GpioId id, GpioDir direction); // Assigns the current direction of GPIO |id| into |direction_p|. Assumes // initialization. Returns true on success, false otherwise. bool GetGpioDirection(GpioId id, GpioDir* direction_p); // Sets the value of GPIO |id| to |value|. Assumues initialization. The GPIO // direction should be set to 'out' prior to this call. If // |is_check_direction| is true, it'll ensure that the direction is indeed // 'out' prior to attempting the write. Returns true on success, false // otherwise. bool SetGpioValue(GpioId id, GpioVal value, bool is_check_direction); // Reads the value of a GPIO |id| and stores it in |value_p|. Assumes // initialization. The GPIO direction should be set to 'in' prior to this // call. If |is_check_direction| is true, it'll ensure that the direction is // indeed 'in' prior to attempting the read. Returns true upon success, false // otherwise. bool GetGpioValue(GpioId id, GpioVal *value_p, bool is_check_direction); // Invokes the actual GPIO handshake protocol to determine whether test mode // was signaled. Returns true iff the handshake has terminated gracefully // without encountering any errors; note that a true value does *not* mean // that a test mode signal has been detected. The spec for this protocol: // https://docs.google.com/a/google.com/document/d/1DB-35ptck1wT1TYrgS5AC5Y3ALfHok-iPA7kLBw2XCI/edit bool DoTestModeSignalingProtocol(); // Dynamic counter for the number of instances this class has. Used to enforce // that no more than one instance created. Thread-unsafe. static unsigned num_instances_; // GPIO control structures. Gpio gpios_[kGpioIdMax]; // Udev interface. UdevInterface* const udev_iface_; // A file abstraction for handling GPIO devices. FileDescriptor* const fd_; // Determines whether test mode signal should be checked at most once and // cached, or reestablished on each query. const bool is_cache_test_mode_; // Indicates whether GPIO discovery was performed, and whether it's been // successful. bool is_discovery_attempted_; bool is_discovery_successful_; // Persistent state of the test mode check. bool is_first_check_; bool is_handshake_completed_; bool is_test_mode_; DISALLOW_COPY_AND_ASSIGN(StandardGpioHandler); }; // A "no-op" GPIO handler, initialized to return either test or normal mode // signal. This is useful for disabling the GPIO functionality in production // code. class NoopGpioHandler : public GpioHandler { public: // This constructor accepts a single argument, which is the value to be // returned by repeated calls to IsTestModeSignaled(). NoopGpioHandler(bool is_test_mode) : is_test_mode_(is_test_mode) {} // Returns the constant Boolean value handed to the constructor. virtual bool IsTestModeSignaled(); private: // Stores the constant value to return on subsequent test mode checks. bool is_test_mode_; DISALLOW_COPY_AND_ASSIGN(NoopGpioHandler); }; } // namespace chromeos_update_engine #endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_GPIO_HANDLER_H__
marineam/update_engine
gpio_handler.h
C
bsd-3-clause
12,396
<?php use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use frontend\assets\AppAsset; use common\widgets\Alert; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $searchModel app\models\EquiposSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Equipos'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="equipos-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Nuevo Equipo', ['create'], ['class' => 'btn btn-success']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id_equipo', 'nombre_equipo', 'clave_equipo', 'numinv', 'modelo', 'marca', 'idArea.nombre_area', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
jose122946/biomedica
frontend/views/equipos/index.php
PHP
bsd-3-clause
1,091
{% extends "base.html" %} <title>{% block title %}julian | Matta{% endblock title %}</title> {% block header %} {% endblock header %} {% block content %} <a href="/"><h3 class="top">JULIÁN MATTA</h3></a> <a href="/about"> <h3 class="top rig">ACERCA</h3> </a> <div class="container"> <div class="wrap"> <div class="example-one glitch" data-text="LA_revolucion_DE_KCOLRUD"><a href="/revolucion">LA REVOLUCIÓN DE DURLOCK</a> </div> </div> {% endblock content %}
diegoduncan21/matta
matta/templates/pages/home.html
HTML
bsd-3-clause
528
package planning.util; public class MutexSet { //no two members of the following sets will appear together public IntSet positives; public IntSet negatives; public MutexSet(int max){ positives = new IntSet(max); negatives = new IntSet(max); } public MutexSet(MutexSet other){ positives = new IntSet(other.positives); negatives= new IntSet(other.negatives); } /** * * @param facts * @return true if the facts set contains no mutex pairs, otherwise false */ public boolean isValid(IntSet facts){ return true; } public boolean isValid(IntSet positive, IntSet negative){ IntSet temp1 = new IntSet(positive); temp1.intersection(positives); IntSet temp2 = new IntSet(negative); temp2.intersection(negatives); if(!temp1.isEmpty()){ if(!temp2.isEmpty()) return false; return !temp1.isSizeGreaterThan(1); } if(!temp2.isEmpty()) return !temp2.isSizeGreaterThan(1); return true; } /** * For each fact in positive or negative, the negation of any mutex facts are added. * @param positive * @param negative * @return whether this is a valid set of facts (with at most one mutex fact) or not */ public boolean infer(IntSet positive, IntSet negative){ boolean positiveMutex = positive.intersects(positives); boolean negativeMutex = negative.intersects(negatives); if(positiveMutex && negativeMutex) return false; //two mutex facts. Invalid. if(positiveMutex){ IntSet temp = new IntSet(positive); temp.intersection(positives); int id = temp.getFirstID(); if(temp.nextID(id) != -1){ //two mutex facts in the set! return false; } positive.addAll(negatives); negative.addAll(positives); negative.remove(id); } else if(negativeMutex){ IntSet temp = new IntSet(negative); temp.intersection(negatives); int id = temp.getFirstID(); if(temp.nextID(id) != -1){ return false; } positive.addAll(negatives); negative.addAll(positives); positive.remove(id); } return true; } public boolean contains(int fact, boolean negative){ return negative ? negatives.contains(fact) : positives.contains(fact); } public boolean isSubsetOf(MutexSet set){ return positives.isSubsetOf(set.positives) && negatives.isSubsetOf(set.negatives); } public void add(int fact, boolean negative){ if(negative) negatives.add(fact); else positives.add(fact); } public void remove(int fact, boolean negative){ if(negative) negatives.remove(fact); else positives.remove(fact); } public void clear(){ positives.clear(); negatives.clear(); } public void equate(MutexSet other) { positives.equate(other.positives); negatives.equate(other.negatives); } /** * Not a singleton and not empty. * @return */ public boolean notSingleton() { if(!positives.isEmpty()){ if(!negatives.isEmpty()) return true; return positives.isSizeGreaterThan(1); } if(!negatives.isEmpty()){ return negatives.isSizeGreaterThan(1); } return false; } public String toString(){ return positives.toString()+" ~("+negatives.toString()+")"; } }
jteutenberg/Planets
planning/util/MutexSet.java
Java
bsd-3-clause
3,117
// Version: $Id$ // // // Commentary: // // // Change Log: // // // Code: #include "dtkVisualProgrammingMainWindow.h" #include <dtkLog> #include <dtkCore> #include <dtkWidgets> #include <dtkComposer> #include <QtWidgets> int main(int argc, char **argv) { #if defined (Q_OS_UNIX) setenv("QT_PLUGIN_PATH", "", 1); #endif dtkApplication *application = dtkApplication::create(argc, argv); application->setApplicationName("dtkVisualProgramming"); application->setOrganizationName("inria"); application->setOrganizationDomain("fr"); application->setApplicationVersion("1.1.3"); QCommandLineParser *parser = application->parser(); parser->setApplicationDescription("dtk visual programming."); application->initialize(); QCommandLineOption verboseOption("verbose", QCoreApplication::translate("main", "verbose plugin initialization")); if (parser->isSet(verboseOption)) { dtkComposer::extension::pluginManager().setVerboseLoading(true); } dtkComposer::node::initialize(); dtkComposer::extension::initialize(); dtkVisualProgrammingMainWindow mainwindow; mainwindow.show(); mainwindow.raise(); int status = application->exec(); return status; } // // main.cpp ends here
d-tk/dtk-visual-programming
app/main.cpp
C++
bsd-3-clause
1,260
<?php namespace app\models; use Yii; use yii\db\ActiveRecord; use yii\db\Expression; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "ctt_staticdata_sourcetypes". * * @property integer $id * @property integer $lang_id * @property string $lang * @property string $name * @property string $status * @property string $created_by * @property string $created_dtm * @property string $modified_by * @property string $modified_dtm * * @property CttJournals[] $cttJournals */ class CttStaticdataSourcetypes extends ActiveRecord { public function behaviors() { return [ 'timestamp' => [ 'class' => TimestampBehavior::className(), 'attributes' => [ ActiveRecord::EVENT_BEFORE_INSERT => ['created_dtm', 'modified_dtm'], ActiveRecord::EVENT_BEFORE_UPDATE => 'modified_dtm', ], 'value' => new Expression('NOW()'), ], ]; } /** * @inheritdoc */ public static function tableName() { return 'ctt_staticdata_sourcetypes'; } /** * @inheritdoc */ public function rules() { return [ [['id', 'lang_id'], 'required'], [['id', 'lang_id'], 'integer'], [['created_dtm', 'modified_dtm'], 'safe'], [['lang', 'name', 'created_by', 'modified_by'], 'string', 'max' => 45], [['status'], 'string', 'max' => 1] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app/backend', 'ID'), 'lang_id' => Yii::t('app/ctt_staticdata_sourcetype', 'Lang ID'), 'lang' => Yii::t('app/ctt_staticdata_sourcetype', 'Lang'), 'name' => Yii::t('app/ctt_staticdata_sourcetype', 'Name'), 'status' => Yii::t('app/backend', 'Status'), 'created_by' => Yii::t('app/backend', 'Created By'), 'created_dtm' => Yii::t('app/backend', 'Created Dtm'), 'modified_by' => Yii::t('app/backend', 'Modified By'), 'modified_dtm' => Yii::t('app/backend', 'Modified Dtm'), ]; } public function getId() { $id = ''; $data = parent::find()->where(['name' => $this->name])->one(); if (empty($data)) { $id = CttSequences::getValue('STATICDATA_SOURCETYPE_SEQ'); } else { $id = $data->id; } return $id; } /** * @return \yii\db\ActiveQuery */ public function getCttJournals() { return $this->hasMany(CttJournals::className(), ['source_type_id' => 'id']); } }
anawatom/lavandula
models/CttStaticdataSourcetypes.php
PHP
bsd-3-clause
2,722
# Copyright (c) 2017 David Sorokin <[email protected]> # # Licensed under BSD3. See the LICENSE.txt file in the root of this distribution. from simulation.aivika.modeler.results import * from simulation.aivika.modeler.util import * from simulation.aivika.modeler.experiment.base.types import * class LastValueView(BasicExperimentView): """It shows the last values in final time points.""" def __init__(self, title = None, run_title = None, descr = None, series = None): """Initializes a new instance.""" BasicExperimentView.__init__(self) self.title = title self.run_title = run_title self.descr = descr self.series = series def write(self, file, indent = ''): """Write the view definition in the file.""" file.write('defaultLastValueView') fields = {} if not (self.title is None): func = lambda file, indent: file.write(encode_str(self.title)) fields['lastValueTitle'] = func if not (self.run_title is None): func = lambda file, indent: file.write(encode_str(self.run_title)) fields['lastValueRunTitle'] = func if not (self.descr is None): func = lambda file, indent: file.write(encode_str(self.descr)) fields['lastValueDescription'] = func if not (self.series is None): func = lambda file, indent: write_sources(self.series, file, indent + ' ') fields['lastValueSeries'] = func write_record_fields(fields, file, indent + ' ')
dsorokin/aivika-modeler
simulation/aivika/modeler/experiment/base/last_value.py
Python
bsd-3-clause
1,628
#!/usr/bin/env python # -*- coding: utf-8 -*- # === haiku.builtin.constant ----------------------------------------------=== # Copyright © 2011-2012, RokuSigma Inc. and contributors. See AUTHORS for more # details. # # Some rights reserved. # # Redistribution and use in source and binary forms of the software as well as # documentation, with or without modification, are permitted provided that the # following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * The names of the copyright holders or contributors may not be used to # endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE AND DOCUMENTATION IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT # NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE AND # DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ===----------------------------------------------------------------------=== "" from haiku.builtin import builtinEnvironment from haiku.types import * __all__ = [] # ===----------------------------------------------------------------------=== _nil, _true, _false, _infinity, _empty = map(Symbol, 'nil true false infinity empty'.split()) builtinEnvironment[_nil] = Procedure( params = Tuple(), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:None, ) builtinEnvironment[_true] = Procedure( params = Tuple(), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:True, ) builtinEnvironment[_false] = Procedure( params = Tuple(), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:False, ) builtinEnvironment[_infinity] = Procedure( params = Tuple(), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:float('inf'), # FIXME ) builtinEnvironment[_empty] = Procedure( params = Tuple(), defaults = Tuple(), ellipsis = False, environment = builtinEnvironment, body = lambda eval_,env:Tuple(), ) # ===----------------------------------------------------------------------=== # End of File # ===----------------------------------------------------------------------===
maaku/haiku-lang
haiku/builtin/constant.py
Python
bsd-3-clause
3,291
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Rice University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include "ompl/control/PathControl.h" #include "ompl/geometric/PathGeometric.h" #include "ompl/base/samplers/UniformValidStateSampler.h" #include "ompl/base/OptimizationObjective.h" #include "ompl/util/Exception.h" #include "ompl/util/Console.h" #include <numeric> #include <cmath> ompl::control::PathControl::PathControl(const base::SpaceInformationPtr &si) : base::Path(si) { if (!dynamic_cast<const SpaceInformation*>(si_.get())) throw Exception("Cannot create a path with controls from a space that does not support controls"); } ompl::control::PathControl::PathControl(const PathControl &path) : base::Path(path.si_) { copyFrom(path); } ompl::geometric::PathGeometric ompl::control::PathControl::asGeometric(void) const { PathControl pc(*this); pc.interpolate(); geometric::PathGeometric pg(si_); pg.getStates().swap(pc.states_); return pg; } ompl::control::PathControl& ompl::control::PathControl::operator=(const PathControl& other) { freeMemory(); si_ = other.si_; copyFrom(other); return *this; } void ompl::control::PathControl::copyFrom(const PathControl& other) { states_.resize(other.states_.size()); controls_.resize(other.controls_.size()); for (unsigned int i = 0 ; i < states_.size() ; ++i) states_[i] = si_->cloneState(other.states_[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls_.size() ; ++i) controls_[i] = si->cloneControl(other.controls_[i]); controlDurations_ = other.controlDurations_; } double ompl::control::PathControl::length(void) const { return std::accumulate(controlDurations_.begin(), controlDurations_.end(), 0.0); } double ompl::control::PathControl::cost(const base::OptimizationObjective &objective) const { double L = 0.0; for (unsigned int i = 1 ; i < states_.size() ; ++i) L = objective.combineObjectiveCosts(L, objective.getIncrementalCost(states_[i-1], states_[i])); if (!states_.empty()) L += objective.getTerminalCost(states_.back()); return L; } void ompl::control::PathControl::print(std::ostream &out) const { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); out << "Control path with " << states_.size() << " states" << std::endl; for (unsigned int i = 0 ; i < controls_.size() ; ++i) { out << "At state "; si_->printState(states_[i], out); out << " apply control "; si->printControl(controls_[i], out); out << " for " << (int)floor(0.5 + controlDurations_[i]/res) << " steps" << std::endl; } out << "Arrive at state "; si_->printState(states_[controls_.size()], out); out << std::endl; } void ompl::control::PathControl::interpolate(void) { if (states_.size() <= controls_.size()) { logError("Interpolation not performed. Number of states in the path should be strictly greater than the number of controls."); return; } const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); std::vector<base::State*> newStates; std::vector<Control*> newControls; std::vector<double> newControlDurations; double res = si->getPropagationStepSize(); for (unsigned int i = 0 ; i < controls_.size() ; ++i) { int steps = (int)floor(0.5 + controlDurations_[i] / res); assert(steps >= 0); if (steps <= 1) { newStates.push_back(states_[i]); newControls.push_back(controls_[i]); newControlDurations.push_back(controlDurations_[i]); continue; } std::vector<base::State*> istates; si->propagate(states_[i], controls_[i], steps, istates, true); // last state is already in the non-interpolated path if (!istates.empty()) { si_->freeState(istates.back()); istates.pop_back(); } newStates.push_back(states_[i]); newStates.insert(newStates.end(), istates.begin(), istates.end()); newControls.push_back(controls_[i]); newControlDurations.push_back(res); for (int j = 1 ; j < steps; ++j) { newControls.push_back(si->cloneControl(controls_[i])); newControlDurations.push_back(res); } } newStates.push_back(states_[controls_.size()]); states_.swap(newStates); controls_.swap(newControls); controlDurations_.swap(newControlDurations); } bool ompl::control::PathControl::check(void) const { if (controls_.empty()) { if (states_.size() == 1) return si_->isValid(states_[0]); else return false; } bool valid = true; const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); double res = si->getPropagationStepSize(); base::State *dummy = si_->allocState(); for (unsigned int i = 0 ; valid && i < controls_.size() ; ++i) { unsigned int steps = (unsigned int)floor(0.5 + controlDurations_[i] / res); if (!si->isValid(states_[i]) || si->propagateWhileValid(states_[i], controls_[i], steps, dummy) != steps) valid = false; } si_->freeState(dummy); return valid; } void ompl::control::PathControl::append(const base::State *state) { states_.push_back(si_->cloneState(state)); } void ompl::control::PathControl::append(const base::State *state, const Control *control, double duration) { const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states_.push_back(si->cloneState(state)); controls_.push_back(si->cloneControl(control)); controlDurations_.push_back(duration); } void ompl::control::PathControl::random(void) { freeMemory(); states_.resize(2); controlDurations_.resize(1); controls_.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states_[0] = si->allocState(); states_[1] = si->allocState(); controls_[0] = si->allocControl(); base::StateSamplerPtr ss = si->allocStateSampler(); ss->sampleUniform(states_[0]); ControlSamplerPtr cs = si->allocControlSampler(); cs->sample(controls_[0], states_[0]); unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); controlDurations_[0] = steps * si->getPropagationStepSize(); si->propagate(states_[0], controls_[0], steps, states_[1]); } bool ompl::control::PathControl::randomValid(unsigned int attempts) { freeMemory(); states_.resize(2); controlDurations_.resize(1); controls_.resize(1); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); states_[0] = si->allocState(); states_[1] = si->allocState(); controls_[0] = si->allocControl(); ControlSamplerPtr cs = si->allocControlSampler(); base::UniformValidStateSampler *uvss = new base::UniformValidStateSampler(si); uvss->setNrAttempts(attempts); bool ok = false; for (unsigned int i = 0 ; i < attempts ; ++i) if (uvss->sample(states_[0])) { cs->sample(controls_[0], states_[0]); unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration()); controlDurations_[0] = steps * si->getPropagationStepSize(); if (si->propagateWhileValid(states_[0], controls_[0], steps, states_[1]) == steps) { ok = true; break; } } delete uvss; if (!ok) { freeMemory(); states_.clear(); controls_.clear(); controlDurations_.clear(); } return ok; } void ompl::control::PathControl::freeMemory(void) { for (unsigned int i = 0 ; i < states_.size() ; ++i) si_->freeState(states_[i]); const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get()); for (unsigned int i = 0 ; i < controls_.size() ; ++i) si->freeControl(controls_[i]); }
davetcoleman/ompl-release
src/ompl/control/src/PathControl.cpp
C++
bsd-3-clause
9,898
/*L Copyright SAIC Distributed under the OSI-approved BSD 3-Clause License. See http://ncip.github.com/cabio/LICENSE.txt for details. L*/ create index ZSTG_PIDTION_INTERACTIO on ZSTG_PID_PATHWAY_INTERACTION(INTERACTION_ID) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT; create index ZSTG_PIDTION_PATHWAY_ID on ZSTG_PID_PATHWAY_INTERACTION(PATHWAY_ID) PARALLEL NOLOGGING tablespace CABIO_MAP_FUT; --EXIT;
NCIP/cabio
software/cabio-database/scripts/sql_loader/no_longer_used/indexes/zstg_pid_pathway_interaction.cols.sql
SQL
bsd-3-clause
425
LegGCharts =========== > **Note:** GoogleChartsImage tool is now deprecated. I will probably change the library to generate > images using another way, but for the moment, you should not use it. [![Build Status](https://travis-ci.org/tgalopin/LegGoogleCharts.png?branch=master)](https://travis-ci.org/tgalopin/LegGoogleCharts) What is LegGCharts ? --------------------- LegGCharts is a library for the PHP 5.3.2+. It provides a set of classes to generate charts using Google Charts Image. > **Note:** This library does *not* create images alone : it use GoogleChartsImage tool. > Therefore you can not display charts without an active internet connection. Documentation ------------- The documentation is stored in the `doc` directory of this library: [Read the Documentation](doc) Installation ------------ All the installation instructions are located in [documentation](doc). License ------- See the license in the bundle: [LICENSE](LICENSE.md) About ----- The LegGCharts library is developped mainly by Titouan Galopin. Reporting an issue or a feature request --------------------------------------- Issues and feature requests are tracked in the [Github issue tracker](issues).
outspaced/LegGoogleCharts
README.md
Markdown
bsd-3-clause
1,198
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.repositories.scope.internal; import androidx.annotation.NonNull; import com.google.auto.value.AutoValue; @AutoValue public abstract class RepositoryScopeFilterItem { @NonNull public abstract String key(); @NonNull public abstract FilterItemOperator operator(); @NonNull public abstract String value(); public static Builder builder() { return new AutoValue_RepositoryScopeFilterItem.Builder(); } @AutoValue.Builder public abstract static class Builder { public abstract Builder key(String key); public abstract Builder operator(FilterItemOperator operator); public abstract Builder value(String value); public abstract RepositoryScopeFilterItem build(); } }
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/arch/repositories/scope/internal/RepositoryScopeFilterItem.java
Java
bsd-3-clause
2,374
<?php namespace Message\Service; use Message\Entity\MessageEntity; use Message\Mapper\MessageMapperInterface; use Workorder\Entity\WorkorderEntity; use Employee\Entity\EmployeeEntity; use User\Entity\UserEntity; class MessageService implements MessageServiceInterface { /** * * @var MessageMapperInterface */ protected $mapper; /** * * @param MessageMapperInterface $mapper */ public function __construct(MessageMapperInterface $mapper) { $this->mapper = $mapper; } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::getAll() */ public function getAll($filter) { return $this->mapper->getAll($filter); } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::get() */ public function get($id) { return $this->mapper->get($id); } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::save() */ public function save(MessageEntity $entity) { return $this->mapper->save($entity); } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::saveEmployeeWorkorder() */ public function saveEmployeeWorkorder(WorkorderEntity $workorderEntity, EmployeeEntity $employeeEntity) { $entity = new MessageEntity(); $messageBody = ""; $entity->setMessageToEmail($employeeEntity->getEmployeeEmail()); $entity->setMessageToName($employeeEntity->getEmployeeName()); $entity->setMessageDate(time()); $entity->setMessageSubject('New work order created #' . $workorderEntity->getWorkorderId()); $entity->setMessageBody($messageBody); $entity = $this->save($entity); return $entity; } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::saveUserWorkorder() */ public function saveUserWorkorder(WorkorderEntity $workorderEntity, UserEntity $userEntity) { $entity = new MessageEntity(); $messageBody = ""; $entity->setMessageToEmail($userEntity->getUserEmail()); $entity->setMessageToName($userEntity->getUserNameFirst() . ' ' . $userEntity->getUserNameLast()); $entity->setMessageDate(time()); $entity->setMessageSubject('New work order created #' . $workorderEntity->getWorkorderId()); $entity->setMessageBody($messageBody); $entity = $this->save($entity); return $entity; } /** * * {@inheritDoc} * * @see \Message\Service\MessageServiceInterface::delete() */ public function delete(MessageEntity $entity) { return $this->mapper->delete($entity); } }
pacificnm/pnm
module/Message/src/Message/Service/MessageService.php
PHP
bsd-3-clause
2,900
from .excitation import Excitation class ExcitationRain(Excitation): """ Rain on the roof excitation """ @property def power(self): raise NotImplementedError
FRidh/seapy
seapy/excitations/excitationrain.py
Python
bsd-3-clause
189
/** * Reusable style properties are defined here */ 'use strict'; export let AppStyle = { Colors: { FG: "#e73b3b", BG: "#efefef", THIRD: "#555" }, Dimensions: { NAVIGATION_TEXT: "12px", VIEW_TITLE: "20px", VIEW_SUBTITLE: "16px" } }; export let ComponentsStyle = { ProgressIndicator: { size: 80, borderWidth: 0, color: 'rgba(150, 150, 150, 1)', unfilledColor: 'rgba(200, 200, 200, 0.2)' } };
tiranacode/jap-jete-app
src/Styles/CommonStyles.js
JavaScript
bsd-3-clause
498
<!doctype html> <!-- @license Copyright (c) 2015 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt --> <html lang="en"> <head> <meta charset="utf-8"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="generator" content="Polymer Starter Kit"> <title>Polymer Starter Kit</title> <!-- Place favicon.ico in the `app/` directory --> <!-- Chrome for Android theme color --> <meta name="theme-color" content="#2E3AA1"> <!-- Web Application Manifest --> <link rel="manifest" href="manifest.json"> <!-- Tile color for Win8 --> <meta name="msapplication-TileColor" content="#3372DF"> <!-- Add to homescreen for Chrome on Android --> <meta name="mobile-web-app-capable" content="yes"> <meta name="application-name" content="PSK"> <link rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png"> <link rel="stylesheet" type="text/css" src="../../typeahead.js/typeahead.css"> <!-- Add to homescreen for Safari on iOS --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="Polymer Starter Kit"> <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png"> <!-- Tile icon for Win8 (144x144) --> <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png"> <!-- build:css styles/main.css --> <link rel="stylesheet" href="styles/main.css"> <!-- endbuild--> <!-- build:js bower_components/webcomponentsjs/webcomponents-lite.min.js --> <script src="bower_components/webcomponentsjs/webcomponents-lite.js"></script> <!-- endbuild --> <script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js'></script> <script src="typeahead.js/typeahead.bundle.min.js"></script> <script src="typeahead.js/typeahead.jquery.js"></script> <!-- Because this project uses vulcanize this should be your only html import in this file. All other imports should go in elements.html --> <link rel="import" href="elements/elements.html"> <!-- For shared styles, shared-styles.html import in elements.html --> <style is="custom-style" include="shared-styles"></style> </head> <body unresolved> <span id="browser-sync-binding"></span> <template is="dom-bind" id="app"> <paper-drawer-panel id="paperDrawerPanel"> <!-- Drawer Scroll Header Panel --> <paper-scroll-header-panel drawer fixed> <!-- Drawer Toolbar --> <paper-toolbar id="drawerToolbar"> <span class="menu-name">Menu</span> </paper-toolbar> <!-- Drawer Content --> <paper-menu attr-for-selected="data-route" selected="[[route]]"> <a data-route="home" href="{{baseUrl}}"> <iron-icon icon="home"></iron-icon> <span>Home</span> </a> <a data-route="users" href="{{baseUrl}}users"> <iron-icon icon="info"></iron-icon> <span>Users</span> </a> <a data-route="contact" href="{{baseUrl}}contact"> <iron-icon icon="mail"></iron-icon> <span>Contact</span> </a> </paper-menu> </paper-scroll-header-panel> <!-- Main Area --> <paper-scroll-header-panel main id="headerPanelMain" condenses keep-condensed-header> <!-- Main Toolbar --> <paper-toolbar id="mainToolbar" class="tall"> <paper-icon-button id="paperToggle" icon="menu" paper-drawer-toggle></paper-icon-button> <span class="space"></span> <!-- Toolbar icons --> <paper-icon-button icon="refresh"></paper-icon-button> <a data-route="users" href="{{baseUrl}}users" style="text-decorations:none; color:inherit;"> <paper-icon-button icon="add"></paper-icon-button> </a> <!-- Application name --> <div class="middle middle-container"> <div class="app-name">Mon Terroir</div> </div> <!-- Application sub title --> <div class="bottom bottom-container"> <div class="bottom-title">L'essentiel de votre terroir en 1 clic!</div> </div> </paper-toolbar> <!-- Main Content --> <div class="content"> <iron-pages attr-for-selected="data-route" selected="{{route}}"> <section data-route="home"> <paper-material elevation="1"> <terroir-name></terroir-name> </paper-material> <paper-material elevation="1"> <terroir-temperature></terroir-temperature> </paper-material> <paper-material elevation="1"> <google-map style="height: 400px" latitude="37.77493" longitude="-122.41942"></google-map> </paper-material> <paper-material elevation="1"> <terroir-rain></terroir-rain> </paper-material> <paper-material elevation="1"> <terroir-wind></terroir-wind> </paper-material> <paper-material elevation="1"> <terroir-water></terroir-water> </paper-material> </section> <section data-route="users"> <paper-material elevation="=1"> <search-bar></search-bar> </paper-material> </section> <section data-route="user-info"> <paper-material elevation="1"> <h2 class="page-title">User: {{params.name}}</h2> <div>This is {{params.name}}'s section</div> </paper-material> </section> <section data-route="contact"> <paper-material elevation="1"> <h2 class="page-title">Contact</h2> <p>This is the contact section</p> </paper-material> </section> </iron-pages> </div> </paper-scroll-header-panel> </paper-drawer-panel> <paper-toast id="toast"> <span class="toast-hide-button" role="button" tabindex="0" onclick="app.$.toast.hide()">Ok</span> </paper-toast> <!-- Uncomment next block to enable Service Worker support (1/2) --> <!-- <paper-toast id="caching-complete" duration="6000" text="Caching complete! This app will work offline."> </paper-toast> <platinum-sw-register auto-register clients-claim skip-waiting base-uri="bower_components/platinum-sw/bootstrap" on-service-worker-installed="displayInstalledToast"> <platinum-sw-cache default-cache-strategy="fastest" cache-config-file="cache-config.json"> </platinum-sw-cache> </platinum-sw-register> --> </template> <!-- build:js scripts/app.js --> <script src="scripts/app.js"></script> <!-- endbuild--> </body> </html>
sirinainblack/test
app/index.html
HTML
bsd-3-clause
7,531
/* * Copyright (c) 2013, 2014, Pyhrol, [email protected] * GEO: N55.703431,E37.623324 .. N48.742359,E44.536997 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the Pyhrol nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <iostream> #include <pyhrol.h> void function_manipulate_objects(pyhrol::Tuples &_args) { PyObject *parg, *pres = NULL; PYHROL_PARSE_TUPLE_1(NULL, _args, parg) PYHROL_AFTER_PARSE_TUPLE(_args) PYHROL_BUILD_VALUE_1(NULL, _args, pres) PYHROL_AFTER_BUILD_VALUE(_args) std::cout << __func__ << ": I am called\n" << " Arg type is: \"" << parg->ob_type->tp_name << "\"\n" ; pres = PyString_FromString(parg->ob_type->tp_name); PYHROL_AFTER_EXECUTE_DEFAULT(_args) } static void __attribute__ ((constructor)) __on_load() { PYHROL_REGISTER_FUNCTION(function_manipulate_objects, "Function takes any PyObject as argument and returns object type name") }
dyomas/pyhrol
examples/example_0080.cpp
C++
bsd-3-clause
2,337
package org.grassroot.android.fragments; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.grassroot.android.R; import org.grassroot.android.adapters.JoinRequestAdapter; import org.grassroot.android.events.JoinRequestEvent; import org.grassroot.android.fragments.dialogs.NetworkErrorDialogFragment; import org.grassroot.android.interfaces.GroupConstants; import org.grassroot.android.models.GroupJoinRequest; import org.grassroot.android.services.ApplicationLoader; import org.grassroot.android.services.GcmListenerService; import org.grassroot.android.services.GroupSearchService; import org.grassroot.android.services.GroupService; import org.grassroot.android.utils.ErrorUtils; import org.grassroot.android.utils.NetworkUtils; import org.grassroot.android.utils.rxutils.SingleObserverFromConsumer; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; import io.reactivex.SingleObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; /** * Created by luke on 2016/07/14. */ public class JoinRequestListFragment extends Fragment implements JoinRequestAdapter.JoinRequestClickListener { private static final String TAG = JoinRequestListFragment.class.getSimpleName(); private JoinRequestAdapter adapter; private String type; @BindView(R.id.jreq_swipe_refresh) SwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.jreq_recycler_view) RecyclerView recyclerView; @BindView(R.id.jreq_no_requests) TextView noRequestsMessage; @BindView(R.id.progressBar) ProgressBar progressBar; Unbinder unbinder; public static JoinRequestListFragment newInstance(final String type) { JoinRequestListFragment fragment = new JoinRequestListFragment(); Bundle args = new Bundle(); args.putString("type", type); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); EventBus.getDefault().register(this); type = getArguments().getString("type"); if (!GroupJoinRequest.SENT_REQUEST.equals(type) && !GroupJoinRequest.REC_REQUEST.equals(type)) { type = GroupJoinRequest.SENT_REQUEST; // default to sent if request is malformed } adapter = new JoinRequestAdapter(context, type, this); } @Override public void backgroundCallComplete() { selectMessageOrList(); } @Override public void positiveClicked(GroupJoinRequest request, int position) { if (GroupJoinRequest.SENT_REQUEST.equals(request.getJoinReqType())) { remindAboutJoinRequest(request.getGroupUid()); } else { respondToJoinRequest(GroupConstants.APPROVE_JOIN_REQUEST, request.getRequestUid(), position); } } @Override public void negativeClicked(final GroupJoinRequest request, final int position) { if (GroupJoinRequest.SENT_REQUEST.equals(request.getJoinReqType())) { new AlertDialog.Builder(getContext()) .setMessage(R.string.jreq_cancel_confirm) .setCancelable(true) .setPositiveButton(R.string.alert_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { cancelJoinRequest(request.getGroupUid(), position); } }) .show(); } else { respondToJoinRequest(GroupConstants.DENY_JOIN_REQUEST, request.getRequestUid(), position); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_join_request_list, container, false); unbinder = ButterKnife.bind(this, view); noRequestsMessage.setText(type.equals(GroupJoinRequest.SENT_REQUEST) ? R.string.jreq_no_requests_sent : R.string.jreq_no_requests); GcmListenerService.clearJoinRequestNotifications(getActivity()); setUpRecyclerView(); return view; } private void setUpRecyclerView() { recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(adapter); recyclerView.setItemAnimator(null); swipeRefreshLayout.setColorSchemeColors(ContextCompat.getColor(getActivity(), R.color.primaryColor)); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshJoinRequests(); } }); } private void selectMessageOrList() { if (adapter.getItemCount() == 0) { switchToEmptyList(); } else { switchToShownList(); } } private void switchToEmptyList() { if (recyclerView != null) { recyclerView.setVisibility(View.GONE); noRequestsMessage.setVisibility(View.VISIBLE); } } private void switchToShownList() { if (recyclerView != null) { recyclerView.setVisibility(View.VISIBLE); noRequestsMessage.setVisibility(View.GONE); } } protected void refreshJoinRequests() { swipeRefreshLayout.setRefreshing(true); GroupService.getInstance().fetchGroupJoinRequests(AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(@NonNull String s) { switch (s) { case NetworkUtils.FETCHED_SERVER: adapter.refreshList(); EventBus.getDefault().post(new JoinRequestEvent(TAG)); break; case NetworkUtils.OFFLINE_SELECTED: NetworkErrorDialogFragment.newInstance(R.string.connect_error_jreqs_offline, progressBar, goOnlineSubscriber()); break; case NetworkUtils.CONNECT_ERROR: ErrorUtils.networkErrorSnackbar(swipeRefreshLayout, R.string.connect_error_jreqs_list, new View.OnClickListener() { @Override public void onClick(View v) { refreshJoinRequests(); } }); break; case NetworkUtils.SERVER_ERROR: Snackbar.make(swipeRefreshLayout, R.string.server_error_general, Snackbar.LENGTH_SHORT).show(); } hideProgess(); } }); } private SingleObserver<String> goOnlineSubscriber() { return new SingleObserverFromConsumer<>(new Consumer<String>() { @Override public void accept(@NonNull String s) throws Exception { progressBar.setVisibility(View.GONE); if (s.equals(NetworkUtils.SERVER_ERROR)) { Snackbar.make(swipeRefreshLayout, R.string.connect_error_failed_retry, Snackbar.LENGTH_SHORT).show(); } else { refreshJoinRequests(); } } }); } private void respondToJoinRequest(final String approvedOrDenied, final String requestUid, final int position) { showProgress(); GroupService.getInstance().respondToJoinRequest(approvedOrDenied, requestUid, AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(@NonNull String s) { adapter.clearRequest(position); hideProgess(); int snackMsg = approvedOrDenied.equals(GroupConstants.APPROVE_JOIN_REQUEST) ? R.string.jreq_approved : R.string.jreq_denied; Toast.makeText(ApplicationLoader.applicationContext, snackMsg, Toast.LENGTH_SHORT).show(); selectMessageOrList(); EventBus.getDefault().post(new JoinRequestEvent(TAG)); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable e) { hideProgess(); if (NetworkUtils.CONNECT_ERROR.equals(e.getMessage())) { Snackbar.make(swipeRefreshLayout, R.string.jreq_response_connect_error, Snackbar.LENGTH_SHORT).show(); } else { Snackbar.make(swipeRefreshLayout, ErrorUtils.serverErrorText(e), Snackbar.LENGTH_SHORT).show(); } } }); } private void remindAboutJoinRequest(final String groupUid) { progressBar.setVisibility(View.VISIBLE); GroupSearchService.getInstance().remindJoinRequest(groupUid, AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(@NonNull String s) { progressBar.setVisibility(View.GONE); Toast.makeText(ApplicationLoader.applicationContext, R.string.gs_req_remind, Toast.LENGTH_SHORT).show(); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable e) { progressBar.setVisibility(View.GONE); if (NetworkUtils.CONNECT_ERROR.equals(e.getMessage())) { final String errorMsg = getString(R.string.gs_req_remind_cancelled_connect_error); Snackbar.make(swipeRefreshLayout, errorMsg, Snackbar.LENGTH_SHORT).show(); } else { Snackbar.make(swipeRefreshLayout, ErrorUtils.serverErrorText(e), Snackbar.LENGTH_LONG).show(); } } }); } private void cancelJoinRequest(final String groupUid, final int position) { progressBar.setVisibility(View.VISIBLE); GroupSearchService.getInstance().cancelJoinRequest(groupUid, AndroidSchedulers.mainThread()) .subscribe(new Consumer<String>() { @Override public void accept(String s) { progressBar.setVisibility(View.GONE); Toast.makeText(ApplicationLoader.applicationContext, R.string.gs_req_cancelled, Toast.LENGTH_SHORT).show(); adapter.clearRequest(position); selectMessageOrList(); EventBus.getDefault().post(new JoinRequestEvent(TAG)); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable e) { progressBar.setVisibility(View.GONE); if (NetworkUtils.CONNECT_ERROR.equals(e.getMessage())) { final String errorMsg = getString(R.string.gs_req_remind_cancelled_connect_error); Snackbar.make(swipeRefreshLayout, errorMsg, Snackbar.LENGTH_SHORT).show(); } else { Snackbar.make(swipeRefreshLayout, ErrorUtils.serverErrorText(e), Snackbar.LENGTH_LONG).show(); } } }); } @Subscribe(threadMode = ThreadMode.MAIN) public void groupJoinRequestReceived(JoinRequestEvent e) { if (!TAG.equals(e.getTAG())) { adapter.refreshList(); } } private void showProgress() { progressBar.setVisibility(View.VISIBLE); } private void hideProgess() { // callbacks might happen after view destroyed if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(false); } if (progressBar != null) { progressBar.setVisibility(View.GONE); } } @Override public void onDestroyView() { super.onDestroyView(); EventBus.getDefault().unregister(this); unbinder.unbind(); } }
grassrootza/grassroot-android
app/src/main/java/org/grassroot/android/fragments/JoinRequestListFragment.java
Java
bsd-3-clause
13,183
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\User */ $this->title = $model->nome; $this->params['breadcrumbs'][] = ['label' => 'Users', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Editar'; ?> <div class="user-update"> <h1><?= Html::encode($this->title) ?></h1> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
charleycesar/Sistema-ERP-Yii
views/users/update.php
PHP
bsd-3-clause
495
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>File: reader.rb [nokogiri-1.4.4.1-x86-mingw32 Documentation]</title> <link type="text/css" media="screen" href="../../../rdoc.css" rel="stylesheet" /> <script src="../../../js/jquery.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/thickbox-compressed.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/quicksearch.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/darkfish.js" type="text/javascript" charset="utf-8"></script> </head> <body class="file file-popup"> <div id="metadata"> <dl> <dt class="modified-date">Last Modified</dt> <dd class="modified-date">2011-05-24 13:26:34 +1000</dd> <dt class="requires">Requires</dt> <dd class="requires"> <ul> </ul> </dd> </dl> </div> <div id="documentation"> <div class="description"> <h2>Description</h2> </div> </div> </body> </html>
MitjaBezensek/shouldly
lib/gems/doc/nokogiri-1.4.4.1-x86-mingw32/rdoc/lib/nokogiri/xml/reader_rb.html
HTML
bsd-3-clause
1,257
<?php namespace Users\Factory\Storage; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\Authentication\AuthenticationService; use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter; class AuthenticationServiceFactory implements FactoryInterface { public function createService(ServiceLocatorInterface $serviceLocator) { $dbAdapter = $serviceLocator->get('Zend\Db\Adapter\Adapter'); $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'usuario', 'usuario', 'clave'); $select = $dbTableAuthAdapter->getDbSelect(); $select->where('estado = "1"'); $authService = new AuthenticationService($serviceLocator->get('AuthStorage'), $dbTableAuthAdapter); return $authService; } }
zirtrex/asistencia_uisrael
module/Users/src/Users/Factory/Storage/AuthenticationServiceFactory.php
PHP
bsd-3-clause
852
<?php namespace app\modules\basket; class Basket extends \yii\base\Module { public $controllerNamespace = 'app\modules\basket\controllers'; public function init() { parent::init(); // custom initialization code goes here } }
kd-brinex/kd
modules/basket/Basket.php
PHP
bsd-3-clause
266
#!/bin/bash dist/build/bftserver/bftserver -d -p public_keys.txt -c client_public_keys.txt -k private_keys/10002.txt -s 10002 10001 10000 10003
chrisnc/tangaroa
bft2.sh
Shell
bsd-3-clause
145
#!/bin/sh java -jar /srv/fedora-working/saxon/saxon.jar \ -o /srv/fedora-working/ingest/VIC/item/mods/003018898.xml \ /srv/fedora-working/ingest/VIC/item/marcXML/003018898.xml \ /srv/fedora-working/xslt/ingest/MARC21slim2MODS3-4.xsl java -jar /srv/fedora-working/saxon/saxon.jar \ -o /srv/fedora-working/ingest/VIC/item/mods/003018899.xml \ /srv/fedora-working/ingest/VIC/item/marcXML/003018899.xml \ /srv/fedora-working/xslt/ingest/MARC21slim2MODS3-4.xsl java -jar /srv/fedora-working/saxon/saxon.jar \ -o /srv/fedora-working/ingest/VIC/item/mods/003018900.xml \ /srv/fedora-working/ingest/VIC/item/marcXML/003018900.xml \ /srv/fedora-working/xslt/ingest/MARC21slim2MODS3-4.xsl
duke-libraries/batch-ingest
VIC/110itemmodscreate.sh
Shell
bsd-3-clause
754
/* module : rollup.c version : 1.10 date : 01/19/20 */ #ifndef ROLLUP_C #define ROLLUP_C /** rollup : X Y Z -> Z X Y Moves X and Y up, moves Z down. */ void do_rollup(void) { intptr_t temp; TERNARY; temp = stack[-1]; stack[-1] = stack[-2]; stack[-2] = stack[-3]; stack[-3] = temp; } #endif
Wodan58/Coy
src/rollup.c
C
bsd-3-clause
336
# BlackBox3 This is a system for hosting task-based CTFs. It was first used for hosting School CTF by SiBears team in 2015 (http://school-ctf.org/) and is currently in clean-up mode. ## Installation Instructions This section describes the process of deploying BlackBox3 for devlopment purposes. The production setup steps are to be written later. The instructions given here are tested on Ubuntu 14.04. You may need to adjust them for your OS. ### Step 1. Install Required Ubuntu Packages * python2.7 * python-pip * git * redis-server * postgresql * libpq-dev TODO: complete the list of packages, including all the libraries. You may use this command to install the packages: ```bash $ sudo apt-get install python2.7 python-pip git redis-server postgresql libpq-dev ... ``` Optionally you may install these packages that are extremely useful for debugging and maintenance: * redis-tools TODO: add more packages here. ### Step 2. Clone BlackBox3 Repository You need to obtain the latest code from the project repository: ```bash $ git clone https://github.com/stefantsov/blackbox3.git $ cd blackbox3 ``` ### Step 3. Install Python Packages The recommended way to install the required python packages is using *virtualenv* utility that itself may be installed globally using *pip* package manager: ```bash $ sudo pip install virtualenv ``` Now, create the virtual environment and install the packages: ```bash $ virtualenv ../bb3-env $ source ../bb3-env/bin/activate (bb3-env)$ pip install -r requirements.txt ``` ### Step 4. Install NodeJS Utilities BlackBox3 uses some utilities from NodeJS, for example *less* and *yuglify*. One of the ways of obtaining those is described here. First, download the archive that matches your OS from [this](https://nodejs.org/en/download/) page. Let's assume it is `node-v4.1.2-linux-x64.tar.gz`. Unpack the archive, and copy its contents to the virtual environment folder. ```bash (bb3-env)$ wget -P /tmp/ https://nodejs.org/dist/v4.1.2/node-v4.1.2-linux-x64.tar.gz (bb3-env)$ tar xvzf /tmp/node-v4.1.2-linux-x64.tar.gz -C /tmp (bb3-env)$ rsync -a /tmp/node-v4.1.2-linux-x64/* ../bb3-env ``` You may check if these steps were successful by issuing the following command: ```bash (bb3-env)$ which npm ``` It should print out the full path to the npm utility. Now that the npm installation utility for NodeJS packages is available to you, install *less* and *yuglify*. ```bash (bb3-env)$ npm install -g less yuglify ``` ### Step 5. Create Local Settings File BlackBox3 uses multiple-file settings setup. The core settings are in `settings/base.py` file, and you aren't supposed to make changes there. Everything specific to your installation should go to `settings/local.py` file. To create one you may start with copying `settings/local_example.py` file to `settings/local.py` and making changes there. ```bash (bb3-env)$ cp settings/local_example.py settings/local.py (bb3-env)$ vim settings/local.py ``` Basically, you want to change the following: * `SECRET_KEY` to any random string, * entries in `DATABASES` dictionary (see further the instructions on database setup), * `EMAIL_HOST`, `EMAIL_HOST_USER`, `EMAIL_HOST_PASSWORD`, and `EMAIL_USE_TLS` if you plan to send emails, or `EMAIL_BACKEND` if you want to change the mailing behavior, * uncomment `WSGI_APPLICATION` for development purposes. ### Step 6. Setup Database If you have the PostgreSQL package installed, you may use the following to create the database user and the database for your BlackBox3 installation. ```bash (bb3-env)$ sudo su - postgres $ createuser -D -E -R -P -S blackbox3 # it will ask for a password $ createdb -E utf8 -O blackbox3 blackbox3 $ exit ``` Now you can use `blackbox3` as the value for `NAME` and `USER` fields in the `DATABASES` dictionary (see Step 5) and the entered password as the value of `PASSWORD` field. You may also need to change the value of `HOST` from `127.0.0.1` to `localhost` depending on your PostgreSQL settings. If everything was setup properly, you may now initialize the database tables: ```bash (bb3-env)$ python manage.py migrate ``` Finally, you want at least one `Game` object in your database. Here is how you create it. ```bash (bb3-env)$ python manage.py shell_plus ... >>> Game.objects.create() >>> exit() ``` ### Step 7. Running BlackBox3 Everything is ready for the first launch of your BlackBox3 installation! For this you need two consoles: one is to run the Django project, and another is to run celery. Make sure your Redis is already running (it's true if you're using Ubuntu, and just installed redis-server package). In the first console type this: ```bash (bb3-env)$ python manage runserver ``` In the second console type this: ```bash (bb3-env)$ celery -A slr1 worker -l info ``` If everything was ok, you may now access http://localhost:8000/ with your browser and see the brand new empty BlackBox3 page! ## Contribution TODO: write about branching model, versioning, testing, etc. ## Contacts Please, email [email protected] if you have any questions of suggestions.
stefantsov/blackbox3
README.md
Markdown
bsd-3-clause
5,098
/**************************************************************************** * * Program: dir.c * Author: Marc van Kempen * desc: Directory routines, sorting and reading * * Copyright (c) 1995, Marc van Kempen * * All rights reserved. * * This software may be used, modified, copied, distributed, and * sold, in both source and binary form provided that the above * copyright and these terms are retained, verbatim, as the first * lines of this file. Under no circumstances is the author * responsible for the proper functioning of this software, nor does * the author assume any responsibility for damages incurred with * its use. * ****************************************************************************/ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> /* XXX for _POSIX_VERSION ifdefs */ #if !defined sgi && !defined _POSIX_VERSION #include <sys/dir.h> #endif #if defined __sun__ #include <sys/dirent.h> #endif #if defined sgi || defined _POSIX_VERSION #include <dirent.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fnmatch.h> #include <sys/param.h> #include "dir.h" /**************************************************************************** * * local prototypes * ****************************************************************************/ void toggle_dotfiles(void); int show_dotfiles(void); int dir_alphasort(const void *d1, const void *d2); int dir_sizesort(const void *d1, const void *d2); int dir_datesort(const void *d1, const void *d2); int dir_extsort(const void *d1, const void *d2); /**************************************************************************** * * global variables * ****************************************************************************/ /* This is user-selectable, I've set them fixed for now however */ void *_sort_func = dir_alphasort; static int _showdotfiles = TRUE; /**************************************************************************** * * Functions * ****************************************************************************/ int dir_select_nd( #if defined __linux__ const struct dirent *d #else struct dirent *d #endif ) /* * desc: allways include a directory entry <d>, except * for the current directory and other dot-files * keep '..' however. * pre: <d> points to a dirent * post: returns TRUE if d->d_name != "." else FALSE */ { if (strcmp(d->d_name, ".")==0 || (d->d_name[0] == '.' && strlen(d->d_name) > 1 && d->d_name[1] != '.')) { return(FALSE); } else { return(TRUE); } }/* dir_select_nd() */ int dir_select( #ifdef __linux__ const struct dirent *d #else struct dirent *d #endif ) /* * desc: allways include a directory entry <d>, except * for the current directory * pre: <d> points to a dirent * post: returns TRUE if d->d_name != "." else FALSE */ { if (strcmp(d->d_name, ".")==0) { /* don't include the current directory */ return(FALSE); } else { return(TRUE); } } /* dir_select() */ int dir_select_root_nd( #ifdef __linux__ const struct dirent *d #else struct dirent *d #endif ) /* * desc: allways include a directory entry <d>, except * for the current directory and the parent directory. * Also skip any other dot-files. * pre: <d> points to a dirent * post: returns TRUE if d->d_name[0] != "." else FALSE */ { if (d->d_name[0] == '.') { /* don't include the current directory */ return(FALSE); /* nor the parent directory */ } else { return(TRUE); } } /* dir_select_root_nd() */ int dir_select_root( #ifdef __linux__ const struct dirent *d #else struct dirent *d #endif ) /* * desc: allways include a directory entry <d>, except * for the current directory and the parent directory * pre: <d> points to a dirent * post: returns TRUE if d->d_name[0] != "." else FALSE */ { if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) { return(FALSE); } else { return(TRUE); } }/* dir_select_root() */ #ifdef NO_ALPHA_SORT int alphasort(const void *d1, const void *d2) /* * desc: a replacement for what should be in the library */ { return(strcmp(((struct dirent *) d1)->d_name, ((struct dirent *) d2)->d_name)); } /* alphasort() */ #endif int dir_alphasort(const void *d1, const void *d2) /* * desc: compare d1 and d2, but put directories always first * put '..' always on top * */ { DirList *f1 = ((DirList *) d1), *f2 = ((DirList *) d2); struct stat *s1 = &(f1->filestatus); struct stat *s2 = &(f2->filestatus); /* check for '..' */ if (strcmp(((DirList *) d1)->filename, "..") == 0) { return(-1); } if (strcmp(((DirList *) d2)->filename, "..") == 0) { return(1); } /* put directories first */ if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) { return(strcmp(f1->filename, f2->filename)); }; if (s1->st_mode & S_IFDIR) { return(-1); } if (s2->st_mode & S_IFDIR) { return(1); } return(strcmp(f1->filename, f2->filename)); } /* dir_alphasort() */ int dir_sizesort(const void *d1, const void *d2) /* * desc: compare d1 and d2, but put directories always first * */ { DirList *f1 = ((DirList *) d1), *f2 = ((DirList *) d2); struct stat *s1 = &(f1->filestatus); struct stat *s2 = &(f2->filestatus); /* check for '..' */ if (strcmp(((DirList *) d1)->filename, "..") == 0) { return(-1); } if (strcmp(((DirList *) d2)->filename, "..") == 0) { return(1); } /* put directories first */ if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) { return(s1->st_size < s2->st_size ? -1 : s1->st_size >= s2->st_size); }; if (s1->st_mode & S_IFDIR) { return(-1); } if (s2->st_mode & S_IFDIR) { return(1); } return(s1->st_size < s2->st_size ? -1 : s1->st_size >= s2->st_size); } /* dir_sizesort() */ int dir_datesort(const void *d1, const void *d2) /* * desc: compare d1 and d2 on date, but put directories always first */ { DirList *f1 = ((DirList *) d1), *f2 = ((DirList *) d2); struct stat *s1 = &(f1->filestatus); struct stat *s2 = &(f2->filestatus); /* check for '..' */ if (strcmp(((DirList *) d1)->filename, "..") == 0) { return(-1); } if (strcmp(((DirList *) d2)->filename, "..") == 0) { return(1); } /* put directories first */ if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) { return(s1->st_mtime < s2->st_mtime ? -1 : s1->st_mtime >= s2->st_mtime); }; if (s1->st_mode & S_IFDIR) { return(-1); } if (s2->st_mode & S_IFDIR) { return(1); } return(s1->st_mtime < s2->st_mtime ? -1 : s1->st_mtime >= s2->st_mtime); } /* dir_datesort() */ int null_strcmp(char *s1, char *s2) /* * desc: compare strings allowing NULL pointers */ { if ((s1 == NULL) && (s2 == NULL)) { return(0); } if (s1 == NULL) { return(-1); } if (s2 == NULL) { return(1); } return(strcmp(s1, s2)); } /* null_strcmp() */ int dir_extsort(const void *d1, const void *d2) /* * desc: compare d1 and d2 on extension, but put directories always first * extension = "the characters after the last dot in the filename" * pre: d1 and d2 are pointers to DirList type records * post: see code */ { DirList *f1 = ((DirList *) d1), *f2 = ((DirList *) d2); struct stat *s1 = &(f1->filestatus); struct stat *s2 = &(f2->filestatus); char *ext1, *ext2; int extf, ret; /* check for '..' */ if (strcmp(((DirList *) d1)->filename, "..") == 0) { return(-1); } if (strcmp(((DirList *) d2)->filename, "..") == 0) { return(1); } /* find the first extension */ ext1 = f1->filename + strlen(f1->filename); extf = FALSE; while (!extf && (ext1 > f1->filename)) { extf = (*--ext1 == '.'); } if (!extf) { ext1 = NULL; } else { ext1++; } /* ext1 == NULL if there's no "extension" else ext1 points */ /* to the first character of the extension string */ /* find the second extension */ ext2 = f2->filename + strlen(f2->filename); extf = FALSE; while (!extf && (ext2 > f2->filename)) { extf = (*--ext2 == '.'); } if (!extf) { ext2 = NULL; } else { ext2++; } /* idem as for ext1 */ if ((s1->st_mode & S_IFDIR) && (s2->st_mode & S_IFDIR)) { ret = null_strcmp(ext1, ext2); if (ret == 0) { return(strcmp(f1->filename, f2->filename)); } else { return(ret); } }; if (s1->st_mode & S_IFDIR) { return(-1); } if (s2->st_mode & S_IFDIR) { return(1); } ret = null_strcmp(ext1, ext2); if (ret == 0) { return(strcmp(f1->filename, f2->filename)); } else { return(ret); } } /* dir_extsort() */ void get_dir(char *dirname, char *fmask, DirList **dir, int *n) /* * desc: get the files in the current directory * pre: <dir> == NULL * post: <dir> contains <n> dir-entries */ { char cwd[MAXPATHLEN]; char buf[256]; struct dirent **dire; struct stat status; int i, j, nb; long d; getcwd(cwd, MAXPATHLEN); if (strcmp(cwd, "/") == 0) { /* we are in the root directory */ if (show_dotfiles()) { *n = scandir(dirname, &dire, dir_select_root, alphasort); } else { *n = scandir(dirname, &dire, dir_select_root_nd, alphasort); } } else { if (show_dotfiles()) { *n = scandir(dirname, &dire, dir_select, alphasort); } else { *n = scandir(dirname, &dire, dir_select_nd, alphasort); } } /* There is the possibility that we have entered a directory */ /* which we are not allowed to read, scandir thus returning */ /* -1 for *n. */ /* Actually I should also check for lack of memory, but I'll */ /* let my application happily crash if this is the case */ /* Solution: */ /* manually insert the parent directory as the only */ /* directory entry, and return. */ if (*n == -1) { *n = 1; *dir = (DirList *) malloc(sizeof(DirList)); strcpy((*dir)[0].filename, ".."); lstat("..", &status); (*dir)[0].filestatus = status; (*dir)[0].link = FALSE; return; } *dir = (DirList *) malloc( *n * sizeof(DirList) ); d = 0; i = 0; j = 0; while (j<*n) { lstat(dire[j]->d_name, &status); /* check if this file is to be included */ /* always include directories, the rest is subject to fmask */ if (S_ISDIR(status.st_mode) || fnmatch(fmask, dire[j]->d_name, FNM_NOESCAPE) != FNM_NOMATCH) { strcpy((*dir)[i].filename, dire[j]->d_name); (*dir)[i].filestatus = status; if ((S_IFMT & status.st_mode) == S_IFLNK) { /* handle links */ (*dir)[i].link = TRUE; stat(dire[j]->d_name, &status); nb = readlink(dire[j]->d_name, buf, 256); if (nb == -1) { printf("get_dir(): Error reading link: %s\n", dire[j]->d_name); exit(-1); } else { (*dir)[i].linkname = malloc(sizeof(char) * nb + 1); strncpy((*dir)[i].linkname, buf, nb); (*dir)[i].linkname[nb] = 0; } (*dir)[i].filestatus = status; } else { (*dir)[i].link = FALSE; (*dir)[i].linkname = NULL; } i++; } else { /* skip this entry */ } j++; } *n = i; /* sort the directory with the directory names on top */ qsort((*dir), *n, sizeof(DirList), _sort_func); /* Free the allocated memory */ for (i=0; i<*n; i++) { free(dire[i]); } free(dire); return; }/* get_dir() */ void FreeDir(DirList *d, int n) /* * desc: free the dirlist d * pre: d != NULL * post: memory allocated to d has been released */ { int i; if (d) { for (i=0; i<n; i++) { if (d[i].linkname) { free(d[i].linkname); } } free(d); } else { printf("dir.c:FreeDir(): d == NULL\n"); exit(-1); } return; } /* FreeDir() */ void toggle_dotfiles(void) /* * desc: toggle visibility of dot-files */ { _showdotfiles = !_showdotfiles; return; } /* toggle_dotfiles() */ int show_dotfiles(void) /* * desc: return the value of _showdotfiles */ { return(_showdotfiles); } /* show_dotfiles() */ void set_dotfiles(int b) /* * desc: set the value of _showdotfiles */ { _showdotfiles = b; return; } /* set_dotfiles() */
MarginC/kame
freebsd2/release/libdialog_wc/dir.c
C
bsd-3-clause
12,166
<?php namespace Authorization; use Zend\Mvc\MvcEvent, Zend\Mvc\Router\RouteMatch; use Authorization\Service\AuthorizationService; use Zend\View\Model\ViewModel; class Module { public function onBootstrap(MvcEvent $e) { $events = $e->getApplication()->getEventManager(); $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'dispatchErrorListener')); $events->attach('route', array($this, 'checkAcl')); } public function checkAcl(MvcEvent $e) { $app = $e->getApplication(); $sm = $app->getServiceManager(); /** @var AuthorizationService $aclService */ $service = $sm->get('Authorization\Service\Authorization'); /** @var RouteMatch $routeMatch */ $routeMatch = $e->getRouteMatch(); $resource = $routeMatch->getParam('controller'); $privilege = $routeMatch->getParam('action'); if($service->hasResource($resource)) { if(!$service->hasAccess($resource, $privilege)) { $e->setError('ACCESS_DENIED') ->setParam('route', $routeMatch->getMatchedRouteName()); $app->getEventManager()->trigger('dispatch.error', $e); } } } public function dispatchErrorListener(MvcEvent $e) { $error = $e->getError(); if(empty($error) || $error != 'ACCESS_DENIED') { return; } $result = $e->getResult(); if($result instanceof \Zend\Stdlib\Response) { return; } $baseModel = new ViewModel(); $baseModel->setTemplate('layout/layout'); $model = new ViewModel(); $model->setTemplate('error/403'); $baseModel->addChild($model); $baseModel->setTerminal(true); $e->setViewModel($baseModel); $response = $e->getResponse(); $response->setStatusCode(403); $e->setResponse($response); $e->setResult($baseModel); return false; } public function getConfig() { return include __DIR__ . '/config/module.config.php'; } public function getAutoloaderConfig() { return array( 'Zend\Loader\StandardAutoloader' => array( 'namespaces' => array( __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__ ) ) ); } }
vikramraj87/refgen3
module/Authorization/Module.php
PHP
bsd-3-clause
2,394
package com.atlassian.plugin.servlet.descriptors; import com.atlassian.plugin.module.PrefixDelegatingModuleFactory; import com.atlassian.plugin.module.PrefixModuleFactory; import com.atlassian.plugin.servlet.filter.FilterDispatcherCondition; import junit.framework.TestCase; import org.dom4j.Element; import org.dom4j.dom.DOMElement; import com.atlassian.plugin.Plugin; import com.atlassian.plugin.PluginParseException; import com.atlassian.plugin.impl.StaticPlugin; import com.atlassian.plugin.servlet.ServletModuleManager; import com.atlassian.plugin.servlet.filter.FilterLocation; import com.atlassian.plugin.servlet.filter.FilterTestUtils.FilterAdapter; import com.mockobjects.dynamic.Mock; import java.util.Collections; public class TestServletFilterModuleDescriptor extends TestCase { ServletFilterModuleDescriptor descriptor; @Override public void setUp() { descriptor = new ServletFilterModuleDescriptor ( new PrefixDelegatingModuleFactory(Collections.<PrefixModuleFactory>emptySet()), (ServletModuleManager) new Mock(ServletModuleManager.class).proxy()); } @Override public void tearDown() { descriptor = null; } public void testInit() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = getValidConfig(); descriptor.init(plugin, e); assertEquals(FilterLocation.BEFORE_DISPATCH, descriptor.getLocation()); assertEquals(100, descriptor.getWeight()); } private Element getValidConfig() { Element e = new DOMElement("servlet-filter"); e.addAttribute("key", "key2"); e.addAttribute("class", FilterAdapter.class.getName()); Element url = new DOMElement("url-pattern"); url.setText("/foo"); e.add(url); Element dispatcher1 = new DOMElement("dispatcher"); dispatcher1.setText("REQUEST"); e.add(dispatcher1); Element dispatcher2 = new DOMElement("dispatcher"); dispatcher2.setText("FORWARD"); e.add(dispatcher2); return e; } public void testInitWithNoUrlPattern() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = new DOMElement("servlet-filter"); e.addAttribute("key", "key2"); e.addAttribute("class", FilterAdapter.class.getName()); try { descriptor.init(plugin, e); fail("Should have thrown exception"); } catch (PluginParseException ex) { // very good } } public void testInitWithDetails() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = getValidConfig(); e.addAttribute("location", "after-encoding"); e.addAttribute("weight", "122"); descriptor.init(plugin, e); assertEquals(FilterLocation.AFTER_ENCODING, descriptor.getLocation()); assertEquals(122, descriptor.getWeight()); assertTrue(descriptor.getDispatcherConditions().contains(FilterDispatcherCondition.REQUEST)); assertTrue(descriptor.getDispatcherConditions().contains(FilterDispatcherCondition.FORWARD)); } public void testInitWithBadLocation() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = getValidConfig(); e.addAttribute("location", "t23op"); try { descriptor.init(plugin, e); fail("Should have thrown exception"); } catch (PluginParseException ex) { // very good } } public void testInitWithBadWeight() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = getValidConfig(); e.addAttribute("weight", "t23op"); try { descriptor.init(plugin, e); fail("Should have thrown exception"); } catch (PluginParseException ex) { // very good } } public void testInitWithBadDispatcher() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = getValidConfig(); Element badDispatcher = new DOMElement("dispatcher"); badDispatcher.setText("badValue"); e.add(badDispatcher); try { descriptor.init(plugin, e); fail("Should have thrown exception"); } catch (PluginParseException ex) { // very good } } public void testWithNoDispatcher() { Plugin plugin = new StaticPlugin(); plugin.setKey("somekey"); Element e = new DOMElement("servlet-filter"); e.addAttribute("key", "key2"); e.addAttribute("class", FilterAdapter.class.getName()); Element url = new DOMElement("url-pattern"); url.setText("/foo"); e.add(url); descriptor.init(plugin, e); } }
mrdon/PLUG
atlassian-plugins-servlet/src/test/java/com/atlassian/plugin/servlet/descriptors/TestServletFilterModuleDescriptor.java
Java
bsd-3-clause
5,025
"""Use Python datetime module to handle date and time columns.""" # datetime is only in Python 2.3 or newer, so it is safe to use # string methods. from time import localtime from datetime import date, datetime, time, timedelta Date = date Time = time TimeDelta = timedelta Timestamp = datetime DateTimeDeltaType = timedelta DateTimeType = datetime def DateFromTicks(ticks): """Convert UNIX ticks into a date instance.""" return date(*localtime(ticks)[:3]) def TimeFromTicks(ticks): """Convert UNIX ticks into a time instance.""" return time(*localtime(ticks)[3:6]) def TimestampFromTicks(ticks): """Convert UNIX ticks into a datetime instance.""" return datetime(*localtime(ticks)[:6]) format_TIME = format_DATE = str def format_TIMESTAMP(d): return d.strftime("%Y-%m-%d %H:%M:%S") def DateTime_or_None(s): if ' ' in s: sep = ' ' elif 'T' in s: sep = 'T' else: return Date_or_None(s) try: d, t = s.split(sep, 1) return datetime(*[ int(x) for x in d.split('-')+t.split(':') ]) except: return Date_or_None(s) def TimeDelta_or_None(s): from math import modf try: h, m, s = s.split(':') td = timedelta(hours=int(h), minutes=int(m), seconds=int(s), microseconds=int(modf(float(s))[0])*1000000) if h < 0: return -td else: return td except: return None def Time_or_None(s): from math import modf try: h, m, s = s.split(':') return time(hour=int(h), minute=int(m), second=int(s), microsecond=int(modf(float(s))[0])*1000000) except: return None def Date_or_None(s): try: return date(*[ int(x) for x in s.split('-',2)]) except: return None
mattduan/proof
driver/mysql/pytimes.py
Python
bsd-3-clause
1,805
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkColorPriv.h" #include "SkImageDecoder.h" #include "SkPixelRef.h" #include "SkScaledBitmapSampler.h" #include "SkStream.h" #include "SkStreamPriv.h" #include "SkTypes.h" #include "ktx.h" #include "etc1.h" ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// // KTX Image decoder // --- // KTX is a general texture data storage file format ratified by the Khronos Group. As an // overview, a KTX file contains all of the appropriate values needed to fully specify a // texture in an OpenGL application, including the use of compressed data. // // This decoder is meant to be used with an SkDiscardablePixelRef so that GPU backends // can sniff the data before creating a texture. If they encounter a compressed format // that they understand, they can then upload the data directly to the GPU. Otherwise, // they will decode the data into a format that Skia supports. class SkKTXImageDecoder : public SkImageDecoder { public: SkKTXImageDecoder() { } virtual Format getFormat() const SK_OVERRIDE { return kKTX_Format; } protected: virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode) SK_OVERRIDE; private: typedef SkImageDecoder INHERITED; }; bool SkKTXImageDecoder::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) { // TODO: Implement SkStream::copyToData() that's cheap for memory and file streams SkAutoDataUnref data(SkCopyStreamToData(stream)); if (NULL == data) { return false; } SkKTXFile ktxFile(data); if (!ktxFile.valid()) { return false; } const unsigned short width = ktxFile.width(); const unsigned short height = ktxFile.height(); #ifdef SK_SUPPORT_LEGACY_IMAGEDECODER_CHOOSER // should we allow the Chooser (if present) to pick a config for us??? if (!this->chooseFromOneChoice(kN32_SkColorType, width, height)) { return false; } #endif // Set a flag if our source is premultiplied alpha const SkString premulKey("KTXPremultipliedAlpha"); const bool bSrcIsPremul = ktxFile.getValueForKey(premulKey) == SkString("True"); // Setup the sampler... SkScaledBitmapSampler sampler(width, height, this->getSampleSize()); // Determine the alpha of the bitmap... SkAlphaType alphaType = kOpaque_SkAlphaType; if (ktxFile.isRGBA8()) { if (this->getRequireUnpremultipliedColors()) { alphaType = kUnpremul_SkAlphaType; // If the client wants unpremul colors and we only have // premul, then we cannot honor their wish. if (bSrcIsPremul) { return false; } } else { alphaType = kPremul_SkAlphaType; } } // Set the config... bm->setInfo(SkImageInfo::MakeN32(sampler.scaledWidth(), sampler.scaledHeight(), alphaType)); if (SkImageDecoder::kDecodeBounds_Mode == mode) { return true; } // If we've made it this far, then we know how to grok the data. if (!this->allocPixelRef(bm, NULL)) { return false; } // Lock the pixels, since we're about to write to them... SkAutoLockPixels alp(*bm); if (ktxFile.isETC1()) { if (!sampler.begin(bm, SkScaledBitmapSampler::kRGB, *this)) { return false; } // ETC1 Data is encoded as RGB pixels, so we should extract it as such int nPixels = width * height; SkAutoMalloc outRGBData(nPixels * 3); etc1_byte *outRGBDataPtr = reinterpret_cast<etc1_byte *>(outRGBData.get()); // Decode ETC1 const etc1_byte *buf = reinterpret_cast<const etc1_byte *>(ktxFile.pixelData()); if (etc1_decode_image(buf, outRGBDataPtr, width, height, 3, width*3)) { return false; } // Set each of the pixels... const int srcRowBytes = width * 3; const int dstHeight = sampler.scaledHeight(); const uint8_t *srcRow = reinterpret_cast<uint8_t *>(outRGBDataPtr); srcRow += sampler.srcY0() * srcRowBytes; for (int y = 0; y < dstHeight; ++y) { sampler.next(srcRow); srcRow += sampler.srcDY() * srcRowBytes; } return true; } else if (ktxFile.isRGB8()) { // Uncompressed RGB data (without alpha) if (!sampler.begin(bm, SkScaledBitmapSampler::kRGB, *this)) { return false; } // Just need to read RGB pixels const int srcRowBytes = width * 3; const int dstHeight = sampler.scaledHeight(); const uint8_t *srcRow = reinterpret_cast<const uint8_t *>(ktxFile.pixelData()); srcRow += sampler.srcY0() * srcRowBytes; for (int y = 0; y < dstHeight; ++y) { sampler.next(srcRow); srcRow += sampler.srcDY() * srcRowBytes; } return true; } else if (ktxFile.isRGBA8()) { // Uncompressed RGBA data // If we know that the image contains premultiplied alpha, then // we need to turn off the premultiplier SkScaledBitmapSampler::Options opts (*this); if (bSrcIsPremul) { SkASSERT(bm->alphaType() == kPremul_SkAlphaType); SkASSERT(!this->getRequireUnpremultipliedColors()); opts.fPremultiplyAlpha = false; } if (!sampler.begin(bm, SkScaledBitmapSampler::kRGBA, opts)) { return false; } // Just need to read RGBA pixels const int srcRowBytes = width * 4; const int dstHeight = sampler.scaledHeight(); const uint8_t *srcRow = reinterpret_cast<const uint8_t *>(ktxFile.pixelData()); srcRow += sampler.srcY0() * srcRowBytes; for (int y = 0; y < dstHeight; ++y) { sampler.next(srcRow); srcRow += sampler.srcDY() * srcRowBytes; } return true; } return false; } /////////////////////////////////////////////////////////////////////////////// // KTX Image Encoder // // This encoder takes a best guess at how to encode the bitmap passed to it. If // there is an installed discardable pixel ref with existing PKM data, then we // will repurpose the existing ETC1 data into a KTX file. If the data contains // KTX data, then we simply return a copy of the same data. For all other files, // the underlying KTX library tries to do its best to encode the appropriate // data specified by the bitmap based on the config. (i.e. kAlpha8_Config will // be represented as a full resolution 8-bit image dump with the appropriate // OpenGL defines in the header). class SkKTXImageEncoder : public SkImageEncoder { protected: virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality) SK_OVERRIDE; private: virtual bool encodePKM(SkWStream* stream, const SkData *data); typedef SkImageEncoder INHERITED; }; bool SkKTXImageEncoder::onEncode(SkWStream* stream, const SkBitmap& bitmap, int) { if (!bitmap.pixelRef()) { return false; } SkAutoDataUnref data(bitmap.pixelRef()->refEncodedData()); // Is this even encoded data? if (NULL != data) { const uint8_t *bytes = data->bytes(); if (etc1_pkm_is_valid(bytes)) { return this->encodePKM(stream, data); } // Is it a KTX file?? if (SkKTXFile::is_ktx(bytes)) { return stream->write(bytes, data->size()); } // If it's neither a KTX nor a PKM, then we need to // get at the actual pixels, so fall through and decompress... } return SkKTXFile::WriteBitmapToKTX(stream, bitmap); } bool SkKTXImageEncoder::encodePKM(SkWStream* stream, const SkData *data) { const uint8_t* bytes = data->bytes(); SkASSERT(etc1_pkm_is_valid(bytes)); etc1_uint32 width = etc1_pkm_get_width(bytes); etc1_uint32 height = etc1_pkm_get_height(bytes); // ETC1 Data is stored as compressed 4x4 pixel blocks, so we must make sure // that our dimensions are valid. if (width == 0 || (width & 3) != 0 || height == 0 || (height & 3) != 0) { return false; } // Advance pointer to etc1 data. bytes += ETC_PKM_HEADER_SIZE; return SkKTXFile::WriteETC1ToKTX(stream, bytes, width, height); } ///////////////////////////////////////////////////////////////////////////////////////// DEFINE_DECODER_CREATOR(KTXImageDecoder); DEFINE_ENCODER_CREATOR(KTXImageEncoder); ///////////////////////////////////////////////////////////////////////////////////////// static SkImageDecoder* sk_libktx_dfactory(SkStreamRewindable* stream) { if (SkKTXFile::is_ktx(stream)) { return SkNEW(SkKTXImageDecoder); } return NULL; } static SkImageDecoder::Format get_format_ktx(SkStreamRewindable* stream) { if (SkKTXFile::is_ktx(stream)) { return SkImageDecoder::kKTX_Format; } return SkImageDecoder::kUnknown_Format; } SkImageEncoder* sk_libktx_efactory(SkImageEncoder::Type t) { return (SkImageEncoder::kKTX_Type == t) ? SkNEW(SkKTXImageEncoder) : NULL; } static SkImageDecoder_DecodeReg gReg(sk_libktx_dfactory); static SkImageDecoder_FormatReg gFormatReg(get_format_ktx); static SkImageEncoder_EncodeReg gEReg(sk_libktx_efactory);
zhangyongfei/StudySkia
src/images/SkImageDecoder_ktx.cpp
C++
bsd-3-clause
9,415
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions described in the aforementioned license. The license # is also available online at http://www.enthought.com/licenses/BSD.txt # Thanks for using Enthought open source! # # Author: Enthought, Inc. # Description: <Enthought pyface package component> #------------------------------------------------------------------------------ """A VTK interactor scene widget for the PyFace wxPython backend. See the class docs for more details. """ # Author: Prabhu Ramachandran <[email protected]> # Copyright (c) 2004-2008, Enthought, Inc. # License: BSD Style. import sys import os import tempfile import wx from tvtk.api import tvtk from tvtk import messenger from traits.api import Instance, Button, Any, Bool from traitsui.api import View, Group, Item, InstanceEditor from pyface.api import Widget, GUI, FileDialog, OK from tvtk.pyface import picker from tvtk.pyface import light_manager from tvtk.pyface.tvtk_scene import TVTKScene from .wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor ###################################################################### # Utility functions. ###################################################################### def popup_save(parent=None): """Popup a dialog asking for an image name to save the scene to. This is used mainly to save a scene in full screen mode. Returns a filename, returns empty string if action was cancelled. `parent` is the parent widget over which the dialog will be popped up. """ extns = ['*.png', '*.jpg', '*.jpeg', '*.tiff', '*.bmp', '*.ps', '*.eps', '*.tex', '*.rib', '*.wrl', '*.oogl', '*.pdf', '*.vrml', '*.obj', '*.iv'] wildcard='|'.join(extns) dialog = FileDialog( parent = parent, title='Save scene to image', action='save as', wildcard=wildcard ) if dialog.open() == OK: return dialog.path else: return '' ###################################################################### # `FullScreen` class. ###################################################################### class FullScreen(object): """Creates a full screen interactor widget. This will use VTK's event loop until the user presses 'q'/'e' on the full screen window. This does not yet support interacting with any widgets on the renderered scene. This class is really meant to be used for VTK versions earlier than 5.1 where there was a bug with reparenting a window. """ def __init__(self, scene): self.scene = scene self.old_rw = scene.render_window self.ren = scene.renderer def run(self): # Remove the renderer from the current render window. self.old_rw.remove_renderer(self.ren) # Creates renderwindow tha should be used ONLY for # visualization in full screen full_rw = tvtk.RenderWindow(stereo_capable_window=True, full_screen=True ) # add the current visualization full_rw.add_renderer(self.ren) # Under OS X there is no support for creating a full screen # window so we set the size of the window here. if sys.platform == 'darwin': full_rw.size = tuple(wx.GetDisplaySize()) # provides a simple interactor style = tvtk.InteractorStyleTrackballCamera() self.iren = tvtk.RenderWindowInteractor(render_window=full_rw, interactor_style=style) # Gets parameters for stereo visualization if self.old_rw.stereo_render: full_rw.set(stereo_type=self.old_rw.stereo_type, stereo_render=True) # Starts the interactor self.iren.initialize() self.iren.render() self.iren.start() # Once the full screen window is quit this releases the # renderer before it is destroyed, and return it to the main # renderwindow. full_rw.remove_renderer(self.ren) self.old_rw.add_renderer(self.ren) self.old_rw.render() self.iren.disable() ###################################################################### # `PopupScene` class. ###################################################################### class PopupScene(object): """Pops up a Scene instance with an independent `wx.Frame` in order to produce either a standalone window or usually a full screen view with *complete* interactivity (including widget interaction). """ def __init__(self, scene): self.orig_parent = None self.orig_size = None self.orig_pos = None self.frame = None self.scene = scene self.vtk_control = self.scene._vtk_control def _setup_frame(self): vtk_control = self.vtk_control self.orig_parent = vtk_control.GetParent() self.orig_size = vtk_control.GetSize() self.orig_pos = vtk_control.GetPosition() f = self.frame = wx.Frame(None, -1) return f def reparent_vtk(self, widget): """Reparent VTK control to another widget. """ scene = self.scene vc = self.vtk_control # We want to disable any rendering at this time so we override # the original render with a dummy after saving it. orig_disable_render = scene.disable_render scene.disable_render = True orig_render = vc.Render vc.Render = lambda : None rw = vc.GetRenderWindow() if sys.platform != 'darwin' and wx.Platform != '__WXMSW__': rw.SetNextWindowInfo(str(widget.GetHandle())) rw.WindowRemap() vc.Reparent(widget) wx.GetApp().Yield(True) # Restore the original render. vc.Render = orig_render vc.Render() scene.disable_render = orig_disable_render def popup(self, size=None): """Create a popup window of scene and set its default size. """ vc = self.vtk_control f = self._setup_frame() if size is None: f.SetSize(vc.GetSize()) else: f.SetSize(size) f.Show(True) self.reparent_vtk(f) def fullscreen(self): """Create a popup window of scene. """ f = self._setup_frame() f.Show(True) self.reparent_vtk(f) f.ShowFullScreen(True) def close(self): """Close the window and reparent the TVTK scene. """ f = self.frame if f is None: return vc = self.vtk_control self.reparent_vtk(self.orig_parent) vc.SetSize(self.orig_size) vc.SetPosition(self.orig_pos) f.ShowFullScreen(False) f.Show(False) f.Close() self.frame = None ###################################################################### # `Scene` class. ###################################################################### class Scene(TVTKScene, Widget): """A VTK interactor scene widget for pyface and wxPython. This widget uses a RenderWindowInteractor and therefore supports interaction with VTK widgets. The widget uses TVTK. In addition to the features that the base TVTKScene provides this widget supports: - saving the rendered scene to the clipboard. - picking data on screen. Press 'p' or 'P' when the mouse is over a point that you need to pick. - The widget also uses a light manager to manage the lighting of the scene. Press 'l' or 'L' to activate a GUI configuration dialog for the lights. - Pressing the left, right, up and down arrow let you rotate the camera in those directions. When shift-arrow is pressed then the camera is panned. Pressing the '+' (or '=') and '-' keys let you zoom in and out. - Pressing the 'f' key will set the camera focal point to the current point. - full screen rendering via the full_screen button on the UI. """ # The version of this class. Used for persistence. __version__ = 0 ########################################################################### # Traits. ########################################################################### # Turn on full-screen rendering. full_screen = Button('Full Screen') # The picker handles pick events. picker = Instance(picker.Picker) ######################################## # Render_window's view. _stereo_view = Group(Item(name='stereo_render'), Item(name='stereo_type'), show_border=True, label='Stereo rendering', ) # The default view of this object. default_view = View(Group( Group(Item(name='background'), Item(name='foreground'), Item(name='parallel_projection'), Item(name='disable_render'), Item(name='off_screen_rendering'), Item(name='jpeg_quality'), Item(name='jpeg_progressive'), Item(name='magnification'), Item(name='anti_aliasing_frames'), Item(name='full_screen', show_label=False), ), Group(Item(name='render_window', style='custom', visible_when='object.stereo', editor=InstanceEditor(view=View(_stereo_view)), show_label=False), ), label='Scene'), Group( Item(name='light_manager', style='custom', show_label=False), label='Lights'), buttons=['OK', 'Cancel'] ) ######################################## # Private traits. _vtk_control = Instance(wxVTKRenderWindowInteractor) _fullscreen = Any _interacting = Bool ########################################################################### # 'object' interface. ########################################################################### def __init__(self, parent=None, **traits): """ Initializes the object. """ # Base class constructor. super(Scene, self).__init__(parent, **traits) # Setup the default picker. self.picker = picker.Picker(self) def __get_pure_state__(self): """Allows us to pickle the scene.""" # The control attribute is not picklable since it is a VTK # object so we remove it. d = super(Scene, self).__get_pure_state__() for x in ['_vtk_control', '_fullscreen', '_interacting']: d.pop(x, None) return d ########################################################################### # 'Scene' interface. ########################################################################### def render(self): """ Force the scene to be rendered. Nothing is done if the `disable_render` trait is set to True.""" if not self.disable_render: self._vtk_control.Render() def get_size(self): """Return size of the render window.""" return self._vtk_control.GetSize() def set_size(self, size): """Set the size of the window.""" self._vtk_control.SetSize(size) def hide_cursor(self): """Hide the cursor.""" self._vtk_control.HideCursor() def show_cursor(self): """Show the cursor.""" self._vtk_control.ShowCursor() ########################################################################### # 'TVTKScene' interface. ########################################################################### def save_to_clipboard(self): """Saves a bitmap of the scene to the clipboard.""" handler, name = tempfile.mkstemp() self.save_bmp(name) bmp = wx.Bitmap(name, wx.BITMAP_TYPE_BMP) bmpdo = wx.BitmapDataObject(bmp) wx.TheClipboard.Open() wx.TheClipboard.SetData(bmpdo) wx.TheClipboard.Close() os.close(handler) os.unlink(name) ########################################################################### # `wxVTKRenderWindowInteractor` interface. ########################################################################### def OnKeyDown(self, event): """This method is overridden to prevent the 's'/'w'/'e'/'q' keys from doing the default thing which is generally useless. It also handles the 'p' and 'l' keys so the picker and light manager are called. """ keycode = event.GetKeyCode() modifiers = event.HasModifiers() camera = self.camera if keycode < 256: key = chr(keycode) if key == '-': camera.zoom(0.8) self.render() self._record_methods('camera.zoom(0.8)\nrender()') return if key in ['=', '+']: camera.zoom(1.25) self.render() self._record_methods('camera.zoom(1.25)\nrender()') return if key.lower() in ['q', 'e'] or keycode == wx.WXK_ESCAPE: self._disable_fullscreen() if key.lower() in ['w']: event.Skip() return if key.lower() in ['r']: self._record_methods('reset_zoom()') # Handle picking. if key.lower() in ['p']: # In wxPython-2.6, there appears to be a bug in # EVT_CHAR so that event.GetX() and event.GetY() are # not correct. Therefore the picker is called on # KeyUp. event.Skip() return # Camera focal point. if key.lower() in ['f']: event.Skip() return # Light configuration. if key.lower() in ['l'] and not modifiers: self.light_manager.configure() return if key.lower() in ['s'] and not modifiers: parent = self._vtk_control.GetParent() fname = popup_save(parent) if len(fname) != 0: self.save(fname) return shift = event.ShiftDown() if keycode == wx.WXK_LEFT: if shift: camera.yaw(-5) self._record_methods('camera.yaw(-5)') else: camera.azimuth(5) self._record_methods('camera.azimuth(5)') self.render() self._record_methods('render()') return elif keycode == wx.WXK_RIGHT: if shift: camera.yaw(5) self._record_methods('camera.yaw(5)') else: camera.azimuth(-5) self._record_methods('camera.azimuth(-5)') self.render() self._record_methods('render()') return elif keycode == wx.WXK_UP: if shift: camera.pitch(-5) self._record_methods('camera.pitch(-5)') else: camera.elevation(-5) self._record_methods('camera.elevation(-5)') camera.orthogonalize_view_up() self.render() self._record_methods('camera.orthogonalize_view_up()\nrender()') return elif keycode == wx.WXK_DOWN: if shift: camera.pitch(5) self._record_methods('camera.pitch(5)') else: camera.elevation(5) self._record_methods('camera.elevation(5)') camera.orthogonalize_view_up() self.render() self._record_methods('camera.orthogonalize_view_up()\nrender()') return self._vtk_control.OnKeyDown(event) # Skipping the event is not ideal but necessary because we # have no way of knowing of the event was really handled or # not and not skipping will break any keyboard accelerators. # In practice this does not seem to pose serious problems. event.Skip() def OnKeyUp(self, event): """This method is overridden to prevent the 's'/'w'/'e'/'q' keys from doing the default thing which is generally useless. It also handles the 'p' and 'l' keys so the picker and light manager are called. The 'f' key sets the camera focus. """ keycode = event.GetKeyCode() modifiers = event.HasModifiers() if keycode < 256: key = chr(keycode) if key.lower() in ['s', 'w', 'e', 'q']: event.Skip() return # Set camera focal point. if key.lower() in ['f']: if not modifiers: if sys.platform == 'darwin': x, y = self._interactor.event_position else: x = event.GetX() y = self._vtk_control.GetSize()[1] - event.GetY() data = self.picker.pick_world(x, y) coord = data.coordinate if coord is not None: self.camera.focal_point = coord self.render() self._record_methods('camera.focal_point = %r\n'\ 'render()'%list(coord)) return # Handle picking. if key.lower() in ['p']: if not modifiers: if sys.platform == 'darwin': x, y = self._interactor.event_position else: x = event.GetX() y = self._vtk_control.GetSize()[1] - event.GetY() self.picker.pick(x, y) return else: # This is here to disable VTK's own pick handler # which can get called when you press Alt/Ctrl + # 'p'. event.Skip() return # Light configuration. if key.lower() in ['l']: event.Skip() return self._vtk_control.OnKeyUp(event) event.Skip() def OnPaint(self, event): """This method is overridden temporarily in order to create the light manager. This is necessary because it makes sense to create the light manager only when the widget is realized. Only when the widget is realized is the VTK render window created and only then are the default lights all setup correctly. This handler is removed on the first Paint event and the default paint handler of the wxVTKRenderWindowInteractor is used instead.""" # Call the original handler (this will Show the widget) self._vtk_control.OnPaint(event) if len(self.renderer.lights) == 0: # The renderer is not ready yet, we do not do anything, and # we do not remove this callback, so that it will be called # later. return # Now create the light manager. self.light_manager = light_manager.LightManager(self) renwin = self._renwin renwin.update_traits() vtk_rw = tvtk.to_vtk(renwin) renwin.add_observer('StartEvent', messenger.send) messenger.connect(vtk_rw, 'StartEvent', self._start_event_callback) renwin.add_observer('EndEvent', messenger.send) messenger.connect(vtk_rw, 'EndEvent', self._end_event_callback) # Reset the event handler to the default since our job is done. wx.EVT_PAINT(self._vtk_control, None) # Remove the default handler. wx.EVT_PAINT(self._vtk_control, self._vtk_control.OnPaint) def OnSize(self, event): """Overrides the default OnSize in order to refresh the traits of the render window.""" if self._renwin is not None: self._vtk_control.OnSize(event) self._renwin.update_traits() def OnButtonDown(self, event): """Overrides the default on button down method. """ self._interacting = True self._vtk_control.OnButtonDown(event) def OnButtonUp(self, event): self._interacting = False self._vtk_control.OnButtonUp(event) ########################################################################### # 'event' interface. ########################################################################### def _closed_fired(self): super(Scene, self)._closed_fired() self.picker = None self._vtk_control = None ########################################################################### # Non-public interface. ########################################################################### def _create_control(self, parent): """ Create the toolkit-specific control that represents the widget. """ # Create the VTK widget. self._vtk_control = window = wxVTKRenderWindowInteractor(parent, -1, stereo=self.stereo) # Override these handlers. wx.EVT_CHAR(window, None) # Remove the default handler. wx.EVT_CHAR(window, self.OnKeyDown) wx.EVT_KEY_UP(window, None) # Remove the default handler. wx.EVT_KEY_UP(window, self.OnKeyUp) wx.EVT_PAINT(window, None) # Remove the default handler. wx.EVT_PAINT(window, self.OnPaint) wx.EVT_SIZE(window, None) # Remove the default handler. wx.EVT_SIZE(window, self.OnSize) # Override the button down and up handlers as well to note the # interaction. This is to toggle the busy status nicely. for evt in (wx.EVT_LEFT_DOWN, wx.EVT_RIGHT_DOWN, wx.EVT_MIDDLE_DOWN): evt(window, None) evt(window, self.OnButtonDown) for evt in (wx.EVT_LEFT_UP, wx.EVT_RIGHT_UP, wx.EVT_MIDDLE_UP): evt(window, None) evt(window, self.OnButtonUp) # Enable the widget. window.Enable(1) # Switch the default interaction style to the trackball one. window.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Grab the renderwindow. renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow()) renwin.set(point_smoothing=self.point_smoothing, line_smoothing=self.line_smoothing, polygon_smoothing=self.polygon_smoothing) # Create a renderer and add it to the renderwindow self._renderer = tvtk.Renderer() renwin.add_renderer(self._renderer) # Save a reference to our camera so it is not GC'd -- needed for # the sync_traits to work. self._camera = self.camera # Sync various traits. self._renderer.background = self.background self.sync_trait('background', self._renderer) self.renderer.on_trait_change(self.render, 'background') self._camera.parallel_projection = self.parallel_projection self.sync_trait('parallel_projection', self._camera) renwin.off_screen_rendering = self.off_screen_rendering self.sync_trait('off_screen_rendering', self._renwin) self.render_window.on_trait_change(self.render, 'off_screen_rendering') self.render_window.on_trait_change(self.render, 'stereo_render') self.render_window.on_trait_change(self.render, 'stereo_type') self.camera.on_trait_change(self.render, 'parallel_projection') def _show_parent_hack(window, parent): """A hack to get the VTK scene properly setup for use.""" # Force the parent to show itself. parent.Show(1) # on some platforms, this SetSize() is necessary to cause # an OnPaint() when the event loop begins; else we get an # empty window until we force a redraw. window.SetSize(parent.GetSize()) # This is necessary on slow machines in order to force the # wx events to be handled. wx.GetApp().Yield(True) window.Render() if wx.Platform == '__WXMSW__': _show_parent_hack(window, parent) else: if (wx.VERSION[0] == 2) and (wx.VERSION[1] < 5): _show_parent_hack(window, parent) window.Update() # Because of the way the VTK widget is setup, and because we # set the size above, the window sizing is usually completely # messed up when the application window is shown. To work # around this a dynamic IDLE event handler is added and # immediately removed once it executes. This event handler # simply forces a resize to occur. The _idle_count allows us # to execute the idle function a few times (this seems to work # better). def _do_idle(event, window=window): w = wx.GetTopLevelParent(window) # Force a resize sz = w.GetSize() w.SetSize((sz[0]-1, sz[1]-1)) w.SetSize(sz) window._idle_count -= 1 if window._idle_count < 1: wx.EVT_IDLE(window, None) del window._idle_count window._idle_count = 2 wx.EVT_IDLE(window, _do_idle) self._interactor = tvtk.to_tvtk(window._Iren) return window def _lift(self): """Lift the window to the top. Useful when saving screen to an image.""" if self.render_window.off_screen_rendering: # Do nothing if off screen rendering is being used. return w = self._vtk_control while w and not w.IsTopLevel(): w = w.GetParent() if w: w.Raise() wx.GetApp().Yield(True) self.render() def _start_event_callback(self, obj, event): if self._interacting: return else: self.busy = True def _end_event_callback(self, obj, event): if self._interacting: return else: self.busy = False def _busy_changed(self, val): GUI.set_busy(val) def _full_screen_fired(self): fs = self._fullscreen if isinstance(fs, PopupScene): fs.close() self._fullscreen = None elif fs is None: ver = tvtk.Version() popup = False if wx.Platform == '__WXMSW__': popup = True elif ver.vtk_major_version > 5: popup = True elif (ver.vtk_major_version == 5) and \ ((ver.vtk_minor_version >= 1) or \ (ver.vtk_build_version > 2)): popup = True if popup: # There is a bug with earlier versions of VTK that # breaks reparenting a window which is why we test for # the version above. f = PopupScene(self) self._fullscreen = f f.fullscreen() else: f = FullScreen(self) f.run() # This will block. self._fullscreen = None def _disable_fullscreen(self): fs = self._fullscreen if isinstance(fs, PopupScene): fs.close() self._fullscreen = None
dmsurti/mayavi
tvtk/pyface/ui/wx/scene.py
Python
bsd-3-clause
28,321
<?php namespace Admin\Entity; use Doctrine\ORM\Mapping as ORM; /** * User * * @ORM\Table(name="user") * @ORM\Entity */ class User { /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="user_name", type="text", nullable=false) */ private $userName; /** * @var string * * @ORM\Column(name="password", type="text", nullable=false) */ private $password; /** * @var string * * @ORM\Column(name="full_name", type="text", nullable=false) */ private $fullName; /** * @var integer * * @ORM\Column(name="type", type="integer", nullable=false) */ private $type; /** * @var string * * @ORM\Column(name="api_key", type="text", nullable=true) */ private $apiKey; /** * @var integer * * @ORM\Column(name="isdelete", type="integer", nullable=false) */ private $isdelete; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getUserName() { return $this->userName; } /** * @param string $userName */ public function setUserName($userName) { $this->userName = $userName; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $password */ public function setPassword($password) { $this->password = $password; } /** * @return string */ public function getFullName() { return $this->fullName; } /** * @param string $fullName */ public function setFullName($fullName) { $this->fullName = $fullName; } /** * @return int */ public function getType() { return $this->type; } /** * @param int $type */ public function setType($type) { $this->type = $type; } /** * @return string */ public function getApiKey() { return $this->apiKey; } /** * @param string $apiKey */ public function setApiKey($apiKey) { $this->apiKey = $apiKey; } /** * @return int */ public function getIsdelete() { return $this->isdelete; } /** * @param int $isdelete */ public function setIsdelete($isdelete) { $this->isdelete = $isdelete; } }
binnguyen/kaffacoffee
module/Admin/src/Admin/Entity/User.php
PHP
bsd-3-clause
2,812
{# ikhaya/suggestionlist.html ~~~~~~~~~~~~~~~~~~~~~~~~~~ The moderators can see all suggestions for ikhaya articles on this page. :copyright: (c) 2013-2015 by the Inyoka Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. #} {% extends 'ikhaya/base.html' %} {% block breadcrumb %} {{ super() }} {{ macros.breadcrumb_item(_('Article suggestions'), href('ikhaya', 'suggestions')) }} {% endblock %} {% block sidebar %} {{ super() }} {% call macros.sidebar() %} {% if is_subscribed %} {{ macros.sidebar_item(_('Do not notify me anymore about new article suggestions'), href('ikhaya', 'suggestions', 'unsubscribe'), 'fa_icon-bell-slash') }} {% else %} {{ macros.sidebar_item(_('Notify me about new article suggestions'), href('ikhaya', 'suggestions', 'subscribe'), 'fa_icon-bell') }} {% endif %} {% endcall %} {% endblock %} {% block content %} <h3>{% trans %}Article suggestions{% endtrans %}</h3> <p> {% trans count=suggestion_count %} Here is one article suggestion which was not yet reviewed. {% pluralize %} Here are {{ count }} article suggestions which were not yet reviewed. {% endtrans %} </p> {% for suggestion in suggestions %} <article class="ikhaya-suggestion" id="{{ suggestion.id }}"> <header class="ikhaya-suggestion-heading"> <h3 class="title"> <a href="#{{ suggestion.id }}">{{ suggestion.title|e }}</a> </h3> <ul class="ikhaya-suggestion-info list-inline"> <li> {% trans link=suggestion.author|url, author=suggestion.author.username|e, date=suggestion.pub_date|datetime %} Suggested by <a href="{{ link }}">{{ author }}</a>, {{ date }} {% endtrans %} </li> </ul> <ul class="ikhaya-suggestion-action list-inline"> <li class="suggestion-{{ suggestion.pk }}"> {% trans %}Assigned to:{% endtrans %} {% if suggestion.owner_id == none %} {% trans %}Nobody{% endtrans %} {% else %} <a href="{{ suggestion.owner|url }}">{{ suggestion.owner.username|e }}</a> {% endif %} </li> {% if suggestion.owner_id != USER.id %} <li> <a href="{{ href('ikhaya', 'suggest', suggestion.id, 'assign', USER.username) }}" id="{{ suggestion.id }}"> {% trans %}Assign to me{% endtrans %} </a> </li> {% endif %} <li> <a href="{{ href('ikhaya', 'suggest', suggestion.id, 'assign', '-') }}" id="{{ suggestion.id }}"> {% trans %}Delete assignment{% endtrans %} </a> </li> <li> <a href="{{ href('ikhaya', 'suggest', suggestion.id, 'delete') }}"> {% trans %}Delete suggestion{% endtrans %} </a> </li> <li> <a href="{{ href('ikhaya', 'article', 'new', suggestion.id) }}"> {% trans %}New article{% endtrans %} </a> </li> </ul> </header> <div class="ikhaya-suggestion-body"> <div class="intro">{{ suggestion.intro_rendered }}</div> <div class="text">{{ suggestion.text_rendered }}</div> </div> {% if suggestion.notes_rendered %} <div class="ikhaya-suggestion-footer"> <h4>{% trans %}Proposers's notes to the admins{% endtrans %}</h4> {{ suggestion.notes_rendered }} </div> {% endif %} </article> {% else %} <p>{% trans %}There are currently no article suggestions.{% endtrans %}</p> {% endfor %} {% endblock %}
jgottfried/theme-default
inyoka_theme_default/templates/ikhaya/suggestions.html
HTML
bsd-3-clause
3,717
<?php /** * @link https://github.com/black-lamp/yii2-email-templates * @copyright Copyright (c) 2016 Vladimir Kuprienko * @license BSD 3-Clause License */ namespace tests\unit\components; use tests\unit\DbTestCase; use Yii; use tests\unit\TestCase; use tests\fixtures\TranslationFixture; use bl\emailTemplates\data\Template; /** * Test case for TemplateManager component * * @property \UnitTester $tester * * @author Vladimir Kuprienko <[email protected]> */ class TemplateManagerTest extends DbTestCase { /** * @var \bl\emailTemplates\components\TemplateManager */ private $object; /** * @inheritdoc */ public function fixtures() { return [ 'translation' => [ 'class' => TranslationFixture::className() ] ]; } public function _before() { parent::_before(); $this->object = Yii::$app->get('templateManager'); } public function testGetTemplate() { $template = $this->object->getTemplate('test', 1); $this->assertInstanceOf(Template::class, $template, 'Method should return Template class object'); } public function testGetTemplates() { $templates = $this->object->getTemplates('test'); $this->assertInternalType('array', $templates, 'Method should return array'); $this->assertInstanceOf(Template::class, $templates[0], 'Array item should be a Template object'); } public function testGetTemplateNull() { $template = $this->object->getTemplate('Nonexistent key', 1); $this->assertEquals(null, $template, 'Method should returns a null value'); } public function testGetTemplatesNull() { $templates = $this->object->getTemplates('Nonexistent key', 1); $this->assertEquals(null, $templates, 'Method should returns a null value'); } public function testGetByLangOrFirst() { $byKey = $this->object->getByLangOrFirst('test', 2); $this->assertInstanceOf(Template::class, $byKey, 'Method should return Template class object'); $this->assertEquals('Тест темы', $byKey->getSubject(), 'Method should returns translation by lang'); $this->assertEquals('Тест тела', $byKey->getBody(), 'Method should returns translation by lang'); $first = $this->object->getByLangOrFirst('test', 7); $this->assertInstanceOf(Template::class, $first, 'Method should return Template class object'); $this->assertEquals('Test subject', $first->getSubject(), 'Method should return a first translation'); $this->assertEquals('Test body', $first->getBody(), 'Method should return a first translation'); $null = $this->object->getByLangOrFirst('Nonexistent key', 1); $this->assertInternalType('null', $null, 'Method should returns null value'); } }
black-lamp/yii2-email-templates
tests/unit/components/TemplateManagerTest.php
PHP
bsd-3-clause
2,905
// // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2010 Alessandro Tasora // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file at the top level of the distribution // and at http://projectchrono.org/license-chrono.txt. // #ifndef CHC_LINE_H #define CHC_LINE_H ////////////////////////////////////////////////// // // ChCLine.h // // Base class for lines // // HEADER file for CHRONO, // Multibody dynamics engine // // ------------------------------------------------ // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include <math.h> #include "ChCGeometry.h" #include "physics/ChFilePS.h" namespace chrono { namespace geometry { #define CH_GEOCLASS_LINE 4 /// /// LINE. /// /// Base class for all geometric objects representing lines /// in 3D space. /// class ChApi ChLine : public ChGeometry { // Chrono simulation of RTTI, needed for serialization CH_RTTI(ChLine,ChGeometry); protected: int closed; int complexityU; public: // // CONSTRUCTORS // ChLine () { closed = FALSE; complexityU = 2;}; ~ChLine () {}; ChLine(const ChLine & source) { Copy(&source); } void Copy (const ChLine* source) { closed = source->closed; complexityU = source->complexityU; }; ChGeometry* Duplicate () { ChGeometry* mgeo = new ChLine(); mgeo->Copy(this); return mgeo; }; // // OVERRIDE BASE CLASS FUNCTIONS // /// Get the class type as unique numerical ID (faster /// than using ChronoRTTI mechanism). /// Each inherited class must return an unique ID. virtual int GetClassType () {return CH_GEOCLASS_LINE;}; /// Tell if the curve is closed virtual int Get_closed() {return closed;}; virtual void Set_closed(int mc) {closed = mc;}; /// Tell the complexity virtual int Get_complexity() {return complexityU;}; virtual void Set_complexity(int mc) {complexityU = mc;}; /// This is a line virtual int GetManifoldDimension() {return 1;} // // CUSTOM FUNCTIONS // /// Find the parameter resU for the nearest point on curve to "point". int FindNearestLinePoint (Vector& point, double& resU, double approxU, double tol); /// Returns curve lenght. Typical sampling 1..5 (1 already gives correct result with degree1 curves) virtual double Lenght (int sampling); /// Returns an adimensional information on "how much" this curve is similar to another /// in its overall shape (doesnot matter parametrization or start point). Try with 20 samples. /// The return value is somewhat the "average distance between the two curves". /// Note that the result is affected by "weight" of curves. If it chnges from default 1.0, the /// distance extimation is higher/lower (ex: if a curve defines low 'weight' in its central segment, /// its CurveCurveDistance from another segment is not much affected by errors near the central segment). double CurveCurveDist (ChLine* compline, int samples); /// Same as before, but returns "how near" is complinesegm to /// whatever segment of this line (does not matter the percentual of line). /// Again, this is affected by "weight" of curves. If weight changes along curves ->'weighted' distance double CurveSegmentDist (ChLine* complinesegm, int samples); /// Same as above, but instead of making average of the distances, /// these functions return the maximum of the distances... double CurveCurveDistMax (ChLine* compline, int samples); double CurveSegmentDistMax (ChLine* complinesegm, int samples); /// Draw into the current graph viewport of a ChFile_ps file virtual int DrawPostscript(ChFile_ps* mfle, int markpoints, int bezier_interpolate); // // STREAMING // void StreamOUT(ChStreamOutBinary& mstream); void StreamIN(ChStreamInBinary& mstream); }; } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ #endif // END of header
scpeters/chrono
src/geometry/ChCLine.h
C
bsd-3-clause
4,073
// Copyright(C) 1999-2017 National Technology & Engineering Solutions // of Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with // NTESS, the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of NTESS nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "Ioss_CodeTypes.h" // for IntVector #include "Ioss_ElementTopology.h" // for ElementTopology #include <Ioss_ElementVariableType.h> // for ElementVariableType #include <Ioss_Super.h> #include <cstddef> // for size_t #include <cstdlib> // for atoi #include <string> // for string //------------------------------------------------------------------------ // Define a variable type for storage of this elements connectivity namespace Ioss { class St_Super : public ElementVariableType { public: St_Super(const std::string &my_name, int node_count) : ElementVariableType(my_name, node_count) { } }; } // namespace Ioss void Ioss::Super::factory() {} // ======================================================================== // Note that since a superelement is created for each node_count, it isn't // possible to precreate these element types statically, so they are created // as needed and therefore, they must be deleted at end of run hence the 'true' // argument to the ElementTopology constructor Ioss::Super::Super(const std::string &my_name, int node_count) : Ioss::ElementTopology(my_name, "Unknown", true), nodeCount(node_count), storageType(new St_Super(my_name, node_count)) { } Ioss::Super::~Super() { delete storageType; } void Ioss::Super::make_super(const std::string &type) { // Decode name to determine number of nodes... // Assume that digits at end specify number of nodes. size_t digits = type.find_last_not_of("0123456789"); if (digits != std::string::npos) { std::string node_count_str = type.substr(digits + 1); int node_count = std::atoi(node_count_str.c_str()); new Ioss::Super(type, node_count); } } int Ioss::Super::parametric_dimension() const { return 3; } int Ioss::Super::spatial_dimension() const { return 3; } int Ioss::Super::order() const { return 1; } int Ioss::Super::number_corner_nodes() const { return nodeCount; } int Ioss::Super::number_nodes() const { return nodeCount; } int Ioss::Super::number_edges() const { return 0; } int Ioss::Super::number_faces() const { return 0; } int Ioss::Super::number_nodes_edge(int /* edge */) const { return 0; } int Ioss::Super::number_nodes_face(int /*face*/) const { return 0; } int Ioss::Super::number_edges_face(int /*face*/) const { return 0; } Ioss::IntVector Ioss::Super::edge_connectivity(int /*edge_number*/) const { Ioss::IntVector connectivity(0); return connectivity; } Ioss::IntVector Ioss::Super::face_connectivity(int /*face_number*/) const { Ioss::IntVector connectivity(0); return connectivity; } Ioss::IntVector Ioss::Super::element_connectivity() const { Ioss::IntVector connectivity(number_nodes()); for (int i = 0; i < number_nodes(); i++) { connectivity[i] = i; } return connectivity; } Ioss::ElementTopology *Ioss::Super::face_type(int /*face_number*/) const { return Ioss::ElementTopology::factory("unknown"); } Ioss::ElementTopology *Ioss::Super::edge_type(int /*edge_number*/) const { return Ioss::ElementTopology::factory("unknown"); } Ioss::IntVector Ioss::Super::face_edge_connectivity(int /*face_number*/) const { Ioss::IntVector fcon(0); return fcon; }
nschloe/seacas
packages/seacas/libraries/ioss/src/Ioss_Super.C
C++
bsd-3-clause
4,945
# -*- coding: utf-8 from __future__ import unicode_literals import os import json from . import FragmentsError, __version__ configuration_file_name = 'config.json' configuration_directory_name = '_fragments' class ConfigurationError(FragmentsError): pass class ConfigurationDirectoryNotFound(ConfigurationError): pass class ConfigurationFileNotFound(ConfigurationError): pass class ConfigurationFileCorrupt(ConfigurationError): pass def find_configuration(current=None): current = current or os.getcwd() path = current while True: configuration_path = os.path.join(path, configuration_directory_name) if os.path.exists(path) and os.path.exists(configuration_path): return configuration_path path, oldpath = os.path.split(path)[0], path if oldpath == path: raise ConfigurationDirectoryNotFound("Could not find fragments configuration directory in %r or any parent directories" % current) class FragmentsConfig(dict): defaults = { 'files': {}, 'version': __version__, } def __init__(self, directory=None, autoload=True): if directory is None: directory = find_configuration() self.directory = directory self.path = os.path.join(self.directory, configuration_file_name) self.root = os.path.split(self.directory)[0] self.update(FragmentsConfig.defaults) if autoload: self.load() def load(self): if os.access(self.path, os.R_OK|os.W_OK): with open(self.path, 'r') as config_file: file_contents = config_file.read() try: parsed_json = json.loads(file_contents) except Exception as exc: raise ConfigurationFileCorrupt(exc.args[0]) self.update(parsed_json) self['version'] = tuple(self['version']) else: raise ConfigurationFileNotFound("Could not access %r, if the file exists, check its permissions" % self.path) def dump(self): self['version'] = __version__ with open(self.path, 'w') as config: config.write(json.dumps(self, sort_keys=True, indent=4))
glyphobet/fragments
fragments/config.py
Python
bsd-3-clause
2,206
;--------------------------------------- ; CLi² (Command Line Interface) default cursor ; 2013,2016 © breeze/fishbone crew ;--------------------------------------- org #C000 sCursor db #7f,"CUR" ; Cursor signature db 16 ; Ширина курсора кратная 8! db 16 ; Высота курсора кратная 8! db 5 ; Количество фаз miceCursor ; 01 23 45 67 89 AB CD EF db #be,#00,#00,#00,#00,#00,#00,#00 ; 0 Стрелка db #1b,#ee,#00,#00,#00,#00,#00,#00 ; 1 db #01,#bb,#ee,#00,#00,#00,#00,#00 ; 2 db #01,#bb,#bb,#ee,#00,#00,#00,#00 ; 3 db #00,#1b,#bb,#bb,#ee,#00,#00,#00 ; 4 db #00,#1b,#bb,#bb,#bb,#00,#00,#00 ; 5 db #00,#01,#bb,#be,#00,#00,#00,#00 ; 6 db #00,#01,#bb,#1b,#e0,#00,#00,#00 ; 7 db #00,#00,#1b,#01,#be,#00,#00,#00 ; 8 db #00,#00,#1b,#00,#1b,#e0,#00,#00 ; 9 db #00,#00,#00,#00,#01,#b0,#00,#00 ; A db #00,#00,#00,#00,#00,#00,#00,#00 ; B db #00,#00,#00,#00,#00,#00,#00,#00 ; C db #00,#00,#00,#00,#00,#00,#00,#00 ; D db #00,#00,#00,#00,#00,#00,#00,#00 ; E db #00,#00,#00,#00,#00,#00,#00,#00 ; F db #00,#00,#07,#11,#11,#10,#00,#00 ; 0 Часы db #00,#00,#01,#11,#11,#10,#00,#00 ; 1 db #00,#00,#00,#17,#71,#00,#00,#00 ; 2 db #00,#00,#01,#11,#11,#10,#00,#00 ; 3 db #00,#01,#17,#77,#77,#11,#10,#00 ; 4 db #00,#17,#77,#77,#77,#7a,#11,#00 ; 5 db #01,#77,#77,#77,#77,#a7,#71,#10 ; 6 db #01,#77,#77,#77,#7a,#77,#71,#10 ; 7 db #17,#77,#77,#77,#a7,#77,#77,#11 ; 8 db #17,#77,#77,#71,#77,#77,#77,#11 ; 9 db #17,#77,#77,#77,#77,#77,#77,#11 ; A db #01,#77,#77,#77,#77,#77,#71,#10 ; B db #01,#77,#77,#77,#77,#77,#71,#10 ; C db #00,#17,#77,#77,#77,#77,#11,#00 ; D db #00,#01,#17,#77,#77,#11,#10,#00 ; E db #00,#00,#01,#11,#11,#10,#00,#00 ; F db #00,#00,#00,#00,#00,#00,#00,#00 ; 0 Выделение db #00,#00,#00,#00,#00,#00,#00,#00 ; 1 db #00,#00,#00,#00,#00,#00,#00,#00 ; 2 db #00,#00,#0b,#b0,#bb,#00,#00,#00 ; 3 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 4 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 5 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 6 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 7 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 8 db #00,#00,#00,#0b,#00,#00,#00,#00 ; 9 db #00,#00,#00,#0b,#00,#00,#00,#00 ; A db #00,#00,#00,#0b,#00,#00,#00,#00 ; B db #00,#00,#00,#0b,#00,#00,#00,#00 ; C db #00,#00,#0b,#b0,#bb,#00,#00,#00 ; D db #00,#00,#00,#00,#00,#00,#00,#00 ; E db #00,#00,#00,#00,#00,#00,#00,#00 ; F db #00,#00,#01,#10,#00,#00,#00,#00 ; 0 Рука db #00,#00,#1e,#e1,#00,#00,#00,#00 ; 1 db #00,#00,#1e,#e1,#00,#00,#00,#00 ; 2 db #00,#00,#1e,#e1,#00,#00,#00,#00 ; 3 db #00,#00,#1e,#e1,#00,#00,#00,#00 ; 4 db #00,#00,#1e,#e1,#11,#00,#00,#00 ; 5 db #00,#11,#1e,#e1,#ee,#11,#10,#00 ; 6 db #01,#ee,#1e,#e1,#ee,#ee,#e1,#00 ; 7 db #01,#ee,#ee,#e1,#ee,#ee,#ee,#10 ; 8 db #00,#1e,#ee,#ee,#ee,#ee,#ee,#10 ; 9 db #00,#01,#ee,#ee,#ee,#ee,#ee,#10 ; A db #00,#00,#1e,#ee,#ee,#ee,#ee,#10 ; B db #00,#00,#1e,#ee,#ee,#ee,#e1,#00 ; C db #00,#00,#01,#ee,#ee,#1e,#e1,#00 ; D db #00,#00,#0b,#bb,#bb,#eb,#b0,#00 ; E db #00,#00,#0b,#bb,#bb,#bb,#b0,#00 ; F db #00,#00,#00,#00,#00,#00,#00,#00 ; 0 Пусто db #00,#00,#00,#00,#00,#00,#00,#00 ; 1 db #00,#00,#00,#00,#00,#00,#00,#00 ; 2 db #00,#00,#00,#00,#00,#00,#00,#00 ; 3 db #00,#00,#00,#00,#00,#00,#00,#00 ; 4 db #00,#00,#00,#00,#00,#00,#00,#00 ; 5 db #00,#00,#00,#00,#00,#00,#00,#00 ; 6 db #00,#00,#00,#00,#00,#00,#00,#00 ; 7 db #00,#00,#00,#00,#00,#00,#00,#00 ; 8 db #00,#00,#00,#00,#00,#00,#00,#00 ; 9 db #00,#00,#00,#00,#00,#00,#00,#00 ; A db #00,#00,#00,#00,#00,#00,#00,#00 ; B db #00,#00,#00,#00,#00,#00,#00,#00 ; C db #00,#00,#00,#00,#00,#00,#00,#00 ; D db #00,#00,#00,#00,#00,#00,#00,#00 ; E db #00,#00,#00,#00,#00,#00,#00,#00 ; F eCursor nop SAVEBIN "install/system/res/cursors/default.cur", sCursor, eCursor-sCursor
LessNick/cli2
src/res/cursors/default.cur.asm
Assembly
bsd-3-clause
4,051
/* main.c -- main entry point for execution. * * * SCL; 2012-2015 */ #define _POSIX_C_SOURCE 200809L #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "common.h" #include "logging.h" #include "ptree.h" #include "solve.h" #include "automaton.h" #include "gr1c_util.h" extern int yyparse( void ); extern void yyrestart( FILE *new_file ); /************************** **** Global variables ****/ extern specification_t spc; /**************************/ /* Output formats */ #define OUTPUT_FORMAT_TEXT 0 #define OUTPUT_FORMAT_TULIP 1 #define OUTPUT_FORMAT_DOT 2 #define OUTPUT_FORMAT_AUT 3 #define OUTPUT_FORMAT_JSON 5 /* Verification model targets */ #define VERMODEL_TARGET_SPIN 1 /* Runtime modes */ #define GR1C_MODE_SYNTAX 0 #define GR1C_MODE_REALIZABLE 1 #define GR1C_MODE_SYNTHESIS 2 #define GR1C_MODE_INTERACTIVE 3 #define PRINT_VERSION() \ printf( "gr1c " GR1C_VERSION "\n\n" GR1C_COPYRIGHT "\n" ) int main( int argc, char **argv ) { FILE *fp; byte run_option = GR1C_MODE_SYNTHESIS; bool help_flag = False; bool ptdump_flag = False; bool logging_flag = False; unsigned char init_flags = ALL_ENV_EXIST_SYS_INIT; byte format_option = OUTPUT_FORMAT_JSON; unsigned char verbose = 0; bool reading_options = True; /* For disabling option parsing using "--" */ int input_index = -1; int output_file_index = -1; /* For command-line flag "-o". */ char dumpfilename[64]; char **command_argv = NULL; byte verification_model = 0; /* For command-line flag "-P". */ ptree_t *original_env_init = NULL; ptree_t *original_sys_init = NULL; ptree_t **original_env_goals = NULL; ptree_t **original_sys_goals = NULL; int original_num_egoals = 0; int original_num_sgoals = 0; ptree_t **original_env_trans_array = NULL; ptree_t **original_sys_trans_array = NULL; int original_et_array_len = 0; int original_st_array_len = 0; int i, j, var_index; ptree_t *tmppt; /* General purpose temporary ptree pointer */ DdManager *manager; DdNode *T = NULL; anode_t *strategy = NULL; int num_env, num_sys; /* Try to handle sub-commands first */ if (argc >= 2) { if (!strncmp( argv[1], "rg", strlen( "rg" ) ) && argv[1][strlen("rg")] == '\0') { /* Pass arguments after rg */ command_argv = malloc( sizeof(char *)*argc ); command_argv[0] = strdup( "gr1c rg" ); command_argv[argc-1] = NULL; for (i = 1; i < argc-1; i++) command_argv[i] = argv[i+1]; if (execvp( "gr1c-rg", command_argv ) < 0) { perror( __FILE__ ", execvp" ); return -1; } } else if (!strncmp( argv[1], "patch", strlen( "patch" ) ) && argv[1][strlen("patch")] == '\0') { command_argv = malloc( sizeof(char *)*argc ); command_argv[0] = strdup( "gr1c patch" ); command_argv[argc-1] = NULL; for (i = 1; i < argc-1; i++) command_argv[i] = argv[i+1]; if (execvp( "gr1c-patch", command_argv ) < 0) { perror( __FILE__ ", execvp" ); return -1; } } else if (!strncmp( argv[1], "autman", strlen( "autman" ) ) && argv[1][strlen("autman")] == '\0') { command_argv = malloc( sizeof(char *)*argc ); command_argv[0] = strdup( "gr1c autman" ); command_argv[argc-1] = NULL; for (i = 1; i < argc-1; i++) command_argv[i] = argv[i+1]; if (execvp( "gr1c-autman", command_argv ) < 0) { perror( __FILE__ ", execvp" ); return -1; } } else if (!strncmp( argv[1], "help", strlen( "help" ) ) && argv[1][strlen("help")] == '\0') { reading_options = False; help_flag = True; } } /* Look for flags in command-line arguments. */ for (i = 1; i < argc; i++) { if (reading_options && argv[i][0] == '-' && argv[i][1] != '-') { if (argv[i][2] != '\0' && !(argv[i][1] == 'v' && argv[i][2] == 'v')) { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } if (argv[i][1] == 'h') { help_flag = True; } else if (argv[i][1] == 'V') { PRINT_VERSION(); PRINT_LINKED_VERSIONS(); return 0; } else if (argv[i][1] == 'v') { verbose++; j = 2; /* Only support up to "level 2" of verbosity */ while (argv[i][j] == 'v' && j <= 2) { verbose++; j++; } } else if (argv[i][1] == 'l') { logging_flag = True; } else if (argv[i][1] == 's') { run_option = GR1C_MODE_SYNTAX; } else if (argv[i][1] == 'p') { ptdump_flag = True; } else if (argv[i][1] == 'r') { run_option = GR1C_MODE_REALIZABLE; } else if (argv[i][1] == 'i') { run_option = GR1C_MODE_INTERACTIVE; } else if (argv[i][1] == 't') { if (i == argc-1) { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } if (!strncmp( argv[i+1], "txt", strlen( "txt" ) )) { format_option = OUTPUT_FORMAT_TEXT; } else if (!strncmp( argv[i+1], "tulip", strlen( "tulip" ) )) { format_option = OUTPUT_FORMAT_TULIP; } else if (!strncmp( argv[i+1], "dot", strlen( "dot" ) )) { format_option = OUTPUT_FORMAT_DOT; } else if (!strncmp( argv[i+1], "aut", strlen( "aut" ) )) { format_option = OUTPUT_FORMAT_AUT; } else if (!strncmp( argv[i+1], "json", strlen( "json" ) )) { format_option = OUTPUT_FORMAT_JSON; } else { fprintf( stderr, "Unrecognized output format. Try \"-h\".\n" ); return 1; } i++; } else if (argv[i][1] == 'n') { if (i == argc-1) { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } for (j = 0; j < strlen( argv[i+1] ); j++) argv[i+1][j] = tolower( argv[i+1][j] ); if (!strncmp( argv[i+1], "all_env_exist_sys_init", strlen( "all_env_exist_sys_init" ) )) { init_flags = ALL_ENV_EXIST_SYS_INIT; } else if (!strncmp( argv[i+1], "all_init", strlen( "all_init" ) )) { init_flags = ALL_INIT; } else if (!strncmp( argv[i+1], "one_side_init", strlen( "one_side_init" ) )) { init_flags = ONE_SIDE_INIT; } else { fprintf( stderr, "Unrecognized init flags. Try \"-h\".\n" ); return 1; } i++; } else if (argv[i][1] == 'o') { if (i == argc-1) { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } output_file_index = i+1; i++; } else if (argv[i][1] == 'P') { verification_model = VERMODEL_TARGET_SPIN; } else { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } } else if (reading_options && argv[i][0] == '-' && argv[i][1] == '-') { if (argv[i][2] == '\0') { reading_options = False; } else if (!strncmp( argv[i]+2, "help", strlen( "help" ) )) { help_flag = True; } else if (!strncmp( argv[i]+2, "version", strlen( "version" ) )) { PRINT_VERSION(); return 0; } else { fprintf( stderr, "Invalid flag given. Try \"-h\".\n" ); return 1; } } else if (input_index < 0) { /* Use first non-flag argument as filename whence to read specification. */ if (i < argc-1) { fprintf( stderr, "Unexpected arguments after filename. Try \"-h\".\n" ); return 1; } input_index = i; } } if (help_flag) { /* Split among printf() calls to conform with ISO C90 string length */ printf( "Usage: %s [-hVvlspriP] [-n INIT] [-t TYPE] [-o FILE] [[--] FILE]\n\n" " -h this help message\n" " -V print version and exit\n" " -v be verbose; use -vv to be more verbose\n" " -l enable logging\n" " -t TYPE strategy output format; default is \"json\";\n" " supported formats: txt, dot, aut, json, tulip\n", argv[0] ); printf( " -n INIT initial condition interpretation; (not case sensitive)\n" " one of\n" " ALL_ENV_EXIST_SYS_INIT (default)\n" " ALL_INIT\n" " ONE_SIDE_INIT\n" " -s only check specification syntax (return 2 on error)\n" ); printf( " -p dump parse trees to DOT files, and echo formulas to screen\n" " -r only check realizability; do not synthesize strategy\n" " (return 0 if realizable, 3 if not)\n" " -i interactive mode\n" " -o FILE output strategy to FILE, rather than stdout (default)\n" " -P create Spin Promela model of strategy;\n" " output to stdout, so requires -o flag to also be used\n" ); printf( "\nFor other commands, use: %s COMMAND [...]\n\n" " rg solve reachability game\n" " autman manipulate finite-memory strategies\n" " patch patch or modify a given strategy (incremental synthesis)\n" " help this help message (equivalent to -h)\n\n" "When applicable, any arguments after COMMAND are passed on to the\n" "appropriate program. Use -h to get the corresponding help message.\n", argv[0] ); return 0; } if (input_index < 0 && (run_option == GR1C_MODE_INTERACTIVE)) { printf( "Reading spec from stdin in interactive mode is not yet" " implemented.\n" ); return 1; } if (verification_model > 0 && output_file_index < 0) { printf( "-P flag can only be used with -o flag because the" " verification model is\noutput to stdout.\n" ); return 1; } if (logging_flag) { openlogfile( NULL ); /* Use default filename prefix */ /* Only change verbosity level if user did not specify it */ if (verbose == 0) verbose = 1; } else { setlogstream( stdout ); setlogopt( LOGOPT_NOTIME ); } if (verbose > 0) logprint( "Running with verbosity level %d.", verbose ); /* If filename for specification given at command-line, then use it. Else, read from stdin. */ if (input_index > 0) { fp = fopen( argv[input_index], "r" ); if (fp == NULL) { perror( __FILE__ ", fopen" ); return -1; } yyrestart( fp ); } else { yyrestart( stdin ); } /* Parse the specification. */ if (verbose) logprint( "Parsing input..." ); SPC_INIT( spc ); if (yyparse()) return 2; if (verbose) logprint( "Done." ); if (check_gr1c_form( spc.evar_list, spc.svar_list, spc.env_init, spc.sys_init, spc.env_trans_array, spc.et_array_len, spc.sys_trans_array, spc.st_array_len, spc.env_goals, spc.num_egoals, spc.sys_goals, spc.num_sgoals, init_flags ) < 0) return 2; if (run_option == GR1C_MODE_SYNTAX) return 0; /* Close input file, if opened. */ if (input_index > 0) fclose( fp ); /* Omission implies empty. */ if (spc.et_array_len == 0) { spc.et_array_len = 1; spc.env_trans_array = malloc( sizeof(ptree_t *) ); if (spc.env_trans_array == NULL) { perror( __FILE__ ", malloc" ); return -1; } *spc.env_trans_array = init_ptree( PT_CONSTANT, NULL, 1 ); } if (spc.st_array_len == 0) { spc.st_array_len = 1; spc.sys_trans_array = malloc( sizeof(ptree_t *) ); if (spc.sys_trans_array == NULL) { perror( __FILE__ ", malloc" ); return -1; } *spc.sys_trans_array = init_ptree( PT_CONSTANT, NULL, 1 ); } if (spc.num_sgoals == 0) { spc.num_sgoals = 1; spc.sys_goals = malloc( sizeof(ptree_t *) ); if (spc.sys_goals == NULL) { perror( __FILE__ ", malloc" ); return -1; } *spc.sys_goals = init_ptree( PT_CONSTANT, NULL, 1 ); } if (ptdump_flag) { tree_dot_dump( spc.env_init, "env_init_ptree.dot" ); tree_dot_dump( spc.sys_init, "sys_init_ptree.dot" ); for (i = 0; i < spc.et_array_len; i++) { snprintf( dumpfilename, sizeof(dumpfilename), "env_trans%05d_ptree.dot", i ); tree_dot_dump( *(spc.env_trans_array+i), dumpfilename ); } for (i = 0; i < spc.st_array_len; i++) { snprintf( dumpfilename, sizeof(dumpfilename), "sys_trans%05d_ptree.dot", i ); tree_dot_dump( *(spc.sys_trans_array+i), dumpfilename ); } if (spc.num_egoals > 0) { for (i = 0; i < spc.num_egoals; i++) { snprintf( dumpfilename, sizeof(dumpfilename), "env_goal%05d_ptree.dot", i ); tree_dot_dump( *(spc.env_goals+i), dumpfilename ); } } if (spc.num_sgoals > 0) { for (i = 0; i < spc.num_sgoals; i++) { snprintf( dumpfilename, sizeof(dumpfilename), "sys_goal%05d_ptree.dot", i ); tree_dot_dump( *(spc.sys_goals+i), dumpfilename ); } } var_index = 0; printf( "Environment variables (indices; domains): " ); if (spc.evar_list == NULL) { printf( "(none)" ); } else { tmppt = spc.evar_list; while (tmppt) { if (tmppt->value == -1) { /* Boolean */ if (tmppt->left == NULL) { printf( "%s (%d; bool)", tmppt->name, var_index ); } else { printf( "%s (%d; bool), ", tmppt->name, var_index); } } else { if (tmppt->left == NULL) { printf( "%s (%d; {0..%d})", tmppt->name, var_index, tmppt->value ); } else { printf( "%s (%d; {0..%d}), ", tmppt->name, var_index, tmppt->value ); } } tmppt = tmppt->left; var_index++; } } printf( "\n\n" ); printf( "System variables (indices; domains): " ); if (spc.svar_list == NULL) { printf( "(none)" ); } else { tmppt = spc.svar_list; while (tmppt) { if (tmppt->value == -1) { /* Boolean */ if (tmppt->left == NULL) { printf( "%s (%d; bool)", tmppt->name, var_index ); } else { printf( "%s (%d; bool), ", tmppt->name, var_index ); } } else { if (tmppt->left == NULL) { printf( "%s (%d; {0..%d})", tmppt->name, var_index, tmppt->value ); } else { printf( "%s (%d; {0..%d}), ", tmppt->name, var_index, tmppt->value ); } } tmppt = tmppt->left; var_index++; } } printf( "\n\n" ); print_GR1_spec( spc.evar_list, spc.svar_list, spc.env_init, spc.sys_init, spc.env_trans_array, spc.et_array_len, spc.sys_trans_array, spc.st_array_len, spc.env_goals, spc.num_egoals, spc.sys_goals, spc.num_sgoals, stdout ); } /* If verification model will be created, then save copy of pristine ptrees, before nonbool expansion. */ if (verification_model > 0) { original_num_egoals = spc.num_egoals; original_num_sgoals = spc.num_sgoals; original_et_array_len = spc.et_array_len; original_st_array_len = spc.st_array_len; original_env_goals = malloc( original_num_egoals*sizeof(ptree_t *) ); original_sys_goals = malloc( original_num_sgoals*sizeof(ptree_t *) ); original_env_trans_array = malloc( original_et_array_len*sizeof(ptree_t *) ); original_sys_trans_array = malloc( original_st_array_len*sizeof(ptree_t *) ); if (original_env_goals == NULL || original_sys_goals == NULL || original_env_trans_array == NULL || original_sys_trans_array == NULL) { perror( __FILE__ ", malloc" ); return -1; } original_env_init = copy_ptree( spc.env_init ); original_sys_init = copy_ptree( spc.sys_init ); for (i = 0; i < original_num_egoals; i++) *(original_env_goals+i) = copy_ptree( *(spc.env_goals+i) ); for (i = 0; i < original_num_sgoals; i++) *(original_sys_goals+i) = copy_ptree( *(spc.sys_goals+i) ); for (i = 0; i < original_et_array_len; i++) *(original_env_trans_array+i) = copy_ptree( *(spc.env_trans_array+i) ); for (i = 0; i < original_st_array_len; i++) *(original_sys_trans_array+i) = copy_ptree( *(spc.sys_trans_array+i) ); } if (expand_nonbool_GR1( spc.evar_list, spc.svar_list, &spc.env_init, &spc.sys_init, &spc.env_trans_array, &spc.et_array_len, &spc.sys_trans_array, &spc.st_array_len, &spc.env_goals, spc.num_egoals, &spc.sys_goals, spc.num_sgoals, init_flags, verbose ) < 0) { if (verification_model > 0) { for (j = 0; j < original_num_egoals; j++) free( *(original_env_goals+j) ); free( original_env_goals ); for (j = 0; j < original_num_sgoals; j++) free( *(original_sys_goals+j) ); free( original_sys_goals ); for (j = 0; j < original_et_array_len; j++) free( *(original_env_trans_array+j) ); free( original_env_trans_array ); for (j = 0; j < original_st_array_len; j++) free( *(original_sys_trans_array+j) ); free( original_sys_trans_array ); } return -1; } spc.nonbool_var_list = expand_nonbool_variables( &spc.evar_list, &spc.svar_list, verbose ); /* Merge component safety (transition) formulas */ if (spc.et_array_len > 1) { spc.env_trans = merge_ptrees( spc.env_trans_array, spc.et_array_len, PT_AND ); } else if (spc.et_array_len == 1) { spc.env_trans = *spc.env_trans_array; } else { fprintf( stderr, "Syntax error: GR(1) specification is missing environment" " transition rules.\n" ); return 2; } if (spc.st_array_len > 1) { spc.sys_trans = merge_ptrees( spc.sys_trans_array, spc.st_array_len, PT_AND ); } else if (spc.st_array_len == 1) { spc.sys_trans = *spc.sys_trans_array; } else { fprintf( stderr, "Syntax error: GR(1) specification is missing system" " transition rules.\n" ); return 2; } if (verbose > 1) /* Dump the spec to show results of conversion (if any). */ print_GR1_spec( spc.evar_list, spc.svar_list, spc.env_init, spc.sys_init, spc.env_trans_array, spc.et_array_len, spc.sys_trans_array, spc.st_array_len, spc.env_goals, spc.num_egoals, spc.sys_goals, spc.num_sgoals, NULL ); num_env = tree_size( spc.evar_list ); num_sys = tree_size( spc.svar_list ); manager = Cudd_Init( 2*(num_env+num_sys), 0, CUDD_UNIQUE_SLOTS, CUDD_CACHE_SLOTS, 0 ); Cudd_SetMaxCacheHard( manager, (unsigned int)-1 ); Cudd_AutodynEnable( manager, CUDD_REORDER_SAME ); if (run_option == GR1C_MODE_INTERACTIVE) { /* NOT IMPLEMENTED YET FOR NONBOOL VARIABLES */ if (spc.nonbool_var_list != NULL) { fprintf( stderr, "gr1c interaction does not yet support specifications" " with nonboolean domains.\n" ); return -1; } i = levelset_interactive( manager, init_flags, stdin, stdout, verbose ); if (i == 0) { printf( "Not realizable.\n" ); return 3; } else if (i < 0) { printf( "Failure during interaction.\n" ); return -1; } T = NULL; /* To avoid seg faults by the generic clean-up code. */ } else { T = check_realizable( manager, init_flags, verbose ); if (run_option == GR1C_MODE_REALIZABLE) { if ((verbose == 0) || (getlogstream() != stdout)) { if (T != NULL) { printf( "Realizable.\n" ); } else { printf( "Not realizable.\n" ); } } } if (verbose) { if (T != NULL) { logprint( "Realizable." ); } else { logprint( "Not realizable." ); } } if (run_option == GR1C_MODE_SYNTHESIS && T != NULL) { if (verbose) logprint( "Synthesizing a strategy..." ); strategy = synthesize( manager, init_flags, verbose ); if (verbose) logprint( "Done." ); if (strategy == NULL) { fprintf( stderr, "Error while attempting synthesis.\n" ); return -1; } } } if (strategy != NULL) { /* De-expand nonboolean variables */ tmppt = spc.nonbool_var_list; while (tmppt) { aut_compact_nonbool( strategy, spc.evar_list, spc.svar_list, tmppt->name, tmppt->value ); tmppt = tmppt->left; } num_env = tree_size( spc.evar_list ); num_sys = tree_size( spc.svar_list ); } if (strategy != NULL) { /* Open output file if specified; else point to stdout. */ if (output_file_index >= 0) { fp = fopen( argv[output_file_index], "w" ); if (fp == NULL) { perror( __FILE__ ", fopen" ); return -1; } } else { fp = stdout; } if (verbose) logprint( "Dumping automaton of size %d...", aut_size( strategy ) ); if (format_option == OUTPUT_FORMAT_TEXT) { list_aut_dump( strategy, num_env+num_sys, fp ); } else if (format_option == OUTPUT_FORMAT_DOT) { if (spc.nonbool_var_list != NULL) { dot_aut_dump( strategy, spc.evar_list, spc.svar_list, DOT_AUT_ATTRIB, fp ); } else { dot_aut_dump( strategy, spc.evar_list, spc.svar_list, DOT_AUT_BINARY | DOT_AUT_ATTRIB, fp ); } } else if (format_option == OUTPUT_FORMAT_AUT) { aut_aut_dump( strategy, num_env+num_sys, fp ); } else if (format_option == OUTPUT_FORMAT_JSON) { json_aut_dump( strategy, spc.evar_list, spc.svar_list, fp ); } else { /* OUTPUT_FORMAT_TULIP */ tulip_aut_dump( strategy, spc.evar_list, spc.svar_list, fp ); } if (fp != stdout) fclose( fp ); if (verification_model > 0) { /* Currently, only target supported is Spin Promela */ spin_aut_dump( strategy, spc.evar_list, spc.svar_list, original_env_init, original_sys_init, original_env_trans_array, original_et_array_len, original_sys_trans_array, original_st_array_len, original_env_goals, original_num_egoals, original_sys_goals, original_num_sgoals, stdout, NULL ); } } /* Clean-up */ delete_tree( spc.evar_list ); delete_tree( spc.svar_list ); delete_tree( spc.nonbool_var_list ); delete_tree( spc.env_init ); delete_tree( spc.sys_init ); delete_tree( spc.env_trans ); free( spc.env_trans_array ); delete_tree( spc.sys_trans ); free( spc.sys_trans_array ); for (i = 0; i < spc.num_egoals; i++) delete_tree( *(spc.env_goals+i) ); if (spc.num_egoals > 0) free( spc.env_goals ); for (i = 0; i < spc.num_sgoals; i++) delete_tree( *(spc.sys_goals+i) ); if (spc.num_sgoals > 0) free( spc.sys_goals ); if (T != NULL) Cudd_RecursiveDeref( manager, T ); if (strategy) delete_aut( strategy ); if (verbose > 1) logprint( "Cudd_CheckZeroRef -> %d", Cudd_CheckZeroRef( manager ) ); Cudd_Quit(manager); if (logging_flag) closelogfile(); /* Return 0 if realizable, 1 if not realizable. */ if (run_option == GR1C_MODE_INTERACTIVE || T != NULL) { return 0; } else { return 3; } return 0; }
slivingston/gr1c
src/main.c
C
bsd-3-clause
26,857
// LessEqualOperator.java. // Copyright (C) 2004 Naom Nisan, Ziv Balshai, Amir Levy. // See full copyright license terms in file ../GPL.txt package SFE.Compiler.Operators; import SFE.Compiler.AssignmentStatement; import SFE.Compiler.BinaryOpExpression; import SFE.Compiler.BlockStatement; import SFE.Compiler.BooleanExpressions; import SFE.Compiler.BooleanType; import SFE.Compiler.Expression; import SFE.Compiler.LvalExpression; import SFE.Compiler.SLPTReduction; import SFE.Compiler.StatementBuffer; import SFE.Compiler.Type; /** * A class for representing &lt;= operator expressions that can be defined * in the program. */ public class LessEqualOperator extends ScalarOperator implements SLPTReduction { //~ Methods ---------------------------------------------------------------- /** * Returns a string representation of the object. */ public String toString() { return "<="; } /** * Returns 2 as the arity of this PlusOperator. * Arity is 1 for unary ops; 2 for binary ops; 3 for ternary ops; * 0 for constants * @return 2 as the arity of this PlusOperator. */ public int arity() { return 2; } /** * Transforms this multibit expression into singlebit statements * and returns the result. * @param obj the AssignmentStatement that holds this GreaterOperator. * @return a BlockStatement contating the result statements. */ public BlockStatement toSLPTCircuit(Object obj) { AssignmentStatement as = ((AssignmentStatement) obj); LvalExpression lhs = as.getLHS(); //LHS of the param statement BinaryOpExpression rhs = (BinaryOpExpression) (as.getRHS()); BlockStatement result = new BlockStatement(); Expression right = rhs.getRight(); Expression left = rhs.getLeft(); Expression less = new BinaryOpExpression(new LessOperator(), left, right); Expression equal = new BinaryOpExpression(new EqualOperator(), left, right); result.addStatement(new AssignmentStatement(lhs, BooleanExpressions.or(less, equal)).toSLPTCircuit(null)); return result; } /** * Returns an int theat represents the priority of the operator * @return an int theat represents the priority of the operator */ public int priority() { return 1; } public Type getType(Object obj) { return new BooleanType(); } public Expression inlineOp(StatementBuffer assignments, Expression... args) { throw new RuntimeException("Not implemented"); } public Expression resolve(Expression... args) { Expression less = new LessOperator().resolve(args[0], args[1]); Expression equal = new EqualOperator().resolve(args[0], args[1]); if (less != null && equal != null){ return new OrOperator().resolve(less, equal); } return null; } }
srinathtv/pepper
compiler/frontend/src/SFE/Compiler/Operators/LessEqualOperator.java
Java
bsd-3-clause
2,810
{% extends "layout.html" %} {% block name %}Your Profile{% endblock %} {% block style %} <style type="text/css"> label, h1 { font-family: "Courier New Lucida Console", couriers, serif; } body { background-image: url("/static/img/profile_bg.jpg"); } </style> {% endblock %} {% block content %} <div class="panel panel-default col-md-6 col-md-offset-3"> <div class="panel-body"> <h1>Your Profile</h1> <form action="/profile" method="POST"> <div class="form-group"> <label for="email">Email Address</label> <input name="email" class="form-control" type="email" placeholder="change email" value="{{ email }}"> </div> <div class="form-group"> <label for="username">Username</label> <input name="username" class="form-control"type:"text" placeholder="username" value="{{ name }}"> </div> <button type="submit">Save Changes</button> </form> <form action="/profile/password" method="POST"> <div class="form-group"> <label for="pwd">New Password</label> <input name="pwd" class="form-control" type="password" placeholder="new password"> </div> <div class="form-group"> <label for="pwd_confirm">Confirm Password</label> <input name="pwd_confirm"class="form-control" type="password" placeholder="confirm password"> </div> <button type="submit">Change Password</button> </form> </div> </div> {% endblock %}
tech-sassy-girlz/Piculiar
piculiar/templates/profile.html
HTML
bsd-3-clause
1,386
{% load staticfiles %} <!doctype html> <!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!-- Consider adding a manifest.appcache: h5bp.com/d/Offline --> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <!-- Use the .htaccess and remove these lines to avoid edge case issues. More info: h5bp.com/i/378 --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>{% block page_title %}{{ _("The Django Tutorial App") }}{% endblock %}</title> <meta name="description" content="{% block meta_description %}{% endblock %}"> <meta name="author" content="{% block meta_author %}{% endblock %}"> <!-- Mobile viewport optimized: h5bp.com/viewport --> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory: mathiasbynens.be/notes/touch-icons --> <link rel="stylesheet" href="{{ STATIC_URL }}css/style.css"> {% block css %}{% endblock %} <!-- More ideas for your <head> here: h5bp.com/d/head-Tips --> <!-- All JavaScript at the bottom, except this Modernizr build. Modernizr enables HTML5 elements & feature detects for optimal performance. Create your own custom Modernizr build: www.modernizr.com/download/ --> <script src="{{ STATIC_URL }}js/libs/modernizr-2.5.3-respond-1.1.0.min.js"></script> </head> <body class="{% block body_class %}{% endblock %}"> {% include "nav.html" %} </div><!-- /.container --> {% block body %} <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you support IE 6. chromium.org/developers/how-tos/chrome-frame-getting-started --> <!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]--> <header> </header> <div role="main"> {% block content %}{% endblock %} </div> {% include "footer.html" %} <!-- JavaScript at the bottom for fast page loading --> <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="{{ STATIC_URL }}js/libs/jquery-1.7.1.min.js"><\/script>')</script> <!-- scripts concatenated and minified via build script --> <script src="{{ STATIC_URL }}js/plugins.js"></script> <script src="{{ STATIC_URL }}js/script.js"></script> <!-- end scripts --> <!-- Asynchronous Google Analytics snippet. Change UA-XXXXX-X to be your site's ID. mathiasbynens.be/notes/async-analytics-snippet --> <script> var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']]; (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; s.parentNode.insertBefore(g,s)}(document,'script')); </script> {% endblock %} </body> </html>
seslattery/django-sample-app
djtut2/base/templates/base.html
HTML
bsd-3-clause
3,370
/* * File: main.h * * Copyright (c) 2011, Kustaa Nyholm / SpareTimeLabs * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its * contributors may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ // Turn off PIC extended instruction set, nobody supports it properly #pragma config XINST=OFF #include "types.h" #include <pic18fregs.h> #include "usb_defs.h" #include "toad4.h" #include "pic-config.c" #include "usb_core.h" #include "command_queue.h" #include "usb_hid.h" #include "usb_pic_defs.h" #include "swuart.h" #include <string.h> // memcpyram2ram, memcpypgm2ram #define HOME_0 HOME_X #define HOME_1 HOME_Y #define HOME_2 HOME_Z #define HOME_3 HOME_A #define HOME_4 HOME_B #define ENABLE_0 ENABLE_X #define ENABLE_1 ENABLE_Y #define ENABLE_2 ENABLE_Z #define ENABLE_3 ENABLE_A #define ENABLE_4 ENABLE_B /* #define TORQUE_0 TORQUE_ #define TORQUE_1 TORQUE_Y #define TORQUE_2 TORQUE_Z #define TORQUE_3 TORQUE_A */ #define ENABLE_MOTOR(i,e) do { \ ENABLE_##i = e; \ } while (0) #define CMD_MOVE 1 #define CMD_RESET_POSITION 2 #define CMD_REINIT_MOTOR 3 #define CMD_RESET_MOTOR 4 typedef union { uint8_t uint8; struct { unsigned bit_0 :1; unsigned bit_1 :1; unsigned bit_2 :1; unsigned bit_3 :1; unsigned bit_4 :1; unsigned bit_5 :1; unsigned bit_6 :1; unsigned bit_7 :1; }; } uint8bits_t; typedef struct { int32_t position; uint8_t queue_state; unsigned home :1; // bit 0 unsigned obs_reserved_1 :1; unsigned obs_reserved_2 :1; unsigned obs_reserved_3 :1; unsigned obs_reserved_4 :1; unsigned obs_reserved_5 :1; unsigned obs_reserved_6 :1; unsigned obs_reserved_7 :1; // bit 7 uint8_t obs_sync_counter; unsigned obs_ready :1; // bit 0 unsigned obs_ready2 :1; unsigned obs_not_busy :1; unsigned obs_not_busy2 :1; unsigned obs_not_empty :1; unsigned obs_reserved_8 :1; unsigned obs_in_sync :1; unsigned obs_reserved_9 :1; // bit 7 } stepper_status_t; // dev => host status typedef struct { uint32_t debug_position; uint8_t debug[4]; uint8_t printf[8]; stepper_status_t steppers[6]; } toad4_status_t; static uint8_t g_group_masks[NUMBER_OF_MOTORS + 1]; static uint8_t g_blink_speed = 0; static uint8_t g_led_toggle_counter = 0; static uint16_t g_blink_counter = 0; static uint8_t g_special_request = 0; static uint8_t g_RCON; static union { uint8_t uint8; struct { unsigned probe_input :1; // bit 0 unsigned probe_triggered :1; unsigned probe_armed_trig_on_1 :1; unsigned probe_armed_trig_on_0 :1; unsigned bit_4 :1; unsigned bit_5 :1; unsigned bit_6 :1; unsigned bit_7 :1; }; } g_probe; static union { uint8_t uint8; struct { unsigned arc_transfer :1; // bit 0 unsigned bit_1 :1; unsigned bit_2 :1; unsigned bit_3 :1; unsigned bit_4 :1; unsigned bit_5 :1; unsigned bit_6 :1; unsigned bit_7 :1; }; } g_digital_inputs; static volatile toad4_status_t g_toad4_status; // this gets sent to host in toto static volatile uint8_t g_low_pri_isr_guard; static uint8_t g_sync_counter[NUMBER_OF_MOTORS] = { 0 }; static uint8_t g_message_id = 0; //extern volatile uint8_t g_pwm_out; // declared in hi_speed_irq.asm static volatile uint8_t g_ADCresult; extern uint8_t g_hipri_int_flags; extern uint8_t g_lopri_int_flags; volatile uint8_t g_uart_msg[2]; volatile uint8_t g_uart_msg_byte = 0; volatile uint8_t g_manmode_switches; volatile uint8_t g_manmode_potentiometer; volatile uint8_t g_manmode_on; #define BITCPY(d,s) do {if (s) d=1; else d=0;} while(0) #define STEPPER(i) g_stepper_states[i] #define INIT_MOTOR(i) do { \ g_toad4_status.steppers[i].position = 0; \ g_stepper_states[i].next_dir = 0; \ g_stepper_states[i].next_forward = 0; \ g_stepper_states[i].next_reverse = 1; \ g_stepper_states[i].next_steps = 0; \ g_stepper_states[i].last_steps = 0; \ g_stepper_states[i].steps = 0; \ g_stepper_states[i].speed = 0; \ g_stepper_states[i].position = 0; \ g_stepper_states[i].sync_group = i; \ g_stepper_states[i].busy_mask = 0xFF; \ g_stepper_states[i].group_mask = 0xFF; \ QUEUE_CLEAR(i); \ } while(0) #define RESET_MOTOR(i) do { \ g_toad4_status.steppers[i].position = 0; \ g_stepper_states[i].next_dir = 0; \ g_stepper_states[i].next_forward = 0; \ g_stepper_states[i].next_reverse = 1; \ g_stepper_states[i].next_steps = 0; \ g_stepper_states[i].last_steps = 0; \ g_stepper_states[i].steps = 0; \ g_stepper_states[i].speed = 0; \ g_stepper_states[i].sync_group = i; \ g_stepper_states[i].busy_mask = 0xFF; \ g_stepper_states[i].group_mask = 0xFF; \ QUEUE_CLEAR(i); \ } while(0) #define UPDATE_POS(i) do { \ if (STEPPER(i).update_pos){ \ STEPPER(i).update_pos = 0; \ if (STEPPER(i).next_dir) \ STEPPER(i).position += STEPPER(i).last_steps; \ else \ STEPPER(i).position -= STEPPER(i).last_steps; \ STEPPER(i).last_steps = 0; \ }\ }while(0) #define FEED_MOREX(i) do { \ }while(0) #define UPDATE_NOT_EMPTY(i) do { \ if (QUEUE_EMPTY(i)) \ g_not_empty_flags.not_empty_##i = 0; \ else \ g_not_empty_flags.not_empty_##i = 1; \ }while(0) extern uint8_t g_debug_count; #define FEED_MORE(i) do { \ if ((g_lopri_int_flags & STEPPER(i).group_mask) == 0) { \ int16_t distance = QUEUE_FRONT(i)->move_distance; \ if (distance < 0) { \ if (STEPPER(i).next_dir) { \ STEPPER(i).next_dir = 0; \ STEPPER(i).next_forward = 0; \ STEPPER(i).next_reverse = 1; \ } \ distance = -distance; \ } \ else if (distance > 0) { \ if (!STEPPER(i).next_dir) { \ STEPPER(i).next_dir = 1; \ STEPPER(i).next_forward = 1; \ STEPPER(i).next_reverse = 0; \ } \ } \ if (distance > 255) \ distance = 255; \ STEPPER(i).next_steps = distance; \ STEPPER(i).last_steps = distance; \ STEPPER(i).update_pos = 1; \ STEPPER(i).next_speed = QUEUE_FRONT(i)->move_speed; \ if (STEPPER(i).next_dir) \ QUEUE_FRONT(i)->move_distance -= distance; \ else \ QUEUE_FRONT(i)->move_distance += distance; \ if (QUEUE_FRONT(i)->move_distance == 0) \ g_pop_flags.pop_##i = 0; \ /* g_not_empty_flags.not_empty_##i = 1; */ \ g_ready_flags.ready_##i = 0; \ } \ }while(0) #define POP_QUEUE(i) do { \ if ((g_pop_flags.pop_bits & STEPPER(i).group_mask) == 0) \ QUEUE_POP(i); \ } while(0) #define UPDATE_HOME(i) do { \ if (STEPPER(i).seek_home || STEPPER(i).seek_not_home) { \ if (STEPPER(i).seek_home && HOME_##i) {\ STEPPER(i).seek_home = 0; \ break; \ } \ if (STEPPER(i).seek_not_home && !HOME_##i) { \ STEPPER(i).seek_not_home = 0; \ break; \ } \ if (STEPPER(i).seek_reverse) \ STEPPER(i).jog_reverse = 1; \ else \ STEPPER(i).jog_reverse = 0; \ STEPPER(i).jog_on = 1; \ } \ }while(0) #define PROCESS_MOTOR_COMMANDS(i) do { \ uint8_t cmd = hid_rx_buffer.uint8[i*8+0]; \ uint8_t flags = hid_rx_buffer.uint8[i*8+1]; \ if (flags & 0x10) \ ENABLE_MOTOR(i,1); \ else \ ENABLE_MOTOR(i,0); \ if (cmd == CMD_MOVE) { \ /* uint8_t dist = hid_rx_buffer.uint8[i*8+2]; */ \ uint16_t dist = hid_rx_buffer.uint16[i*4+1]; \ /* uint8_t dir = hid_rx_buffer.uint8[i*8+3]; */ \ uint16_t speed = hid_rx_buffer.uint16[i*4+2]; \ /* QUEUE_REAR(i)->move_dir = dir; */ \ QUEUE_REAR(i)->move_distance = dist; \ QUEUE_REAR(i)->move_speed = speed; \ QUEUE_PUSH(i); \ } else if (cmd == CMD_RESET_POSITION) { \ STEPPER(i).position = hid_rx_buffer.int32[i*2+1]; \ } else if (cmd == CMD_REINIT_MOTOR) { \ INIT_MOTOR(i); \ } else if (cmd == CMD_RESET_MOTOR) { \ RESET_MOTOR(i); \ } \ }while(0) #define UPDATE_STATUS(i) do { \ if (!g_probe.probe_triggered) \ g_toad4_status.steppers[i].position = get_position(i); \ g_toad4_status.steppers[i].queue_state =QUEUE_SIZE(i)+(QUEUE_CAPACITY<<4); \ if (g_busy_flags.busy_##i) \ g_toad4_status.steppers[i].queue_state++; \ BITCPY(g_toad4_status.steppers[i].home , HOME_##i); \ }while(0) #define UPDATE_SYNC_GROUP(i) \ STEPPER(i).sync_group = hid_rx_buffer.uint8[i*8+1] & 0x07 #define UPDATE_GROUP_MASK_1(i) \ g_group_masks[i] = 0 #define UPDATE_GROUP_MASK_2(i) \ g_group_masks[STEPPER(i).sync_group] |= 1 << i #define UPDATE_GROUP_MASK_3(i) \ STEPPER(i).group_mask = g_group_masks[STEPPER(i).sync_group] void UPDATE_OUTPUTS(unsigned char x) { if ((x) & 0x01) SPINDLE_FWD = 1; else SPINDLE_FWD = 0; if ((x) & 0x02) SPINDLE_REV = 1; else SPINDLE_REV = 0; if ((x) & 0x04) COOLANT = 1; else COOLANT = 0; #if TOAD_HW_VERSION== HW5 if ((x) & 0x08) ARC_START = 1; else ARC_START = 0; #endif } // 0-17 => 0 // 18 => 0 // 255 => 948 #define UPDATE_PWM(x) do {\ uint16_t x16 = 0; \ if ((x)>0) \ x16=35+x*62/16; \ CCPR2L = x16>>2; \ CCP2CON = (CCP2CON & 0xCF) | ((x16 << 4) & 0x30); \ } while(0) // To change number of motors supported you need to // 1) change this macro // 2) possibly adjust the hi-speed interrupt frequency // 3) update the number of motor in the hi speed interrupt asm code where it is hard coded #if NUMBER_OF_MOTORS==3 #define FOR_EACH_MOTOR_DO(DO_THIS_FOR_ONE_MOTOR) do { \ DO_THIS_FOR_ONE_MOTOR(0); \ DO_THIS_FOR_ONE_MOTOR(1); \ DO_THIS_FOR_ONE_MOTOR(2); \ }while(0) #endif #if NUMBER_OF_MOTORS==4 #define FOR_EACH_MOTOR_DO(DO_THIS_FOR_ONE_MOTOR) do { \ DO_THIS_FOR_ONE_MOTOR(0); \ DO_THIS_FOR_ONE_MOTOR(1); \ DO_THIS_FOR_ONE_MOTOR(2); \ DO_THIS_FOR_ONE_MOTOR(3); \ }while(0) #endif #if NUMBER_OF_MOTORS==5 #define FOR_EACH_MOTOR_DO(DO_THIS_FOR_ONE_MOTOR) do { \ DO_THIS_FOR_ONE_MOTOR(0); \ DO_THIS_FOR_ONE_MOTOR(1); \ DO_THIS_FOR_ONE_MOTOR(2); \ DO_THIS_FOR_ONE_MOTOR(3); \ DO_THIS_FOR_ONE_MOTOR(4); \ }while(0) #endif #if NUMBER_OF_MOTORS==6 #define FOR_EACH_MOTOR_DO(DO_THIS_FOR_ONE_MOTOR) do { \ DO_THIS_FOR_ONE_MOTOR(0); \ DO_THIS_FOR_ONE_MOTOR(1); \ DO_THIS_FOR_ONE_MOTOR(2); \ DO_THIS_FOR_ONE_MOTOR(3); \ DO_THIS_FOR_ONE_MOTOR(4); \ DO_THIS_FOR_ONE_MOTOR(5); \ }while(0) #endif #pragma save #pragma nooverlay int32_t get_position(uint8_t i) { uint8_t stp; int32_t pos; do { // loop until we have a reading not disturbed by the lo priority interrupt stp = g_low_pri_isr_guard; pos = g_stepper_states[i].position; } while (stp != g_low_pri_isr_guard); return pos; } #pragma restore #pragma save #pragma nojtbound #pragma nooverlay typedef union { uint16_t as_uint16; struct { uint8_t as_uint8_lo; uint8_t as_uint8_hi; }; } uint8uint16_t; volatile uint8_t g_pwm_toggle = 0; volatile uint16_t g_pwm_lo = 2400; volatile uint16_t g_pwm_hi = 2400; volatile uint8uint16_t g_ccp2_next; volatile uint8uint16_t g_tmr3; char rxbyte[4]={0}; static unsigned char rxcnt=0; void low_priority_interrupt_service() __interrupt(2) { if (PIR2bits.CCP2IF) { g_low_pri_isr_guard++; PIR2bits.CCP2IF = 0; FOR_EACH_MOTOR_DO(UPDATE_NOT_EMPTY); g_lopri_int_flags = ~(g_ready_flags.ready_bits & g_not_empty_flags.not_empty_bits); g_pop_flags.pop_bits = 0xFF; FOR_EACH_MOTOR_DO(FEED_MORE); FOR_EACH_MOTOR_DO(POP_QUEUE); FOR_EACH_MOTOR_DO(UPDATE_POS); } // End of 'software' interrupt processing if (PIR2bits.TMR3IF) { PIR2bits.TMR3IF = 0; } if (INTCONbits.TMR0IF) { INTCONbits.TMR0IF = 0; swuart_tick(SW_UART); } // if (PIR2bits.CCP2IF) { // PIR2bits.CCP2IF = 0; // } if (PIR3bits.USBIF) { PIR3bits.USBIF = 0; usb_core_handler(); } if (PIR1bits.RC1IF) { uint8_t temp = RCREG1; PIR1bits.RC1IF = 0; if (temp==0xff && RCSTA1bits.RX9D==1) { rxcnt=0; } else { if (rxcnt<4) { rxbyte[rxcnt++]=temp; } } } } #pragma restore void enterBootloader() { __asm__ (" goto 0x0016\n"); } #define TOGGLE_LED_PIN() do {if (LED_PIN==LED_OFF) LED_PIN = LED_ON; else LED_PIN = LED_OFF; } while(0) //#define TOGGLE_LED_PIN() do {} while(0) void blink_led() { static uint8_t old = 0; uint8_t new; //new = TMR0L; // need to read TMR0L to get TMR0H updated //new = TMR0H; new = g_uart_tick_cntr; // since uart tick increments when 8 bit TMR0 overflows this is equivalent to previous if (new != old) { old = new; g_blink_counter++; if (g_blink_speed == 0 && g_blink_counter > 732) { g_blink_counter = 0; TOGGLE_LED_PIN(); } if (g_blink_speed == 1 && g_blink_counter > 732 / 2) { g_blink_counter = 0; g_blink_speed = 0; TOGGLE_LED_PIN(); } } } void toggle_led() { g_blink_counter = 0; g_led_toggle_counter++; if ((g_led_toggle_counter & 3) == 0) TOGGLE_LED_PIN(); } void check_for_firmware_update() { if ((hid_rx_buffer.uint8[0] == 0xFE) && (hid_rx_buffer.uint8[1] == 0xED) && (hid_rx_buffer.uint8[2] == 0xC0) && (hid_rx_buffer.uint8[3] == 0xDE)) { hid_rx_buffer.uint8[63] = 0; // WHY? enterBootloader(); } } void check_probe() { BITCPY(g_probe.probe_input, PROBE); if (g_probe.probe_input & g_probe.probe_armed_trig_on_1) g_probe.probe_triggered = 1; if (!g_probe.probe_input & g_probe.probe_armed_trig_on_0) g_probe.probe_triggered = 1; } void handle_manual_mode() { if (g_uart_rx_ready) { g_uart_rx_ready = 0; // note that a new char arrives at 30 msec interval so we trust // that g_uart_rx_data does not change on us if (g_uart_rx_bit9 == 1) { // first byte if (g_uart_rx_data == 0xFF) { //LED_PIN=1; g_uart_msg_byte = 1; } } else { // rest of the bytes if (g_uart_rx_bit9 == 1) g_uart_msg_byte = 0; switch (g_uart_msg_byte++) { default: g_uart_msg_byte = 0; break; case 1: g_uart_msg[0] = g_uart_rx_data; break; case 2: if (g_uart_msg[0] != (uint8_t)(~g_uart_rx_data)) g_uart_msg_byte = 0; break; case 3: g_uart_msg[1] = g_uart_rx_data; break; case 4: if (g_uart_msg[1] != (uint8_t)(~g_uart_rx_data)) { g_uart_msg_byte = 0; break; } if (((g_uart_msg[0] ^ (g_uart_msg[0] >> 4)) & 0xF) == 0xF) { //LED_PIN=0; // Got the full message, now process it g_manmode_potentiometer = g_uart_msg[1]; UPDATE_PWM(g_manmode_potentiometer); g_manmode_switches = g_uart_msg[0] >> 4; SPINDLE_FWD = g_manmode_switches & 0x2; SPINDLE_REV = g_manmode_switches & 0x4; COOLANT = g_manmode_switches & 0x8; } break; } } } } void main(void) { // Capture the reset cause flags and clear them // FIXME, should we actually clear them not at startup (here) // but AFTER connecting to the host so that cycling MACH // in EazyCNC would clear the watcdog error/message? unsigned int i; ANSELA = 0x00; TRISA = 0xC0; LATA = 0x15; g_RCON = RCON; RCON |= 0x1F; initIO(); g_ready_flags.ready_bits = 0xFF; g_busy_flags.busy_bits = 0x00; g_not_empty_flags.not_empty_bits = 0x00; FOR_EACH_MOTOR_DO(INIT_MOTOR); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_1); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_2); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_3); // FIXME why do we configure RC6 which is USART TX as output, it is not used. // Was it for debugging? TRISCbits.TRISC6 = 0; T0CONbits.T0CS = 0; // Internal instruction clock as source for timer 0 T0CONbits.PSA = 0; // Enable prescaler for Timer 0 T0CONbits.T08BIT = 1; // 8 bit T0CONbits.T0PS2 = 1; // prescaler 1:32 => 1464 Hz T0CONbits.T0PS1 = 0; T0CONbits.T0PS0 = 0; T0CONbits.TMR0ON = 1; // XXX T0CONbits.T0SE = 1; // high to low (no effect when timer clock coming from instruction clock...) INTCON = 0; // Clear interrupt flag bits. TMR0L = 0; TMR0H = 0; T1CONbits.T1CKPS0 = 0; T1CONbits.T1CKPS1 = 0; T1CONbits.TMR1CS = 0; CCPTMRSbits.C1TSEL = 0; // CCP1 uses TMR1 (compares agains it) CCPR1H = 0; CCPR1L = 120; // 12 MHz/120 = 100 kHz CCP1CON = 0x0B; // special event trigger, set CCP1IF on match, reset timer T1CONbits.TMR1ON = 1; // NOTE! CCP2IF is used as software interrupt flag, // in the TMR2 PWM mode/configuration it is not set or cleared by the hardware PIR2bits.CCP2IF = 1; // Ensure no interrupts are enabled at this point PIE1 = 0; PIE2 = 0; PIE3 = 0; // Ensure that all interrupts are low priority IPR1 = 0; IPR2 = 0; IPR3 = 0; // FIXME there are other than interrupt priority bits in these regs so // would be cleaner to set (clear) each one separately or relay on reset values INTCON = 0; INTCON2 = 0; INTCON3 = 0; // ... except make CCP1 interrupt high priority IPR1bits.CCP1IP = 1; // was TMR2IP !! RCONbits.IPEN = 1; // enable priorities // TIMER 2 configuration T2CONbits.T2CKPS0 = 1; T2CONbits.T2CKPS1 = 1; PR2 = 255; CCPR2L = 25; CCP2CONbits.CCP2M = 0x0C; // PWM mode T2CONbits.TMR2ON = 1; T3GCONbits.TMR3GE = 0; T3CONbits.T3CKPS0 = 1; T3CONbits.T3CKPS1 = 1; T3CONbits.TMR3CS0 = 0; T3CONbits.TMR3CS1 = 0; T3CONbits.SOSCEN = 0; T3CONbits.NOT_T3SYNC = 0; T3CONbits.RD16 = 0; T3CONbits.TMR3ON = 1; CCPTMRSbits.C2TSEL = 1; // Make the PWM pin PB3 output TRISBbits.TRISB3 = 0; // Initialize the USB stack usb_core_init(); // Turn the run LED on LED_PIN = LED_ON; // Init EUSART // ABDOVF no_overflow; CKTXP async_noninverted_sync_fallingedge; BRG16 16bit_generator; WUE disabled; ABDEN disabled; DTRXP not_inverted; BAUDCON1 = 0x08; // SPEN enabled; RX9 9-bit; CREN enabled; ADDEN disabled; SREN disabled; RCSTA1 = 0xD0; // TX9 9-bit; TX9D 0; SENDB sync_break_complete; TXEN enabled; SYNC asynchronous; BRGH hi_speed; CSRC slave_mode; TXSTA1 = 0x64; // SPBRG1 1249; SPBRG1 = 1249%256; // SPBRGH1 0; SPBRGH1 = 1249/256; // This seems to be as good a place as any to document interrupt usage // TMR2 interrupt = high priority, written in asm, running the NCOs (Numerically Controlled Oscillators) // CCP1 interrupt = used to feed the high priority NCO interrupt // USB interrupt = low priority, runs the USB stack, what else // TMR3 interrupt = no funtion // CCP2 interrupt = no function // Enable interrupts PIE1bits.CCP1IE = 1; PIE3bits.USBIE = 1; PIE2bits.CCP2IE = 1; INTCONbits.TMR0IE = 1; PIE1bits.RCIE = 1; INTCONbits.PEIE = 1; // enable peripheral interrupts INTCONbits.GIE = 1; // global interrupt enable /* g_manmode_on = 1; TRISCbits.TRISC2 = 0; // dir=output LATCbits.LATC2 = 1; while (1) { unsigned int i=0; for (i=0; i<65535; i++) g_manmode_on=1; LATCbits.LATC2 = !LATCbits.LATC2; } */ // Enable the watchdog WDTCONbits.SWDTEN = 1; while (1) { __asm__ (" CLRWDT "); // trig sw interrupt so that the queues get updated PIR2bits.CCP2IF = 1; // If manual/cnc mode changes clear spindle and coolant if (g_manmode_on != (g_uart_connected != 0)) { g_manmode_on = !g_manmode_on; UPDATE_OUTPUTS(0); UPDATE_PWM(0); } if (g_manmode_on) handle_manual_mode(); if (!(ep2_o.STAT & UOWN)) { // new data from host, so process it g_message_id = hid_rx_buffer.uint8[63]; toggle_led(); while (hid_rx_buffer.uint8[0] == 0x73) { // watchdog test // loops until watchdog reset } if (hid_rx_buffer.uint8[0] == 0xFE) { // special message check_for_firmware_update(); // may not ever return g_special_request = hid_rx_buffer.uint8[1]; } else { // normal message g_special_request = 0; FOR_EACH_MOTOR_DO(UPDATE_SYNC_GROUP); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_1); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_2); FOR_EACH_MOTOR_DO(UPDATE_GROUP_MASK_3); FOR_EACH_MOTOR_DO(PROCESS_MOTOR_COMMANDS); UPDATE_OUTPUTS(hid_rx_buffer.uint8[50]); UPDATE_PWM(hid_rx_buffer.uint8[52]); BITCPY(g_probe.probe_armed_trig_on_1, 0x01 & hid_rx_buffer.uint8[49]); BITCPY(g_probe.probe_armed_trig_on_0, 0x02 & hid_rx_buffer.uint8[49]); if (!g_probe.probe_armed_trig_on_1 && !g_probe.probe_armed_trig_on_0) g_probe.probe_triggered = 0; } // turn the buffer over to SIE so we can get more data ep2_o.CNT = 64; if (ep2_o.STAT & DTS) ep2_o.STAT = DTSEN; else ep2_o.STAT = DTS | DTSEN; ep2_o.STAT |= UOWN; } // update toad4 status, we do this all the time so as to be ready when we can send it over check_probe(); FOR_EACH_MOTOR_DO(UPDATE_STATUS); if (ADCON0bits.GO_NOT_DONE == 0) { g_ADCresult = ADRESH; ADCON0bits.GO_NOT_DONE = 1; } if (!(ep2_i.STAT & UOWN)) { // we own the USB buffer, so update data going to the host g_blink_speed = 1; hid_tx_buffer.uint8[63] = g_message_id; if (g_special_request == 0x01) { memcpypgm2ram(&hid_tx_buffer.uint8[0], get_toad4_config(), 63); hid_tx_buffer.uint8[62] = g_RCON; g_RCON = RCON; } else { uint8_t updf = 0; // FIXME make structure g_toad4_status so that we can use a single copy // or see if it would be better to create a memcpyram2ram that move 8 bytes // with direct move commands and no looping memcpyram2ram(&hid_tx_buffer.uint8[0], &g_toad4_status.steppers[0], 8); memcpyram2ram(&hid_tx_buffer.uint8[8], &g_toad4_status.steppers[1], 8); memcpyram2ram(&hid_tx_buffer.uint8[16], &g_toad4_status.steppers[2], 8); memcpyram2ram(&hid_tx_buffer.uint8[24], &g_toad4_status.steppers[3], 8); memcpyram2ram(&hid_tx_buffer.uint8[32], &g_toad4_status.steppers[4], 8); // FIXME, see if above and below could be combined to a single memcpyram2ram by // rearranging the structures /* DEBUG STUFF hid_tx_buffer.uint8[32] = g_stepper_states[0].steps; hid_tx_buffer.uint8[33] = g_stepper_states[0].last_steps; hid_tx_buffer.uint8[34] = g_stepper_states[0].next_steps; hid_tx_buffer.uint8[35] = g_stepper_states[0].update_pos; hid_tx_buffer.uint8[36] = g_stepper_states[1].steps; hid_tx_buffer.uint8[37] = g_stepper_states[1].last_steps; hid_tx_buffer.uint8[38] = g_stepper_states[1].next_steps; hid_tx_buffer.uint8[39] = g_stepper_states[1].update_pos; hid_tx_buffer.uint8[40] = g_stepper_states[2].steps; hid_tx_buffer.uint8[41] = g_stepper_states[2].last_steps; hid_tx_buffer.uint8[42] = g_stepper_states[2].next_steps; hid_tx_buffer.uint8[43] = g_stepper_states[2].update_pos; hid_tx_buffer.uint8[44] = g_stepper_states[3].steps; hid_tx_buffer.uint8[45] = g_stepper_states[3].last_steps; hid_tx_buffer.uint8[46] = g_stepper_states[3].next_steps; hid_tx_buffer.uint8[47] = g_stepper_states[3].update_pos; */ hid_tx_buffer.uint8[49] = g_probe.uint8; // & 0x03; // #if TOAD_HW_VERSION== HW5 g_digital_inputs.arc_transfer = ARC_TRANSFER; #endif hid_tx_buffer.uint8[50] = g_digital_inputs.uint8; hid_tx_buffer.uint8[51] = 0; // digital inputs 8-15 hid_tx_buffer.uint8[52] = rxbyte[0]; // g_ADCresult; // analog input 0 if (g_manmode_on) { hid_tx_buffer.uint8[53] = g_manmode_switches; hid_tx_buffer.uint8[54] = g_manmode_potentiometer; } else { hid_tx_buffer.uint8[53] = 0; hid_tx_buffer.uint8[54] = 0; } hid_tx_buffer.uint8[55] = rxbyte[0]; //rxbyte[0];// STEPPER(0).group_mask; hid_tx_buffer.uint8[56] = rxbyte[1];//STEPPER(1).group_mask; hid_tx_buffer.uint8[57] = rxbyte[2];//STEPPER(2).group_mask; hid_tx_buffer.uint8[58] = rxbyte[3];//STEPPER(3).group_mask; hid_tx_buffer.uint8[59] = g_debug_count; hid_tx_buffer.uint8[60] = g_not_empty_flags.not_empty_bits; hid_tx_buffer.uint8[61] = g_busy_flags.busy_bits; hid_tx_buffer.uint8[62] = g_ready_flags.ready_bits; } // turn the buffer over to the SIE so the host will pick it up ep2_i.CNT = 64; if (ep2_i.STAT & DTS) ep2_i.STAT = DTSEN; else ep2_i.STAT = DTS | DTSEN; ep2_i.STAT |= UOWN; } if(1 == RCSTA1bits.OERR) { // EUSART1 error - restart RCSTA1bits.CREN = 0; RCSTA1bits.CREN = 1; } if (PIR1bits.TX1IF) TXREG1 =0x00; blink_led(); } }
nyholku/TOAD4
src/main.c
C
bsd-3-clause
24,836
@echo off set KITTI_NAME="KITTI minimal validation dataset" rem ##################################################################### echo. echo "Downloading %KITTI_NAME% from '%KITTI_URL%' ..." wget --no-check-certificate -c "%KITTI_URL%" -O "%KITTI_ARCHIVE%" if %errorlevel% neq 0 ( echo. echo Error: Failed downloading archive ... goto err ) rem ##################################################################### echo. echo "Unpacking '%KITTI_ARCHIVE%' ..." cd /D "%INSTALL_DIR%" tar xvf "%KITTI_ARCHIVE%" if EXIST "%KITTI_ARCHIVE%" ( del /Q /S "%KITTI_ARCHIVE%" ) rem ##################################################################### echo. echo "Successfully installed %KITTI_NAME% ..." exit /b 0 :err exit /b 1
dsavenko/ck-tensorflow
package/dataset-kitti-min/install.bat
Batchfile
bsd-3-clause
740
# Mark Recapture Helper Scripts import json import DeriveFinalResultSet as DRS, mongod_helper as mh import DataStructsHelperAPI as DS import importlib import pandas as pd import warnings import sys, math importlib.reload(mh) def PRINT(jsonLike): print(json.dumps(jsonLike, indent=4)) def genNidMarkRecapDict(mongo_client, source, days_dict, filter_species=None): exif_tab_obj = mh.mongod_table(mongo_client, "exif_tab", source) cursor = exif_tab_obj.query(cols=['date']) img_dt_dict = mh.key_val_converter(cursor, 'date') # population estimation using GGR and GZC datasets are done using dates if source in ["GZC", "GGR"]: img_dt_dict = {gid: DS.getDateFromStr(img_dt_dict[gid], '%Y-%m-%d %H:%M:%S', '%Y-%m-%d') for gid in img_dt_dict.keys()} else: ''' generally, for population estimation using Flickr/Bing images, the images were divided into annual epochs, this could change and in that case the below line should be modified ''' img_dt_dict = {gid: DS.getDateFromStr(img_dt_dict[gid], '%Y-%m-%d %H:%M:%S', '%Y') for gid in img_dt_dict.keys()} # Retain only the gids for the dates in the days_dict filtered_gid = list(filter(lambda x: img_dt_dict[x] in days_dict.keys(), img_dt_dict.keys())) gid_days_num = {gid: days_dict[img_dt_dict[gid]] for gid in filtered_gid} gid_nid = DRS.getCountingLogic(mongo_client, "NID", source, False, mongo=True) if filter_species != None: try: gid_species = DRS.getCountingLogic(mongo_client, "SPECIES", source, False, mongo=True) except Exception as e: print("Exception occured at counting logic step") print(e) return gid_days_num = {gid: gid_days_num[gid] for gid in gid_days_num if gid in gid_species.keys() and filter_species in gid_species[gid]} nidMarkRecap = {} for gid in gid_days_num.keys(): # only iterate over the GIDs of interest if gid in gid_nid.keys(): # not all images with valid EXIF feature will have an annotation for nid in gid_nid[gid]: if int(nid) > 0: # and int(nid) != 45: # ignore all the false positives --and ignore NID 45 nidMarkRecap[nid] = nidMarkRecap.get(nid, []) + [gid_days_num[gid]] nidMarkRecapSet = {nid: list(set(nidMarkRecap[nid])) for nid in nidMarkRecap.keys()} return nidMarkRecapSet # Return Petersen-Lincoln Index for mark-recapture def applyMarkRecap(nidMarkRecapSet): uniqueIndsDay1 = {nid for nid in nidMarkRecapSet if 1 in nidMarkRecapSet[nid]} uniqueIndsDay2 = {nid for nid in nidMarkRecapSet if 2 in nidMarkRecapSet[nid]} marks = len(uniqueIndsDay1) recaptures = len(uniqueIndsDay1 & uniqueIndsDay2) day2_sights = len(uniqueIndsDay2) try: population = day2_sights * marks / recaptures confidence = 1.96 * math.sqrt(marks ** 2 * day2_sights * (day2_sights - recaptures) / recaptures ** 2) except: warnings.warn("There are no recaptures for this case.") population = 0 confidence = 0 return marks, recaptures, population, confidence def genSharedGids(gidList, gidPropMapFl, shareData='proportion', probabThreshold=1): df = pd.DataFrame.from_csv(gidPropMapFl) if shareData == 'proportion': gidPropDict = df['Proportion'].to_dict() highSharedGids = {str(gid) for gid in gidPropDict.keys() if float(gidPropDict[gid]) >= 80.0} else: gidShrDict = df['share'].to_dict() highSharedGids = {str(gid) for gid in gidShrDict.keys() if float(gidShrDict[gid]) >= probabThreshold} return list(set(gidList) & highSharedGids) def runMarkRecap(source, days_dict, filter_species=None): client = mh.mongod_instance() return applyMarkRecap(genNidMarkRecapDict(client, source, days_dict, filter_species=filter_species)) if __name__ == "__main__": client = mh.mongod_instance() source = "flickr_giraffe" days_dict = {'2014':1, "2015" : 2} print(genNidMarkRecapDict(client, source, days_dict, filter_species="giraffe_reticulated"))
smenon8/AnimalWildlifeEstimator
script/MarkRecapHelper.py
Python
bsd-3-clause
4,133
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using FlowChart.Models; using FlowChart.Utility; using System.Drawing.Drawing2D; namespace FlowChart.Views.Default { public class DefaultRectangleView : RectangleView { public override void Draw(Graphics g) { RectangleF rect = this.rectComponent.TopLeftCorner.MakeRectangleFTill(this.rectComponent.BottomRightCorner); using (LinearGradientBrush brush = new LinearGradientBrush(rect, ViewFactory.GradStartColor, ViewFactory.GradEndColor, 90.0f)) { g.FillRectangle(brush, rect); g.DrawRectangle(ViewFactory.BorderPen, rect.X, rect.Y, rect.Width, rect.Height); base.Draw(g); } } } }
pradeepkodical/FlowChart
Views/Default/RectangleView.cs
C#
bsd-3-clause
845
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright (C) 2011 - 2016 * * Dominik Charousset <dominik.charousset (at) haw-hamburg.de> * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #ifndef CAF_LOCKS_HPP #define CAF_LOCKS_HPP #include <mutex> namespace caf { template <class Lockable> using unique_lock = std::unique_lock<Lockable>; template <class SharedLockable> class shared_lock { public: using lockable = SharedLockable; explicit shared_lock(lockable& arg) : lockable_(&arg) { lockable_->lock_shared(); } ~shared_lock() { unlock(); } bool owns_lock() const { return lockable_ != nullptr; } void unlock() { if (lockable_) { lockable_->unlock_shared(); lockable_ = nullptr; } } lockable* release() { auto result = lockable_; lockable_ = nullptr; return result; } private: lockable* lockable_; }; template <class SharedLockable> using upgrade_lock = shared_lock<SharedLockable>; template <class UpgradeLockable> class upgrade_to_unique_lock { public: using lockable = UpgradeLockable; template <class LockType> explicit upgrade_to_unique_lock(LockType& other) { lockable_ = other.release(); if (lockable_) lockable_->unlock_upgrade_and_lock(); } ~upgrade_to_unique_lock() { unlock(); } bool owns_lock() const { return lockable_ != nullptr; } void unlock() { if (lockable_) { lockable_->unlock(); lockable_ = nullptr; } } private: lockable* lockable_; }; } // namespace caf #endif // CAF_LOCKS_HPP
nq-ebaratte/actor-framework
libcaf_core/caf/locks.hpp
C++
bsd-3-clause
2,804
package foundation // #include <virgil/crypto/foundation/vscf_foundation_public.h> import "C" import unsafe "unsafe" import "runtime" /* * This class provides hybrid encryption algorithm that combines symmetric * cipher for data encryption and asymmetric cipher and password based * cipher for symmetric key encryption. */ type RecipientCipher struct { cCtx *C.vscf_recipient_cipher_t /*ct2*/ } /* Handle underlying C context. */ func (obj *RecipientCipher) Ctx() uintptr { return uintptr(unsafe.Pointer(obj.cCtx)) } func NewRecipientCipher() *RecipientCipher { ctx := C.vscf_recipient_cipher_new() obj := &RecipientCipher{ cCtx: ctx, } runtime.SetFinalizer(obj, (*RecipientCipher).Delete) return obj } /* Acquire C context. * Note. This method is used in generated code only, and SHOULD NOT be used in another way. */ func newRecipientCipherWithCtx(ctx *C.vscf_recipient_cipher_t /*ct2*/) *RecipientCipher { obj := &RecipientCipher{ cCtx: ctx, } runtime.SetFinalizer(obj, (*RecipientCipher).Delete) return obj } /* Acquire retained C context. * Note. This method is used in generated code only, and SHOULD NOT be used in another way. */ func newRecipientCipherCopy(ctx *C.vscf_recipient_cipher_t /*ct2*/) *RecipientCipher { obj := &RecipientCipher{ cCtx: C.vscf_recipient_cipher_shallow_copy(ctx), } runtime.SetFinalizer(obj, (*RecipientCipher).Delete) return obj } /* * Release underlying C context. */ func (obj *RecipientCipher) Delete() { if obj == nil { return } runtime.SetFinalizer(obj, nil) obj.delete() } /* * Release underlying C context. */ func (obj *RecipientCipher) delete() { C.vscf_recipient_cipher_delete(obj.cCtx) } func (obj *RecipientCipher) SetRandom(random Random) { C.vscf_recipient_cipher_release_random(obj.cCtx) C.vscf_recipient_cipher_use_random(obj.cCtx, (*C.vscf_impl_t)(unsafe.Pointer(random.Ctx()))) runtime.KeepAlive(random) runtime.KeepAlive(obj) } func (obj *RecipientCipher) SetEncryptionCipher(encryptionCipher Cipher) { C.vscf_recipient_cipher_release_encryption_cipher(obj.cCtx) C.vscf_recipient_cipher_use_encryption_cipher(obj.cCtx, (*C.vscf_impl_t)(unsafe.Pointer(encryptionCipher.Ctx()))) runtime.KeepAlive(encryptionCipher) runtime.KeepAlive(obj) } func (obj *RecipientCipher) SetEncryptionPadding(encryptionPadding Padding) { C.vscf_recipient_cipher_release_encryption_padding(obj.cCtx) C.vscf_recipient_cipher_use_encryption_padding(obj.cCtx, (*C.vscf_impl_t)(unsafe.Pointer(encryptionPadding.Ctx()))) runtime.KeepAlive(encryptionPadding) runtime.KeepAlive(obj) } func (obj *RecipientCipher) SetPaddingParams(paddingParams *PaddingParams) { C.vscf_recipient_cipher_release_padding_params(obj.cCtx) C.vscf_recipient_cipher_use_padding_params(obj.cCtx, (*C.vscf_padding_params_t)(unsafe.Pointer(paddingParams.Ctx()))) runtime.KeepAlive(paddingParams) runtime.KeepAlive(obj) } func (obj *RecipientCipher) SetSignerHash(signerHash Hash) { C.vscf_recipient_cipher_release_signer_hash(obj.cCtx) C.vscf_recipient_cipher_use_signer_hash(obj.cCtx, (*C.vscf_impl_t)(unsafe.Pointer(signerHash.Ctx()))) runtime.KeepAlive(signerHash) runtime.KeepAlive(obj) } /* * Return true if a key recipient with a given id has been added. * Note, operation has O(N) time complexity. */ func (obj *RecipientCipher) HasKeyRecipient(recipientId []byte) bool { recipientIdData := helperWrapData(recipientId) proxyResult := /*pr4*/ C.vscf_recipient_cipher_has_key_recipient(obj.cCtx, recipientIdData) runtime.KeepAlive(obj) return bool(proxyResult) /* r9 */ } /* * Add recipient defined with id and public key. */ func (obj *RecipientCipher) AddKeyRecipient(recipientId []byte, publicKey PublicKey) { recipientIdData := helperWrapData(recipientId) C.vscf_recipient_cipher_add_key_recipient(obj.cCtx, recipientIdData, (*C.vscf_impl_t)(unsafe.Pointer(publicKey.Ctx()))) runtime.KeepAlive(obj) runtime.KeepAlive(publicKey) return } /* * Remove all recipients. */ func (obj *RecipientCipher) ClearRecipients() { C.vscf_recipient_cipher_clear_recipients(obj.cCtx) runtime.KeepAlive(obj) return } /* * Add identifier and private key to sign initial plain text. * Return error if the private key can not sign. */ func (obj *RecipientCipher) AddSigner(signerId []byte, privateKey PrivateKey) error { signerIdData := helperWrapData(signerId) proxyResult := /*pr4*/ C.vscf_recipient_cipher_add_signer(obj.cCtx, signerIdData, (*C.vscf_impl_t)(unsafe.Pointer(privateKey.Ctx()))) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return err } runtime.KeepAlive(obj) runtime.KeepAlive(privateKey) return nil } /* * Remove all signers. */ func (obj *RecipientCipher) ClearSigners() { C.vscf_recipient_cipher_clear_signers(obj.cCtx) runtime.KeepAlive(obj) return } /* * Provide access to the custom params object. * The returned object can be used to add custom params or read it. */ func (obj *RecipientCipher) CustomParams() *MessageInfoCustomParams { proxyResult := /*pr4*/ C.vscf_recipient_cipher_custom_params(obj.cCtx) runtime.KeepAlive(obj) return newMessageInfoCustomParamsCopy(proxyResult) /* r5 */ } /* * Start encryption process. */ func (obj *RecipientCipher) StartEncryption() error { proxyResult := /*pr4*/ C.vscf_recipient_cipher_start_encryption(obj.cCtx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return err } runtime.KeepAlive(obj) return nil } /* * Start encryption process with known plain text size. * * Precondition: At least one signer should be added. * Note, store message info footer as well. */ func (obj *RecipientCipher) StartSignedEncryption(dataSize uint) error { proxyResult := /*pr4*/ C.vscf_recipient_cipher_start_signed_encryption(obj.cCtx, (C.size_t)(dataSize) /*pa10*/) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return err } runtime.KeepAlive(obj) return nil } /* * Return buffer length required to hold message info returned by the * "pack message info" method. * Precondition: all recipients and custom parameters should be set. */ func (obj *RecipientCipher) MessageInfoLen() uint { proxyResult := /*pr4*/ C.vscf_recipient_cipher_message_info_len(obj.cCtx) runtime.KeepAlive(obj) return uint(proxyResult) /* r9 */ } /* * Return serialized message info to the buffer. * * Precondition: this method should be called after "start encryption". * Precondition: this method should be called before "finish encryption". * * Note, store message info to use it for decryption process, * or place it at the encrypted data beginning (embedding). * * Return message info - recipients public information, * algorithm information, etc. */ func (obj *RecipientCipher) PackMessageInfo() []byte { messageInfoBuf, messageInfoBufErr := newBuffer(int(obj.MessageInfoLen() /* lg2 */)) if messageInfoBufErr != nil { return nil } defer messageInfoBuf.delete() C.vscf_recipient_cipher_pack_message_info(obj.cCtx, messageInfoBuf.ctx) runtime.KeepAlive(obj) return messageInfoBuf.getData() /* r7 */ } /* * Return buffer length required to hold output of the method * "process encryption" and method "finish" during encryption. */ func (obj *RecipientCipher) EncryptionOutLen(dataLen uint) uint { proxyResult := /*pr4*/ C.vscf_recipient_cipher_encryption_out_len(obj.cCtx, (C.size_t)(dataLen) /*pa10*/) runtime.KeepAlive(obj) return uint(proxyResult) /* r9 */ } /* * Process encryption of a new portion of data. */ func (obj *RecipientCipher) ProcessEncryption(data []byte) ([]byte, error) { outBuf, outBufErr := newBuffer(int(obj.EncryptionOutLen(uint(len(data))) /* lg2 */)) if outBufErr != nil { return nil, outBufErr } defer outBuf.delete() dataData := helperWrapData(data) proxyResult := /*pr4*/ C.vscf_recipient_cipher_process_encryption(obj.cCtx, dataData, outBuf.ctx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return nil, err } runtime.KeepAlive(obj) return outBuf.getData() /* r7 */, nil } /* * Accomplish encryption. */ func (obj *RecipientCipher) FinishEncryption() ([]byte, error) { outBuf, outBufErr := newBuffer(int(obj.EncryptionOutLen(0) /* lg2 */)) if outBufErr != nil { return nil, outBufErr } defer outBuf.delete() proxyResult := /*pr4*/ C.vscf_recipient_cipher_finish_encryption(obj.cCtx, outBuf.ctx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return nil, err } runtime.KeepAlive(obj) return outBuf.getData() /* r7 */, nil } /* * Initiate decryption process with a recipient private key. * Message Info can be empty if it was embedded to encrypted data. */ func (obj *RecipientCipher) StartDecryptionWithKey(recipientId []byte, privateKey PrivateKey, messageInfo []byte) error { recipientIdData := helperWrapData(recipientId) messageInfoData := helperWrapData(messageInfo) proxyResult := /*pr4*/ C.vscf_recipient_cipher_start_decryption_with_key(obj.cCtx, recipientIdData, (*C.vscf_impl_t)(unsafe.Pointer(privateKey.Ctx())), messageInfoData) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return err } runtime.KeepAlive(obj) runtime.KeepAlive(privateKey) return nil } /* * Initiate decryption process with a recipient private key. * Message Info can be empty if it was embedded to encrypted data. * Message Info footer can be empty if it was embedded to encrypted data. * If footer was embedded, method "start decryption with key" can be used. */ func (obj *RecipientCipher) StartVerifiedDecryptionWithKey(recipientId []byte, privateKey PrivateKey, messageInfo []byte, messageInfoFooter []byte) error { recipientIdData := helperWrapData(recipientId) messageInfoData := helperWrapData(messageInfo) messageInfoFooterData := helperWrapData(messageInfoFooter) proxyResult := /*pr4*/ C.vscf_recipient_cipher_start_verified_decryption_with_key(obj.cCtx, recipientIdData, (*C.vscf_impl_t)(unsafe.Pointer(privateKey.Ctx())), messageInfoData, messageInfoFooterData) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return err } runtime.KeepAlive(obj) runtime.KeepAlive(privateKey) return nil } /* * Return buffer length required to hold output of the method * "process decryption" and method "finish" during decryption. */ func (obj *RecipientCipher) DecryptionOutLen(dataLen uint) uint { proxyResult := /*pr4*/ C.vscf_recipient_cipher_decryption_out_len(obj.cCtx, (C.size_t)(dataLen) /*pa10*/) runtime.KeepAlive(obj) return uint(proxyResult) /* r9 */ } /* * Process with a new portion of data. * Return error if data can not be encrypted or decrypted. */ func (obj *RecipientCipher) ProcessDecryption(data []byte) ([]byte, error) { outBuf, outBufErr := newBuffer(int(obj.DecryptionOutLen(uint(len(data))) /* lg2 */)) if outBufErr != nil { return nil, outBufErr } defer outBuf.delete() dataData := helperWrapData(data) proxyResult := /*pr4*/ C.vscf_recipient_cipher_process_decryption(obj.cCtx, dataData, outBuf.ctx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return nil, err } runtime.KeepAlive(obj) return outBuf.getData() /* r7 */, nil } /* * Accomplish decryption. */ func (obj *RecipientCipher) FinishDecryption() ([]byte, error) { outBuf, outBufErr := newBuffer(int(obj.DecryptionOutLen(0) /* lg2 */)) if outBufErr != nil { return nil, outBufErr } defer outBuf.delete() proxyResult := /*pr4*/ C.vscf_recipient_cipher_finish_decryption(obj.cCtx, outBuf.ctx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return nil, err } runtime.KeepAlive(obj) return outBuf.getData() /* r7 */, nil } /* * Return true if data was signed by a sender. * * Precondition: this method should be called after "finish decryption". */ func (obj *RecipientCipher) IsDataSigned() bool { proxyResult := /*pr4*/ C.vscf_recipient_cipher_is_data_signed(obj.cCtx) runtime.KeepAlive(obj) return bool(proxyResult) /* r9 */ } /* * Return information about signers that sign data. * * Precondition: this method should be called after "finish decryption". * Precondition: method "is data signed" returns true. */ func (obj *RecipientCipher) SignerInfos() *SignerInfoList { proxyResult := /*pr4*/ C.vscf_recipient_cipher_signer_infos(obj.cCtx) runtime.KeepAlive(obj) return newSignerInfoListCopy(proxyResult) /* r5 */ } /* * Verify given cipher info. */ func (obj *RecipientCipher) VerifySignerInfo(signerInfo *SignerInfo, publicKey PublicKey) bool { proxyResult := /*pr4*/ C.vscf_recipient_cipher_verify_signer_info(obj.cCtx, (*C.vscf_signer_info_t)(unsafe.Pointer(signerInfo.Ctx())), (*C.vscf_impl_t)(unsafe.Pointer(publicKey.Ctx()))) runtime.KeepAlive(obj) runtime.KeepAlive(signerInfo) runtime.KeepAlive(publicKey) return bool(proxyResult) /* r9 */ } /* * Return buffer length required to hold message footer returned by the * "pack message footer" method. * * Precondition: this method should be called after "finish encryption". */ func (obj *RecipientCipher) MessageInfoFooterLen() uint { proxyResult := /*pr4*/ C.vscf_recipient_cipher_message_info_footer_len(obj.cCtx) runtime.KeepAlive(obj) return uint(proxyResult) /* r9 */ } /* * Return serialized message info footer to the buffer. * * Precondition: this method should be called after "finish encryption". * * Note, store message info to use it for verified decryption process, * or place it at the encrypted data ending (embedding). * * Return message info footer - signers public information, etc. */ func (obj *RecipientCipher) PackMessageInfoFooter() ([]byte, error) { outBuf, outBufErr := newBuffer(int(obj.MessageInfoFooterLen() /* lg2 */)) if outBufErr != nil { return nil, outBufErr } defer outBuf.delete() proxyResult := /*pr4*/ C.vscf_recipient_cipher_pack_message_info_footer(obj.cCtx, outBuf.ctx) err := FoundationErrorHandleStatus(proxyResult) if err != nil { return nil, err } runtime.KeepAlive(obj) return outBuf.getData() /* r7 */, nil }
go-virgil/virgil
crypto/wrapper/foundation/recipient_cipher.go
GO
bsd-3-clause
13,941
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/search_engines/template_url_prepopulate_data.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h" #include "net/base/mock_host_resolver.h" #include "net/base/net_util.h" namespace { class TemplateURLScraperTest : public InProcessBrowserTest { public: TemplateURLScraperTest() { } private: DISALLOW_COPY_AND_ASSIGN(TemplateURLScraperTest); }; class TemplateURLServiceLoader : public content::NotificationObserver { public: explicit TemplateURLServiceLoader(TemplateURLService* model) : model_(model) { registrar_.Add(this, chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED, content::Source<TemplateURLService>(model)); model_->Load(); ui_test_utils::RunMessageLoop(); } virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == chrome::NOTIFICATION_TEMPLATE_URL_SERVICE_LOADED && content::Source<TemplateURLService>(source).ptr() == model_) { MessageLoop::current()->Quit(); } } private: content::NotificationRegistrar registrar_; TemplateURLService* model_; DISALLOW_COPY_AND_ASSIGN(TemplateURLServiceLoader); }; } // namespace /* IN_PROC_BROWSER_TEST_F(TemplateURLScraperTest, ScrapeWithOnSubmit) { host_resolver()->AddRule("*.foo.com", "localhost"); TemplateURLService* template_urls = TemplateURLServiceFactory::GetInstance(browser()->profile()); TemplateURLServiceLoader loader(template_urls); std::vector<const TemplateURL*> all_urls = template_urls->GetTemplateURLs(); // We need to substract the default pre-populated engines that the profile is // set up with. size_t default_index = 0; std::vector<TemplateURL*> prepopulate_urls; TemplateURLPrepopulateData::GetPrepopulatedEngines( browser()->profile()->GetPrefs(), &prepopulate_urls, &default_index); EXPECT_EQ(prepopulate_urls.size(), all_urls.size()); scoped_refptr<HTTPTestServer> server( HTTPTestServer::CreateServerWithFileRootURL( L"chrome/test/data/template_url_scraper/submit_handler", L"/", g_browser_process->io_thread()->message_loop())); ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( browser(), GURL("http://www.foo.com:1337/"), 2); all_urls = template_urls->GetTemplateURLs(); EXPECT_EQ(1, all_urls.size() - prepopulate_urls.size()); } */
aYukiSekiguchi/ACCESS-Chromium
chrome/browser/search_engines/template_url_scraper_unittest.cc
C++
bsd-3-clause
3,053
angular.module("RadCalc").directive("nmTable", function() { return { restrict: 'E', transclude: true, templateUrl: "views/partial-nm-table-header.html" }; });
CTSIatUCSF/RadiationDoseCalculator
app/directives/NMTableDirective.js
JavaScript
bsd-3-clause
190
module Tester where import LazyCrossCheck main :: IO () main = test test :: IO () test = lazyCrossCheck 5 "version" $ (version1 --> version2) `with` [ ints ==> [1,2,3] ] version1 :: Maybe Int -> Int version1 Nothing = 1 version1 (Just x) = x version2 :: Maybe Int -> Int version2 Nothing = 1 version2 (Just _) = 2
TristanAllwood/lazyCrossCheck
Tester.hs
Haskell
bsd-3-clause
327
--- layout: article title: Introducing Prose Bootstrap abstract: Prose Bootstrap is a minimal template intendet to get you started with Jekyll. author_twitter: _mql author: Michael Aufreiter permalink: /blog/:year/:month/:day/:title.html categories: - blog published: true --- This is a test blog post!! Innit
allanw/allanw.github.com
_posts/blog/2012-06-18-test-blog.md
Markdown
bsd-3-clause
313
def extractNinetysevenkoiWordpressCom(item): ''' Parser for 'ninetysevenkoi.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractNinetysevenkoiWordpressCom.py
Python
bsd-3-clause
568
#!/bin/sh optionerror=0 script_dir=`dirname $0` key_file_location="" cert_file_location="" csr_file_location="" printHelp () { echo "usage: $0 [-k <file name for key file>] [-c <file name of old certificate>] [-o <file name of resulting CSR>] [-h]" echo "" echo "https://elbosso.github.io/expect-dialog-ca/" echo "" echo "-k <file name for key file>\tIf this file exists, the key in it\n\t\tis used - if it does not exist, a new key is generated and\n\t\tsaved to it\n" echo "-c <file name of old certificate>\tThe file containing the old\n\t\tcertificate that should be renewed\n" echo "-o <file name of resulting CSR>\tThe file the new certificate signing\n\t\trequest is to be saved in\n" echo "-h\t\tPrint this help text\n" } while getopts ":k:c:o:h" opt; do case $opt in k) # echo "-k was triggered! ($OPTARG)" >&2 key_file_location=$OPTARG ;; c) # echo "-c was triggered! ($OPTARG)" >&2 cert_file_location=$OPTARG ;; o) # echo "-o was triggered! ($OPTARG)" >&2 csr_file_location=$OPTARG ;; h) printHelp exit 0 ;; \?) echo "Invalid option: -$OPTARG" >&2 printHelp optionerror=1 ;; :) echo "Option -$OPTARG requires an argument." >&2 printHelp optionerror=1 ;; esac done if [ "$optionerror" = "1" ] then exit 1 fi if [ "$key_file_location" = "" ]; then echo "key_file_location must be given (specify via -k)" >&2 exit fi if [ "$cert_file_location" = "" ]; then echo "cert_file_location must be given (specify via -c)" >&2 exit fi if [ "$csr_file_location" = "" ]; then echo "csr_file_location must be given (specify via -o)" >&2 exit fi openssl x509 -in "${cert_file_location}" -signkey "${key_file_location}" -x509toreq -out "${csr_file_location}"
elbosso/expect-dialog-ca
request_certificate_renewal.sh
Shell
bsd-3-clause
1,782
/*! X-editable - v1.5.1 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ .editableform { margin-bottom: 0; /* overwrites bootstrap margin */ } .editableform .control-group { margin-bottom: 0; /* overwrites bootstrap margin */ white-space: nowrap; /* prevent wrapping buttons on new line */ line-height: 20px; /* overwriting bootstrap line-height. See #133 */ } /* BS3 width:1005 for inputs breaks editable form in popup See: https://github.com/vitalets/x-editable/issues/393 */ .editableform .form-control { width: auto; } .editable-buttons { display: inline-block; /* should be inline to take effect of parent's white-space: nowrap */ vertical-align: top; margin-left: 7px; /* inline-block emulation for IE7*/ zoom: 1; *display: inline; } .editable-buttons.editable-buttons-bottom { display: block; margin-top: 7px; margin-left: 0; } .editable-input { vertical-align: top; display: inline-block; /* should be inline to take effect of parent's white-space: nowrap */ width: auto; /* bootstrap-responsive has width: 100% that breakes layout */ white-space: normal; /* reset white-space decalred in parent*/ /* display-inline emulation for IE7*/ zoom: 1; *display: inline; } .editable-buttons .editable-cancel { margin-left: 7px; } /*for jquery-ui buttons need set height to look more pretty*/ .editable-buttons button.ui-button-icon-only { height: 24px; width: 30px; } .editableform-loading { background: url('../img/loading.gif') center center no-repeat; height: 25px; width: auto; min-width: 25px; } .editable-inline .editableform-loading { background-position: left 5px; } .editable-error-block { max-width: 300px; margin: 5px 0 0 0; width: auto; white-space: normal; } /*add padding for jquery ui*/ .editable-error-block.ui-state-error { padding: 3px; } .editable-error { color: red; } /* ---- For specific types ---- */ .editableform .editable-date { padding: 0; margin: 0; float: left; } /* move datepicker icon to center of add-on button. See https://github.com/vitalets/x-editable/issues/183 */ .editable-inline .add-on .icon-th { margin-top: 3px; margin-left: 1px; } /* checklist vertical alignment */ .editable-checklist label input[type="checkbox"], .editable-checklist label span { vertical-align: middle; margin: 0; } .editable-checklist label { white-space: nowrap; } /* set exact width of textarea to fit buttons toolbar */ .editable-wysihtml5 { width: 566px; height: 250px; } /* clear button shown as link in date inputs */ .editable-clear { clear: both; font-size: 0.9em; text-decoration: none; text-align: right; } /* IOS-style clear button for text inputs */ .editable-clear-x { background: url('../img/clear.png') center center no-repeat; display: block; width: 13px; height: 13px; position: absolute; opacity: 0.6; z-index: 100; top: 50%; right: 6px; margin-top: -6px; } .editable-clear-x:hover { opacity: 1; } .editable-pre-wrapped { white-space: pre-wrap; } .editable-container.editable-popup { max-width: none !important; /* without this rule poshytip/tooltip does not stretch */ } .editable-container.popover { width: 350px; /* without this rule popover does not stretch */ } .editable-container.editable-inline { display: inline-block; vertical-align: middle; width: auto; /* inline-block emulation for IE7*/ zoom: 1; *display: inline; } .editable-container.ui-widget { font-size: inherit; /* jqueryui widget font 1.1em too big, overwrite it */ z-index: 9990; /* should be less than select2 dropdown z-index to close dropdown first when click */ } .editable-click, a.editable-click, a.editable-click:hover { text-decoration: none; border-bottom: dashed 1px #0088cc; } .editable-click.editable-disabled, a.editable-click.editable-disabled, a.editable-click.editable-disabled:hover { color: #585858; cursor: default; border-bottom: none; } .editable-empty, .editable-empty:hover, .editable-empty:focus{ font-style: italic; color: #DD1144; /* border-bottom: none; */ text-decoration: none; } .editable-unsaved { font-weight: bold; } .editable-unsaved:after { /* content: '*'*/ } .editable-bg-transition { -webkit-transition: background-color 1400ms ease-out; -moz-transition: background-color 1400ms ease-out; -o-transition: background-color 1400ms ease-out; -ms-transition: background-color 1400ms ease-out; transition: background-color 1400ms ease-out; } /*see https://github.com/vitalets/x-editable/issues/139 */ .form-horizontal .editable { padding-top: 5px; display:inline-block; } /*! * Datepicker for Bootstrap * * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * */ .datepicker { padding: 4px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; direction: ltr; /*.dow { border-top: 1px solid #ddd !important; }*/ } .datepicker-inline { width: 220px; } .datepicker.datepicker-rtl { direction: rtl; } .datepicker.datepicker-rtl table tr td span { float: right; } .datepicker-dropdown { top: 0; left: 0; } .datepicker-dropdown:before { content: ''; display: inline-block; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 7px solid #ccc; border-bottom-color: rgba(0, 0, 0, 0.2); position: absolute; top: -7px; left: 6px; } .datepicker-dropdown:after { content: ''; display: inline-block; border-left: 6px solid transparent; border-right: 6px solid transparent; border-bottom: 6px solid #ffffff; position: absolute; top: -6px; left: 7px; } .datepicker > div { display: none; } .datepicker.days div.datepicker-days { display: block; } .datepicker.months div.datepicker-months { display: block; } .datepicker.years div.datepicker-years { display: block; } .datepicker table { margin: 0; } .datepicker td, .datepicker th { text-align: center; width: 20px; height: 20px; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; border: none; } .table-striped .datepicker table tr td, .table-striped .datepicker table tr th { background-color: transparent; } .datepicker table tr td.day:hover { background: #eeeeee; cursor: pointer; } .datepicker table tr td.old, .datepicker table tr td.new { color: #999999; } .datepicker table tr td.disabled, .datepicker table tr td.disabled:hover { background: none; color: #999999; cursor: default; } .datepicker table tr td.today, .datepicker table tr td.today:hover, .datepicker table tr td.today.disabled, .datepicker table tr td.today.disabled:hover { background-color: #fde19a; background-image: -moz-linear-gradient(top, #fdd49a, #fdf59a); background-image: -ms-linear-gradient(top, #fdd49a, #fdf59a); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#fdd49a), to(#fdf59a)); background-image: -webkit-linear-gradient(top, #fdd49a, #fdf59a); background-image: -o-linear-gradient(top, #fdd49a, #fdf59a); background-image: linear-gradient(top, #fdd49a, #fdf59a); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fdd49a', endColorstr='#fdf59a', GradientType=0); border-color: #fdf59a #fdf59a #fbed50; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); color: #000; } .datepicker table tr td.today:hover, .datepicker table tr td.today:hover:hover, .datepicker table tr td.today.disabled:hover, .datepicker table tr td.today.disabled:hover:hover, .datepicker table tr td.today:active, .datepicker table tr td.today:hover:active, .datepicker table tr td.today.disabled:active, .datepicker table tr td.today.disabled:hover:active, .datepicker table tr td.today.active, .datepicker table tr td.today:hover.active, .datepicker table tr td.today.disabled.active, .datepicker table tr td.today.disabled:hover.active, .datepicker table tr td.today.disabled, .datepicker table tr td.today:hover.disabled, .datepicker table tr td.today.disabled.disabled, .datepicker table tr td.today.disabled:hover.disabled, .datepicker table tr td.today[disabled], .datepicker table tr td.today:hover[disabled], .datepicker table tr td.today.disabled[disabled], .datepicker table tr td.today.disabled:hover[disabled] { background-color: #fdf59a; } .datepicker table tr td.today:active, .datepicker table tr td.today:hover:active, .datepicker table tr td.today.disabled:active, .datepicker table tr td.today.disabled:hover:active, .datepicker table tr td.today.active, .datepicker table tr td.today:hover.active, .datepicker table tr td.today.disabled.active, .datepicker table tr td.today.disabled:hover.active { background-color: #fbf069 \9; } .datepicker table tr td.today:hover:hover { color: #000; } .datepicker table tr td.today.active:hover { color: #fff; } .datepicker table tr td.range, .datepicker table tr td.range:hover, .datepicker table tr td.range.disabled, .datepicker table tr td.range.disabled:hover { background: #eeeeee; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .datepicker table tr td.range.today, .datepicker table tr td.range.today:hover, .datepicker table tr td.range.today.disabled, .datepicker table tr td.range.today.disabled:hover { background-color: #f3d17a; background-image: -moz-linear-gradient(top, #f3c17a, #f3e97a); background-image: -ms-linear-gradient(top, #f3c17a, #f3e97a); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#f3c17a), to(#f3e97a)); background-image: -webkit-linear-gradient(top, #f3c17a, #f3e97a); background-image: -o-linear-gradient(top, #f3c17a, #f3e97a); background-image: linear-gradient(top, #f3c17a, #f3e97a); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3c17a', endColorstr='#f3e97a', GradientType=0); border-color: #f3e97a #f3e97a #edde34; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; } .datepicker table tr td.range.today:hover, .datepicker table tr td.range.today:hover:hover, .datepicker table tr td.range.today.disabled:hover, .datepicker table tr td.range.today.disabled:hover:hover, .datepicker table tr td.range.today:active, .datepicker table tr td.range.today:hover:active, .datepicker table tr td.range.today.disabled:active, .datepicker table tr td.range.today.disabled:hover:active, .datepicker table tr td.range.today.active, .datepicker table tr td.range.today:hover.active, .datepicker table tr td.range.today.disabled.active, .datepicker table tr td.range.today.disabled:hover.active, .datepicker table tr td.range.today.disabled, .datepicker table tr td.range.today:hover.disabled, .datepicker table tr td.range.today.disabled.disabled, .datepicker table tr td.range.today.disabled:hover.disabled, .datepicker table tr td.range.today[disabled], .datepicker table tr td.range.today:hover[disabled], .datepicker table tr td.range.today.disabled[disabled], .datepicker table tr td.range.today.disabled:hover[disabled] { background-color: #f3e97a; } .datepicker table tr td.range.today:active, .datepicker table tr td.range.today:hover:active, .datepicker table tr td.range.today.disabled:active, .datepicker table tr td.range.today.disabled:hover:active, .datepicker table tr td.range.today.active, .datepicker table tr td.range.today:hover.active, .datepicker table tr td.range.today.disabled.active, .datepicker table tr td.range.today.disabled:hover.active { background-color: #efe24b \9; } .datepicker table tr td.selected, .datepicker table tr td.selected:hover, .datepicker table tr td.selected.disabled, .datepicker table tr td.selected.disabled:hover { background-color: #9e9e9e; background-image: -moz-linear-gradient(top, #b3b3b3, #808080); background-image: -ms-linear-gradient(top, #b3b3b3, #808080); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#b3b3b3), to(#808080)); background-image: -webkit-linear-gradient(top, #b3b3b3, #808080); background-image: -o-linear-gradient(top, #b3b3b3, #808080); background-image: linear-gradient(top, #b3b3b3, #808080); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#b3b3b3', endColorstr='#808080', GradientType=0); border-color: #808080 #808080 #595959; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); color: #fff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .datepicker table tr td.selected:hover, .datepicker table tr td.selected:hover:hover, .datepicker table tr td.selected.disabled:hover, .datepicker table tr td.selected.disabled:hover:hover, .datepicker table tr td.selected:active, .datepicker table tr td.selected:hover:active, .datepicker table tr td.selected.disabled:active, .datepicker table tr td.selected.disabled:hover:active, .datepicker table tr td.selected.active, .datepicker table tr td.selected:hover.active, .datepicker table tr td.selected.disabled.active, .datepicker table tr td.selected.disabled:hover.active, .datepicker table tr td.selected.disabled, .datepicker table tr td.selected:hover.disabled, .datepicker table tr td.selected.disabled.disabled, .datepicker table tr td.selected.disabled:hover.disabled, .datepicker table tr td.selected[disabled], .datepicker table tr td.selected:hover[disabled], .datepicker table tr td.selected.disabled[disabled], .datepicker table tr td.selected.disabled:hover[disabled] { background-color: #808080; } .datepicker table tr td.selected:active, .datepicker table tr td.selected:hover:active, .datepicker table tr td.selected.disabled:active, .datepicker table tr td.selected.disabled:hover:active, .datepicker table tr td.selected.active, .datepicker table tr td.selected:hover.active, .datepicker table tr td.selected.disabled.active, .datepicker table tr td.selected.disabled:hover.active { background-color: #666666 \9; } .datepicker table tr td.active, .datepicker table tr td.active:hover, .datepicker table tr td.active.disabled, .datepicker table tr td.active.disabled:hover { background-color: #006dcc; background-image: -moz-linear-gradient(top, #0088cc, #0044cc); background-image: -ms-linear-gradient(top, #0088cc, #0044cc); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); background-image: -o-linear-gradient(top, #0088cc, #0044cc); background-image: linear-gradient(top, #0088cc, #0044cc); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0); border-color: #0044cc #0044cc #002a80; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); color: #fff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .datepicker table tr td.active:hover, .datepicker table tr td.active:hover:hover, .datepicker table tr td.active.disabled:hover, .datepicker table tr td.active.disabled:hover:hover, .datepicker table tr td.active:active, .datepicker table tr td.active:hover:active, .datepicker table tr td.active.disabled:active, .datepicker table tr td.active.disabled:hover:active, .datepicker table tr td.active.active, .datepicker table tr td.active:hover.active, .datepicker table tr td.active.disabled.active, .datepicker table tr td.active.disabled:hover.active, .datepicker table tr td.active.disabled, .datepicker table tr td.active:hover.disabled, .datepicker table tr td.active.disabled.disabled, .datepicker table tr td.active.disabled:hover.disabled, .datepicker table tr td.active[disabled], .datepicker table tr td.active:hover[disabled], .datepicker table tr td.active.disabled[disabled], .datepicker table tr td.active.disabled:hover[disabled] { background-color: #0044cc; } .datepicker table tr td.active:active, .datepicker table tr td.active:hover:active, .datepicker table tr td.active.disabled:active, .datepicker table tr td.active.disabled:hover:active, .datepicker table tr td.active.active, .datepicker table tr td.active:hover.active, .datepicker table tr td.active.disabled.active, .datepicker table tr td.active.disabled:hover.active { background-color: #003399 \9; } .datepicker table tr td span { display: block; width: 23%; height: 54px; line-height: 54px; float: left; margin: 1%; cursor: pointer; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .datepicker table tr td span:hover { background: #eeeeee; } .datepicker table tr td span.disabled, .datepicker table tr td span.disabled:hover { background: none; color: #999999; cursor: default; } .datepicker table tr td span.active, .datepicker table tr td span.active:hover, .datepicker table tr td span.active.disabled, .datepicker table tr td span.active.disabled:hover { background-color: #006dcc; background-image: -moz-linear-gradient(top, #0088cc, #0044cc); background-image: -ms-linear-gradient(top, #0088cc, #0044cc); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc)); background-image: -webkit-linear-gradient(top, #0088cc, #0044cc); background-image: -o-linear-gradient(top, #0088cc, #0044cc); background-image: linear-gradient(top, #0088cc, #0044cc); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#0088cc', endColorstr='#0044cc', GradientType=0); border-color: #0044cc #0044cc #002a80; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); color: #fff; text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .datepicker table tr td span.active:hover, .datepicker table tr td span.active:hover:hover, .datepicker table tr td span.active.disabled:hover, .datepicker table tr td span.active.disabled:hover:hover, .datepicker table tr td span.active:active, .datepicker table tr td span.active:hover:active, .datepicker table tr td span.active.disabled:active, .datepicker table tr td span.active.disabled:hover:active, .datepicker table tr td span.active.active, .datepicker table tr td span.active:hover.active, .datepicker table tr td span.active.disabled.active, .datepicker table tr td span.active.disabled:hover.active, .datepicker table tr td span.active.disabled, .datepicker table tr td span.active:hover.disabled, .datepicker table tr td span.active.disabled.disabled, .datepicker table tr td span.active.disabled:hover.disabled, .datepicker table tr td span.active[disabled], .datepicker table tr td span.active:hover[disabled], .datepicker table tr td span.active.disabled[disabled], .datepicker table tr td span.active.disabled:hover[disabled] { background-color: #0044cc; } .datepicker table tr td span.active:active, .datepicker table tr td span.active:hover:active, .datepicker table tr td span.active.disabled:active, .datepicker table tr td span.active.disabled:hover:active, .datepicker table tr td span.active.active, .datepicker table tr td span.active:hover.active, .datepicker table tr td span.active.disabled.active, .datepicker table tr td span.active.disabled:hover.active { background-color: #003399 \9; } .datepicker table tr td span.old, .datepicker table tr td span.new { color: #999999; } .datepicker th.datepicker-switch { width: 145px; } .datepicker thead tr:first-child th, .datepicker tfoot tr th { cursor: pointer; } .datepicker thead tr:first-child th:hover, .datepicker tfoot tr th:hover { background: #eeeeee; } .datepicker .cw { font-size: 10px; width: 12px; padding: 0 2px 0 5px; vertical-align: middle; } .datepicker thead tr:first-child th.cw { cursor: default; background-color: transparent; } .input-append.date .add-on i, .input-prepend.date .add-on i { display: block; cursor: pointer; width: 16px; height: 16px; } .input-daterange input { text-align: center; } .input-daterange input:first-child { -webkit-border-radius: 3px 0 0 3px; -moz-border-radius: 3px 0 0 3px; border-radius: 3px 0 0 3px; } .input-daterange input:last-child { -webkit-border-radius: 0 3px 3px 0; -moz-border-radius: 0 3px 3px 0; border-radius: 0 3px 3px 0; } .input-daterange .add-on { display: inline-block; width: auto; min-width: 16px; height: 18px; padding: 4px 5px; font-weight: normal; line-height: 18px; text-align: center; text-shadow: 0 1px 0 #ffffff; vertical-align: middle; background-color: #eeeeee; border: 1px solid #ccc; margin-left: -5px; margin-right: -5px; }
kienbk1910/RDCAdmin
public/bootstrap3-editable/css/bootstrap-editable.css
CSS
bsd-3-clause
21,203
<?php Use \yii\helpers\Html; ?> <h2>Клиенты</h2> <table class="table"> <tr> <th>№ </th> <th>Фамилия </th> <th>Имя </th> <th>Отчество </th> <th>День рождения(гггг-мм-дд) </th> <th>Адрес </th> <th>Действия </th> </tr> <?php foreach($clients as $client){ ?> <tr> <td> <?= $client->ID_client ?> </td> <td> <?= htmlspecialchars($client->last_name_client) ?> </td> <td> <?= htmlspecialchars($client->first_name_client) ?> </td> <td> <?= htmlspecialchars($client->patronimic_name_client) ?> </td> <td> <?= htmlspecialchars($client->date_birth) ?> </td> <td> <?= htmlspecialchars($client->address) ?> </td> <td> <?= Html::a('<span class="glyphicon glyphicon-edit"></span>Редактировать', ['client/edit', 'ID_client' => $client ->ID_client],['class'=>'btn btn-primary']) ?> <?php if ($client->getOrders()->count()==0) { echo Html::a('<span class="glyphicon glyphicon-remove"></span>Удалить', ['client/delete', 'ID_client' => $client ->ID_client],['class'=>'btn btn-danger']); }?> </td> </tr> <?php } ?> <tr> <td colspan="6" ></td> <td><?= Html::a('<span class="glyphicon glyphicon-plus"></span>Добавить нового', ['client/add']) ?> </tr> </table>
mkrivozyateva/sale
backend/views/client/index.php
PHP
bsd-3-clause
1,296
<?php namespace api\modules\v1\controllers; use yii\rest\ActiveController; use backend\models\Departamento; class DepartamentosController extends ActiveController { public $modelClass = 'backend\models\Departamento'; /*public function actions() { $actions = parent::actions(); unset($actions['view']); return $actions; } public function actionView($id){ // $inmueble = new Inmuebles(); //var_dump($inmueble->primaryKey());die; return Barrios::find()->where(['idBarrios' => $id])->one(); }*/ } ?>
Nacho2126/php20162
api/modules/v1/controllers/DepartamentosController.php
PHP
bsd-3-clause
568
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.stats.descriptivestats.Description.summary &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.stats.descriptivestats.Description.categorical" href="statsmodels.stats.descriptivestats.Description.categorical.html" /> <link rel="prev" title="statsmodels.stats.descriptivestats.Description" href="statsmodels.stats.descriptivestats.Description.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.stats.descriptivestats.Description.summary" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.stats.descriptivestats.Description.summary </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../stats.html" class="md-tabs__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a></li> <li class="md-tabs__item"><a href="statsmodels.stats.descriptivestats.Description.html" class="md-tabs__link">statsmodels.stats.descriptivestats.Description</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../stats.html" class="md-nav__link">Statistics <code class="xref py py-mod docutils literal notranslate"><span class="pre">stats</span></code></a> </li> <li class="md-nav__item"> <a href="../contingency_tables.html" class="md-nav__link">Contingency tables</a> </li> <li class="md-nav__item"> <a href="../imputation.html" class="md-nav__link">Multiple Imputation with Chained Equations</a> </li> <li class="md-nav__item"> <a href="../emplike.html" class="md-nav__link">Empirical Likelihood <code class="xref py py-mod docutils literal notranslate"><span class="pre">emplike</span></code></a> </li> <li class="md-nav__item"> <a href="../distributions.html" class="md-nav__link">Distributions</a> </li> <li class="md-nav__item"> <a href="../graphics.html" class="md-nav__link">Graphics</a> </li> <li class="md-nav__item"> <a href="../iolib.html" class="md-nav__link">Input-Output <code class="xref py py-mod docutils literal notranslate"><span class="pre">iolib</span></code></a> </li> <li class="md-nav__item"> <a href="../tools.html" class="md-nav__link">Tools</a> </li> <li class="md-nav__item"> <a href="../large_data.html" class="md-nav__link">Working with Large Data Sets</a> </li> <li class="md-nav__item"> <a href="../optimization.html" class="md-nav__link">Optimization</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.stats.descriptivestats.Description.summary.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-stats-descriptivestats-description-summary--page-root">statsmodels.stats.descriptivestats.Description.summary<a class="headerlink" href="#generated-statsmodels-stats-descriptivestats-description-summary--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.stats.descriptivestats.Description.summary"> <code class="sig-prename descclassname">Description.</code><code class="sig-name descname">summary</code><span class="sig-paren">(</span><span class="sig-paren">)</span> → <a class="reference internal" href="statsmodels.iolib.table.SimpleTable.html#statsmodels.iolib.table.SimpleTable" title="statsmodels.iolib.table.SimpleTable">statsmodels.iolib.table.SimpleTable</a><a class="reference internal" href="../_modules/statsmodels/stats/descriptivestats.html#Description.summary"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.stats.descriptivestats.Description.summary" title="Permalink to this definition">¶</a></dt> <dd><p>Summary table of the descriptive statistics</p> <dl class="field-list simple"> <dt class="field-odd">Returns</dt> <dd class="field-odd"><dl class="simple"> <dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">SimpleTable</span></code></dt><dd><p>A table instance supporting export to text, csv and LaTeX</p> </dd> </dl> </dd> </dl> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.stats.descriptivestats.Description.html" title="statsmodels.stats.descriptivestats.Description" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.stats.descriptivestats.Description </span> </div> </a> <a href="statsmodels.stats.descriptivestats.Description.categorical.html" title="statsmodels.stats.descriptivestats.Description.categorical" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.stats.descriptivestats.Description.categorical </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
statsmodels/statsmodels.github.io
v0.12.2/generated/statsmodels.stats.descriptivestats.Description.summary.html
HTML
bsd-3-clause
19,341
find_package(Clang REQUIRED) set(CLANG_LIBRARIES clangAST clangASTMatchers clangAnalysis clangBasic clangDriver clangEdit clangFrontend clangFrontendTool clangLex clangParse clangSema clangEdit clangRewrite clangRewriteFrontend clangStaticAnalyzerFrontend clangStaticAnalyzerCheckers clangStaticAnalyzerCore clangSerialization clangToolingCore clangTooling clangFormat) macro(add_clang_plugin _name) add_library(${_name} SHARED "") set_target_properties(${_name} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED On CXX_EXTENSIONS Off) target_include_directories(${_name} PRIVATE ${LLVM_INCLUDE_DIR}) target_link_libraries(${_name} libclang) endmacro(add_clang_plugin) macro(add_clang_executable _name) add_executable(${_name} "") set_target_properties(${_name} PROPERTIES CXX_STANDARD 11 CXX_STANDARD_REQUIRED On CXX_EXTENSIONS Off) target_include_directories(${_name} PRIVATE ${LLVM_INCLUDE_DIR}) target_link_libraries(${_name} ${CLANG_LIBRARIES} ${LLVM_AVAILABLE_LIBS}) endmacro(add_clang_executable)
ptaffet/preprocessor-debug
cmake/AddClangPlugin.cmake
CMake
bsd-3-clause
1,078
#!/bin/sh # Package PACKAGE="nzbdrone" DNAME="Sonarr" # Others INSTALL_DIR="/usr/local/${PACKAGE}" PATH="${INSTALL_DIR}/bin:${PATH}" BUILDNUMBER="$(/bin/get_key_value /etc.defaults/VERSION buildnumber)" PID_FILE="${INSTALL_DIR}/.config/NzbDrone/nzbdrone.pid" INSTALL_LOG="${INSTALL_DIR}/.config/install.log" MONO_PATH="/usr/local/mono/bin" MONO="${MONO_PATH}/mono" SONARR="${INSTALL_DIR}/share/NzbDrone/NzbDrone.exe" COMMAND="env PATH=${MONO_PATH}:${PATH} LD_LIBRARY_PATH=${INSTALL_DIR}/lib ${MONO} -- --debug ${SONARR}" SC_USER="sc-sonarr" LEGACY_USER="nzbdrone" USER="$([ "${BUILDNUMBER}" -ge "7321" ] && echo -n ${SC_USER} || echo -n ${LEGACY_USER})" start_daemon () { start-stop-daemon -c ${USER} -S -q -b -N 10 -x ${COMMAND} > /dev/null sleep 2 } stop_daemon () { start-stop-daemon -K -q -u ${USER} -p ${PID_FILE} wait_for_status 1 20 || start-stop-daemon -K -s 9 -q -p ${PID_FILE} } daemon_status () { start-stop-daemon -K -q -t -u ${USER} -p ${PID_FILE} } wait_for_status () { counter=$2 while [ ${counter} -gt 0 ]; do daemon_status [ $? -eq $1 ] && return let counter=counter-1 sleep 1 done return 1 } case $1 in start) if daemon_status; then echo ${DNAME} is already running else echo Starting ${DNAME} ... start_daemon fi ;; stop) if daemon_status; then echo Stopping ${DNAME} ... stop_daemon else echo ${DNAME} is not running fi ;; status) if daemon_status; then echo ${DNAME} is running exit 0 else echo ${DNAME} is not running exit 1 fi ;; log) echo "${INSTALL_LOG}" exit 0 ;; *) exit 1 ;; esac
saschpe/spksrc
spk/sonarr/src/dsm-control.sh
Shell
bsd-3-clause
1,854