file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DefaultUpdater} from '../default';
/**
* Updates a Terraform module's README.
*/
export class ReadMe extends DefaultUpdater {
/**
* Given initial file contents, return updated contents.
* @param {string} content The initial content
* @returns {string} The updated content
*/
updateContent(content: string): string |
}
| {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
`version = "~> ${this.version.major}.${this.version.minor}"`
);
} | identifier_body |
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DefaultUpdater} from '../default';
/**
* Updates a Terraform module's README. | export class ReadMe extends DefaultUpdater {
/**
* Given initial file contents, return updated contents.
* @param {string} content The initial content
* @returns {string} The updated content
*/
updateContent(content: string): string {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
`version = "~> ${this.version.major}.${this.version.minor}"`
);
}
} | */ | random_line_split |
readme.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {DefaultUpdater} from '../default';
/**
* Updates a Terraform module's README.
*/
export class | extends DefaultUpdater {
/**
* Given initial file contents, return updated contents.
* @param {string} content The initial content
* @returns {string} The updated content
*/
updateContent(content: string): string {
return content.replace(
/version = "~> [\d]+.[\d]+"/,
`version = "~> ${this.version.major}.${this.version.minor}"`
);
}
}
| ReadMe | identifier_name |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self).to_representation(instance)
ret = OrderedDict(list(filter(lambda x: not_none(x[1]), ret.items())))
return ret
class RawDataSerializer(ShareModelSerializer):
class Meta:
model = models.RawData
fields = ('id', 'source', 'app_label', 'provider_doc_id', 'data', 'sha256', 'date_seen', 'date_harvested')
class ProviderRegistrationSerializer(ShareModelSerializer):
status = serializers.SerializerMethodField()
submitted_at = serializers.DateTimeField(read_only=True)
submitted_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_status(self, obj):
return ProviderRegistration.STATUS[obj.status]
class Meta:
model = models.ProviderRegistration
fields = '__all__'
class FullNormalizedDataSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=CeleryProviderTask.objects.all())
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source', 'raw', 'tasks')
class BasicNormalizedDataSerializer(serializers.ModelSerializer):
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source')
class ChangeSerializer(ShareModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name='api:change-detail')
target_type = serializers.StringRelatedField()
class Meta:
model = models.Change
fields = ('self', 'id', 'change', 'node_id', 'type', 'target_type', 'target_id')
class ShareUserSerializer(ShareModelSerializer):
def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'π¦': serializers.SerializerMethodField(method_name='is_superuser'),
'π€': serializers.SerializerMethodField(method_name='is_robot'),
})
def is_robot(self, obj):
if not isinstance(obj, AnonymousUser):
return | return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login',
'is_active', 'gravatar', 'locale', 'time_zone'
)
class ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.SerializerMethodField()
def get_status(self, obj):
return ChangeSet.STATUS[obj.status]
def get_change_count(self, obj):
return obj.changes.count()
class Meta:
model = models.ChangeSet
fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class ProviderSerializer(ShareUserSerializer):
def __init__(self, *args, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
self.fields.update({
'π€': serializers.SerializerMethodField(method_name='is_robot'),
'provider_name': serializers.SerializerMethodField(method_name='provider_name')
})
def provider_name(self, obj):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar')
| obj.is_robot
| conditional_block |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self).to_representation(instance)
ret = OrderedDict(list(filter(lambda x: not_none(x[1]), ret.items())))
return ret
class RawDataSerializer(ShareModelSerializer):
class Meta:
model = models.RawData
fields = ('id', 'source', 'app_label', 'provider_doc_id', 'data', 'sha256', 'date_seen', 'date_harvested')
class ProviderRegistrationSerializer(ShareModelSerializer):
status = serializers.SerializerMethodField()
submitted_at = serializers.DateTimeField(read_only=True)
submitted_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_status(self, obj):
return ProviderRegistration.STATUS[obj.status]
class Meta:
model = models.ProviderRegistration
fields = '__all__'
class FullNormalizedDataSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=CeleryProviderTask.objects.all())
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source', 'raw', 'tasks')
class BasicNormalizedDataSerializer(serializers.ModelSerializer):
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source')
class ChangeSerializer(ShareModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name='api:change-detail')
target_type = serializers.StringRelatedField()
class Meta:
model = models.Change
fields = ('self', 'id', 'change', 'node_id', 'type', 'target_type', 'target_id')
class ShareUserSerializer(ShareModelSerializer):
| ss ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.SerializerMethodField()
def get_status(self, obj):
return ChangeSet.STATUS[obj.status]
def get_change_count(self, obj):
return obj.changes.count()
class Meta:
model = models.ChangeSet
fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class ProviderSerializer(ShareUserSerializer):
def __init__(self, *args, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
self.fields.update({
'π€': serializers.SerializerMethodField(method_name='is_robot'),
'provider_name': serializers.SerializerMethodField(method_name='provider_name')
})
def provider_name(self, obj):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar')
| def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'π¦': serializers.SerializerMethodField(method_name='is_superuser'),
'π€': serializers.SerializerMethodField(method_name='is_robot'),
})
def is_robot(self, obj):
if not isinstance(obj, AnonymousUser):
return obj.is_robot
return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login',
'is_active', 'gravatar', 'locale', 'time_zone'
)
cla | identifier_body |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
|
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self).to_representation(instance)
ret = OrderedDict(list(filter(lambda x: not_none(x[1]), ret.items())))
return ret
class RawDataSerializer(ShareModelSerializer):
class Meta:
model = models.RawData
fields = ('id', 'source', 'app_label', 'provider_doc_id', 'data', 'sha256', 'date_seen', 'date_harvested')
class ProviderRegistrationSerializer(ShareModelSerializer):
status = serializers.SerializerMethodField()
submitted_at = serializers.DateTimeField(read_only=True)
submitted_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_status(self, obj):
return ProviderRegistration.STATUS[obj.status]
class Meta:
model = models.ProviderRegistration
fields = '__all__'
class FullNormalizedDataSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=CeleryProviderTask.objects.all())
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source', 'raw', 'tasks')
class BasicNormalizedDataSerializer(serializers.ModelSerializer):
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source')
class ChangeSerializer(ShareModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name='api:change-detail')
target_type = serializers.StringRelatedField()
class Meta:
model = models.Change
fields = ('self', 'id', 'change', 'node_id', 'type', 'target_type', 'target_id')
class ShareUserSerializer(ShareModelSerializer):
def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'π¦': serializers.SerializerMethodField(method_name='is_superuser'),
'π€': serializers.SerializerMethodField(method_name='is_robot'),
})
def is_robot(self, obj):
if not isinstance(obj, AnonymousUser):
return obj.is_robot
return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login',
'is_active', 'gravatar', 'locale', 'time_zone'
)
class ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.SerializerMethodField()
def get_status(self, obj):
return ChangeSet.STATUS[obj.status]
def get_change_count(self, obj):
return obj.changes.count()
class Meta:
model = models.ChangeSet
fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class ProviderSerializer(ShareUserSerializer):
def __init__(self, *args, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
self.fields.update({
'π€': serializers.SerializerMethodField(method_name='is_robot'),
'provider_name': serializers.SerializerMethodField(method_name='provider_name')
})
def provider_name(self, obj):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar') | from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
| random_line_split |
serializers.py | from collections import OrderedDict
from django.contrib.auth.models import AnonymousUser
from rest_framework_json_api import serializers
from share import models
from share.models import ChangeSet, ProviderRegistration, CeleryProviderTask
class ShareModelSerializer(serializers.ModelSerializer):
# http://stackoverflow.com/questions/27015931/remove-null-fields-from-django-rest-framework-response
def to_representation(self, instance):
def not_none(value):
return value is not None
ret = super(ShareModelSerializer, self).to_representation(instance)
ret = OrderedDict(list(filter(lambda x: not_none(x[1]), ret.items())))
return ret
class RawDataSerializer(ShareModelSerializer):
class Meta:
model = models.RawData
fields = ('id', 'source', 'app_label', 'provider_doc_id', 'data', 'sha256', 'date_seen', 'date_harvested')
class ProviderRegistrationSerializer(ShareModelSerializer):
status = serializers.SerializerMethodField()
submitted_at = serializers.DateTimeField(read_only=True)
submitted_by = serializers.HiddenField(default=serializers.CurrentUserDefault())
def get_status(self, obj):
return ProviderRegistration.STATUS[obj.status]
class Meta:
model = models.ProviderRegistration
fields = '__all__'
class FullNormalizedDataSerializer(serializers.ModelSerializer):
tasks = serializers.PrimaryKeyRelatedField(many=True, read_only=False, queryset=CeleryProviderTask.objects.all())
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source', 'raw', 'tasks')
class BasicNormalizedDataSerializer(serializers.ModelSerializer):
source = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = models.NormalizedData
fields = ('data', 'source')
class ChangeSerializer(ShareModelSerializer):
self = serializers.HyperlinkedIdentityField(view_name='api:change-detail')
target_type = serializers.StringRelatedField()
class Meta:
model = models.Change
fields = ('self', 'id', 'change', 'node_id', 'type', 'target_type', 'target_id')
class ShareUserSerializer(ShareModelSerializer):
def __init__(self, *args, token=None, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
if token:
self.fields.update({
'token': serializers.SerializerMethodField()
})
self.fields.update({
'π¦': serializers.SerializerMethodField(method_name='is_superuser'),
'π€': serializers.SerializerMethodField(method_name='is_robot'),
})
def is_robot(self, obj):
if not isinstance(obj, AnonymousUser):
return obj.is_robot
return False
def get_token(self, obj):
try:
return obj.accesstoken_set.first().token
except AttributeError:
return None
def is_superuser(self, obj):
return obj.is_superuser
class Meta:
model = models.ShareUser
fields = (
'username', 'first_name', 'last_name', 'email', 'date_joined', 'last_login',
'is_active', 'gravatar', 'locale', 'time_zone'
)
class ChangeSetSerializer(ShareModelSerializer):
# changes = ChangeSerializer(many=True)
change_count = serializers.SerializerMethodField()
self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
source = ShareUserSerializer(source='normalized_data.source')
status = serializers.SerializerMethodField()
def get_status(self, obj):
return ChangeSet.STATUS[obj.status]
def get_change_count(self, obj):
return obj.changes.count()
class Meta:
model = models.ChangeSet
fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class ProviderSerializer(ShareUserSerializer):
def __init__(self, *args, **kwargs):
super(ShareUserSerializer, self).__init__(*args, **kwargs)
self.fields.update({
'π€': serializers.SerializerMethodField(method_name='is_robot'),
'provider_name': serializers.SerializerMethodField(method_name='provider_name')
})
def provider_ | j):
return obj.username.replace('providers.', '')
class Meta:
model = models.ShareUser
fields = ('home_page', 'long_title', 'date_joined', 'gravatar')
| name(self, ob | identifier_name |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn | () -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <joris.guisson@gmail.com>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0)
} else if let Some(matches) = matches.subcommand_matches("build") {
build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
{
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
}
| run | identifier_name |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn run() -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <joris.guisson@gmail.com>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0)
} else if let Some(matches) = matches.subcommand_matches("build") {
build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
| {
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
} | identifier_body | |
main.rs | extern crate llvm_sys as llvm;
extern crate libc;
extern crate itertools;
#[macro_use]
extern crate clap;
extern crate uuid;
extern crate toml;
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate bincode;
extern crate time;
extern crate either;
macro_rules! try_opt {
($e:expr) =>(
match $e {
Some(v) => v,
None => return None,
}
)
}
mod ast;
mod compileerror;
mod bytecode;
mod exportlibrary;
mod parser;
mod typechecker;
mod span;
mod llvmbackend;
mod target;
mod timer;
mod package;
mod packagebuild;
use std::fs::File;
use std::process::exit;
use std::path::PathBuf;
use clap::ArgMatches;
use compileerror::{CompileResult};
use llvmbackend::{OutputType, llvm_init, llvm_shutdown};
use packagebuild::{PackageData, BuildOptions};
use exportlibrary::ExportLibrary;
fn build_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let input_file = matches.value_of("INPUT_FILE").expect("No input file given");
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: String::new(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
let output_type = match matches.value_of("LIB") {
Some("static") => OutputType::StaticLib,
Some("shared") => OutputType::SharedLib,
_ => OutputType::Binary,
};
let pkg = PackageData::single_file(&input_file, output_type)?;
pkg.build(&build_options)?;
Ok(0)
}
fn build_package_command(matches: &ArgMatches, dump_flags: &str) -> CompileResult<i32>
{
let package_toml = if let Some(toml) = matches.value_of("PACKAGE_TOML") {
toml
} else {
"./package.toml"
};
let pkg = PackageData::load(package_toml)?;
let build_options = BuildOptions{
optimize: matches.is_present("OPTIMIZE"),
dump_flags: dump_flags.into(),
target_machine: llvm_init()?,
sources_directory: "src".into(),
import_directories: matches.value_of("IMPORTS")
.map(|dirs| dirs.split(',').map(PathBuf::from).collect())
.unwrap_or_else(Vec::new),
};
pkg.build(&build_options)?;
Ok(0)
}
fn exports_command(matches: &ArgMatches) -> CompileResult<i32>
{
let exports_file_path = matches.value_of("EXPORTS_FILE").ok_or_else(|| "No exports file given".to_owned())?;
let mut exports_file = File::open(&exports_file_path)?;
let lib = ExportLibrary::load(&mut exports_file)?;
println!("{}", lib);
Ok(0)
}
fn run() -> CompileResult<i32>
{
let app = clap_app!(cobrac =>
(version: "0.1")
(author: "Joris Guisson <joris.guisson@gmail.com>")
(about: "Nomad language compiler")
(@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ir. A comma separated list of these values is also supported.")
(@arg TARGET_TRIPLET: -t --triplet "Print the default target triplet of the current system, and exit")
(@subcommand build =>
(about: "Build a menhir file")
(@arg INPUT_FILE: +required "File to build")
(@arg OUTPUT_FILE: -o --output +takes_value "Name of binary to create (by default input file without the extensions)")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
(@arg LIB: -l --lib +takes_value possible_value[static shared] "Create a library, type of library must be pass")
)
(@subcommand buildpkg =>
(about: "Build a menhir package.")
(@arg PACKAGE_TOML: -p --package +takes_value "Specify the package.toml file. If not specified, menhir will look in the current directory for one.")
(@arg OPTIMIZE: -O --optimize "Optimize the code")
(@arg IMPORTS: -I --imports +takes_value "Directory to look for imports, use a comma separated list for more then one.")
)
(@subcommand exports =>
(about: "List the exported symbols in an exports file")
(@arg EXPORTS_FILE: +required "Exports file")
)
);
let matches = app.get_matches();
let dump_flags = matches.value_of("DUMP").unwrap_or("");
if matches.is_present("TARGET_TRIPLET") {
let target_machine = llvm_init()?;
print!("{}", target_machine.target.triplet);
Ok(0) | build_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("buildpkg") {
build_package_command(matches, dump_flags)
} else if let Some(matches) = matches.subcommand_matches("exports") {
exports_command(matches)
} else {
println!("{}", matches.usage());
Ok(1)
}
}
fn main()
{
match run()
{
Ok(ret) => {
llvm_shutdown();
exit(ret)
},
Err(e) => {
e.print();
llvm_shutdown();
exit(-1);
},
}
} | } else if let Some(matches) = matches.subcommand_matches("build") { | random_line_split |
encryptData.js | function hashPassword(password) | ;
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.getBytes();
var strData = forge.util.encode64(encrypted);
};
return strData;
};
function date2Str(x){
var d = new Date(x * 1000);
return d.toISOString().replace('Z', '');
}
function encryptData(data, encrypt=null) {
var encryptedData = [];
for (var i0=0; i0<data.length; i0++) {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
};
return encryptedData;
};
// AJAX for posting
function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#id_your_name').val(''); // remove the value from the input
console.log('Python result: ' + json['result']);
console.log(json);
console.log('success'); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}; | {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
} | identifier_body |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.getBytes();
var strData = forge.util.encode64(encrypted);
};
return strData;
};
function date2Str(x){
var d = new Date(x * 1000);
return d.toISOString().replace('Z', '');
}
function encryptData(data, encrypt=null) {
var encryptedData = [];
for (var i0=0; i0<data.length; i0++) | ;
return encryptedData;
};
// AJAX for posting
function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#id_your_name').val(''); // remove the value from the input
console.log('Python result: ' + json['result']);
console.log(json);
console.log('success'); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}; | {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
} | conditional_block |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function | (value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.getBytes();
var strData = forge.util.encode64(encrypted);
};
return strData;
};
function date2Str(x){
var d = new Date(x * 1000);
return d.toISOString().replace('Z', '');
}
function encryptData(data, encrypt=null) {
var encryptedData = [];
for (var i0=0; i0<data.length; i0++) {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
};
return encryptedData;
};
// AJAX for posting
function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#id_your_name').val(''); // remove the value from the input
console.log('Python result: ' + json['result']);
console.log(json);
console.log('success'); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}; | encryptValue | identifier_name |
encryptData.js | function hashPassword(password) {
// Define and hash password
// TODO: interact with the server for passwords
return forge.md.sha256.create().update(password).digest().getBytes();
};
function encryptValue(value, encrypt=null) {
// Define encryption function
var strData = JSON.stringify(value);
if (encrypt !=null) {
// encrypt data
var cipher = forge.cipher.createCipher('AES-ECB', encrypt);
cipher.start();
cipher.update(forge.util.createBuffer(strData));
cipher.finish();
var encrypted = cipher.output.getBytes();
var strData = forge.util.encode64(encrypted);
};
return strData;
};
function date2Str(x){
var d = new Date(x * 1000);
return d.toISOString().replace('Z', '');
}
function encryptData(data, encrypt=null) {
var encryptedData = [];
for (var i0=0; i0<data.length; i0++) {
encryptedData.push({date: date2Str(data[i0].x), value: encryptValue(data[i0].y, encrypt)});
};
return encryptedData;
};
// AJAX for posting | function uploadData() {
$.ajax({
url : "upload/", // the endpoint
type : "POST", // http method
data : {
series: $('#id_series').val(),
date : $('#id_date').val(),
record : encryptData($('#id_record').val()),
}, // data sent with the post request
// handle a successful response
success : function(json) {
$('#id_your_name').val(''); // remove the value from the input
console.log('Python result: ' + json['result']);
console.log(json);
console.log('success'); // another sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: " + errmsg +
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}; | random_line_split | |
edits.ts | import {letters} from './letters'
| results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// alteration
for (i=0; i < word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i+1));
});
// insertion
for (i=0; i <= word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i));
});
return results;
} | export function edits(word): string[] {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1) | random_line_split |
edits.ts | import {letters} from './letters'
export function | (word): string[] {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1)
results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// alteration
for (i=0; i < word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i+1));
});
// insertion
for (i=0; i <= word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i));
});
return results;
} | edits | identifier_name |
edits.ts | import {letters} from './letters'
export function edits(word): string[] | {
let i, results: string[] = [];
// deletion
for (i=0; i < word.length; i+=1)
results.push(word.slice(0, i) + word.slice(i+1));
// transposition
for (i=0; i < word.length-1; i+=1)
results.push(word.slice(0, i) + word.slice(i+1, i+2) + word.slice(i, i+1) + word.slice(i+2));
// alteration
for (i=0; i < word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i+1));
});
// insertion
for (i=0; i <= word.length; i+=1)
letters.forEach(function (l) {
results.push(word.slice(0, i) + l + word.slice(i));
});
return results;
} | identifier_body | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
| // 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
} | random_line_split | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn main() | {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
// 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
} | identifier_body | |
compound2d.rs | extern crate nalgebra as na;
use na::{Isometry2, Vector2};
use ncollide2d::shape::{Compound, Cuboid, ShapeHandle};
fn | () {
// Delta transformation matrices.
let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero());
let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero());
let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero());
// 1) Initialize the shape list.
let mut shapes = Vec::new();
let horizontal_box = ShapeHandle::new(Cuboid::new(Vector2::new(1.5f32, 0.25)));
let vertical_box = ShapeHandle::new(Cuboid::new(Vector2::new(0.25f32, 1.5)));
shapes.push((delta1, horizontal_box));
shapes.push((delta2, vertical_box.clone()));
shapes.push((delta3, vertical_box));
// 2) Create the compound shape.
let compound = Compound::new(shapes);
assert!(compound.shapes().len() == 3)
}
| main | identifier_name |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys
from weboob.capabilities.job import ICapJob
from weboob.tools.application.repl import ReplApplication, defaultcount
from weboob.tools.application.formatters.iformatter import IFormatter, PrettyFormatter
__all__ = ['Handjoob']
class JobAdvertFormatter(IFormatter):
MANDATORY_FIELDS = ('id', 'url', 'publication_date', 'title')
def format_obj(self, obj, alias):
result = u'%s%s%s\n' % (self.BOLD, obj.title, self.NC)
result += 'url: %s\n' % obj.url
if hasattr(obj, 'publication_date') and obj.publication_date:
result += 'Publication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += 'Location: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += 'Society : %s\n' % obj.society_name
if hasattr(obj, 'job_name') and obj.job_name:
result += 'Job name : %s\n' % obj.job_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += 'Contract : %s\n' % obj.contract_type
if hasattr(obj, 'pay') and obj.pay:
result += 'Pay : %s\n' % obj.pay
if hasattr(obj, 'formation') and obj.formation:
result += 'Formation : %s\n' % obj.formation
if hasattr(obj, 'experience') and obj.experience:
result += 'Experience : %s\n' % obj.experience
if hasattr(obj, 'description') and obj.description:
result += 'Description : %s\n' % obj.description
return result
class JobAdvertListFormatter(PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj):
return '%s' % (obj.title)
def get_description(self, obj):
result = u''
if hasattr(obj, 'publication_date') and obj.publication_date:
result += '\tPublication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += '\tLocation: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += '\tSociety : %s\n' % obj.society_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += '\tContract : %s\n' % obj.contract_type
return result.strip('\n\t')
class Handjoob(ReplApplication):
APPNAME = 'handjoob'
VERSION = '0.i'
COPYRIGHT = 'Copyright(C) 2012 Bezleputh'
DESCRIPTION = "Console application to search for a job."
SHORT_DESCRIPTION = "search for a job"
CAPS = ICapJob
EXTRA_FORMATTERS = {'job_advert_list': JobAdvertListFormatter,
'job_advert': JobAdvertFormatter,
}
COMMANDS_FORMATTERS = {'search': 'job_advert_list',
'ls': 'job_advert_list',
'info': 'job_advert',
}
@defaultcount(10)
def do_search(self, pattern):
"""
search PATTERN
Search for an advert matching a PATTERN.
"""
self.change_path([u'search'])
self.start_format(pattern=pattern)
for backend, job_advert in self.do('search_job', pattern):
self.cached_format(job_advert)
@defaultcount(10)
def do_ls(self, line):
"""
advanced search
Search for an advert matching to advanced filters.
"""
self.change_path([u'advanced'])
for backend, job_advert in self.do('advanced_search_job'):
self.cached_format(job_advert)
def complete_info(self, text, line, *ignored):
args = line.split(' ')
if len(args) == 2:
return self._complete_object()
def do_info(self, _id):
| """
info ID
Get information about an advert.
"""
if not _id:
print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
print >>sys.stderr, 'Job advert not found: %s' % _id
return 3
self.start_format()
self.format(job_advert) | identifier_body | |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys
from weboob.capabilities.job import ICapJob
from weboob.tools.application.repl import ReplApplication, defaultcount
from weboob.tools.application.formatters.iformatter import IFormatter, PrettyFormatter
__all__ = ['Handjoob']
class JobAdvertFormatter(IFormatter):
MANDATORY_FIELDS = ('id', 'url', 'publication_date', 'title')
def format_obj(self, obj, alias):
result = u'%s%s%s\n' % (self.BOLD, obj.title, self.NC)
result += 'url: %s\n' % obj.url
if hasattr(obj, 'publication_date') and obj.publication_date:
result += 'Publication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += 'Location: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += 'Society : %s\n' % obj.society_name
if hasattr(obj, 'job_name') and obj.job_name:
result += 'Job name : %s\n' % obj.job_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += 'Contract : %s\n' % obj.contract_type
if hasattr(obj, 'pay') and obj.pay:
result += 'Pay : %s\n' % obj.pay
if hasattr(obj, 'formation') and obj.formation:
result += 'Formation : %s\n' % obj.formation
if hasattr(obj, 'experience') and obj.experience:
result += 'Experience : %s\n' % obj.experience
if hasattr(obj, 'description') and obj.description:
result += 'Description : %s\n' % obj.description
return result
class JobAdvertListFormatter(PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj):
return '%s' % (obj.title)
def get_description(self, obj):
result = u''
if hasattr(obj, 'publication_date') and obj.publication_date:
result += '\tPublication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += '\tLocation: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += '\tSociety : %s\n' % obj.society_name
if hasattr(obj, 'contract_type') and obj.contract_type:
|
return result.strip('\n\t')
class Handjoob(ReplApplication):
APPNAME = 'handjoob'
VERSION = '0.i'
COPYRIGHT = 'Copyright(C) 2012 Bezleputh'
DESCRIPTION = "Console application to search for a job."
SHORT_DESCRIPTION = "search for a job"
CAPS = ICapJob
EXTRA_FORMATTERS = {'job_advert_list': JobAdvertListFormatter,
'job_advert': JobAdvertFormatter,
}
COMMANDS_FORMATTERS = {'search': 'job_advert_list',
'ls': 'job_advert_list',
'info': 'job_advert',
}
@defaultcount(10)
def do_search(self, pattern):
"""
search PATTERN
Search for an advert matching a PATTERN.
"""
self.change_path([u'search'])
self.start_format(pattern=pattern)
for backend, job_advert in self.do('search_job', pattern):
self.cached_format(job_advert)
@defaultcount(10)
def do_ls(self, line):
"""
advanced search
Search for an advert matching to advanced filters.
"""
self.change_path([u'advanced'])
for backend, job_advert in self.do('advanced_search_job'):
self.cached_format(job_advert)
def complete_info(self, text, line, *ignored):
args = line.split(' ')
if len(args) == 2:
return self._complete_object()
def do_info(self, _id):
"""
info ID
Get information about an advert.
"""
if not _id:
print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
print >>sys.stderr, 'Job advert not found: %s' % _id
return 3
self.start_format()
self.format(job_advert)
| result += '\tContract : %s\n' % obj.contract_type | conditional_block |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys
from weboob.capabilities.job import ICapJob
from weboob.tools.application.repl import ReplApplication, defaultcount
from weboob.tools.application.formatters.iformatter import IFormatter, PrettyFormatter
__all__ = ['Handjoob']
class JobAdvertFormatter(IFormatter):
MANDATORY_FIELDS = ('id', 'url', 'publication_date', 'title')
def format_obj(self, obj, alias):
result = u'%s%s%s\n' % (self.BOLD, obj.title, self.NC)
result += 'url: %s\n' % obj.url
if hasattr(obj, 'publication_date') and obj.publication_date:
result += 'Publication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += 'Location: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += 'Society : %s\n' % obj.society_name
if hasattr(obj, 'job_name') and obj.job_name:
result += 'Job name : %s\n' % obj.job_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += 'Contract : %s\n' % obj.contract_type
if hasattr(obj, 'pay') and obj.pay:
result += 'Pay : %s\n' % obj.pay
if hasattr(obj, 'formation') and obj.formation:
result += 'Formation : %s\n' % obj.formation
if hasattr(obj, 'experience') and obj.experience:
result += 'Experience : %s\n' % obj.experience
if hasattr(obj, 'description') and obj.description:
result += 'Description : %s\n' % obj.description
return result
class | (PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj):
return '%s' % (obj.title)
def get_description(self, obj):
result = u''
if hasattr(obj, 'publication_date') and obj.publication_date:
result += '\tPublication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += '\tLocation: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += '\tSociety : %s\n' % obj.society_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += '\tContract : %s\n' % obj.contract_type
return result.strip('\n\t')
class Handjoob(ReplApplication):
APPNAME = 'handjoob'
VERSION = '0.i'
COPYRIGHT = 'Copyright(C) 2012 Bezleputh'
DESCRIPTION = "Console application to search for a job."
SHORT_DESCRIPTION = "search for a job"
CAPS = ICapJob
EXTRA_FORMATTERS = {'job_advert_list': JobAdvertListFormatter,
'job_advert': JobAdvertFormatter,
}
COMMANDS_FORMATTERS = {'search': 'job_advert_list',
'ls': 'job_advert_list',
'info': 'job_advert',
}
@defaultcount(10)
def do_search(self, pattern):
"""
search PATTERN
Search for an advert matching a PATTERN.
"""
self.change_path([u'search'])
self.start_format(pattern=pattern)
for backend, job_advert in self.do('search_job', pattern):
self.cached_format(job_advert)
@defaultcount(10)
def do_ls(self, line):
"""
advanced search
Search for an advert matching to advanced filters.
"""
self.change_path([u'advanced'])
for backend, job_advert in self.do('advanced_search_job'):
self.cached_format(job_advert)
def complete_info(self, text, line, *ignored):
args = line.split(' ')
if len(args) == 2:
return self._complete_object()
def do_info(self, _id):
"""
info ID
Get information about an advert.
"""
if not _id:
print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
print >>sys.stderr, 'Job advert not found: %s' % _id
return 3
self.start_format()
self.format(job_advert)
| JobAdvertListFormatter | identifier_name |
handjoob.py | # -*- coding: utf-8 -*-
# Copyright(C) 2013 Bezleputh
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.
import sys
from weboob.capabilities.job import ICapJob
from weboob.tools.application.repl import ReplApplication, defaultcount
from weboob.tools.application.formatters.iformatter import IFormatter, PrettyFormatter
__all__ = ['Handjoob']
class JobAdvertFormatter(IFormatter):
MANDATORY_FIELDS = ('id', 'url', 'publication_date', 'title')
def format_obj(self, obj, alias):
result = u'%s%s%s\n' % (self.BOLD, obj.title, self.NC)
result += 'url: %s\n' % obj.url
if hasattr(obj, 'publication_date') and obj.publication_date:
result += 'Publication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += 'Location: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += 'Society : %s\n' % obj.society_name
if hasattr(obj, 'job_name') and obj.job_name:
result += 'Job name : %s\n' % obj.job_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += 'Contract : %s\n' % obj.contract_type
if hasattr(obj, 'pay') and obj.pay:
result += 'Pay : %s\n' % obj.pay
if hasattr(obj, 'formation') and obj.formation:
result += 'Formation : %s\n' % obj.formation
if hasattr(obj, 'experience') and obj.experience:
result += 'Experience : %s\n' % obj.experience
if hasattr(obj, 'description') and obj.description:
result += 'Description : %s\n' % obj.description
return result
class JobAdvertListFormatter(PrettyFormatter):
MANDATORY_FIELDS = ('id', 'title')
def get_title(self, obj):
return '%s' % (obj.title)
def get_description(self, obj):
result = u''
if hasattr(obj, 'publication_date') and obj.publication_date:
result += '\tPublication date : %s\n' % obj.publication_date.strftime('%Y-%m-%d')
if hasattr(obj, 'place') and obj.place:
result += '\tLocation: %s\n' % obj.place
if hasattr(obj, 'society_name') and obj.society_name:
result += '\tSociety : %s\n' % obj.society_name
if hasattr(obj, 'contract_type') and obj.contract_type:
result += '\tContract : %s\n' % obj.contract_type
return result.strip('\n\t')
class Handjoob(ReplApplication):
APPNAME = 'handjoob'
VERSION = '0.i'
COPYRIGHT = 'Copyright(C) 2012 Bezleputh'
DESCRIPTION = "Console application to search for a job."
SHORT_DESCRIPTION = "search for a job"
CAPS = ICapJob
EXTRA_FORMATTERS = {'job_advert_list': JobAdvertListFormatter,
'job_advert': JobAdvertFormatter,
}
COMMANDS_FORMATTERS = {'search': 'job_advert_list',
'ls': 'job_advert_list',
'info': 'job_advert',
}
@defaultcount(10)
def do_search(self, pattern):
"""
search PATTERN
Search for an advert matching a PATTERN.
"""
self.change_path([u'search'])
self.start_format(pattern=pattern)
for backend, job_advert in self.do('search_job', pattern):
self.cached_format(job_advert)
@defaultcount(10)
def do_ls(self, line):
"""
advanced search
Search for an advert matching to advanced filters. | for backend, job_advert in self.do('advanced_search_job'):
self.cached_format(job_advert)
def complete_info(self, text, line, *ignored):
args = line.split(' ')
if len(args) == 2:
return self._complete_object()
def do_info(self, _id):
"""
info ID
Get information about an advert.
"""
if not _id:
print >>sys.stderr, 'This command takes an argument: %s' % self.get_command_help('info', short=True)
return 2
job_advert = self.get_object(_id, 'get_job_advert')
if not job_advert:
print >>sys.stderr, 'Job advert not found: %s' % _id
return 3
self.start_format()
self.format(job_advert) | """
self.change_path([u'advanced']) | random_line_split |
lib.rs | // Copyright TUNTAP, 2017 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.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use base::{ioctl_ior_nr, ioctl_iow_nr};
// generated with bindgen /usr/include/linux/if.h --no-unstable-rust
// --constified-enum '*' --with-derive-default -- -D __UAPI_DEF_IF_IFNAMSIZ -D
// __UAPI_DEF_IF_NET_DEVICE_FLAGS -D __UAPI_DEF_IF_IFREQ -D __UAPI_DEF_IF_IFMAP
// Name is "iff" to avoid conflicting with "if" keyword.
// Generated against Linux 4.11 to include fix "uapi: fix linux/if.h userspace
// compilation errors".
// Manual fixup of ifrn_name to be of type c_uchar instead of c_char.
#[allow(clippy::all)]
pub mod iff;
// generated with bindgen /usr/include/linux/if_tun.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
pub mod if_tun;
// generated with bindgen /usr/include/linux/in.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
// Name is "inn" to avoid conflicting with "in" keyword.
pub mod inn;
// generated with bindgen /usr/include/linux/sockios.h --no-unstable-rust
// --constified-enum '*' --with-derive-default
pub mod sockios;
pub use crate::if_tun::*;
pub use crate::iff::*;
pub use crate::inn::*;
pub use crate::sockios::*;
pub const TUNTAP: ::std::os::raw::c_uint = 84;
pub const ARPHRD_ETHER: sa_family_t = 1;
ioctl_iow_nr!(TUNSETNOCSUM, TUNTAP, 200, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETDEBUG, TUNTAP, 201, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETIFF, TUNTAP, 202, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETPERSIST, TUNTAP, 203, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETOWNER, TUNTAP, 204, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETLINK, TUNTAP, 205, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETGROUP, TUNTAP, 206, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETFEATURES, TUNTAP, 207, ::std::os::raw::c_uint);
ioctl_iow_nr!(TUNSETOFFLOAD, TUNTAP, 208, ::std::os::raw::c_uint);
ioctl_iow_nr!(TUNSETTXFILTER, TUNTAP, 209, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETIFF, TUNTAP, 210, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETSNDBUF, TUNTAP, 211, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETSNDBUF, TUNTAP, 212, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNATTACHFILTER, TUNTAP, 213, sock_fprog);
ioctl_iow_nr!(TUNDETACHFILTER, TUNTAP, 214, sock_fprog);
ioctl_ior_nr!(TUNGETVNETHDRSZ, TUNTAP, 215, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETVNETHDRSZ, TUNTAP, 216, ::std::os::raw::c_int); | ioctl_iow_nr!(TUNSETIFINDEX, TUNTAP, 218, ::std::os::raw::c_uint);
ioctl_ior_nr!(TUNGETFILTER, TUNTAP, 219, sock_fprog);
ioctl_iow_nr!(TUNSETVNETLE, TUNTAP, 220, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETVNETLE, TUNTAP, 221, ::std::os::raw::c_int);
ioctl_iow_nr!(TUNSETVNETBE, TUNTAP, 222, ::std::os::raw::c_int);
ioctl_ior_nr!(TUNGETVNETBE, TUNTAP, 223, ::std::os::raw::c_int); | ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 217, ::std::os::raw::c_int); | random_line_split |
cube-portfolio-2-ns.js | (function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 2
}, {
width: 500,
cols: 2
}, {
width: 320,
cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) | else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/click.cbp', '.cbp-filter-item', function() {
var me = $(this);
if (me.hasClass('cbp-filter-item-active')) {
return;
}
// get cubeportfolio data and check if is still animating (reposition) the items.
if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) {
filtersCallback.call(null, me);
}
// filter the items
gridContainer.cubeportfolio('filter', me.data('filter'), function() {});
});
/*********************************
activate counter for filters
*********************************/
gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() {
// read from url and change filter active
var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href),
item;
if (match !== null) {
item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]');
if (item.length) {
filtersCallback.call(null, item);
}
}
});
})(jQuery, window, document);
| {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp': function() {
wrap.removeClass('cbp-l-filters-dropdownWrap-open');
}
});
filtersCallback = function(me) {
wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active');
wrap.find('.cbp-l-filters-dropdownHeader').text(me.text());
me.addClass('cbp-filter-item-active');
wrap.trigger('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp');
};
} | conditional_block |
cube-portfolio-2-ns.js | (function($, window, document, undefined) {
'use strict';
var gridContainer = $('#grid-container'),
filtersContainer = $('#filters-container'),
wrap, filtersCallback;
/*********************************
init cubeportfolio
*********************************/
gridContainer.cubeportfolio({
layoutMode: 'grid',
rewindNav: true,
scrollByPage: false,
defaultFilter: '*',
animationType: 'slideLeft',
gapHorizontal: 0,
gapVertical: 0,
gridAdjustment: 'responsive',
mediaQueries: [{
width: 800,
cols: 2
}, {
width: 500,
| cols: 1
}],
caption: 'zoom',
displayType: 'lazyLoading',
displayTypeSpeed: 100
});
/*********************************
add listener for filters
*********************************/
if (filtersContainer.hasClass('cbp-l-filters-dropdown')) {
wrap = filtersContainer.find('.cbp-l-filters-dropdownWrap');
wrap.on({
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseover.cbp': function() {
wrap.addClass('cbp-l-filters-dropdownWrap-open');
},
'http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp': function() {
wrap.removeClass('cbp-l-filters-dropdownWrap-open');
}
});
filtersCallback = function(me) {
wrap.find('.cbp-filter-item').removeClass('cbp-filter-item-active');
wrap.find('.cbp-l-filters-dropdownHeader').text(me.text());
me.addClass('cbp-filter-item-active');
wrap.trigger('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/mouseleave.cbp');
};
} else {
filtersCallback = function(me) {
me.addClass('cbp-filter-item-active').siblings().removeClass('cbp-filter-item-active');
};
}
filtersContainer.on('http://htmlstream.com/preview/unify-v1.9/assets/js/plugins/cube-portfolio/click.cbp', '.cbp-filter-item', function() {
var me = $(this);
if (me.hasClass('cbp-filter-item-active')) {
return;
}
// get cubeportfolio data and check if is still animating (reposition) the items.
if (!$.data(gridContainer[0], 'cubeportfolio').isAnimating) {
filtersCallback.call(null, me);
}
// filter the items
gridContainer.cubeportfolio('filter', me.data('filter'), function() {});
});
/*********************************
activate counter for filters
*********************************/
gridContainer.cubeportfolio('showCounter', filtersContainer.find('.cbp-filter-item'), function() {
// read from url and change filter active
var match = /#cbpf=(.*?)([#|?&]|$)/gi.exec(location.href),
item;
if (match !== null) {
item = filtersContainer.find('.cbp-filter-item').filter('[data-filter="' + match[1] + '"]');
if (item.length) {
filtersCallback.call(null, item);
}
}
});
})(jQuery, window, document); | cols: 2
}, {
width: 320,
| random_line_split |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var THREE = require('./three-math.js');
var PredictionMode = {
NONE: 'none',
INTERPOLATE: 'interpolate',
PREDICT: 'predict'
}
// How much to interpolate between the current orientation estimate and the
// previous estimate position. This is helpful for devices with low
// deviceorientation firing frequency (eg. on iOS8 and below, it is 20 Hz). The
// larger this value (in [0, 1]), the smoother but more delayed the head
// tracking is.
var INTERPOLATION_SMOOTHING_FACTOR = 0.01;
// Angular threshold, if the angular speed (in deg/s) is less than this, do no
// prediction. Without it, the screen flickers quite a bit.
var PREDICTION_THRESHOLD_DEG_PER_S = 0.01;
//var PREDICTION_THRESHOLD_DEG_PER_S = 0;
// How far into the future to predict.
window.WEBVR_PREDICTION_TIME_MS = 80;
// Whether to predict or what.
window.WEBVR_PREDICTION_MODE = PredictionMode.PREDICT;
function PosePredictor() {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
}
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
// later.
if (!this.lastTimestamp) {
this.lastQ.copy(currentQ);
this.lastTimestamp = timestamp;
return currentQ;
}
// DEBUG ONLY: Try with a fixed 60 Hz update speed.
//var elapsedMs = 1000/60;
var elapsedMs = timestamp - this.lastTimestamp;
switch (WEBVR_PREDICTION_MODE) {
case PredictionMode.INTERPOLATE:
this.outQ.copy(currentQ);
this.outQ.slerp(this.lastQ, INTERPOLATION_SMOOTHING_FACTOR);
// Save the current quaternion for later.
this.lastQ.copy(currentQ);
break;
case PredictionMode.PREDICT:
var axisAngle;
if (rotationRate) {
axisAngle = this.getAxisAngularSpeedFromRotationRate_(rotationRate);
} else {
axisAngle = this.getAxisAngularSpeedFromGyroDelta_(currentQ, elapsedMs);
}
// If there is no predicted axis/angle, don't do prediction.
if (!axisAngle) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
var angularSpeedDegS = axisAngle.speed;
var axis = axisAngle.axis;
var predictAngleDeg = (WEBVR_PREDICTION_TIME_MS / 1000) * angularSpeedDegS;
// If we're rotating slowly, don't do prediction.
if (angularSpeedDegS < PREDICTION_THRESHOLD_DEG_PER_S) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
// Calculate the prediction delta to apply to the original angle.
this.deltaQ.setFromAxisAngle(axis, THREE.Math.degToRad(predictAngleDeg));
// DEBUG ONLY: As a sanity check, use the same axis and angle as before,
// which should cause no prediction to happen.
//this.deltaQ.setFromAxisAngle(axis, angle);
this.outQ.copy(this.lastQ);
this.outQ.multiply(this.deltaQ);
// Use the predicted quaternion as the new last one.
//this.lastQ.copy(this.outQ);
this.lastQ.copy(currentQ);
break;
case PredictionMode.NONE:
default:
this.outQ.copy(currentQ);
}
this.lastTimestamp = timestamp;
return this.outQ;
};
PosePredictor.prototype.setScreenOrientation = function(screenOrientation) {
this.screenOrientation = screenOrientation;
};
PosePredictor.prototype.getAxis_ = function(quat) {
// x = qx / sqrt(1-qw*qw)
// y = qy / sqrt(1-qw*qw)
// z = qz / sqrt(1-qw*qw)
var d = Math.sqrt(1 - quat.w * quat.w);
return new THREE.Vector3(quat.x / d, quat.y / d, quat.z / d);
};
PosePredictor.prototype.getAngle_ = function(quat) {
// angle = 2 * acos(qw)
// If w is greater than 1 (THREE.js, how can this be?), arccos is not defined.
if (quat.w > 1) {
return 0;
}
var angle = 2 * Math.acos(quat.w);
// Normalize the angle to be in [-Ο, Ο].
if (angle > Math.PI) {
| return angle;
};
PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) {
if (!rotationRate) {
return null;
}
var screenRotationRate;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
// iOS: angular speed in deg/s.
var screenRotationRate = this.getScreenAdjustedRotationRateIOS_(rotationRate);
} else {
// Android: angular speed in rad/s, so need to convert.
rotationRate.alpha = THREE.Math.radToDeg(rotationRate.alpha);
rotationRate.beta = THREE.Math.radToDeg(rotationRate.beta);
rotationRate.gamma = THREE.Math.radToDeg(rotationRate.gamma);
var screenRotationRate = this.getScreenAdjustedRotationRate_(rotationRate);
}
var vec = new THREE.Vector3(
screenRotationRate.beta, screenRotationRate.alpha, screenRotationRate.gamma);
/*
var vec;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
vec = new THREE.Vector3(rotationRate.gamma, rotationRate.alpha, rotationRate.beta);
} else {
vec = new THREE.Vector3(rotationRate.beta, rotationRate.alpha, rotationRate.gamma);
}
// Take into account the screen orientation too!
vec.applyQuaternion(this.screenTransform);
*/
// Angular speed in deg/s.
var angularSpeedDegS = vec.length();
var axis = vec.normalize();
return {
speed: angularSpeedDegS,
axis: axis
}
};
PosePredictor.prototype.getScreenAdjustedRotationRate_ = function(rotationRate) {
var screenRotationRate = {
alpha: -rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = - rotationRate.gamma;
screenRotationRate.gamma = rotationRate.beta;
break;
case 180:
screenRotationRate.beta = - rotationRate.beta;
screenRotationRate.gamma = - rotationRate.gamma;
break;
case 270:
case -90:
screenRotationRate.beta = rotationRate.gamma;
screenRotationRate.gamma = - rotationRate.beta;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getScreenAdjustedRotationRateIOS_ = function(rotationRate) {
var screenRotationRate = {
alpha: rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
// Values empirically derived.
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = -rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
case 180:
// You can't even do this on iOS.
break;
case 270:
case -90:
screenRotationRate.alpha = -rotationRate.alpha;
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.alpha = rotationRate.beta;
screenRotationRate.beta = rotationRate.alpha;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getAxisAngularSpeedFromGyroDelta_ = function(currentQ, elapsedMs) {
// Sometimes we use the same sensor timestamp, in which case prediction
// won't work.
if (elapsedMs == 0) {
return null;
}
// Q_delta = Q_last^-1 * Q_curr
this.deltaQ.copy(this.lastQ);
this.deltaQ.inverse();
this.deltaQ.multiply(currentQ);
// Convert from delta quaternion to axis-angle.
var axis = this.getAxis_(this.deltaQ);
var angleRad = this.getAngle_(this.deltaQ);
// It took `elapsed` ms to travel the angle amount over the axis. Now,
// we make a new quaternion based how far in the future we want to
// calculate.
var angularSpeedRadMs = angleRad / elapsedMs;
var angularSpeedDegS = THREE.Math.radToDeg(angularSpeedRadMs) * 1000;
// If no rotation rate is provided, do no prediction.
return {
speed: angularSpeedDegS,
axis: axis
};
};
module.exports = PosePredictor;
| angle -= 2 * Math.PI;
}
| conditional_block |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var THREE = require('./three-math.js');
var PredictionMode = {
NONE: 'none',
INTERPOLATE: 'interpolate',
PREDICT: 'predict'
}
// How much to interpolate between the current orientation estimate and the
// previous estimate position. This is helpful for devices with low
// deviceorientation firing frequency (eg. on iOS8 and below, it is 20 Hz). The
// larger this value (in [0, 1]), the smoother but more delayed the head
// tracking is.
var INTERPOLATION_SMOOTHING_FACTOR = 0.01;
// Angular threshold, if the angular speed (in deg/s) is less than this, do no
// prediction. Without it, the screen flickers quite a bit.
var PREDICTION_THRESHOLD_DEG_PER_S = 0.01;
//var PREDICTION_THRESHOLD_DEG_PER_S = 0;
// How far into the future to predict.
window.WEBVR_PREDICTION_TIME_MS = 80;
// Whether to predict or what.
window.WEBVR_PREDICTION_MODE = PredictionMode.PREDICT;
function PosePredictor() {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
}
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
// later.
if (!this.lastTimestamp) {
this.lastQ.copy(currentQ);
this.lastTimestamp = timestamp;
return currentQ;
}
// DEBUG ONLY: Try with a fixed 60 Hz update speed.
//var elapsedMs = 1000/60;
var elapsedMs = timestamp - this.lastTimestamp;
switch (WEBVR_PREDICTION_MODE) {
case PredictionMode.INTERPOLATE:
this.outQ.copy(currentQ);
this.outQ.slerp(this.lastQ, INTERPOLATION_SMOOTHING_FACTOR);
// Save the current quaternion for later.
this.lastQ.copy(currentQ);
break;
case PredictionMode.PREDICT:
var axisAngle;
if (rotationRate) {
axisAngle = this.getAxisAngularSpeedFromRotationRate_(rotationRate);
} else {
axisAngle = this.getAxisAngularSpeedFromGyroDelta_(currentQ, elapsedMs);
}
// If there is no predicted axis/angle, don't do prediction.
if (!axisAngle) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
var angularSpeedDegS = axisAngle.speed;
var axis = axisAngle.axis;
var predictAngleDeg = (WEBVR_PREDICTION_TIME_MS / 1000) * angularSpeedDegS;
// If we're rotating slowly, don't do prediction.
if (angularSpeedDegS < PREDICTION_THRESHOLD_DEG_PER_S) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
// Calculate the prediction delta to apply to the original angle.
this.deltaQ.setFromAxisAngle(axis, THREE.Math.degToRad(predictAngleDeg));
// DEBUG ONLY: As a sanity check, use the same axis and angle as before,
// which should cause no prediction to happen.
//this.deltaQ.setFromAxisAngle(axis, angle);
this.outQ.copy(this.lastQ);
this.outQ.multiply(this.deltaQ);
// Use the predicted quaternion as the new last one.
//this.lastQ.copy(this.outQ);
this.lastQ.copy(currentQ);
break;
case PredictionMode.NONE:
default:
this.outQ.copy(currentQ);
}
this.lastTimestamp = timestamp;
return this.outQ;
}; |
PosePredictor.prototype.setScreenOrientation = function(screenOrientation) {
this.screenOrientation = screenOrientation;
};
PosePredictor.prototype.getAxis_ = function(quat) {
// x = qx / sqrt(1-qw*qw)
// y = qy / sqrt(1-qw*qw)
// z = qz / sqrt(1-qw*qw)
var d = Math.sqrt(1 - quat.w * quat.w);
return new THREE.Vector3(quat.x / d, quat.y / d, quat.z / d);
};
PosePredictor.prototype.getAngle_ = function(quat) {
// angle = 2 * acos(qw)
// If w is greater than 1 (THREE.js, how can this be?), arccos is not defined.
if (quat.w > 1) {
return 0;
}
var angle = 2 * Math.acos(quat.w);
// Normalize the angle to be in [-Ο, Ο].
if (angle > Math.PI) {
angle -= 2 * Math.PI;
}
return angle;
};
PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) {
if (!rotationRate) {
return null;
}
var screenRotationRate;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
// iOS: angular speed in deg/s.
var screenRotationRate = this.getScreenAdjustedRotationRateIOS_(rotationRate);
} else {
// Android: angular speed in rad/s, so need to convert.
rotationRate.alpha = THREE.Math.radToDeg(rotationRate.alpha);
rotationRate.beta = THREE.Math.radToDeg(rotationRate.beta);
rotationRate.gamma = THREE.Math.radToDeg(rotationRate.gamma);
var screenRotationRate = this.getScreenAdjustedRotationRate_(rotationRate);
}
var vec = new THREE.Vector3(
screenRotationRate.beta, screenRotationRate.alpha, screenRotationRate.gamma);
/*
var vec;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
vec = new THREE.Vector3(rotationRate.gamma, rotationRate.alpha, rotationRate.beta);
} else {
vec = new THREE.Vector3(rotationRate.beta, rotationRate.alpha, rotationRate.gamma);
}
// Take into account the screen orientation too!
vec.applyQuaternion(this.screenTransform);
*/
// Angular speed in deg/s.
var angularSpeedDegS = vec.length();
var axis = vec.normalize();
return {
speed: angularSpeedDegS,
axis: axis
}
};
PosePredictor.prototype.getScreenAdjustedRotationRate_ = function(rotationRate) {
var screenRotationRate = {
alpha: -rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = - rotationRate.gamma;
screenRotationRate.gamma = rotationRate.beta;
break;
case 180:
screenRotationRate.beta = - rotationRate.beta;
screenRotationRate.gamma = - rotationRate.gamma;
break;
case 270:
case -90:
screenRotationRate.beta = rotationRate.gamma;
screenRotationRate.gamma = - rotationRate.beta;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getScreenAdjustedRotationRateIOS_ = function(rotationRate) {
var screenRotationRate = {
alpha: rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
// Values empirically derived.
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = -rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
case 180:
// You can't even do this on iOS.
break;
case 270:
case -90:
screenRotationRate.alpha = -rotationRate.alpha;
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.alpha = rotationRate.beta;
screenRotationRate.beta = rotationRate.alpha;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getAxisAngularSpeedFromGyroDelta_ = function(currentQ, elapsedMs) {
// Sometimes we use the same sensor timestamp, in which case prediction
// won't work.
if (elapsedMs == 0) {
return null;
}
// Q_delta = Q_last^-1 * Q_curr
this.deltaQ.copy(this.lastQ);
this.deltaQ.inverse();
this.deltaQ.multiply(currentQ);
// Convert from delta quaternion to axis-angle.
var axis = this.getAxis_(this.deltaQ);
var angleRad = this.getAngle_(this.deltaQ);
// It took `elapsed` ms to travel the angle amount over the axis. Now,
// we make a new quaternion based how far in the future we want to
// calculate.
var angularSpeedRadMs = angleRad / elapsedMs;
var angularSpeedDegS = THREE.Math.radToDeg(angularSpeedRadMs) * 1000;
// If no rotation rate is provided, do no prediction.
return {
speed: angularSpeedDegS,
axis: axis
};
};
module.exports = PosePredictor; | random_line_split | |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var THREE = require('./three-math.js');
var PredictionMode = {
NONE: 'none',
INTERPOLATE: 'interpolate',
PREDICT: 'predict'
}
// How much to interpolate between the current orientation estimate and the
// previous estimate position. This is helpful for devices with low
// deviceorientation firing frequency (eg. on iOS8 and below, it is 20 Hz). The
// larger this value (in [0, 1]), the smoother but more delayed the head
// tracking is.
var INTERPOLATION_SMOOTHING_FACTOR = 0.01;
// Angular threshold, if the angular speed (in deg/s) is less than this, do no
// prediction. Without it, the screen flickers quite a bit.
var PREDICTION_THRESHOLD_DEG_PER_S = 0.01;
//var PREDICTION_THRESHOLD_DEG_PER_S = 0;
// How far into the future to predict.
window.WEBVR_PREDICTION_TIME_MS = 80;
// Whether to predict or what.
window.WEBVR_PREDICTION_MODE = PredictionMode.PREDICT;
function | () {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
}
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
// later.
if (!this.lastTimestamp) {
this.lastQ.copy(currentQ);
this.lastTimestamp = timestamp;
return currentQ;
}
// DEBUG ONLY: Try with a fixed 60 Hz update speed.
//var elapsedMs = 1000/60;
var elapsedMs = timestamp - this.lastTimestamp;
switch (WEBVR_PREDICTION_MODE) {
case PredictionMode.INTERPOLATE:
this.outQ.copy(currentQ);
this.outQ.slerp(this.lastQ, INTERPOLATION_SMOOTHING_FACTOR);
// Save the current quaternion for later.
this.lastQ.copy(currentQ);
break;
case PredictionMode.PREDICT:
var axisAngle;
if (rotationRate) {
axisAngle = this.getAxisAngularSpeedFromRotationRate_(rotationRate);
} else {
axisAngle = this.getAxisAngularSpeedFromGyroDelta_(currentQ, elapsedMs);
}
// If there is no predicted axis/angle, don't do prediction.
if (!axisAngle) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
var angularSpeedDegS = axisAngle.speed;
var axis = axisAngle.axis;
var predictAngleDeg = (WEBVR_PREDICTION_TIME_MS / 1000) * angularSpeedDegS;
// If we're rotating slowly, don't do prediction.
if (angularSpeedDegS < PREDICTION_THRESHOLD_DEG_PER_S) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
// Calculate the prediction delta to apply to the original angle.
this.deltaQ.setFromAxisAngle(axis, THREE.Math.degToRad(predictAngleDeg));
// DEBUG ONLY: As a sanity check, use the same axis and angle as before,
// which should cause no prediction to happen.
//this.deltaQ.setFromAxisAngle(axis, angle);
this.outQ.copy(this.lastQ);
this.outQ.multiply(this.deltaQ);
// Use the predicted quaternion as the new last one.
//this.lastQ.copy(this.outQ);
this.lastQ.copy(currentQ);
break;
case PredictionMode.NONE:
default:
this.outQ.copy(currentQ);
}
this.lastTimestamp = timestamp;
return this.outQ;
};
PosePredictor.prototype.setScreenOrientation = function(screenOrientation) {
this.screenOrientation = screenOrientation;
};
PosePredictor.prototype.getAxis_ = function(quat) {
// x = qx / sqrt(1-qw*qw)
// y = qy / sqrt(1-qw*qw)
// z = qz / sqrt(1-qw*qw)
var d = Math.sqrt(1 - quat.w * quat.w);
return new THREE.Vector3(quat.x / d, quat.y / d, quat.z / d);
};
PosePredictor.prototype.getAngle_ = function(quat) {
// angle = 2 * acos(qw)
// If w is greater than 1 (THREE.js, how can this be?), arccos is not defined.
if (quat.w > 1) {
return 0;
}
var angle = 2 * Math.acos(quat.w);
// Normalize the angle to be in [-Ο, Ο].
if (angle > Math.PI) {
angle -= 2 * Math.PI;
}
return angle;
};
PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) {
if (!rotationRate) {
return null;
}
var screenRotationRate;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
// iOS: angular speed in deg/s.
var screenRotationRate = this.getScreenAdjustedRotationRateIOS_(rotationRate);
} else {
// Android: angular speed in rad/s, so need to convert.
rotationRate.alpha = THREE.Math.radToDeg(rotationRate.alpha);
rotationRate.beta = THREE.Math.radToDeg(rotationRate.beta);
rotationRate.gamma = THREE.Math.radToDeg(rotationRate.gamma);
var screenRotationRate = this.getScreenAdjustedRotationRate_(rotationRate);
}
var vec = new THREE.Vector3(
screenRotationRate.beta, screenRotationRate.alpha, screenRotationRate.gamma);
/*
var vec;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
vec = new THREE.Vector3(rotationRate.gamma, rotationRate.alpha, rotationRate.beta);
} else {
vec = new THREE.Vector3(rotationRate.beta, rotationRate.alpha, rotationRate.gamma);
}
// Take into account the screen orientation too!
vec.applyQuaternion(this.screenTransform);
*/
// Angular speed in deg/s.
var angularSpeedDegS = vec.length();
var axis = vec.normalize();
return {
speed: angularSpeedDegS,
axis: axis
}
};
PosePredictor.prototype.getScreenAdjustedRotationRate_ = function(rotationRate) {
var screenRotationRate = {
alpha: -rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = - rotationRate.gamma;
screenRotationRate.gamma = rotationRate.beta;
break;
case 180:
screenRotationRate.beta = - rotationRate.beta;
screenRotationRate.gamma = - rotationRate.gamma;
break;
case 270:
case -90:
screenRotationRate.beta = rotationRate.gamma;
screenRotationRate.gamma = - rotationRate.beta;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getScreenAdjustedRotationRateIOS_ = function(rotationRate) {
var screenRotationRate = {
alpha: rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
// Values empirically derived.
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = -rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
case 180:
// You can't even do this on iOS.
break;
case 270:
case -90:
screenRotationRate.alpha = -rotationRate.alpha;
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.alpha = rotationRate.beta;
screenRotationRate.beta = rotationRate.alpha;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getAxisAngularSpeedFromGyroDelta_ = function(currentQ, elapsedMs) {
// Sometimes we use the same sensor timestamp, in which case prediction
// won't work.
if (elapsedMs == 0) {
return null;
}
// Q_delta = Q_last^-1 * Q_curr
this.deltaQ.copy(this.lastQ);
this.deltaQ.inverse();
this.deltaQ.multiply(currentQ);
// Convert from delta quaternion to axis-angle.
var axis = this.getAxis_(this.deltaQ);
var angleRad = this.getAngle_(this.deltaQ);
// It took `elapsed` ms to travel the angle amount over the axis. Now,
// we make a new quaternion based how far in the future we want to
// calculate.
var angularSpeedRadMs = angleRad / elapsedMs;
var angularSpeedDegS = THREE.Math.radToDeg(angularSpeedRadMs) * 1000;
// If no rotation rate is provided, do no prediction.
return {
speed: angularSpeedDegS,
axis: axis
};
};
module.exports = PosePredictor;
| PosePredictor | identifier_name |
pose-predictor.js | /*
* Copyright 2015 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var THREE = require('./three-math.js');
var PredictionMode = {
NONE: 'none',
INTERPOLATE: 'interpolate',
PREDICT: 'predict'
}
// How much to interpolate between the current orientation estimate and the
// previous estimate position. This is helpful for devices with low
// deviceorientation firing frequency (eg. on iOS8 and below, it is 20 Hz). The
// larger this value (in [0, 1]), the smoother but more delayed the head
// tracking is.
var INTERPOLATION_SMOOTHING_FACTOR = 0.01;
// Angular threshold, if the angular speed (in deg/s) is less than this, do no
// prediction. Without it, the screen flickers quite a bit.
var PREDICTION_THRESHOLD_DEG_PER_S = 0.01;
//var PREDICTION_THRESHOLD_DEG_PER_S = 0;
// How far into the future to predict.
window.WEBVR_PREDICTION_TIME_MS = 80;
// Whether to predict or what.
window.WEBVR_PREDICTION_MODE = PredictionMode.PREDICT;
function PosePredictor() |
PosePredictor.prototype.getPrediction = function(currentQ, rotationRate, timestamp) {
// If there's no previous quaternion, output the current one and save for
// later.
if (!this.lastTimestamp) {
this.lastQ.copy(currentQ);
this.lastTimestamp = timestamp;
return currentQ;
}
// DEBUG ONLY: Try with a fixed 60 Hz update speed.
//var elapsedMs = 1000/60;
var elapsedMs = timestamp - this.lastTimestamp;
switch (WEBVR_PREDICTION_MODE) {
case PredictionMode.INTERPOLATE:
this.outQ.copy(currentQ);
this.outQ.slerp(this.lastQ, INTERPOLATION_SMOOTHING_FACTOR);
// Save the current quaternion for later.
this.lastQ.copy(currentQ);
break;
case PredictionMode.PREDICT:
var axisAngle;
if (rotationRate) {
axisAngle = this.getAxisAngularSpeedFromRotationRate_(rotationRate);
} else {
axisAngle = this.getAxisAngularSpeedFromGyroDelta_(currentQ, elapsedMs);
}
// If there is no predicted axis/angle, don't do prediction.
if (!axisAngle) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
var angularSpeedDegS = axisAngle.speed;
var axis = axisAngle.axis;
var predictAngleDeg = (WEBVR_PREDICTION_TIME_MS / 1000) * angularSpeedDegS;
// If we're rotating slowly, don't do prediction.
if (angularSpeedDegS < PREDICTION_THRESHOLD_DEG_PER_S) {
this.outQ.copy(currentQ);
this.lastQ.copy(currentQ);
break;
}
// Calculate the prediction delta to apply to the original angle.
this.deltaQ.setFromAxisAngle(axis, THREE.Math.degToRad(predictAngleDeg));
// DEBUG ONLY: As a sanity check, use the same axis and angle as before,
// which should cause no prediction to happen.
//this.deltaQ.setFromAxisAngle(axis, angle);
this.outQ.copy(this.lastQ);
this.outQ.multiply(this.deltaQ);
// Use the predicted quaternion as the new last one.
//this.lastQ.copy(this.outQ);
this.lastQ.copy(currentQ);
break;
case PredictionMode.NONE:
default:
this.outQ.copy(currentQ);
}
this.lastTimestamp = timestamp;
return this.outQ;
};
PosePredictor.prototype.setScreenOrientation = function(screenOrientation) {
this.screenOrientation = screenOrientation;
};
PosePredictor.prototype.getAxis_ = function(quat) {
// x = qx / sqrt(1-qw*qw)
// y = qy / sqrt(1-qw*qw)
// z = qz / sqrt(1-qw*qw)
var d = Math.sqrt(1 - quat.w * quat.w);
return new THREE.Vector3(quat.x / d, quat.y / d, quat.z / d);
};
PosePredictor.prototype.getAngle_ = function(quat) {
// angle = 2 * acos(qw)
// If w is greater than 1 (THREE.js, how can this be?), arccos is not defined.
if (quat.w > 1) {
return 0;
}
var angle = 2 * Math.acos(quat.w);
// Normalize the angle to be in [-Ο, Ο].
if (angle > Math.PI) {
angle -= 2 * Math.PI;
}
return angle;
};
PosePredictor.prototype.getAxisAngularSpeedFromRotationRate_ = function(rotationRate) {
if (!rotationRate) {
return null;
}
var screenRotationRate;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
// iOS: angular speed in deg/s.
var screenRotationRate = this.getScreenAdjustedRotationRateIOS_(rotationRate);
} else {
// Android: angular speed in rad/s, so need to convert.
rotationRate.alpha = THREE.Math.radToDeg(rotationRate.alpha);
rotationRate.beta = THREE.Math.radToDeg(rotationRate.beta);
rotationRate.gamma = THREE.Math.radToDeg(rotationRate.gamma);
var screenRotationRate = this.getScreenAdjustedRotationRate_(rotationRate);
}
var vec = new THREE.Vector3(
screenRotationRate.beta, screenRotationRate.alpha, screenRotationRate.gamma);
/*
var vec;
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
vec = new THREE.Vector3(rotationRate.gamma, rotationRate.alpha, rotationRate.beta);
} else {
vec = new THREE.Vector3(rotationRate.beta, rotationRate.alpha, rotationRate.gamma);
}
// Take into account the screen orientation too!
vec.applyQuaternion(this.screenTransform);
*/
// Angular speed in deg/s.
var angularSpeedDegS = vec.length();
var axis = vec.normalize();
return {
speed: angularSpeedDegS,
axis: axis
}
};
PosePredictor.prototype.getScreenAdjustedRotationRate_ = function(rotationRate) {
var screenRotationRate = {
alpha: -rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = - rotationRate.gamma;
screenRotationRate.gamma = rotationRate.beta;
break;
case 180:
screenRotationRate.beta = - rotationRate.beta;
screenRotationRate.gamma = - rotationRate.gamma;
break;
case 270:
case -90:
screenRotationRate.beta = rotationRate.gamma;
screenRotationRate.gamma = - rotationRate.beta;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getScreenAdjustedRotationRateIOS_ = function(rotationRate) {
var screenRotationRate = {
alpha: rotationRate.alpha,
beta: rotationRate.beta,
gamma: rotationRate.gamma
};
// Values empirically derived.
switch (this.screenOrientation) {
case 90:
screenRotationRate.beta = -rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
case 180:
// You can't even do this on iOS.
break;
case 270:
case -90:
screenRotationRate.alpha = -rotationRate.alpha;
screenRotationRate.beta = rotationRate.beta;
screenRotationRate.gamma = rotationRate.gamma;
break;
default: // SCREEN_ROTATION_0
screenRotationRate.alpha = rotationRate.beta;
screenRotationRate.beta = rotationRate.alpha;
screenRotationRate.gamma = rotationRate.gamma;
break;
}
return screenRotationRate;
};
PosePredictor.prototype.getAxisAngularSpeedFromGyroDelta_ = function(currentQ, elapsedMs) {
// Sometimes we use the same sensor timestamp, in which case prediction
// won't work.
if (elapsedMs == 0) {
return null;
}
// Q_delta = Q_last^-1 * Q_curr
this.deltaQ.copy(this.lastQ);
this.deltaQ.inverse();
this.deltaQ.multiply(currentQ);
// Convert from delta quaternion to axis-angle.
var axis = this.getAxis_(this.deltaQ);
var angleRad = this.getAngle_(this.deltaQ);
// It took `elapsed` ms to travel the angle amount over the axis. Now,
// we make a new quaternion based how far in the future we want to
// calculate.
var angularSpeedRadMs = angleRad / elapsedMs;
var angularSpeedDegS = THREE.Math.radToDeg(angularSpeedRadMs) * 1000;
// If no rotation rate is provided, do no prediction.
return {
speed: angularSpeedDegS,
axis: axis
};
};
module.exports = PosePredictor;
| {
this.lastQ = new THREE.Quaternion();
this.lastTimestamp = null;
this.outQ = new THREE.Quaternion();
this.deltaQ = new THREE.Quaternion();
} | identifier_body |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
| // the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
} | // Registers the type for our element, and then registers in GStreamer under | random_line_split |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
// Registers the type for our element, and then registers in GStreamer under
// the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn r | plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| egister( | identifier_name |
mod.rs | // Copyright (C) 2020 Sebastian DrΓΆge <sebastian@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use glib::prelude::*;
mod imp;
// The public Rust wrapper type for our element
glib::glib_wrapper! {
pub struct Rgb2Gray(ObjectSubclass<imp::Rgb2Gray>) @extends gst_base::BaseTransform, gst::Element, gst::Object;
}
// GStreamer elements need to be thread-safe. For the private implementation this is automatically
// enforced but for the public wrapper type we need to specify this manually.
unsafe impl Send for Rgb2Gray {}
unsafe impl Sync for Rgb2Gray {}
// Registers the type for our element, and then registers in GStreamer under
// the name "rsrgb2gray" for being able to instantiate it via e.g.
// gst::ElementFactory::make().
pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { |
gst::Element::register(
Some(plugin),
"rsrgb2gray",
gst::Rank::None,
Rgb2Gray::static_type(),
)
}
| identifier_body | |
driver.py | #! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outputs a binary string.
Eg : 1110111 means out of 7 test cases 4th failed and rest
all passed.
Resource/Time limit errors will be produced from docker container'''
#opening and parsing test cases
with open ("answer") as file: # change after development finishes
cases=file.readlines();
cases = [x.strip() for x in cases]
cases = [ast.literal_eval(x) for x in cases]
s="" #return string
number_of_cases = len(cases)/2
for i in range(number_of_cases):
if type(cases[i]) is tuple:
if cases[number_of_cases+i] == solution.answer(*cases):
s+="1"
else:
s+="0"
else:
if cases[number_of_cases+i] == solution.answer(cases[i]): | print s | s+="1"
else:
s+="0"
| random_line_split |
driver.py | #! /usr/bin/python
#should move this file inside docker image
import ast
import solution
'''driver file running the program
takes the test cases from the answers/question_name file
and executes each test case. The output of each execution
will be compared and the program outputs a binary string.
Eg : 1110111 means out of 7 test cases 4th failed and rest
all passed.
Resource/Time limit errors will be produced from docker container'''
#opening and parsing test cases
with open ("answer") as file: # change after development finishes
cases=file.readlines();
cases = [x.strip() for x in cases]
cases = [ast.literal_eval(x) for x in cases]
s="" #return string
number_of_cases = len(cases)/2
for i in range(number_of_cases):
if type(cases[i]) is tuple:
if cases[number_of_cases+i] == solution.answer(*cases):
|
else:
s+="0"
else:
if cases[number_of_cases+i] == solution.answer(cases[i]):
s+="1"
else:
s+="0"
print s
| s+="1" | conditional_block |
tests.py | from django.test import TestCase
from finance.models import Banking_Account |
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227')
self.assertEqual(Banking_Account.isBBAN("679-2005502-27"), True)
self.assertEqual(Banking_Account.isBBAN('BE48679200550227'), False)
self.assertEqual(Banking_Account.isIBAN("679-2005502-27"), False)
self.assertEqual(Banking_Account.isIBAN('BE48679200550227'), True) |
class IBANTestCase(TestCase):
def setUp(self):
pass | random_line_split |
tests.py | from django.test import TestCase
from finance.models import Banking_Account
class IBANTestCase(TestCase):
| def setUp(self):
pass
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227')
self.assertEqual(Banking_Account.isBBAN("679-2005502-27"), True)
self.assertEqual(Banking_Account.isBBAN('BE48679200550227'), False)
self.assertEqual(Banking_Account.isIBAN("679-2005502-27"), False)
self.assertEqual(Banking_Account.isIBAN('BE48679200550227'), True) | identifier_body | |
tests.py | from django.test import TestCase
from finance.models import Banking_Account
class | (TestCase):
def setUp(self):
pass
def test_iban_converter(self):
"""BBAN to IBAN conversion"""
self.assertEqual(Banking_Account.convertBBANToIBAN("091-0002777-90"), 'BE34091000277790')
self.assertEqual(Banking_Account.convertBBANToIBAN("679-2005502-27"), 'BE48679200550227')
self.assertEqual(Banking_Account.isBBAN("679-2005502-27"), True)
self.assertEqual(Banking_Account.isBBAN('BE48679200550227'), False)
self.assertEqual(Banking_Account.isIBAN("679-2005502-27"), False)
self.assertEqual(Banking_Account.isIBAN('BE48679200550227'), True)
| IBANTestCase | identifier_name |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
* 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.
*/
import _ from 'lodash';
import moment from 'moment';
const dummyUsers = [
'Jeff',
'Ryan',
'Brad',
'Alex',
'Matt',
];
const projectIds = [
'project_1',
'project_2',
'project_3',
'project_4',
'project_5',
'project_6',
];
const DATE_FORMAT = 'YYYY-MM-DD';
const bucketMaps = {
DAILY: {
interval: [1, 'd'],
multiplier: 1,
},
WEEKLY: {
interval: [1, 'w'],
multiplier: 7,
},
MONTHLY: {
interval: [1, 'm'],
multiplier: 30,
},
YEARLY: {
interval: [1, 'y'],
multiplier: 365,
},
}
function randomDate(start, end) |
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FORMAT),
bucket: bucketSize,
entries: _.sortBy(_.range(number).map((x, i) => {
const bucketStartDate = moment(randomDate(startDate.toDate(), endDate.toDate()));
const bucketEndDate = bucketStartDate.add(bucketMaps[bucketSize].interval[0], bucketMaps[bucketSize].interval[1]);
return {
fromDate: bucketStartDate.format(DATE_FORMAT),
toDate: bucketEndDate.format(DATE_FORMAT),
user: _.sample(dummyUsers),
projectId: _.sample(projectIds),
cpu: _.random(1, 50 * bucketVars.multiplier),
volume: _.random(10 * bucketVars.multiplier, 60 * bucketVars.multiplier),
image: _.random(1, 40 * bucketVars.multiplier),
};
}), 'fromDate')
}
}; | {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
} | identifier_body |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
* 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.
*/
import _ from 'lodash';
import moment from 'moment';
const dummyUsers = [
'Jeff',
'Ryan',
'Brad',
'Alex',
'Matt',
];
const projectIds = [
'project_1',
'project_2',
'project_3',
'project_4',
'project_5',
'project_6',
];
const DATE_FORMAT = 'YYYY-MM-DD';
const bucketMaps = {
DAILY: {
interval: [1, 'd'],
multiplier: 1,
},
WEEKLY: {
interval: [1, 'w'],
multiplier: 7,
},
MONTHLY: {
interval: [1, 'm'],
multiplier: 30,
},
YEARLY: {
interval: [1, 'y'],
multiplier: 365,
},
}
function randomDate(start, end) { | }
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FORMAT),
bucket: bucketSize,
entries: _.sortBy(_.range(number).map((x, i) => {
const bucketStartDate = moment(randomDate(startDate.toDate(), endDate.toDate()));
const bucketEndDate = bucketStartDate.add(bucketMaps[bucketSize].interval[0], bucketMaps[bucketSize].interval[1]);
return {
fromDate: bucketStartDate.format(DATE_FORMAT),
toDate: bucketEndDate.format(DATE_FORMAT),
user: _.sample(dummyUsers),
projectId: _.sample(projectIds),
cpu: _.random(1, 50 * bucketVars.multiplier),
volume: _.random(10 * bucketVars.multiplier, 60 * bucketVars.multiplier),
image: _.random(1, 40 * bucketVars.multiplier),
};
}), 'fromDate')
}
}; | return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); | random_line_split |
makeDummyReport.js | /*
* Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public
* License v3.0. You should have received a copy of the GNU General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*
* 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.
*/
import _ from 'lodash';
import moment from 'moment';
const dummyUsers = [
'Jeff',
'Ryan',
'Brad',
'Alex',
'Matt',
];
const projectIds = [
'project_1',
'project_2',
'project_3',
'project_4',
'project_5',
'project_6',
];
const DATE_FORMAT = 'YYYY-MM-DD';
const bucketMaps = {
DAILY: {
interval: [1, 'd'],
multiplier: 1,
},
WEEKLY: {
interval: [1, 'w'],
multiplier: 7,
},
MONTHLY: {
interval: [1, 'm'],
multiplier: 30,
},
YEARLY: {
interval: [1, 'y'],
multiplier: 365,
},
}
function | (start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
export default function makeDummyReport({number, bucketSize, fromDate, toDate}) {
const startDate = moment(fromDate, DATE_FORMAT);
const endDate = moment(toDate, DATE_FORMAT);
const bucketVars = bucketMaps[bucketSize];
return {
fromDate: startDate.format(DATE_FORMAT),
toDate: endDate.format(DATE_FORMAT),
bucket: bucketSize,
entries: _.sortBy(_.range(number).map((x, i) => {
const bucketStartDate = moment(randomDate(startDate.toDate(), endDate.toDate()));
const bucketEndDate = bucketStartDate.add(bucketMaps[bucketSize].interval[0], bucketMaps[bucketSize].interval[1]);
return {
fromDate: bucketStartDate.format(DATE_FORMAT),
toDate: bucketEndDate.format(DATE_FORMAT),
user: _.sample(dummyUsers),
projectId: _.sample(projectIds),
cpu: _.random(1, 50 * bucketVars.multiplier),
volume: _.random(10 * bucketVars.multiplier, 60 * bucketVars.multiplier),
image: _.random(1, 40 * bucketVars.multiplier),
};
}), 'fromDate')
}
}; | randomDate | identifier_name |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}; | var context_1 = require("./context/context");
var context_2 = require("./context/context");
var LoggerFactory = (function () {
function LoggerFactory() {
}
LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) {
this.logging = gridOptionsWrapper.isDebug();
};
LoggerFactory.prototype.create = function (name) {
return new Logger(name, this.isLogging.bind(this));
};
LoggerFactory.prototype.isLogging = function () {
return this.logging;
};
return LoggerFactory;
}());
__decorate([
__param(0, context_2.Qualifier('gridOptionsWrapper')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [gridOptionsWrapper_1.GridOptionsWrapper]),
__metadata("design:returntype", void 0)
], LoggerFactory.prototype, "setBeans", null);
LoggerFactory = __decorate([
context_1.Bean('loggerFactory')
], LoggerFactory);
exports.LoggerFactory = LoggerFactory;
var Logger = (function () {
function Logger(name, isLoggingFunc) {
this.name = name;
this.isLoggingFunc = isLoggingFunc;
}
Logger.prototype.isLogging = function () {
return this.isLoggingFunc();
};
Logger.prototype.log = function (message) {
if (this.isLoggingFunc()) {
console.log('ag-Grid.' + this.name + ': ' + message);
}
};
return Logger;
}());
exports.Logger = Logger; | var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper"); | random_line_split |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var context_1 = require("./context/context");
var context_2 = require("./context/context");
var LoggerFactory = (function () {
function | () {
}
LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) {
this.logging = gridOptionsWrapper.isDebug();
};
LoggerFactory.prototype.create = function (name) {
return new Logger(name, this.isLogging.bind(this));
};
LoggerFactory.prototype.isLogging = function () {
return this.logging;
};
return LoggerFactory;
}());
__decorate([
__param(0, context_2.Qualifier('gridOptionsWrapper')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [gridOptionsWrapper_1.GridOptionsWrapper]),
__metadata("design:returntype", void 0)
], LoggerFactory.prototype, "setBeans", null);
LoggerFactory = __decorate([
context_1.Bean('loggerFactory')
], LoggerFactory);
exports.LoggerFactory = LoggerFactory;
var Logger = (function () {
function Logger(name, isLoggingFunc) {
this.name = name;
this.isLoggingFunc = isLoggingFunc;
}
Logger.prototype.isLogging = function () {
return this.isLoggingFunc();
};
Logger.prototype.log = function (message) {
if (this.isLoggingFunc()) {
console.log('ag-Grid.' + this.name + ': ' + message);
}
};
return Logger;
}());
exports.Logger = Logger;
| LoggerFactory | identifier_name |
logger.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v11.0.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("./gridOptionsWrapper");
var context_1 = require("./context/context");
var context_2 = require("./context/context");
var LoggerFactory = (function () {
function LoggerFactory() {
}
LoggerFactory.prototype.setBeans = function (gridOptionsWrapper) {
this.logging = gridOptionsWrapper.isDebug();
};
LoggerFactory.prototype.create = function (name) {
return new Logger(name, this.isLogging.bind(this));
};
LoggerFactory.prototype.isLogging = function () {
return this.logging;
};
return LoggerFactory;
}());
__decorate([
__param(0, context_2.Qualifier('gridOptionsWrapper')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [gridOptionsWrapper_1.GridOptionsWrapper]),
__metadata("design:returntype", void 0)
], LoggerFactory.prototype, "setBeans", null);
LoggerFactory = __decorate([
context_1.Bean('loggerFactory')
], LoggerFactory);
exports.LoggerFactory = LoggerFactory;
var Logger = (function () {
function Logger(name, isLoggingFunc) |
Logger.prototype.isLogging = function () {
return this.isLoggingFunc();
};
Logger.prototype.log = function (message) {
if (this.isLoggingFunc()) {
console.log('ag-Grid.' + this.name + ': ' + message);
}
};
return Logger;
}());
exports.Logger = Logger;
| {
this.name = name;
this.isLoggingFunc = isLoggingFunc;
} | identifier_body |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-outside-init
import systemtesting
from mantid.simpleapi import *
from reduction_workflow.instruments.sans.sns_command_interface import *
from reduction_workflow.instruments.sans.hfir_command_interface import *
FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/"
class EQSANSFlatTest(systemtesting.MantidSystemTest):
| def requiredFiles(self):
files = []
files.append(FILE_LOCATION+"EQSANS_5704_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5734_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5732_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5738_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5729_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5737_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5703_event.nxs")
files.append("bl6_flux_at_sample")
return files
def runTest(self):
"""
System test for EQSANS.
This test is meant to be run at SNS and takes a long time.
It is used to verify that the complete reduction chain works
and reproduces reference results.
"""
configI = ConfigService.Instance()
configI["facilityName"]='SNS'
EQSANS()
SolidAngle()
DarkCurrent(FILE_LOCATION+"EQSANS_5704_event.nxs")
TotalChargeNormalization(beam_file="bl6_flux_at_sample")
AzimuthalAverage(n_bins=100, n_subpix=1, log_binning=False)
IQxQy(nbins=100)
UseConfigTOFTailsCutoff(True)
PerformFlightPathCorrection(True)
UseConfigMask(True)
SetBeamCenter(89.6749, 129.693)
SensitivityCorrection(FILE_LOCATION+'EQSANS_5703_event.nxs',
min_sensitivity=0.5,
max_sensitivity=1.5, use_sample_dc=True)
DirectBeamTransmission(FILE_LOCATION+"EQSANS_5734_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
ThetaDependentTransmission(False)
AppendDataFile([FILE_LOCATION+"EQSANS_5729_event.nxs"])
CombineTransmissionFits(True)
Background(FILE_LOCATION+"EQSANS_5732_event.nxs")
BckDirectBeamTransmission(FILE_LOCATION+"EQSANS_5737_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
BckThetaDependentTransmission(False)
BckCombineTransmissionFits(True)
SaveIqAscii(process='None')
SetAbsoluteScale(277.781)
Reduce1D()
# This reference is old, ignore the first non-zero point and
# give the comparison a reasonable tolerance (less than 0.5%).
mtd['EQSANS_5729_event_frame1_Iq'].dataY(0)[1] = 856.30028119108
def validate(self):
self.tolerance = 5.0
self.disableChecking.append('Instrument')
self.disableChecking.append('Sample')
self.disableChecking.append('SpectraMap')
self.disableChecking.append('Axes')
return "EQSANS_5729_event_frame1_Iq", 'EQSANSFlatTest.nxs' | identifier_body | |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-outside-init
import systemtesting
from mantid.simpleapi import *
from reduction_workflow.instruments.sans.sns_command_interface import *
from reduction_workflow.instruments.sans.hfir_command_interface import *
FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/"
class EQSANSFlatTest(systemtesting.MantidSystemTest):
def requiredFiles(self):
files = []
files.append(FILE_LOCATION+"EQSANS_5704_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5734_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5732_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5738_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5729_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5737_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5703_event.nxs")
files.append("bl6_flux_at_sample")
return files
def runTest(self):
"""
System test for EQSANS.
This test is meant to be run at SNS and takes a long time.
It is used to verify that the complete reduction chain works
and reproduces reference results.
"""
configI = ConfigService.Instance()
configI["facilityName"]='SNS'
EQSANS()
SolidAngle()
DarkCurrent(FILE_LOCATION+"EQSANS_5704_event.nxs")
TotalChargeNormalization(beam_file="bl6_flux_at_sample")
AzimuthalAverage(n_bins=100, n_subpix=1, log_binning=False)
IQxQy(nbins=100)
UseConfigTOFTailsCutoff(True)
PerformFlightPathCorrection(True)
UseConfigMask(True)
SetBeamCenter(89.6749, 129.693)
SensitivityCorrection(FILE_LOCATION+'EQSANS_5703_event.nxs',
min_sensitivity=0.5,
max_sensitivity=1.5, use_sample_dc=True)
DirectBeamTransmission(FILE_LOCATION+"EQSANS_5734_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
ThetaDependentTransmission(False)
AppendDataFile([FILE_LOCATION+"EQSANS_5729_event.nxs"])
CombineTransmissionFits(True)
Background(FILE_LOCATION+"EQSANS_5732_event.nxs")
BckDirectBeamTransmission(FILE_LOCATION+"EQSANS_5737_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
BckThetaDependentTransmission(False)
BckCombineTransmissionFits(True)
SaveIqAscii(process='None') | mtd['EQSANS_5729_event_frame1_Iq'].dataY(0)[1] = 856.30028119108
def validate(self):
self.tolerance = 5.0
self.disableChecking.append('Instrument')
self.disableChecking.append('Sample')
self.disableChecking.append('SpectraMap')
self.disableChecking.append('Axes')
return "EQSANS_5729_event_frame1_Iq", 'EQSANSFlatTest.nxs' | SetAbsoluteScale(277.781)
Reduce1D()
# This reference is old, ignore the first non-zero point and
# give the comparison a reasonable tolerance (less than 0.5%). | random_line_split |
EQSANSFlatTestAPIv2.py | # Mantid Repository : https://github.com/mantidproject/mantid
#
# Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
# NScD Oak Ridge National Laboratory, European Spallation Source
# & Institut Laue - Langevin
# SPDX - License - Identifier: GPL - 3.0 +
#pylint: disable=no-init,attribute-defined-outside-init
import systemtesting
from mantid.simpleapi import *
from reduction_workflow.instruments.sans.sns_command_interface import *
from reduction_workflow.instruments.sans.hfir_command_interface import *
FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/"
class EQSANSFlatTest(systemtesting.MantidSystemTest):
def requiredFiles(self):
files = []
files.append(FILE_LOCATION+"EQSANS_5704_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5734_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5732_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5738_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5729_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5737_event.nxs")
files.append(FILE_LOCATION+"EQSANS_5703_event.nxs")
files.append("bl6_flux_at_sample")
return files
def runTest(self):
"""
System test for EQSANS.
This test is meant to be run at SNS and takes a long time.
It is used to verify that the complete reduction chain works
and reproduces reference results.
"""
configI = ConfigService.Instance()
configI["facilityName"]='SNS'
EQSANS()
SolidAngle()
DarkCurrent(FILE_LOCATION+"EQSANS_5704_event.nxs")
TotalChargeNormalization(beam_file="bl6_flux_at_sample")
AzimuthalAverage(n_bins=100, n_subpix=1, log_binning=False)
IQxQy(nbins=100)
UseConfigTOFTailsCutoff(True)
PerformFlightPathCorrection(True)
UseConfigMask(True)
SetBeamCenter(89.6749, 129.693)
SensitivityCorrection(FILE_LOCATION+'EQSANS_5703_event.nxs',
min_sensitivity=0.5,
max_sensitivity=1.5, use_sample_dc=True)
DirectBeamTransmission(FILE_LOCATION+"EQSANS_5734_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
ThetaDependentTransmission(False)
AppendDataFile([FILE_LOCATION+"EQSANS_5729_event.nxs"])
CombineTransmissionFits(True)
Background(FILE_LOCATION+"EQSANS_5732_event.nxs")
BckDirectBeamTransmission(FILE_LOCATION+"EQSANS_5737_event.nxs",
FILE_LOCATION+"EQSANS_5738_event.nxs", beam_radius=3)
BckThetaDependentTransmission(False)
BckCombineTransmissionFits(True)
SaveIqAscii(process='None')
SetAbsoluteScale(277.781)
Reduce1D()
# This reference is old, ignore the first non-zero point and
# give the comparison a reasonable tolerance (less than 0.5%).
mtd['EQSANS_5729_event_frame1_Iq'].dataY(0)[1] = 856.30028119108
def | (self):
self.tolerance = 5.0
self.disableChecking.append('Instrument')
self.disableChecking.append('Sample')
self.disableChecking.append('SpectraMap')
self.disableChecking.append('Axes')
return "EQSANS_5729_event_frame1_Iq", 'EQSANSFlatTest.nxs'
| validate | identifier_name |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class QoSPolicy(neutron.NeutronResource):
"""A resource for Neutron QoS Policy.
This QoS policy can be associated with neutron resources,
such as port and network, to provide QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
NAME, DESCRIPTION, SHARED, TENANT_ID,
) = (
'name', 'description', 'shared', 'tenant_id',
)
ATTRIBUTES = (
RULES_ATTR,
) = (
'rules',
)
properties_schema = {
NAME: properties.Schema(
properties.Schema.STRING,
_('The name for the QoS policy.'),
required=True,
update_allowed=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('The description for the QoS policy.'),
update_allowed=True
),
SHARED: properties.Schema(
properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
),
}
attributes_schema = {
RULES_ATTR: attributes.Schema(
_("A list of all rules for the QoS policy."),
type=attributes.Schema.LIST
)
}
def handle_create(self):
props = self.prepare_properties(
self.properties,
self.physical_resource_name())
policy = self.client().create_qos_policy({'policy': props})['policy']
self.resource_id_set(policy['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_qos_policy(self.resource_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
|
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
POLICY, TENANT_ID,
) = (
'policy', 'tenant_id',
)
properties_schema = {
POLICY: properties.Schema(
properties.Schema.STRING,
_('ID or name of the QoS policy.'),
required=True,
constraints=[constraints.CustomConstraint('neutron.qos_policy')]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this rule.')
),
}
def __init__(self, name, json_snippet, stack):
super(QoSRule, self).__init__(name, json_snippet, stack)
self._policy_id = None
@property
def policy_id(self):
if not self._policy_id:
self._policy_id = self.client_plugin().get_qos_policy_id(
self.properties[self.POLICY])
return self._policy_id
class QoSBandwidthLimitRule(QoSRule):
"""A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPERTIES = (
MAX_BANDWIDTH, MAX_BURST_BANDWIDTH,
) = (
'max_kbps', 'max_burst_kbps',
)
properties_schema = {
MAX_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max bandwidth in kbps.'),
required=True,
update_allowed=True,
constraints=[
constraints.Range(min=0)
]
),
MAX_BURST_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max burst bandwidth in kbps.'),
update_allowed=True,
constraints=[
constraints.Range(min=0)
],
default=0
)
}
properties_schema.update(QoSRule.properties_schema)
def handle_create(self):
props = self.prepare_properties(self.properties,
self.physical_resource_name())
props.pop(self.POLICY)
rule = self.client().create_bandwidth_limit_rule(
self.policy_id,
{'bandwidth_limit_rule': props})['bandwidth_limit_rule']
self.resource_id_set(rule['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_bandwidth_limit_rule(
self.resource_id, self.policy_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit_rule(
self.resource_id, self.policy_id)['bandwidth_limit_rule']
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
}
| self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff}) | conditional_block |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class QoSPolicy(neutron.NeutronResource):
"""A resource for Neutron QoS Policy.
This QoS policy can be associated with neutron resources,
such as port and network, to provide QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
NAME, DESCRIPTION, SHARED, TENANT_ID,
) = (
'name', 'description', 'shared', 'tenant_id',
)
ATTRIBUTES = (
RULES_ATTR,
) = (
'rules',
)
properties_schema = {
NAME: properties.Schema(
properties.Schema.STRING,
_('The name for the QoS policy.'),
required=True,
update_allowed=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('The description for the QoS policy.'),
update_allowed=True
),
SHARED: properties.Schema(
properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
),
}
attributes_schema = {
RULES_ATTR: attributes.Schema(
_("A list of all rules for the QoS policy."),
type=attributes.Schema.LIST
)
}
def handle_create(self):
props = self.prepare_properties(
self.properties,
self.physical_resource_name())
policy = self.client().create_qos_policy({'policy': props})['policy']
self.resource_id_set(policy['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_qos_policy(self.resource_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff})
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
POLICY, TENANT_ID,
) = (
'policy', 'tenant_id',
)
properties_schema = {
POLICY: properties.Schema(
properties.Schema.STRING,
_('ID or name of the QoS policy.'),
required=True,
constraints=[constraints.CustomConstraint('neutron.qos_policy')]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this rule.')
),
}
def __init__(self, name, json_snippet, stack):
super(QoSRule, self).__init__(name, json_snippet, stack)
self._policy_id = None
@property
def policy_id(self):
if not self._policy_id:
self._policy_id = self.client_plugin().get_qos_policy_id(
self.properties[self.POLICY])
return self._policy_id
class QoSBandwidthLimitRule(QoSRule):
"""A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPERTIES = (
MAX_BANDWIDTH, MAX_BURST_BANDWIDTH,
) = (
'max_kbps', 'max_burst_kbps',
)
properties_schema = {
MAX_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max bandwidth in kbps.'),
required=True,
update_allowed=True,
constraints=[
constraints.Range(min=0)
]
),
MAX_BURST_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max burst bandwidth in kbps.'),
update_allowed=True,
constraints=[
constraints.Range(min=0)
],
default=0
)
}
properties_schema.update(QoSRule.properties_schema)
def handle_create(self):
props = self.prepare_properties(self.properties,
self.physical_resource_name())
props.pop(self.POLICY)
rule = self.client().create_bandwidth_limit_rule(
self.policy_id,
{'bandwidth_limit_rule': props})['bandwidth_limit_rule']
self.resource_id_set(rule['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_bandwidth_limit_rule(
self.resource_id, self.policy_id)
def | (self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit_rule(
self.resource_id, self.policy_id)['bandwidth_limit_rule']
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
}
| handle_update | identifier_name |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class QoSPolicy(neutron.NeutronResource):
"""A resource for Neutron QoS Policy.
This QoS policy can be associated with neutron resources,
such as port and network, to provide QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
NAME, DESCRIPTION, SHARED, TENANT_ID,
) = (
'name', 'description', 'shared', 'tenant_id',
)
ATTRIBUTES = (
RULES_ATTR,
) = (
'rules',
)
properties_schema = {
NAME: properties.Schema(
properties.Schema.STRING,
_('The name for the QoS policy.'),
required=True,
update_allowed=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('The description for the QoS policy.'),
update_allowed=True
),
SHARED: properties.Schema(
properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
),
}
attributes_schema = {
RULES_ATTR: attributes.Schema(
_("A list of all rules for the QoS policy."),
type=attributes.Schema.LIST
)
}
def handle_create(self):
props = self.prepare_properties(
self.properties,
self.physical_resource_name())
policy = self.client().create_qos_policy({'policy': props})['policy']
self.resource_id_set(policy['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_qos_policy(self.resource_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff})
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
POLICY, TENANT_ID,
) = (
'policy', 'tenant_id',
)
properties_schema = {
POLICY: properties.Schema(
properties.Schema.STRING,
_('ID or name of the QoS policy.'),
required=True,
constraints=[constraints.CustomConstraint('neutron.qos_policy')]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this rule.')
),
}
def __init__(self, name, json_snippet, stack):
super(QoSRule, self).__init__(name, json_snippet, stack)
self._policy_id = None
@property
def policy_id(self):
if not self._policy_id:
self._policy_id = self.client_plugin().get_qos_policy_id(
self.properties[self.POLICY])
return self._policy_id
class QoSBandwidthLimitRule(QoSRule):
|
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
}
| """A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPERTIES = (
MAX_BANDWIDTH, MAX_BURST_BANDWIDTH,
) = (
'max_kbps', 'max_burst_kbps',
)
properties_schema = {
MAX_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max bandwidth in kbps.'),
required=True,
update_allowed=True,
constraints=[
constraints.Range(min=0)
]
),
MAX_BURST_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max burst bandwidth in kbps.'),
update_allowed=True,
constraints=[
constraints.Range(min=0)
],
default=0
)
}
properties_schema.update(QoSRule.properties_schema)
def handle_create(self):
props = self.prepare_properties(self.properties,
self.physical_resource_name())
props.pop(self.POLICY)
rule = self.client().create_bandwidth_limit_rule(
self.policy_id,
{'bandwidth_limit_rule': props})['bandwidth_limit_rule']
self.resource_id_set(rule['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_bandwidth_limit_rule(
self.resource_id, self.policy_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit_rule(
self.resource_id, self.policy_id)['bandwidth_limit_rule'] | identifier_body |
qos.py | #
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from heat.common.i18n import _
from heat.engine import attributes
from heat.engine import constraints
from heat.engine import properties
from heat.engine.resources.openstack.neutron import neutron
from heat.engine import support
class QoSPolicy(neutron.NeutronResource):
"""A resource for Neutron QoS Policy.
This QoS policy can be associated with neutron resources,
such as port and network, to provide QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
NAME, DESCRIPTION, SHARED, TENANT_ID,
) = (
'name', 'description', 'shared', 'tenant_id',
)
ATTRIBUTES = (
RULES_ATTR,
) = (
'rules',
)
properties_schema = {
NAME: properties.Schema(
properties.Schema.STRING,
_('The name for the QoS policy.'),
required=True,
update_allowed=True
),
DESCRIPTION: properties.Schema(
properties.Schema.STRING,
_('The description for the QoS policy.'),
update_allowed=True | properties.Schema.BOOLEAN,
_('Whether this QoS policy should be shared to other tenants.'),
default=False,
update_allowed=True
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this QoS policy.')
),
}
attributes_schema = {
RULES_ATTR: attributes.Schema(
_("A list of all rules for the QoS policy."),
type=attributes.Schema.LIST
)
}
def handle_create(self):
props = self.prepare_properties(
self.properties,
self.physical_resource_name())
policy = self.client().create_qos_policy({'policy': props})['policy']
self.resource_id_set(policy['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_qos_policy(self.resource_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.prepare_update_properties(prop_diff)
self.client().update_qos_policy(
self.resource_id,
{'policy': prop_diff})
def _show_resource(self):
return self.client().show_qos_policy(
self.resource_id)['policy']
class QoSRule(neutron.NeutronResource):
"""A resource for Neutron QoS base rule."""
required_service_extension = 'qos'
support_status = support.SupportStatus(version='6.0.0')
PROPERTIES = (
POLICY, TENANT_ID,
) = (
'policy', 'tenant_id',
)
properties_schema = {
POLICY: properties.Schema(
properties.Schema.STRING,
_('ID or name of the QoS policy.'),
required=True,
constraints=[constraints.CustomConstraint('neutron.qos_policy')]
),
TENANT_ID: properties.Schema(
properties.Schema.STRING,
_('The owner tenant ID of this rule.')
),
}
def __init__(self, name, json_snippet, stack):
super(QoSRule, self).__init__(name, json_snippet, stack)
self._policy_id = None
@property
def policy_id(self):
if not self._policy_id:
self._policy_id = self.client_plugin().get_qos_policy_id(
self.properties[self.POLICY])
return self._policy_id
class QoSBandwidthLimitRule(QoSRule):
"""A resource for Neutron QoS bandwidth limit rule.
This rule can be associated with QoS policy, and then the policy
can be used by neutron port and network, to provide bandwidth limit
QoS capabilities.
The default policy usage of this resource is limited to
administrators only.
"""
PROPERTIES = (
MAX_BANDWIDTH, MAX_BURST_BANDWIDTH,
) = (
'max_kbps', 'max_burst_kbps',
)
properties_schema = {
MAX_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max bandwidth in kbps.'),
required=True,
update_allowed=True,
constraints=[
constraints.Range(min=0)
]
),
MAX_BURST_BANDWIDTH: properties.Schema(
properties.Schema.INTEGER,
_('Max burst bandwidth in kbps.'),
update_allowed=True,
constraints=[
constraints.Range(min=0)
],
default=0
)
}
properties_schema.update(QoSRule.properties_schema)
def handle_create(self):
props = self.prepare_properties(self.properties,
self.physical_resource_name())
props.pop(self.POLICY)
rule = self.client().create_bandwidth_limit_rule(
self.policy_id,
{'bandwidth_limit_rule': props})['bandwidth_limit_rule']
self.resource_id_set(rule['id'])
def handle_delete(self):
if self.resource_id is None:
return
with self.client_plugin().ignore_not_found:
self.client().delete_bandwidth_limit_rule(
self.resource_id, self.policy_id)
def handle_update(self, json_snippet, tmpl_diff, prop_diff):
if prop_diff:
self.client().update_bandwidth_limit_rule(
self.resource_id,
self.policy_id,
{'bandwidth_limit_rule': prop_diff})
def _show_resource(self):
return self.client().show_bandwidth_limit_rule(
self.resource_id, self.policy_id)['bandwidth_limit_rule']
def resource_mapping():
return {
'OS::Neutron::QoSPolicy': QoSPolicy,
'OS::Neutron::QoSBandwidthLimitRule': QoSBandwidthLimitRule
} | ),
SHARED: properties.Schema( | random_line_split |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keypress", true, true, document.defaultView, false, false, false, false, k, k);
} else |
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function keyupcode(el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.dispatchEvent(eventObj) : el.fireEvent("onkeyup", eventObj);
if (eventObj.initEvent) {
el.dispatchEvent(eventObj)
} else {
iekeyup(keyCode)
}
}
describe('Gym page', function(){
var gym
var typedText
beforeEach(function(){
gym = new Gym({id: 1})
spyOn(gym.model, 'load')
gym.init()
gym.model.data = {
id: 1,
title: "Moby dick",
text: "Ishmael"
}
gym.render()
typedText = sizzle('#typedText', gym.element)
})
it('should show the excerpt text', function(){
var text = sizzle('#excerpt-text', gym.element)
expect(text[0].textContent).toContain('Ishmael')
})
describe('typing the "o" key', function(){
beforeEach(function(){
keyup(document.body, 'o')
})
it('should show the letter "o" on the screen', function(){
expect(typedText[0].textContent).toEqual("o")
})
describe('then typing the "e" key', function(){
beforeEach(function(){
keyup(document.body, 'e')
})
it('should show "oe" on the screen', function(){
expect(typedText[0].textContent).toEqual("oe")
})
describe('then clicking backspace', function(){
it('should show "o" on the screen', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("o")
})
})
})
})
describe('clicking the space key', function(){
beforeEach(function(){
keyup(document.body, ' ')
})
it('should show a space on the screen', function(){
expect(typedText[0].innerHTML).toEqual(" ")
})
describe('then clicking backspace', function(){
it('should empty line', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("")
})
})
})
})
| {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
} | conditional_block |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keypress", true, true, document.defaultView, false, false, false, false, k, k);
} else {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
}
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function | (el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.dispatchEvent(eventObj) : el.fireEvent("onkeyup", eventObj);
if (eventObj.initEvent) {
el.dispatchEvent(eventObj)
} else {
iekeyup(keyCode)
}
}
describe('Gym page', function(){
var gym
var typedText
beforeEach(function(){
gym = new Gym({id: 1})
spyOn(gym.model, 'load')
gym.init()
gym.model.data = {
id: 1,
title: "Moby dick",
text: "Ishmael"
}
gym.render()
typedText = sizzle('#typedText', gym.element)
})
it('should show the excerpt text', function(){
var text = sizzle('#excerpt-text', gym.element)
expect(text[0].textContent).toContain('Ishmael')
})
describe('typing the "o" key', function(){
beforeEach(function(){
keyup(document.body, 'o')
})
it('should show the letter "o" on the screen', function(){
expect(typedText[0].textContent).toEqual("o")
})
describe('then typing the "e" key', function(){
beforeEach(function(){
keyup(document.body, 'e')
})
it('should show "oe" on the screen', function(){
expect(typedText[0].textContent).toEqual("oe")
})
describe('then clicking backspace', function(){
it('should show "o" on the screen', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("o")
})
})
})
})
describe('clicking the space key', function(){
beforeEach(function(){
keyup(document.body, ' ')
})
it('should show a space on the screen', function(){
expect(typedText[0].innerHTML).toEqual(" ")
})
describe('then clicking backspace', function(){
it('should empty line', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("")
})
})
})
})
| keyupcode | identifier_name |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keypress", true, true, document.defaultView, false, false, false, false, k, k);
} else {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
}
| oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
{
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
}
function keyupcode(el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.dispatchEvent(eventObj) : el.fireEvent("onkeyup", eventObj);
if (eventObj.initEvent) {
el.dispatchEvent(eventObj)
} else {
iekeyup(keyCode)
}
}
describe('Gym page', function(){
var gym
var typedText
beforeEach(function(){
gym = new Gym({id: 1})
spyOn(gym.model, 'load')
gym.init()
gym.model.data = {
id: 1,
title: "Moby dick",
text: "Ishmael"
}
gym.render()
typedText = sizzle('#typedText', gym.element)
})
it('should show the excerpt text', function(){
var text = sizzle('#excerpt-text', gym.element)
expect(text[0].textContent).toContain('Ishmael')
})
describe('typing the "o" key', function(){
beforeEach(function(){
keyup(document.body, 'o')
})
it('should show the letter "o" on the screen', function(){
expect(typedText[0].textContent).toEqual("o")
})
describe('then typing the "e" key', function(){
beforeEach(function(){
keyup(document.body, 'e')
})
it('should show "oe" on the screen', function(){
expect(typedText[0].textContent).toEqual("oe")
})
describe('then clicking backspace', function(){
it('should show "o" on the screen', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("o")
})
})
})
})
describe('clicking the space key', function(){
beforeEach(function(){
keyup(document.body, ' ')
})
it('should show a space on the screen', function(){
expect(typedText[0].innerHTML).toEqual(" ")
})
describe('then clicking backspace', function(){
it('should empty line', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("")
})
})
})
}) | random_line_split | |
gymSpecs.js | var Gym = require('../client/gym')
, sizzle = require('sizzle')
, getkeycode = require('keycode')
var iekeyup = function(k) {
var oEvent = document.createEvent('KeyboardEvent');
// Chromium Hack
Object.defineProperty(oEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(oEvent, 'which', {
get : function() {
return this.keyCodeVal;
}
});
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent("keypress", true, true, document.defaultView, false, false, false, false, k, k);
} else {
oEvent.initKeyEvent("keypress", true, true, document.defaultView, false, false, false, false, k, 0);
}
oEvent.keyCodeVal = k;
if (oEvent.keyCode !== k) {
alert("keyCode mismatch " + oEvent.keyCode + "(" + oEvent.which + ")");
}
document.dispatchEvent(oEvent);
}
function keyup(el, letter)
|
function keyupcode(el, keyCode) {
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent){
eventObj.initEvent("keypress", true, true);
}
eventObj.keyCode = keyCode;
eventObj.which = keyCode;
//el.dispatchEvent ? el.dispatchEvent(eventObj) : el.fireEvent("onkeyup", eventObj);
if (eventObj.initEvent) {
el.dispatchEvent(eventObj)
} else {
iekeyup(keyCode)
}
}
describe('Gym page', function(){
var gym
var typedText
beforeEach(function(){
gym = new Gym({id: 1})
spyOn(gym.model, 'load')
gym.init()
gym.model.data = {
id: 1,
title: "Moby dick",
text: "Ishmael"
}
gym.render()
typedText = sizzle('#typedText', gym.element)
})
it('should show the excerpt text', function(){
var text = sizzle('#excerpt-text', gym.element)
expect(text[0].textContent).toContain('Ishmael')
})
describe('typing the "o" key', function(){
beforeEach(function(){
keyup(document.body, 'o')
})
it('should show the letter "o" on the screen', function(){
expect(typedText[0].textContent).toEqual("o")
})
describe('then typing the "e" key', function(){
beforeEach(function(){
keyup(document.body, 'e')
})
it('should show "oe" on the screen', function(){
expect(typedText[0].textContent).toEqual("oe")
})
describe('then clicking backspace', function(){
it('should show "o" on the screen', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("o")
})
})
})
})
describe('clicking the space key', function(){
beforeEach(function(){
keyup(document.body, ' ')
})
it('should show a space on the screen', function(){
expect(typedText[0].innerHTML).toEqual(" ")
})
describe('then clicking backspace', function(){
it('should empty line', function(){
keyupcode(document.body, 8)
expect(typedText[0].innerHTML).toEqual("")
})
})
})
})
| {
var keyCode = getkeycode(letter)
keyupcode(el, keyCode)
} | identifier_body |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
This file implements the CLA Classifier region. See the comments in the class
definition of CLAClassifierRegion for a description.
"""
from PyRegion import PyRegion
from nupic.algorithms.cla_classifier_factory import CLAClassifierFactory
###############################################################################
class CLAClassifierRegion(PyRegion):
"""
CLAClassifierRegion implements a CLA specific classifier that accepts a binary
input from the level below (the "activationPattern") and information from the
sensor and encoders (the "classification") describing the input to the system
at that time step.
When learning, for every bit in activation pattern, it records a history of the
classification each time that bit was active. The history is bounded by a
maximum allowed age so that old entries are thrown away.
For inference, it takes an ensemble approach. For every active bit in the
activationPattern, it looks up the most likely classification(s) from the
history stored for that bit and then votes across these to get the resulting
classification(s).
The caller can choose to tell the region that the classifications for
iteration N+K should be aligned with the activationPattern for iteration N.
This results in the classifier producing predictions for K steps in advance.
Any number of different K's can be specified, allowing the classifier to learn
and infer multi-step predictions for a number of steps in advance.
"""
###############################################################################
@classmethod
def getSpec(cls):
ns = dict(
description=CLAClassifierRegion.__doc__,
singleNodeOnly=True,
# The inputs and outputs are not used in this region because they are
# either sparse vectors or dictionaries and hence don't fit the "vector
# of real" input/output pattern.
# There is a custom compute() function provided that accepts the
# inputs and outputs.
inputs=dict(
categoryIn=dict(
description='Category of the input sample',
dataType='Real32',
count=1,
required=True,
regionLevel=True,
isDefaultInput=False,
requireSplitterMap=False),
bottomUpIn=dict(
description='Belief values over children\'s groups',
dataType='Real32',
count=0,
required=True,
regionLevel=False,
isDefaultInput=True,
requireSplitterMap=False),
),
outputs=dict(),
parameters=dict(
learningMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in learning mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=1,
accessMode='ReadWrite'),
inferenceMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in inference mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=0,
accessMode='ReadWrite'),
steps=dict(
description='Comma separated list of the desired steps of '
'prediction that the classifier should learn',
dataType="Byte",
count=0,
constraints='',
defaultValue='1',
accessMode='Create'),
alpha=dict(
description='The alpha used to compute running averages of the '
'bucket duty cycles for each activation pattern bit. A lower '
'alpha results in longer term memory',
dataType="Real32",
count=1,
constraints='',
defaultValue=0.001,
accessMode='Create'),
implementation=dict(
description='The classifier implementation to use.',
accessMode='ReadWrite',
dataType='Byte',
count=0,
constraints='enum: py, cpp'),
clVerbosity=dict(
description='An integer that controls the verbosity level, '
'0 means no verbose output, increasing integers '
'provide more verbosity.',
dataType='UInt32',
count=1,
constraints='',
defaultValue=0 ,
accessMode='ReadWrite'),
),
commands=dict()
)
return ns
###############################################################################
def __init__(self,
steps='1',
alpha=0.001,
clVerbosity=0,
implementation=None,
):
# Convert the steps designation to a list
self.steps = steps
self.stepsList = eval("[%s]" % (steps))
self.alpha = alpha
self.verbosity = clVerbosity
# Initialize internal structures
self._claClassifier = CLAClassifierFactory.create(
steps=self.stepsList,
alpha=self.alpha,
verbosity=self.verbosity,
implementation=implementation,
)
self.learningMode = True
self.inferenceMode = False
self._initEphemerals()
###############################################################################
def _initEphemerals(self):
pass
###############################################################################
def initialize(self, dims, splitterMaps):
pass
###############################################################################
def clear(self):
self._claClassifier.clear()
###############################################################################
def getParameter(self, name, index=-1):
"""
Get the value of the parameter.
@param name -- the name of the parameter to retrieve, as defined
by the Node Spec.
"""
# If any spec parameter name is the same as an attribute, this call
# will get it automatically, e.g. self.learningMode
return PyRegion.getParameter(self, name, index)
###############################################################################
def setParameter(self, name, index, value):
"""
Set the value of the parameter.
@param name -- the name of the parameter to update, as defined
by the Node Spec.
@param value -- the value to which the parameter is to be set.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
|
else:
return PyRegion.setParameter(self, name, index, value)
###############################################################################
def reset(self):
pass
###############################################################################
def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
We don't use this method in this region because the inputs and outputs don't
fit the standard "vector of reals" used by the engine. Instead, call
the customCompute() method directly
"""
pass
###############################################################################
def customCompute(self, recordNum, patternNZ, classification):
"""
Process one input sample.
This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.
Parameters:
--------------------------------------------------------------------
patternNZ: list of the active indices from the output below
classification: dict of the classification information:
bucketIdx: index of the encoder bucket
actValue: actual value going into the encoder
retval: dict containing inference results, one entry for each step in
self.steps. The key is the number of steps, the value is an
array containing the relative likelihood for each bucketIdx
starting from bucketIdx 0.
for example:
{1 : [0.1, 0.3, 0.2, 0.7]
4 : [0.2, 0.4, 0.3, 0.5]}
"""
return self._claClassifier.compute( recordNum=recordNum,
patternNZ=patternNZ,
classification=classification,
learn = self.learningMode,
infer = self.inferenceMode)
###############################################################################
if __name__=='__main__':
from nupic.engine import Network
n = Network()
classifier = n.addRegion(
'classifier',
'py.CLAClassifierRegion',
'{ steps: "1,2", maxAge: 1000}'
)
| self.inferenceMode = bool(int(value)) | conditional_block |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
This file implements the CLA Classifier region. See the comments in the class
definition of CLAClassifierRegion for a description.
"""
from PyRegion import PyRegion
from nupic.algorithms.cla_classifier_factory import CLAClassifierFactory
###############################################################################
class CLAClassifierRegion(PyRegion):
"""
CLAClassifierRegion implements a CLA specific classifier that accepts a binary
input from the level below (the "activationPattern") and information from the
sensor and encoders (the "classification") describing the input to the system
at that time step.
When learning, for every bit in activation pattern, it records a history of the
classification each time that bit was active. The history is bounded by a
maximum allowed age so that old entries are thrown away.
For inference, it takes an ensemble approach. For every active bit in the
activationPattern, it looks up the most likely classification(s) from the
history stored for that bit and then votes across these to get the resulting
classification(s).
The caller can choose to tell the region that the classifications for
iteration N+K should be aligned with the activationPattern for iteration N.
This results in the classifier producing predictions for K steps in advance.
Any number of different K's can be specified, allowing the classifier to learn
and infer multi-step predictions for a number of steps in advance.
"""
###############################################################################
@classmethod
def getSpec(cls):
ns = dict(
description=CLAClassifierRegion.__doc__,
singleNodeOnly=True,
# The inputs and outputs are not used in this region because they are
# either sparse vectors or dictionaries and hence don't fit the "vector
# of real" input/output pattern.
# There is a custom compute() function provided that accepts the
# inputs and outputs.
inputs=dict(
categoryIn=dict(
description='Category of the input sample',
dataType='Real32',
count=1,
required=True,
regionLevel=True,
isDefaultInput=False,
requireSplitterMap=False),
bottomUpIn=dict(
description='Belief values over children\'s groups',
dataType='Real32',
count=0,
required=True,
regionLevel=False,
isDefaultInput=True,
requireSplitterMap=False),
),
outputs=dict(),
parameters=dict(
learningMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in learning mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=1,
accessMode='ReadWrite'),
inferenceMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in inference mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=0,
accessMode='ReadWrite'),
steps=dict(
description='Comma separated list of the desired steps of '
'prediction that the classifier should learn',
dataType="Byte",
count=0,
constraints='',
defaultValue='1',
accessMode='Create'),
alpha=dict(
description='The alpha used to compute running averages of the '
'bucket duty cycles for each activation pattern bit. A lower '
'alpha results in longer term memory',
dataType="Real32",
count=1,
constraints='',
defaultValue=0.001,
accessMode='Create'),
implementation=dict(
description='The classifier implementation to use.',
accessMode='ReadWrite',
dataType='Byte',
count=0,
constraints='enum: py, cpp'),
clVerbosity=dict(
description='An integer that controls the verbosity level, '
'0 means no verbose output, increasing integers '
'provide more verbosity.',
dataType='UInt32',
count=1,
constraints='',
defaultValue=0 ,
accessMode='ReadWrite'),
),
commands=dict()
)
return ns
###############################################################################
def __init__(self,
steps='1',
alpha=0.001,
clVerbosity=0,
implementation=None,
):
# Convert the steps designation to a list
self.steps = steps
self.stepsList = eval("[%s]" % (steps))
self.alpha = alpha
self.verbosity = clVerbosity
# Initialize internal structures
self._claClassifier = CLAClassifierFactory.create(
steps=self.stepsList,
alpha=self.alpha,
verbosity=self.verbosity,
implementation=implementation,
)
self.learningMode = True
self.inferenceMode = False
self._initEphemerals()
###############################################################################
def _initEphemerals(self):
pass
###############################################################################
def initialize(self, dims, splitterMaps):
|
###############################################################################
def clear(self):
self._claClassifier.clear()
###############################################################################
def getParameter(self, name, index=-1):
"""
Get the value of the parameter.
@param name -- the name of the parameter to retrieve, as defined
by the Node Spec.
"""
# If any spec parameter name is the same as an attribute, this call
# will get it automatically, e.g. self.learningMode
return PyRegion.getParameter(self, name, index)
###############################################################################
def setParameter(self, name, index, value):
"""
Set the value of the parameter.
@param name -- the name of the parameter to update, as defined
by the Node Spec.
@param value -- the value to which the parameter is to be set.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion.setParameter(self, name, index, value)
###############################################################################
def reset(self):
pass
###############################################################################
def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
We don't use this method in this region because the inputs and outputs don't
fit the standard "vector of reals" used by the engine. Instead, call
the customCompute() method directly
"""
pass
###############################################################################
def customCompute(self, recordNum, patternNZ, classification):
"""
Process one input sample.
This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.
Parameters:
--------------------------------------------------------------------
patternNZ: list of the active indices from the output below
classification: dict of the classification information:
bucketIdx: index of the encoder bucket
actValue: actual value going into the encoder
retval: dict containing inference results, one entry for each step in
self.steps. The key is the number of steps, the value is an
array containing the relative likelihood for each bucketIdx
starting from bucketIdx 0.
for example:
{1 : [0.1, 0.3, 0.2, 0.7]
4 : [0.2, 0.4, 0.3, 0.5]}
"""
return self._claClassifier.compute( recordNum=recordNum,
patternNZ=patternNZ,
classification=classification,
learn = self.learningMode,
infer = self.inferenceMode)
###############################################################################
if __name__=='__main__':
from nupic.engine import Network
n = Network()
classifier = n.addRegion(
'classifier',
'py.CLAClassifierRegion',
'{ steps: "1,2", maxAge: 1000}'
)
| pass | identifier_body |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
This file implements the CLA Classifier region. See the comments in the class
definition of CLAClassifierRegion for a description.
"""
from PyRegion import PyRegion
from nupic.algorithms.cla_classifier_factory import CLAClassifierFactory
###############################################################################
class CLAClassifierRegion(PyRegion):
"""
CLAClassifierRegion implements a CLA specific classifier that accepts a binary
input from the level below (the "activationPattern") and information from the
sensor and encoders (the "classification") describing the input to the system
at that time step.
When learning, for every bit in activation pattern, it records a history of the
classification each time that bit was active. The history is bounded by a
maximum allowed age so that old entries are thrown away.
For inference, it takes an ensemble approach. For every active bit in the
activationPattern, it looks up the most likely classification(s) from the
history stored for that bit and then votes across these to get the resulting
classification(s).
The caller can choose to tell the region that the classifications for
iteration N+K should be aligned with the activationPattern for iteration N.
This results in the classifier producing predictions for K steps in advance.
Any number of different K's can be specified, allowing the classifier to learn
and infer multi-step predictions for a number of steps in advance.
"""
###############################################################################
@classmethod
def getSpec(cls):
ns = dict(
description=CLAClassifierRegion.__doc__,
singleNodeOnly=True,
# The inputs and outputs are not used in this region because they are
# either sparse vectors or dictionaries and hence don't fit the "vector
# of real" input/output pattern.
# There is a custom compute() function provided that accepts the
# inputs and outputs.
inputs=dict(
categoryIn=dict(
description='Category of the input sample',
dataType='Real32',
count=1,
required=True,
regionLevel=True,
isDefaultInput=False,
requireSplitterMap=False),
bottomUpIn=dict(
description='Belief values over children\'s groups',
dataType='Real32',
count=0,
required=True,
regionLevel=False,
isDefaultInput=True,
requireSplitterMap=False),
),
outputs=dict(),
parameters=dict(
learningMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in learning mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=1,
accessMode='ReadWrite'),
inferenceMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in inference mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=0,
accessMode='ReadWrite'),
steps=dict(
description='Comma separated list of the desired steps of '
'prediction that the classifier should learn',
dataType="Byte",
count=0,
constraints='',
defaultValue='1',
accessMode='Create'),
alpha=dict(
description='The alpha used to compute running averages of the '
'bucket duty cycles for each activation pattern bit. A lower '
'alpha results in longer term memory',
dataType="Real32",
count=1,
constraints='',
defaultValue=0.001,
accessMode='Create'),
implementation=dict(
description='The classifier implementation to use.',
accessMode='ReadWrite',
dataType='Byte',
count=0,
constraints='enum: py, cpp'),
clVerbosity=dict(
description='An integer that controls the verbosity level, '
'0 means no verbose output, increasing integers '
'provide more verbosity.',
dataType='UInt32',
count=1,
constraints='',
defaultValue=0 ,
accessMode='ReadWrite'),
),
commands=dict()
)
return ns
###############################################################################
def __init__(self,
steps='1',
alpha=0.001,
clVerbosity=0,
implementation=None,
):
# Convert the steps designation to a list
self.steps = steps
self.stepsList = eval("[%s]" % (steps))
self.alpha = alpha
self.verbosity = clVerbosity
# Initialize internal structures
self._claClassifier = CLAClassifierFactory.create(
steps=self.stepsList,
alpha=self.alpha,
verbosity=self.verbosity,
implementation=implementation,
)
self.learningMode = True
self.inferenceMode = False
self._initEphemerals()
###############################################################################
def | (self):
pass
###############################################################################
def initialize(self, dims, splitterMaps):
pass
###############################################################################
def clear(self):
self._claClassifier.clear()
###############################################################################
def getParameter(self, name, index=-1):
"""
Get the value of the parameter.
@param name -- the name of the parameter to retrieve, as defined
by the Node Spec.
"""
# If any spec parameter name is the same as an attribute, this call
# will get it automatically, e.g. self.learningMode
return PyRegion.getParameter(self, name, index)
###############################################################################
def setParameter(self, name, index, value):
"""
Set the value of the parameter.
@param name -- the name of the parameter to update, as defined
by the Node Spec.
@param value -- the value to which the parameter is to be set.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion.setParameter(self, name, index, value)
###############################################################################
def reset(self):
pass
###############################################################################
def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
We don't use this method in this region because the inputs and outputs don't
fit the standard "vector of reals" used by the engine. Instead, call
the customCompute() method directly
"""
pass
###############################################################################
def customCompute(self, recordNum, patternNZ, classification):
"""
Process one input sample.
This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.
Parameters:
--------------------------------------------------------------------
patternNZ: list of the active indices from the output below
classification: dict of the classification information:
bucketIdx: index of the encoder bucket
actValue: actual value going into the encoder
retval: dict containing inference results, one entry for each step in
self.steps. The key is the number of steps, the value is an
array containing the relative likelihood for each bucketIdx
starting from bucketIdx 0.
for example:
{1 : [0.1, 0.3, 0.2, 0.7]
4 : [0.2, 0.4, 0.3, 0.5]}
"""
return self._claClassifier.compute( recordNum=recordNum,
patternNZ=patternNZ,
classification=classification,
learn = self.learningMode,
infer = self.inferenceMode)
###############################################################################
if __name__=='__main__':
from nupic.engine import Network
n = Network()
classifier = n.addRegion(
'classifier',
'py.CLAClassifierRegion',
'{ steps: "1,2", maxAge: 1000}'
)
| _initEphemerals | identifier_name |
CLAClassifierRegion.py | #!/usr/bin/env python
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
This file implements the CLA Classifier region. See the comments in the class
definition of CLAClassifierRegion for a description.
"""
from PyRegion import PyRegion
from nupic.algorithms.cla_classifier_factory import CLAClassifierFactory
###############################################################################
class CLAClassifierRegion(PyRegion):
"""
CLAClassifierRegion implements a CLA specific classifier that accepts a binary
input from the level below (the "activationPattern") and information from the
sensor and encoders (the "classification") describing the input to the system
at that time step.
When learning, for every bit in activation pattern, it records a history of the
classification each time that bit was active. The history is bounded by a
maximum allowed age so that old entries are thrown away.
For inference, it takes an ensemble approach. For every active bit in the
activationPattern, it looks up the most likely classification(s) from the
history stored for that bit and then votes across these to get the resulting
classification(s).
The caller can choose to tell the region that the classifications for
iteration N+K should be aligned with the activationPattern for iteration N.
This results in the classifier producing predictions for K steps in advance.
Any number of different K's can be specified, allowing the classifier to learn
and infer multi-step predictions for a number of steps in advance.
"""
###############################################################################
@classmethod
def getSpec(cls):
ns = dict(
description=CLAClassifierRegion.__doc__,
singleNodeOnly=True,
# The inputs and outputs are not used in this region because they are
# either sparse vectors or dictionaries and hence don't fit the "vector
# of real" input/output pattern.
# There is a custom compute() function provided that accepts the
# inputs and outputs.
inputs=dict(
categoryIn=dict(
description='Category of the input sample',
dataType='Real32',
count=1,
required=True,
regionLevel=True,
isDefaultInput=False,
requireSplitterMap=False),
bottomUpIn=dict(
description='Belief values over children\'s groups',
dataType='Real32',
count=0,
required=True,
regionLevel=False,
isDefaultInput=True,
requireSplitterMap=False),
),
outputs=dict(),
parameters=dict(
learningMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in learning mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=1,
accessMode='ReadWrite'),
inferenceMode=dict(
description='Boolean (0/1) indicating whether or not a region '
'is in inference mode.',
dataType='UInt32',
count=1,
constraints='bool',
defaultValue=0,
accessMode='ReadWrite'),
steps=dict(
description='Comma separated list of the desired steps of '
'prediction that the classifier should learn',
dataType="Byte",
count=0,
constraints='',
defaultValue='1',
accessMode='Create'),
alpha=dict(
description='The alpha used to compute running averages of the '
'bucket duty cycles for each activation pattern bit. A lower '
'alpha results in longer term memory',
dataType="Real32",
count=1,
constraints='',
defaultValue=0.001,
accessMode='Create'),
implementation=dict(
description='The classifier implementation to use.',
accessMode='ReadWrite',
dataType='Byte',
count=0,
constraints='enum: py, cpp'),
clVerbosity=dict(
description='An integer that controls the verbosity level, '
'0 means no verbose output, increasing integers '
'provide more verbosity.',
dataType='UInt32',
count=1,
constraints='',
defaultValue=0 ,
accessMode='ReadWrite'),
),
commands=dict()
)
return ns
###############################################################################
def __init__(self,
steps='1',
alpha=0.001,
clVerbosity=0,
implementation=None,
):
# Convert the steps designation to a list
self.steps = steps
self.stepsList = eval("[%s]" % (steps))
self.alpha = alpha
self.verbosity = clVerbosity
# Initialize internal structures
self._claClassifier = CLAClassifierFactory.create(
steps=self.stepsList,
alpha=self.alpha,
verbosity=self.verbosity,
implementation=implementation,
)
self.learningMode = True
self.inferenceMode = False
self._initEphemerals()
###############################################################################
def _initEphemerals(self):
pass
###############################################################################
def initialize(self, dims, splitterMaps):
pass
###############################################################################
def clear(self):
self._claClassifier.clear()
###############################################################################
def getParameter(self, name, index=-1):
"""
Get the value of the parameter.
@param name -- the name of the parameter to retrieve, as defined
by the Node Spec.
"""
# If any spec parameter name is the same as an attribute, this call
# will get it automatically, e.g. self.learningMode
return PyRegion.getParameter(self, name, index)
###############################################################################
def setParameter(self, name, index, value):
"""
Set the value of the parameter. | @param value -- the value to which the parameter is to be set.
"""
if name == "learningMode":
self.learningMode = bool(int(value))
elif name == "inferenceMode":
self.inferenceMode = bool(int(value))
else:
return PyRegion.setParameter(self, name, index, value)
###############################################################################
def reset(self):
pass
###############################################################################
def compute(self, inputs, outputs):
"""
Process one input sample.
This method is called by the runtime engine.
We don't use this method in this region because the inputs and outputs don't
fit the standard "vector of reals" used by the engine. Instead, call
the customCompute() method directly
"""
pass
###############################################################################
def customCompute(self, recordNum, patternNZ, classification):
"""
Process one input sample.
This method is called by outer loop code outside the nupic-engine. We
use this instead of the nupic engine compute() because our inputs and
outputs aren't fixed size vectors of reals.
Parameters:
--------------------------------------------------------------------
patternNZ: list of the active indices from the output below
classification: dict of the classification information:
bucketIdx: index of the encoder bucket
actValue: actual value going into the encoder
retval: dict containing inference results, one entry for each step in
self.steps. The key is the number of steps, the value is an
array containing the relative likelihood for each bucketIdx
starting from bucketIdx 0.
for example:
{1 : [0.1, 0.3, 0.2, 0.7]
4 : [0.2, 0.4, 0.3, 0.5]}
"""
return self._claClassifier.compute( recordNum=recordNum,
patternNZ=patternNZ,
classification=classification,
learn = self.learningMode,
infer = self.inferenceMode)
###############################################################################
if __name__=='__main__':
from nupic.engine import Network
n = Network()
classifier = n.addRegion(
'classifier',
'py.CLAClassifierRegion',
'{ steps: "1,2", maxAge: 1000}'
) |
@param name -- the name of the parameter to update, as defined
by the Node Spec. | random_line_split |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") |
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| {
x = x[5..].trim().to_string();
} | conditional_block |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String |
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
} | identifier_body |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn rustc_version()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd | \"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
} | pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\", | random_line_split |
build.rs | use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use std::process::Command;
fn | ()->String {
let cmd = Command::new(env::var("RUSTC").unwrap())
.args(&["--version"])
.output()
.expect("failed to execute process");
let mut x = String::from_utf8(cmd.stdout).unwrap();
x = x.trim().to_string();
if x.starts_with("rustc") {
x = x[5..].trim().to_string();
}
x
}
fn pybuildinfo()->Vec<u8> {
let pyscript = "
import os
import sys
if __name__ == '__main__':
path = os.path.abspath(os.path.join(os.getcwd(), '..'))
sys.path.append(path)
import pybuildinfo.cmd
pybuildinfo.cmd.cmd(sys.argv[2:])
";
let dict = format!("-dict={}", format!("{{
\"build_toolchain\": \"rustc\",
\"build_toolchain_version\": \"{}\",
\"build_target\": \"{}\"
}}", rustc_version(), env::var("TARGET").unwrap()));
let cmd = Command::new("python")
.args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict])
.output()
.expect("failed to execute process");
assert_eq!(cmd.status.code().unwrap(), 0);
cmd.stdout
}
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let dest_path = Path::new(&out_dir).join("pybuildinfo.rs");
let mut f = File::create(&dest_path).unwrap();
let buildinfo = pybuildinfo();
f.write_all(&buildinfo).unwrap();
}
| rustc_version | identifier_name |
mod.rs | use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
} | ///
///
///
impl Generate<()> for HtmlState {
fn generate(
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
}
} | random_line_split | |
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
}
///
///
///
impl Generate<()> for HtmlState {
fn | (
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
}
}
| generate | identifier_name |
mod.rs |
use syntax::ptr::P;
use syntax::{ast, codemap};
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use html::HtmlState;
mod template;
/// Trait meaning something can be turned into an ast::Item with configuration.
pub trait Generate<Cfg> {
/// Turn Self into an ast::Item with a configuration object.
fn generate(
self,
codemap::Span,
&mut base::ExtCtxt,
Cfg
) -> P<ast::Item>;
}
///
///
///
impl Generate<()> for HtmlState {
fn generate(
self,
sp: codemap::Span,
cx: &mut base::ExtCtxt,
_: ()
) -> P<ast::Item> |
}
| {
let skin = self.skin.clone().unwrap();
let template_items = self.templates.into_iter().map(
|template| template.generate(sp, cx, ())
).collect();
// we create the module made of the created function
cx.item_mod(sp, sp, skin, vec![], vec![], template_items)
} | identifier_body |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
self.ensure_one() | included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal
else:
price_unit = included_taxes.compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included']
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
price_subtotal = included_taxes.compute_all(
price, invoice.currency_id, self.quantity, self.product_id, invoice.partner_id)['total_included']
price_net = price_unit * (1 - (self.discount or 0.0) / 100.0)
return {
'price_unit': price_unit,
'price_subtotal': price_subtotal,
'price_net': price_net,
} | invoice = self.move_id | random_line_split |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def | (self):
self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal
else:
price_unit = included_taxes.compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included']
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
price_subtotal = included_taxes.compute_all(
price, invoice.currency_id, self.quantity, self.product_id, invoice.partner_id)['total_included']
price_net = price_unit * (1 - (self.discount or 0.0) / 100.0)
return {
'price_unit': price_unit,
'price_subtotal': price_subtotal,
'price_net': price_net,
}
| _l10n_ar_prices_and_taxes | identifier_name |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
|
else:
price_unit = included_taxes.compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included']
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
price_subtotal = included_taxes.compute_all(
price, invoice.currency_id, self.quantity, self.product_id, invoice.partner_id)['total_included']
price_net = price_unit * (1 - (self.discount or 0.0) / 100.0)
return {
'price_unit': price_unit,
'price_subtotal': price_subtotal,
'price_net': price_net,
}
| price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal | conditional_block |
account_move_line.py | # Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class AccountMoveLine(models.Model):
_inherit = 'account.move.line'
def _l10n_ar_prices_and_taxes(self):
| self.ensure_one()
invoice = self.move_id
included_taxes = self.tax_ids.filtered('tax_group_id.l10n_ar_vat_afip_code') if self.move_id._l10n_ar_include_vat() else self.tax_ids
if not included_taxes:
price_unit = self.tax_ids.with_context(round=False).compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)
price_unit = price_unit['total_excluded']
price_subtotal = self.price_subtotal
else:
price_unit = included_taxes.compute_all(
self.price_unit, invoice.currency_id, 1.0, self.product_id, invoice.partner_id)['total_included']
price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
price_subtotal = included_taxes.compute_all(
price, invoice.currency_id, self.quantity, self.product_id, invoice.partner_id)['total_included']
price_net = price_unit * (1 - (self.discount or 0.0) / 100.0)
return {
'price_unit': price_unit,
'price_subtotal': price_subtotal,
'price_net': price_net,
} | identifier_body | |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVersion = "2017-07-01";
private _apiVersionKey = "appsvc-api-version";
constructor(private _aiService: AiService) {
let apiVersion = localStorage.getItem(this._apiVersionKey);
if (!apiVersion || apiVersion !== this._apiVersion) {
this._resetStorage();
}
// Ensures that saving tab state should only happen per-session
localStorage.removeItem(LocalStorageKeys.siteTabs);
}
getItem(key: string): StorageItem {
return JSON.parse(localStorage.getItem(key));
}
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscriptions>this.getItem(LocalStorageKeys.savedSubsKey);
if (!savedSubs) {
savedSubs = <StoredSubscriptions>{
id: LocalStorageKeys.savedSubsKey,
subscriptions: []
};
}
savedSubs.subscriptions.push(sub);
this.setItem(LocalStorageKeys.savedSubsKey, savedSubs);
}
setItem(key: string, item: StorageItem) {
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Clearing local storage with ${localStorage.length} items. ${e}`
});
this._resetStorage();
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e2) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to save to local storage on 2nd attempt. ${e2}`
});
}
}
}
removeItem(key: string) {
try {
localStorage.removeItem(key);
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to remove from local storage. ${e}`
});
}
}
public addEventListener(handler: (StorageEvent) => void, caller: any) {
try {
window.addEventListener("storage", handler.bind(caller));
}
catch (e) { | this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to add local storage event listener. ${e}`
}
)
}
}
private _resetStorage() {
localStorage.clear();
localStorage.setItem(this._apiVersionKey, this._apiVersion);
}
} | random_line_split | |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVersion = "2017-07-01";
private _apiVersionKey = "appsvc-api-version";
constructor(private _aiService: AiService) {
let apiVersion = localStorage.getItem(this._apiVersionKey);
if (!apiVersion || apiVersion !== this._apiVersion) |
// Ensures that saving tab state should only happen per-session
localStorage.removeItem(LocalStorageKeys.siteTabs);
}
getItem(key: string): StorageItem {
return JSON.parse(localStorage.getItem(key));
}
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscriptions>this.getItem(LocalStorageKeys.savedSubsKey);
if (!savedSubs) {
savedSubs = <StoredSubscriptions>{
id: LocalStorageKeys.savedSubsKey,
subscriptions: []
};
}
savedSubs.subscriptions.push(sub);
this.setItem(LocalStorageKeys.savedSubsKey, savedSubs);
}
setItem(key: string, item: StorageItem) {
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Clearing local storage with ${localStorage.length} items. ${e}`
});
this._resetStorage();
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e2) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to save to local storage on 2nd attempt. ${e2}`
});
}
}
}
removeItem(key: string) {
try {
localStorage.removeItem(key);
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to remove from local storage. ${e}`
});
}
}
public addEventListener(handler: (StorageEvent) => void, caller: any) {
try {
window.addEventListener("storage", handler.bind(caller));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to add local storage event listener. ${e}`
}
)
}
}
private _resetStorage() {
localStorage.clear();
localStorage.setItem(this._apiVersionKey, this._apiVersion);
}
} | {
this._resetStorage();
} | conditional_block |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVersion = "2017-07-01";
private _apiVersionKey = "appsvc-api-version";
constructor(private _aiService: AiService) {
let apiVersion = localStorage.getItem(this._apiVersionKey);
if (!apiVersion || apiVersion !== this._apiVersion) {
this._resetStorage();
}
// Ensures that saving tab state should only happen per-session
localStorage.removeItem(LocalStorageKeys.siteTabs);
}
getItem(key: string): StorageItem {
return JSON.parse(localStorage.getItem(key));
}
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscriptions>this.getItem(LocalStorageKeys.savedSubsKey);
if (!savedSubs) {
savedSubs = <StoredSubscriptions>{
id: LocalStorageKeys.savedSubsKey,
subscriptions: []
};
}
savedSubs.subscriptions.push(sub);
this.setItem(LocalStorageKeys.savedSubsKey, savedSubs);
}
setItem(key: string, item: StorageItem) {
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Clearing local storage with ${localStorage.length} items. ${e}`
});
this._resetStorage();
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e2) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to save to local storage on 2nd attempt. ${e2}`
});
}
}
}
removeItem(key: string) {
try {
localStorage.removeItem(key);
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to remove from local storage. ${e}`
});
}
}
public addEventListener(handler: (StorageEvent) => void, caller: any) {
try {
window.addEventListener("storage", handler.bind(caller));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to add local storage event listener. ${e}`
}
)
}
}
private | () {
localStorage.clear();
localStorage.setItem(this._apiVersionKey, this._apiVersion);
}
} | _resetStorage | identifier_name |
local-storage.service.ts | import { LocalStorageKeys } from './../models/constants';
import { Injectable } from '@angular/core';
import { StorageItem, StoredSubscriptions } from '../models/localStorage/local-storage';
import { AiService } from "app/shared/services/ai.service";
@Injectable()
export class LocalStorageService {
private _apiVersion = "2017-07-01";
private _apiVersionKey = "appsvc-api-version";
constructor(private _aiService: AiService) {
let apiVersion = localStorage.getItem(this._apiVersionKey);
if (!apiVersion || apiVersion !== this._apiVersion) {
this._resetStorage();
}
// Ensures that saving tab state should only happen per-session
localStorage.removeItem(LocalStorageKeys.siteTabs);
}
getItem(key: string): StorageItem |
addtoSavedSubsKey(sub: string) {
let savedSubs = <StoredSubscriptions>this.getItem(LocalStorageKeys.savedSubsKey);
if (!savedSubs) {
savedSubs = <StoredSubscriptions>{
id: LocalStorageKeys.savedSubsKey,
subscriptions: []
};
}
savedSubs.subscriptions.push(sub);
this.setItem(LocalStorageKeys.savedSubsKey, savedSubs);
}
setItem(key: string, item: StorageItem) {
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Clearing local storage with ${localStorage.length} items. ${e}`
});
this._resetStorage();
try {
localStorage.setItem(key, JSON.stringify(item));
}
catch (e2) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to save to local storage on 2nd attempt. ${e2}`
});
}
}
}
removeItem(key: string) {
try {
localStorage.removeItem(key);
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to remove from local storage. ${e}`
});
}
}
public addEventListener(handler: (StorageEvent) => void, caller: any) {
try {
window.addEventListener("storage", handler.bind(caller));
}
catch (e) {
this._aiService.trackEvent(
'/storage-service/error', {
error: `Failed to add local storage event listener. ${e}`
}
)
}
}
private _resetStorage() {
localStorage.clear();
localStorage.setItem(this._apiVersionKey, this._apiVersion);
}
} | {
return JSON.parse(localStorage.getItem(key));
} | identifier_body |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import os
import socket
from cloudinit import helpers
from cloudinit import util
PUPPET_CONF_PATH = '/etc/puppet/puppet.conf'
PUPPET_SSL_CERT_DIR = '/var/lib/puppet/ssl/certs/'
PUPPET_SSL_DIR = '/var/lib/puppet/ssl'
PUPPET_SSL_CERT_PATH = '/var/lib/puppet/ssl/certs/ca.pem'
def | (log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable', 'puppet.service'],
capture=False)
elif os.path.exists('/sbin/chkconfig'):
util.subp(['/sbin/chkconfig', 'puppet', 'on'], capture=False)
else:
log.warn(("Sorry we do not know how to enable"
" puppet services on this system"))
def handle(name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
version = util.get_cfg_option_str(puppet_cfg, 'version', None)
if not install and version:
log.warn(("Puppet install set false but version supplied,"
" doing nothing."))
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to puppet.conf
contents = util.load_file(PUPPET_CONF_PATH)
# Create object for reading puppet.conf values
puppet_config = helpers.DefaultingConfigParser()
# Read puppet.conf values from original file in order to be able to
# mix the rest up. First clean them up
# (TODO(harlowja) is this really needed??)
cleaned_lines = [i.lstrip() for i in contents.splitlines()]
cleaned_contents = '\n'.join(cleaned_lines)
puppet_config.readfp(StringIO(cleaned_contents),
filename=PUPPET_CONF_PATH)
for (cfg_name, cfg) in puppet_cfg['conf'].iteritems():
# Cert configuration is a special case
# Dump the puppet master ca certificate in the correct place
if cfg_name == 'ca_cert':
# Puppet ssl sub-directory isn't created yet
# Create it with the proper permissions and ownership
util.ensure_dir(PUPPET_SSL_DIR, 0771)
util.chownbyname(PUPPET_SSL_DIR, 'puppet', 'root')
util.ensure_dir(PUPPET_SSL_CERT_DIR)
util.chownbyname(PUPPET_SSL_CERT_DIR, 'puppet', 'root')
util.write_file(PUPPET_SSL_CERT_PATH, str(cfg))
util.chownbyname(PUPPET_SSL_CERT_PATH, 'puppet', 'root')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for (o, v) in cfg.iteritems():
if o == 'certname':
# Expand %f as the fqdn
# TODO(harlowja) should this use the cloud fqdn??
v = v.replace("%f", socket.getfqdn())
# Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
util.rename(PUPPET_CONF_PATH, "%s.old" % (PUPPET_CONF_PATH))
util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
# Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False)
| _autostart_puppet | identifier_name |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import os
import socket
from cloudinit import helpers
from cloudinit import util
PUPPET_CONF_PATH = '/etc/puppet/puppet.conf'
PUPPET_SSL_CERT_DIR = '/var/lib/puppet/ssl/certs/'
PUPPET_SSL_DIR = '/var/lib/puppet/ssl'
PUPPET_SSL_CERT_PATH = '/var/lib/puppet/ssl/certs/ca.pem'
def _autostart_puppet(log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable', 'puppet.service'],
capture=False)
elif os.path.exists('/sbin/chkconfig'):
util.subp(['/sbin/chkconfig', 'puppet', 'on'], capture=False)
else:
log.warn(("Sorry we do not know how to enable"
" puppet services on this system"))
def handle(name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
version = util.get_cfg_option_str(puppet_cfg, 'version', None)
if not install and version:
|
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to puppet.conf
contents = util.load_file(PUPPET_CONF_PATH)
# Create object for reading puppet.conf values
puppet_config = helpers.DefaultingConfigParser()
# Read puppet.conf values from original file in order to be able to
# mix the rest up. First clean them up
# (TODO(harlowja) is this really needed??)
cleaned_lines = [i.lstrip() for i in contents.splitlines()]
cleaned_contents = '\n'.join(cleaned_lines)
puppet_config.readfp(StringIO(cleaned_contents),
filename=PUPPET_CONF_PATH)
for (cfg_name, cfg) in puppet_cfg['conf'].iteritems():
# Cert configuration is a special case
# Dump the puppet master ca certificate in the correct place
if cfg_name == 'ca_cert':
# Puppet ssl sub-directory isn't created yet
# Create it with the proper permissions and ownership
util.ensure_dir(PUPPET_SSL_DIR, 0771)
util.chownbyname(PUPPET_SSL_DIR, 'puppet', 'root')
util.ensure_dir(PUPPET_SSL_CERT_DIR)
util.chownbyname(PUPPET_SSL_CERT_DIR, 'puppet', 'root')
util.write_file(PUPPET_SSL_CERT_PATH, str(cfg))
util.chownbyname(PUPPET_SSL_CERT_PATH, 'puppet', 'root')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for (o, v) in cfg.iteritems():
if o == 'certname':
# Expand %f as the fqdn
# TODO(harlowja) should this use the cloud fqdn??
v = v.replace("%f", socket.getfqdn())
# Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
util.rename(PUPPET_CONF_PATH, "%s.old" % (PUPPET_CONF_PATH))
util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
# Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False)
| log.warn(("Puppet install set false but version supplied,"
" doing nothing.")) | conditional_block |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import os
import socket
from cloudinit import helpers
from cloudinit import util
PUPPET_CONF_PATH = '/etc/puppet/puppet.conf'
PUPPET_SSL_CERT_DIR = '/var/lib/puppet/ssl/certs/'
PUPPET_SSL_DIR = '/var/lib/puppet/ssl'
PUPPET_SSL_CERT_PATH = '/var/lib/puppet/ssl/certs/ca.pem'
def _autostart_puppet(log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable', 'puppet.service'],
capture=False)
elif os.path.exists('/sbin/chkconfig'):
util.subp(['/sbin/chkconfig', 'puppet', 'on'], capture=False)
else:
log.warn(("Sorry we do not know how to enable"
" puppet services on this system"))
def handle(name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
| if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
version = util.get_cfg_option_str(puppet_cfg, 'version', None)
if not install and version:
log.warn(("Puppet install set false but version supplied,"
" doing nothing."))
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to puppet.conf
contents = util.load_file(PUPPET_CONF_PATH)
# Create object for reading puppet.conf values
puppet_config = helpers.DefaultingConfigParser()
# Read puppet.conf values from original file in order to be able to
# mix the rest up. First clean them up
# (TODO(harlowja) is this really needed??)
cleaned_lines = [i.lstrip() for i in contents.splitlines()]
cleaned_contents = '\n'.join(cleaned_lines)
puppet_config.readfp(StringIO(cleaned_contents),
filename=PUPPET_CONF_PATH)
for (cfg_name, cfg) in puppet_cfg['conf'].iteritems():
# Cert configuration is a special case
# Dump the puppet master ca certificate in the correct place
if cfg_name == 'ca_cert':
# Puppet ssl sub-directory isn't created yet
# Create it with the proper permissions and ownership
util.ensure_dir(PUPPET_SSL_DIR, 0771)
util.chownbyname(PUPPET_SSL_DIR, 'puppet', 'root')
util.ensure_dir(PUPPET_SSL_CERT_DIR)
util.chownbyname(PUPPET_SSL_CERT_DIR, 'puppet', 'root')
util.write_file(PUPPET_SSL_CERT_PATH, str(cfg))
util.chownbyname(PUPPET_SSL_CERT_PATH, 'puppet', 'root')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for (o, v) in cfg.iteritems():
if o == 'certname':
# Expand %f as the fqdn
# TODO(harlowja) should this use the cloud fqdn??
v = v.replace("%f", socket.getfqdn())
# Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
util.rename(PUPPET_CONF_PATH, "%s.old" % (PUPPET_CONF_PATH))
util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
# Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False) | identifier_body | |
cc_puppet.py | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from StringIO import StringIO
import os
import socket
from cloudinit import helpers
from cloudinit import util
PUPPET_CONF_PATH = '/etc/puppet/puppet.conf'
PUPPET_SSL_CERT_DIR = '/var/lib/puppet/ssl/certs/'
PUPPET_SSL_DIR = '/var/lib/puppet/ssl'
PUPPET_SSL_CERT_PATH = '/var/lib/puppet/ssl/certs/ca.pem'
def _autostart_puppet(log):
# Set puppet to automatically start
if os.path.exists('/etc/default/puppet'):
util.subp(['sed', '-i',
'-e', 's/^START=.*/START=yes/',
'/etc/default/puppet'], capture=False)
elif os.path.exists('/bin/systemctl'):
util.subp(['/bin/systemctl', 'enable', 'puppet.service'],
capture=False)
elif os.path.exists('/sbin/chkconfig'):
util.subp(['/sbin/chkconfig', 'puppet', 'on'], capture=False)
else:
log.warn(("Sorry we do not know how to enable"
" puppet services on this system"))
def handle(name, cfg, cloud, log, _args):
# If there isn't a puppet key in the configuration don't do anything
if 'puppet' not in cfg:
log.debug(("Skipping module named %s,"
" no 'puppet' configuration found"), name)
return
puppet_cfg = cfg['puppet']
# Start by installing the puppet package if necessary...
install = util.get_cfg_option_bool(puppet_cfg, 'install', True)
version = util.get_cfg_option_str(puppet_cfg, 'version', None)
if not install and version:
log.warn(("Puppet install set false but version supplied,"
" doing nothing."))
elif install:
log.debug(("Attempting to install puppet %s,"),
version if version else 'latest')
cloud.distro.install_packages(('puppet', version))
# ... and then update the puppet configuration
if 'conf' in puppet_cfg:
# Add all sections from the conf object to puppet.conf
contents = util.load_file(PUPPET_CONF_PATH)
# Create object for reading puppet.conf values
puppet_config = helpers.DefaultingConfigParser()
# Read puppet.conf values from original file in order to be able to
# mix the rest up. First clean them up
# (TODO(harlowja) is this really needed??)
cleaned_lines = [i.lstrip() for i in contents.splitlines()]
cleaned_contents = '\n'.join(cleaned_lines)
puppet_config.readfp(StringIO(cleaned_contents),
filename=PUPPET_CONF_PATH)
for (cfg_name, cfg) in puppet_cfg['conf'].iteritems():
# Cert configuration is a special case
# Dump the puppet master ca certificate in the correct place
if cfg_name == 'ca_cert':
# Puppet ssl sub-directory isn't created yet
# Create it with the proper permissions and ownership
util.ensure_dir(PUPPET_SSL_DIR, 0771)
util.chownbyname(PUPPET_SSL_DIR, 'puppet', 'root')
util.ensure_dir(PUPPET_SSL_CERT_DIR)
util.chownbyname(PUPPET_SSL_CERT_DIR, 'puppet', 'root')
util.write_file(PUPPET_SSL_CERT_PATH, str(cfg))
util.chownbyname(PUPPET_SSL_CERT_PATH, 'puppet', 'root')
else:
# Iterate throug the config items, we'll use ConfigParser.set
# to overwrite or create new items as needed
for (o, v) in cfg.iteritems():
if o == 'certname':
# Expand %f as the fqdn
# TODO(harlowja) should this use the cloud fqdn??
v = v.replace("%f", socket.getfqdn())
# Expand %i as the instance id
v = v.replace("%i", cloud.get_instance_id())
# certname needs to be downcased
v = v.lower()
puppet_config.set(cfg_name, o, v)
# We got all our config as wanted we'll rename
# the previous puppet.conf and create our new one
util.rename(PUPPET_CONF_PATH, "%s.old" % (PUPPET_CONF_PATH)) | # Set it up so it autostarts
_autostart_puppet(log)
# Start puppetd
util.subp(['service', 'puppet', 'start'], capture=False) | util.write_file(PUPPET_CONF_PATH, puppet_config.stringify())
| random_line_split |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER_XYZ = "xyz"
EULER_XZX = "xzx"
EULER_XZY = "xzy"
EULER_YXY = "yxy"
EULER_YXZ = "yxz"
EULER_YZX = "yzx"
EULER_YZY = "yzy"
EULER_ZXY = "zxy"
EULER_ZXZ = "zxz"
EULER_ZYX = "zyx"
EULER_ZYZ = "zyz"
FIXED_XYX = "xyx"
FIXED_XYZ = "zyx"
FIXED_XZX = "xzx"
FIXED_XZY = "yzx"
FIXED_YXY = "yxy"
FIXED_YXZ = "zxy"
FIXED_YZX = "xzy"
FIXED_YZY = "yzy"
FIXED_ZXY = "yxz"
FIXED_ZXZ = "zxz"
FIXED_ZYX = "xyz"
FIXED_ZYZ = "zyz"
def vector_2_matrix(
vector: Sequence[float],
convention: Union[OrientationConvention, str] = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""
Calculate the pose from the position and euler angles.
:param convention:
:param vector: transform vector
:return: 4x4 transform matrix
"""
# get individual variables
translation_component = vector[:3]
rotation_component = vector[-3:]
# validate and extract orientation info
if isinstance(convention, OrientationConvention):
convention = convention.value
try:
OrientationConvention(convention)
except ValueError as e:
raise PyboticsError(str(e))
# iterate through rotation order
# build rotation matrix
transform_matrix = np.eye(4)
for axis, value in zip(convention, rotation_component): # type: ignore
current_rotation = globals()[f"rotation_matrix_{axis}"](value)
transform_matrix = np.dot(transform_matrix, current_rotation)
# add translation component
transform_matrix[:-1, -1] = translation_component
return transform_matrix
def position_from_matrix(matrix: np.ndarray) -> np.ndarray:
|
def matrix_2_vector(
matrix: np.ndarray,
convention: OrientationConvention = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""Convert 4x4 matrix to a vector."""
# call function
try:
return globals()[f"_matrix_2_{convention.name.lower()}"](matrix)
except KeyError: # pragma: no cover
raise NotImplementedError
def _matrix_2_euler_zyx(matrix: np.ndarray) -> np.ndarray:
"""
Calculate the equivalent position and euler angles of the given pose.
From: Craig, John J. Introduction to robotics: mechanics and control, 2005
:param matrix: 4x4 transform matrix
:return: transform vector
"""
# solution degenerates near ry = +/- 90deg
sb = -matrix[2, 0]
cb = np.sqrt(matrix[0, 0] ** 2 + matrix[1, 0] ** 2)
if np.isclose(cb, 0):
a = 0.0
b = np.sign(sb) * np.pi / 2
sc = matrix[0, 1]
cc = matrix[1, 1]
c = np.sign(sb) * np.arctan2(sc, cc)
else:
b = np.arctan2(sb, cb)
sa = matrix[1, 0] / cb
ca = matrix[0, 0] / cb
a = np.arctan2(sa, ca)
sc = matrix[2, 1] / cb
cc = matrix[2, 2] / cb
c = np.arctan2(sc, cc)
vector = np.hstack((matrix[:-1, -1], [a, b, c]))
return vector
def wrap_2_pi(angle: float) -> float:
"""
Wrap given angle to +/- PI.
:param angle: angle to wrap
:return: wrapped angle
"""
# FIXME: remove float() cast when numpy is supported in mypy
result = float((angle + np.pi) % (2 * np.pi) - np.pi)
return result
def rotation_matrix_x(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the X axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_y(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Y axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_z(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Z axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def translation_matrix(xyz: Sequence[float]) -> np.ndarray:
"""Generate a basic 4x4 translation matrix."""
# validate
if len(xyz) != 3:
raise PyboticsError("len(xyz) must be 3")
matrix = np.eye(4)
matrix[:-1, -1] = xyz
return matrix
| """Get the position values from a 4x4 transform matrix."""
return matrix[:-1, -1] | identifier_body |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER_XYZ = "xyz"
EULER_XZX = "xzx"
EULER_XZY = "xzy"
EULER_YXY = "yxy"
EULER_YXZ = "yxz"
EULER_YZX = "yzx"
EULER_YZY = "yzy"
EULER_ZXY = "zxy"
EULER_ZXZ = "zxz"
EULER_ZYX = "zyx"
EULER_ZYZ = "zyz"
FIXED_XYX = "xyx"
FIXED_XYZ = "zyx"
FIXED_XZX = "xzx"
FIXED_XZY = "yzx"
FIXED_YXY = "yxy"
FIXED_YXZ = "zxy"
FIXED_YZX = "xzy"
FIXED_YZY = "yzy"
FIXED_ZXY = "yxz"
FIXED_ZXZ = "zxz"
FIXED_ZYX = "xyz"
FIXED_ZYZ = "zyz"
def vector_2_matrix(
vector: Sequence[float],
convention: Union[OrientationConvention, str] = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""
Calculate the pose from the position and euler angles.
:param convention:
:param vector: transform vector
:return: 4x4 transform matrix
"""
# get individual variables
translation_component = vector[:3]
rotation_component = vector[-3:]
# validate and extract orientation info
if isinstance(convention, OrientationConvention):
convention = convention.value
try:
OrientationConvention(convention)
except ValueError as e:
raise PyboticsError(str(e))
# iterate through rotation order
# build rotation matrix
transform_matrix = np.eye(4)
for axis, value in zip(convention, rotation_component): # type: ignore
current_rotation = globals()[f"rotation_matrix_{axis}"](value)
transform_matrix = np.dot(transform_matrix, current_rotation)
# add translation component
transform_matrix[:-1, -1] = translation_component
return transform_matrix
def position_from_matrix(matrix: np.ndarray) -> np.ndarray:
"""Get the position values from a 4x4 transform matrix."""
return matrix[:-1, -1]
def matrix_2_vector(
matrix: np.ndarray,
convention: OrientationConvention = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""Convert 4x4 matrix to a vector."""
# call function
try:
return globals()[f"_matrix_2_{convention.name.lower()}"](matrix)
except KeyError: # pragma: no cover
raise NotImplementedError
def _matrix_2_euler_zyx(matrix: np.ndarray) -> np.ndarray:
"""
Calculate the equivalent position and euler angles of the given pose.
From: Craig, John J. Introduction to robotics: mechanics and control, 2005
:param matrix: 4x4 transform matrix
:return: transform vector
"""
# solution degenerates near ry = +/- 90deg
sb = -matrix[2, 0]
cb = np.sqrt(matrix[0, 0] ** 2 + matrix[1, 0] ** 2)
if np.isclose(cb, 0):
a = 0.0
b = np.sign(sb) * np.pi / 2
sc = matrix[0, 1]
cc = matrix[1, 1]
c = np.sign(sb) * np.arctan2(sc, cc)
else:
b = np.arctan2(sb, cb)
sa = matrix[1, 0] / cb
ca = matrix[0, 0] / cb
a = np.arctan2(sa, ca)
sc = matrix[2, 1] / cb
cc = matrix[2, 2] / cb
c = np.arctan2(sc, cc)
vector = np.hstack((matrix[:-1, -1], [a, b, c]))
return vector
def wrap_2_pi(angle: float) -> float:
"""
Wrap given angle to +/- PI.
:param angle: angle to wrap
:return: wrapped angle
"""
# FIXME: remove float() cast when numpy is supported in mypy
result = float((angle + np.pi) % (2 * np.pi) - np.pi)
return result
def rotation_matrix_x(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the X axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]).reshape((4, 4))
| """Generate a basic 4x4 rotation matrix about the Y axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_z(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Z axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def translation_matrix(xyz: Sequence[float]) -> np.ndarray:
"""Generate a basic 4x4 translation matrix."""
# validate
if len(xyz) != 3:
raise PyboticsError("len(xyz) must be 3")
matrix = np.eye(4)
matrix[:-1, -1] = xyz
return matrix | return matrix
def rotation_matrix_y(angle: float) -> np.ndarray: | random_line_split |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER_XYZ = "xyz"
EULER_XZX = "xzx"
EULER_XZY = "xzy"
EULER_YXY = "yxy"
EULER_YXZ = "yxz"
EULER_YZX = "yzx"
EULER_YZY = "yzy"
EULER_ZXY = "zxy"
EULER_ZXZ = "zxz"
EULER_ZYX = "zyx"
EULER_ZYZ = "zyz"
FIXED_XYX = "xyx"
FIXED_XYZ = "zyx"
FIXED_XZX = "xzx"
FIXED_XZY = "yzx"
FIXED_YXY = "yxy"
FIXED_YXZ = "zxy"
FIXED_YZX = "xzy"
FIXED_YZY = "yzy"
FIXED_ZXY = "yxz"
FIXED_ZXZ = "zxz"
FIXED_ZYX = "xyz"
FIXED_ZYZ = "zyz"
def vector_2_matrix(
vector: Sequence[float],
convention: Union[OrientationConvention, str] = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""
Calculate the pose from the position and euler angles.
:param convention:
:param vector: transform vector
:return: 4x4 transform matrix
"""
# get individual variables
translation_component = vector[:3]
rotation_component = vector[-3:]
# validate and extract orientation info
if isinstance(convention, OrientationConvention):
convention = convention.value
try:
OrientationConvention(convention)
except ValueError as e:
raise PyboticsError(str(e))
# iterate through rotation order
# build rotation matrix
transform_matrix = np.eye(4)
for axis, value in zip(convention, rotation_component): # type: ignore
current_rotation = globals()[f"rotation_matrix_{axis}"](value)
transform_matrix = np.dot(transform_matrix, current_rotation)
# add translation component
transform_matrix[:-1, -1] = translation_component
return transform_matrix
def position_from_matrix(matrix: np.ndarray) -> np.ndarray:
"""Get the position values from a 4x4 transform matrix."""
return matrix[:-1, -1]
def matrix_2_vector(
matrix: np.ndarray,
convention: OrientationConvention = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""Convert 4x4 matrix to a vector."""
# call function
try:
return globals()[f"_matrix_2_{convention.name.lower()}"](matrix)
except KeyError: # pragma: no cover
raise NotImplementedError
def _matrix_2_euler_zyx(matrix: np.ndarray) -> np.ndarray:
"""
Calculate the equivalent position and euler angles of the given pose.
From: Craig, John J. Introduction to robotics: mechanics and control, 2005
:param matrix: 4x4 transform matrix
:return: transform vector
"""
# solution degenerates near ry = +/- 90deg
sb = -matrix[2, 0]
cb = np.sqrt(matrix[0, 0] ** 2 + matrix[1, 0] ** 2)
if np.isclose(cb, 0):
|
else:
b = np.arctan2(sb, cb)
sa = matrix[1, 0] / cb
ca = matrix[0, 0] / cb
a = np.arctan2(sa, ca)
sc = matrix[2, 1] / cb
cc = matrix[2, 2] / cb
c = np.arctan2(sc, cc)
vector = np.hstack((matrix[:-1, -1], [a, b, c]))
return vector
def wrap_2_pi(angle: float) -> float:
"""
Wrap given angle to +/- PI.
:param angle: angle to wrap
:return: wrapped angle
"""
# FIXME: remove float() cast when numpy is supported in mypy
result = float((angle + np.pi) % (2 * np.pi) - np.pi)
return result
def rotation_matrix_x(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the X axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_y(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Y axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_z(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Z axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def translation_matrix(xyz: Sequence[float]) -> np.ndarray:
"""Generate a basic 4x4 translation matrix."""
# validate
if len(xyz) != 3:
raise PyboticsError("len(xyz) must be 3")
matrix = np.eye(4)
matrix[:-1, -1] = xyz
return matrix
| a = 0.0
b = np.sign(sb) * np.pi / 2
sc = matrix[0, 1]
cc = matrix[1, 1]
c = np.sign(sb) * np.arctan2(sc, cc) | conditional_block |
geometry.py | """Geometry functions and utilities."""
from enum import Enum
from typing import Sequence, Union
import numpy as np # type: ignore
from pybotics.errors import PyboticsError
class OrientationConvention(Enum):
"""Orientation of a body with respect to a fixed coordinate system."""
EULER_XYX = "xyx"
EULER_XYZ = "xyz"
EULER_XZX = "xzx"
EULER_XZY = "xzy"
EULER_YXY = "yxy"
EULER_YXZ = "yxz"
EULER_YZX = "yzx"
EULER_YZY = "yzy"
EULER_ZXY = "zxy"
EULER_ZXZ = "zxz"
EULER_ZYX = "zyx"
EULER_ZYZ = "zyz"
FIXED_XYX = "xyx"
FIXED_XYZ = "zyx"
FIXED_XZX = "xzx"
FIXED_XZY = "yzx"
FIXED_YXY = "yxy"
FIXED_YXZ = "zxy"
FIXED_YZX = "xzy"
FIXED_YZY = "yzy"
FIXED_ZXY = "yxz"
FIXED_ZXZ = "zxz"
FIXED_ZYX = "xyz"
FIXED_ZYZ = "zyz"
def vector_2_matrix(
vector: Sequence[float],
convention: Union[OrientationConvention, str] = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""
Calculate the pose from the position and euler angles.
:param convention:
:param vector: transform vector
:return: 4x4 transform matrix
"""
# get individual variables
translation_component = vector[:3]
rotation_component = vector[-3:]
# validate and extract orientation info
if isinstance(convention, OrientationConvention):
convention = convention.value
try:
OrientationConvention(convention)
except ValueError as e:
raise PyboticsError(str(e))
# iterate through rotation order
# build rotation matrix
transform_matrix = np.eye(4)
for axis, value in zip(convention, rotation_component): # type: ignore
current_rotation = globals()[f"rotation_matrix_{axis}"](value)
transform_matrix = np.dot(transform_matrix, current_rotation)
# add translation component
transform_matrix[:-1, -1] = translation_component
return transform_matrix
def position_from_matrix(matrix: np.ndarray) -> np.ndarray:
"""Get the position values from a 4x4 transform matrix."""
return matrix[:-1, -1]
def matrix_2_vector(
matrix: np.ndarray,
convention: OrientationConvention = OrientationConvention.EULER_ZYX,
) -> np.ndarray:
"""Convert 4x4 matrix to a vector."""
# call function
try:
return globals()[f"_matrix_2_{convention.name.lower()}"](matrix)
except KeyError: # pragma: no cover
raise NotImplementedError
def _matrix_2_euler_zyx(matrix: np.ndarray) -> np.ndarray:
"""
Calculate the equivalent position and euler angles of the given pose.
From: Craig, John J. Introduction to robotics: mechanics and control, 2005
:param matrix: 4x4 transform matrix
:return: transform vector
"""
# solution degenerates near ry = +/- 90deg
sb = -matrix[2, 0]
cb = np.sqrt(matrix[0, 0] ** 2 + matrix[1, 0] ** 2)
if np.isclose(cb, 0):
a = 0.0
b = np.sign(sb) * np.pi / 2
sc = matrix[0, 1]
cc = matrix[1, 1]
c = np.sign(sb) * np.arctan2(sc, cc)
else:
b = np.arctan2(sb, cb)
sa = matrix[1, 0] / cb
ca = matrix[0, 0] / cb
a = np.arctan2(sa, ca)
sc = matrix[2, 1] / cb
cc = matrix[2, 2] / cb
c = np.arctan2(sc, cc)
vector = np.hstack((matrix[:-1, -1], [a, b, c]))
return vector
def wrap_2_pi(angle: float) -> float:
"""
Wrap given angle to +/- PI.
:param angle: angle to wrap
:return: wrapped angle
"""
# FIXME: remove float() cast when numpy is supported in mypy
result = float((angle + np.pi) % (2 * np.pi) - np.pi)
return result
def rotation_matrix_x(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the X axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([1, 0, 0, 0, 0, c, -s, 0, 0, s, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def rotation_matrix_y(angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Y axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, 0, s, 0, 0, 1, 0, 0, -s, 0, c, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def | (angle: float) -> np.ndarray:
"""Generate a basic 4x4 rotation matrix about the Z axis."""
s = np.sin(angle)
c = np.cos(angle)
matrix = np.array([c, -s, 0, 0, s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]).reshape((4, 4))
return matrix
def translation_matrix(xyz: Sequence[float]) -> np.ndarray:
"""Generate a basic 4x4 translation matrix."""
# validate
if len(xyz) != 3:
raise PyboticsError("len(xyz) must be 3")
matrix = np.eye(4)
matrix[:-1, -1] = xyz
return matrix
| rotation_matrix_z | identifier_name |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2-1)/2).expand()
assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
assert legendre(4, x) == ((35*x**4-30*x**2+3)/8).expand()
assert legendre(5, x) == ((63*x**5-70*x**3+15*x)/8).expand()
assert legendre(6, x) == ((231*x**6-315*x**4+105*x**2-5)/16).expand()
assert legendre(10, -1) == 1
assert legendre(11, -1) == -1
assert legendre(10, 1) == 1
assert legendre(11, 1) == 1
assert legendre(10, 0) != 0
assert legendre(11, 0) == 0
assert roots(legendre(4,x), x) == {
(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
}
def test_assoc_legendre():
Plm=assoc_legendre
Q=(1-x**2)**Rational(1,2)
assert Plm(0, 0, x) == 1
assert Plm(1, 0, x) == x
assert Plm(1, 1, x) == -Q
assert Plm(2, 0, x) == (3*x**2-1)/2
assert Plm(2, 1, x) == -3*x*Q
assert Plm(2, 2, x) == 3*Q**2
assert Plm(3, 0, x) == (5*x**3-3*x)/2
assert Plm(3, 1, x).expand() == (( 3*(1-5*x**2)/2 ).expand() * Q).expand()
assert Plm(3, 2, x) == 15*x * Q**2
assert Plm(3, 3, x) == -15 * Q**3
# negative m
assert Plm(1,-1, x) == -Plm(1, 1, x)/2
assert Plm(2,-2, x) == Plm(2, 2, x)/24
assert Plm(2,-1, x) == -Plm(2, 1, x)/6
assert Plm(3,-3, x) == -Plm(3, 3, x)/720
assert Plm(3,-2, x) == Plm(3, 2, x)/120
assert Plm(3,-1, x) == -Plm(3, 1, x)/12
def test_chebyshev():
assert chebyshevt(0, x) == 1 | assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2-1
assert chebyshevt(3, x) == 4*x**3-3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
for n in range(1, 4):
for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0
def test_hermite():
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert laguerre_l(3, alpha, x).expand() == (-x**3/6 + (alpha+3)*x**2/2 - (alpha+2)*(alpha+3)*x/2 + (alpha+1)*(alpha+2)*(alpha+3)/6).expand()
# Laguerre polynomials:
assert laguerre_l(0, 0, x) == 1
assert laguerre_l(1, 0, x) == 1 - x
assert laguerre_l(2, 0, x).expand() == 1 - 2*x + x**2/2
assert laguerre_l(3, 0, x).expand() == 1 - 3*x + 3*x**2/2 - x**3/6
# Test the lowest 10 polynomials with laguerre_poly, to make sure that it
# works:
for i in range(10):
assert laguerre_l(i, 0, x).expand() == laguerre_poly(i, x) | random_line_split | |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2-1)/2).expand()
assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
assert legendre(4, x) == ((35*x**4-30*x**2+3)/8).expand()
assert legendre(5, x) == ((63*x**5-70*x**3+15*x)/8).expand()
assert legendre(6, x) == ((231*x**6-315*x**4+105*x**2-5)/16).expand()
assert legendre(10, -1) == 1
assert legendre(11, -1) == -1
assert legendre(10, 1) == 1
assert legendre(11, 1) == 1
assert legendre(10, 0) != 0
assert legendre(11, 0) == 0
assert roots(legendre(4,x), x) == {
(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
}
def test_assoc_legendre():
Plm=assoc_legendre
Q=(1-x**2)**Rational(1,2)
assert Plm(0, 0, x) == 1
assert Plm(1, 0, x) == x
assert Plm(1, 1, x) == -Q
assert Plm(2, 0, x) == (3*x**2-1)/2
assert Plm(2, 1, x) == -3*x*Q
assert Plm(2, 2, x) == 3*Q**2
assert Plm(3, 0, x) == (5*x**3-3*x)/2
assert Plm(3, 1, x).expand() == (( 3*(1-5*x**2)/2 ).expand() * Q).expand()
assert Plm(3, 2, x) == 15*x * Q**2
assert Plm(3, 3, x) == -15 * Q**3
# negative m
assert Plm(1,-1, x) == -Plm(1, 1, x)/2
assert Plm(2,-2, x) == Plm(2, 2, x)/24
assert Plm(2,-1, x) == -Plm(2, 1, x)/6
assert Plm(3,-3, x) == -Plm(3, 3, x)/720
assert Plm(3,-2, x) == Plm(3, 2, x)/120
assert Plm(3,-1, x) == -Plm(3, 1, x)/12
def test_chebyshev():
assert chebyshevt(0, x) == 1
assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2-1
assert chebyshevt(3, x) == 4*x**3-3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
for n in range(1, 4):
for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0
def test_hermite():
|
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert laguerre_l(3, alpha, x).expand() == (-x**3/6 + (alpha+3)*x**2/2 - (alpha+2)*(alpha+3)*x/2 + (alpha+1)*(alpha+2)*(alpha+3)/6).expand()
# Laguerre polynomials:
assert laguerre_l(0, 0, x) == 1
assert laguerre_l(1, 0, x) == 1 - x
assert laguerre_l(2, 0, x).expand() == 1 - 2*x + x**2/2
assert laguerre_l(3, 0, x).expand() == 1 - 3*x + 3*x**2/2 - x**3/6
# Test the lowest 10 polynomials with laguerre_poly, to make sure that it
# works:
for i in range(10):
assert laguerre_l(i, 0, x).expand() == laguerre_poly(i, x)
| assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120 | identifier_body |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2-1)/2).expand()
assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
assert legendre(4, x) == ((35*x**4-30*x**2+3)/8).expand()
assert legendre(5, x) == ((63*x**5-70*x**3+15*x)/8).expand()
assert legendre(6, x) == ((231*x**6-315*x**4+105*x**2-5)/16).expand()
assert legendre(10, -1) == 1
assert legendre(11, -1) == -1
assert legendre(10, 1) == 1
assert legendre(11, 1) == 1
assert legendre(10, 0) != 0
assert legendre(11, 0) == 0
assert roots(legendre(4,x), x) == {
(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
}
def test_assoc_legendre():
Plm=assoc_legendre
Q=(1-x**2)**Rational(1,2)
assert Plm(0, 0, x) == 1
assert Plm(1, 0, x) == x
assert Plm(1, 1, x) == -Q
assert Plm(2, 0, x) == (3*x**2-1)/2
assert Plm(2, 1, x) == -3*x*Q
assert Plm(2, 2, x) == 3*Q**2
assert Plm(3, 0, x) == (5*x**3-3*x)/2
assert Plm(3, 1, x).expand() == (( 3*(1-5*x**2)/2 ).expand() * Q).expand()
assert Plm(3, 2, x) == 15*x * Q**2
assert Plm(3, 3, x) == -15 * Q**3
# negative m
assert Plm(1,-1, x) == -Plm(1, 1, x)/2
assert Plm(2,-2, x) == Plm(2, 2, x)/24
assert Plm(2,-1, x) == -Plm(2, 1, x)/6
assert Plm(3,-3, x) == -Plm(3, 3, x)/720
assert Plm(3,-2, x) == Plm(3, 2, x)/120
assert Plm(3,-1, x) == -Plm(3, 1, x)/12
def test_chebyshev():
assert chebyshevt(0, x) == 1
assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2-1
assert chebyshevt(3, x) == 4*x**3-3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
for n in range(1, 4):
|
def test_hermite():
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert laguerre_l(3, alpha, x).expand() == (-x**3/6 + (alpha+3)*x**2/2 - (alpha+2)*(alpha+3)*x/2 + (alpha+1)*(alpha+2)*(alpha+3)/6).expand()
# Laguerre polynomials:
assert laguerre_l(0, 0, x) == 1
assert laguerre_l(1, 0, x) == 1 - x
assert laguerre_l(2, 0, x).expand() == 1 - 2*x + x**2/2
assert laguerre_l(3, 0, x).expand() == 1 - 3*x + 3*x**2/2 - x**3/6
# Test the lowest 10 polynomials with laguerre_poly, to make sure that it
# works:
for i in range(10):
assert laguerre_l(i, 0, x).expand() == laguerre_poly(i, x)
| for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0 | conditional_block |
test_spec_polynomials.py | from sympy import (legendre, Symbol, hermite, chebyshevu, chebyshevt,
chebyshevt_root, chebyshevu_root, assoc_legendre, Rational,
roots, sympify, S, laguerre_l, laguerre_poly)
x = Symbol('x')
def test_legendre():
assert legendre(0, x) == 1
assert legendre(1, x) == x
assert legendre(2, x) == ((3*x**2-1)/2).expand()
assert legendre(3, x) == ((5*x**3-3*x)/2).expand()
assert legendre(4, x) == ((35*x**4-30*x**2+3)/8).expand()
assert legendre(5, x) == ((63*x**5-70*x**3+15*x)/8).expand()
assert legendre(6, x) == ((231*x**6-315*x**4+105*x**2-5)/16).expand()
assert legendre(10, -1) == 1
assert legendre(11, -1) == -1
assert legendre(10, 1) == 1
assert legendre(11, 1) == 1
assert legendre(10, 0) != 0
assert legendre(11, 0) == 0
assert roots(legendre(4,x), x) == {
(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) - Rational(2, 35)*30**S.Half)**S.Half: 1,
(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
-(Rational(3, 7) + Rational(2, 35)*30**S.Half)**S.Half: 1,
}
def test_assoc_legendre():
Plm=assoc_legendre
Q=(1-x**2)**Rational(1,2)
assert Plm(0, 0, x) == 1
assert Plm(1, 0, x) == x
assert Plm(1, 1, x) == -Q
assert Plm(2, 0, x) == (3*x**2-1)/2
assert Plm(2, 1, x) == -3*x*Q
assert Plm(2, 2, x) == 3*Q**2
assert Plm(3, 0, x) == (5*x**3-3*x)/2
assert Plm(3, 1, x).expand() == (( 3*(1-5*x**2)/2 ).expand() * Q).expand()
assert Plm(3, 2, x) == 15*x * Q**2
assert Plm(3, 3, x) == -15 * Q**3
# negative m
assert Plm(1,-1, x) == -Plm(1, 1, x)/2
assert Plm(2,-2, x) == Plm(2, 2, x)/24
assert Plm(2,-1, x) == -Plm(2, 1, x)/6
assert Plm(3,-3, x) == -Plm(3, 3, x)/720
assert Plm(3,-2, x) == Plm(3, 2, x)/120
assert Plm(3,-1, x) == -Plm(3, 1, x)/12
def test_chebyshev():
assert chebyshevt(0, x) == 1
assert chebyshevt(1, x) == x
assert chebyshevt(2, x) == 2*x**2-1
assert chebyshevt(3, x) == 4*x**3-3*x
for n in range(1, 4):
for k in range(n):
z = chebyshevt_root(n, k)
assert chebyshevt(n, z) == 0
for n in range(1, 4):
for k in range(n):
z = chebyshevu_root(n, k)
assert chebyshevu(n, z) == 0
def | ():
assert hermite(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120
def test_laguerre():
alpha = Symbol("alpha")
# generalized Laguerre polynomials:
assert laguerre_l(0, alpha, x) == 1
assert laguerre_l(1, alpha, x) == -x + alpha + 1
assert laguerre_l(2, alpha, x).expand() == (x**2/2 - (alpha+2)*x + (alpha+2)*(alpha+1)/2).expand()
assert laguerre_l(3, alpha, x).expand() == (-x**3/6 + (alpha+3)*x**2/2 - (alpha+2)*(alpha+3)*x/2 + (alpha+1)*(alpha+2)*(alpha+3)/6).expand()
# Laguerre polynomials:
assert laguerre_l(0, 0, x) == 1
assert laguerre_l(1, 0, x) == 1 - x
assert laguerre_l(2, 0, x).expand() == 1 - 2*x + x**2/2
assert laguerre_l(3, 0, x).expand() == 1 - 3*x + 3*x**2/2 - x**3/6
# Test the lowest 10 polynomials with laguerre_poly, to make sure that it
# works:
for i in range(10):
assert laguerre_l(i, 0, x).expand() == laguerre_poly(i, x)
| test_hermite | identifier_name |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lines([
'logto',
], Section(), assert_in=False)
assert_lines([
'enable-threads = true',
'uid = www-data',
'gid = www-data',
'logto = /a/b.log',
], Section(threads=True, log_into='/a/b.log').configure_owner())
assert_lines([
'workers = 13',
'touch-reload', 'test_nice.py',
], Section(workers=13, touch_reload=__file__))
assert_lines([
'disable-write-exception = true',
'ignore-write-errors = true',
'ignore-sigpipe = true',
'log-master = true',
'threaded-logger = true',
], Section(log_dedicated=True, ignore_write_errors=True))
assert '%(headers) headers in %(hsize) bytes' in Section().get_log_format_default()
def test_get_bundled_static_path(assert_lines):
path = Section.get_bundled_static_path('503.html')
assert path.endswith('uwsgiconf/contrib/django/uwsgify/static/uwsgify/503.html')
def test_configure_https_redirect(assert_lines):
section = Section()
section.configure_https_redirect()
assert_lines(
'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
section
)
def test_configure_maintenance_mode(assert_lines, tmpdir):
section = Section()
section.configure_maintenance_mode('/watch/that/file', '/serve/this/file')
section.configure_maintenance_mode('/watch/that/file/also', 'http://pythonz.net')
assert_lines([
'route-if = exists:/watch/that/file static:/serve/this/file',
'route-if = exists:/watch/that/file/also redirect-302:http://pythonz.net',
], section)
afile = tmpdir.join('maintenance_file')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
], section)
assert_lines([
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section, assert_in=False)
# Create file
afile.write('')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
'env = UWSGICONF_MAINTENANCE_INPLACE=1',
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section)
assert environ['UWSGICONF_MAINTENANCE'] == f'{afile}'
assert environ['UWSGICONF_MAINTENANCE_INPLACE'] == '1'
section.configure_maintenance_mode(f'{afile}', 'app::mypack.here.there:myfunc')
assert_lines([
'wsgi = mypack.here.there:myfunc',
], section)
def test_configure_logging_json(assert_lines):
section = Section()
section.configure_logging_json()
assert_lines([
'logger-req = stdio:',
'log-format = %(method) %(uri) -> %(status)',
'log-req-encoder = json {"dt": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S%%z}", "src": "uwsgi.req"',
'log-req-encoder = nl',
'"src": "uwsgi.out"',
], section)
def test_configure_certbot_https(assert_lines, monkeypatch):
monkeypatch.setattr('pathlib.Path.exists', lambda self: True)
section = Section()
section.configure_certbot_https('mydomain.org', '/var/www/', address=':4443')
assert_lines([
'static-map2 = /.well-known/=/var/www/',
'https-socket = :4443,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem',
], section)
section = Section.bootstrap(['http://:80'])
section.configure_certbot_https('mydomain.org', '/var/www/', http_redirect=True)
assert_lines([
'shared-socket = :80',
'shared-socket = :443',
'http-socket = =0',
'https-socket = =1,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem', | def test_nice_python(assert_lines):
assert_lines([
'plugin = python',
'pyhome = /home/idle/venv/\npythonpath = /home/idle/apps/',
'wsgi = somepackage.module',
'need-app = true',
], PythonSection(
params_python=dict(
# We'll run our app using virtualenv.
python_home='/home/idle/venv/',
search_path='/home/idle/apps/',
),
wsgi_module='somepackage.module',
embedded_plugins=None
))
# Embedded plugins = True
assert_lines('plugin = python', PythonSection(wsgi_module='somepackage.module'), assert_in=False) | 'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
], section)
| random_line_split |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lines([
'logto',
], Section(), assert_in=False)
assert_lines([
'enable-threads = true',
'uid = www-data',
'gid = www-data',
'logto = /a/b.log',
], Section(threads=True, log_into='/a/b.log').configure_owner())
assert_lines([
'workers = 13',
'touch-reload', 'test_nice.py',
], Section(workers=13, touch_reload=__file__))
assert_lines([
'disable-write-exception = true',
'ignore-write-errors = true',
'ignore-sigpipe = true',
'log-master = true',
'threaded-logger = true',
], Section(log_dedicated=True, ignore_write_errors=True))
assert '%(headers) headers in %(hsize) bytes' in Section().get_log_format_default()
def | (assert_lines):
path = Section.get_bundled_static_path('503.html')
assert path.endswith('uwsgiconf/contrib/django/uwsgify/static/uwsgify/503.html')
def test_configure_https_redirect(assert_lines):
section = Section()
section.configure_https_redirect()
assert_lines(
'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
section
)
def test_configure_maintenance_mode(assert_lines, tmpdir):
section = Section()
section.configure_maintenance_mode('/watch/that/file', '/serve/this/file')
section.configure_maintenance_mode('/watch/that/file/also', 'http://pythonz.net')
assert_lines([
'route-if = exists:/watch/that/file static:/serve/this/file',
'route-if = exists:/watch/that/file/also redirect-302:http://pythonz.net',
], section)
afile = tmpdir.join('maintenance_file')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
], section)
assert_lines([
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section, assert_in=False)
# Create file
afile.write('')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
'env = UWSGICONF_MAINTENANCE_INPLACE=1',
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section)
assert environ['UWSGICONF_MAINTENANCE'] == f'{afile}'
assert environ['UWSGICONF_MAINTENANCE_INPLACE'] == '1'
section.configure_maintenance_mode(f'{afile}', 'app::mypack.here.there:myfunc')
assert_lines([
'wsgi = mypack.here.there:myfunc',
], section)
def test_configure_logging_json(assert_lines):
section = Section()
section.configure_logging_json()
assert_lines([
'logger-req = stdio:',
'log-format = %(method) %(uri) -> %(status)',
'log-req-encoder = json {"dt": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S%%z}", "src": "uwsgi.req"',
'log-req-encoder = nl',
'"src": "uwsgi.out"',
], section)
def test_configure_certbot_https(assert_lines, monkeypatch):
monkeypatch.setattr('pathlib.Path.exists', lambda self: True)
section = Section()
section.configure_certbot_https('mydomain.org', '/var/www/', address=':4443')
assert_lines([
'static-map2 = /.well-known/=/var/www/',
'https-socket = :4443,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem',
], section)
section = Section.bootstrap(['http://:80'])
section.configure_certbot_https('mydomain.org', '/var/www/', http_redirect=True)
assert_lines([
'shared-socket = :80',
'shared-socket = :443',
'http-socket = =0',
'https-socket = =1,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem',
'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
], section)
def test_nice_python(assert_lines):
assert_lines([
'plugin = python',
'pyhome = /home/idle/venv/\npythonpath = /home/idle/apps/',
'wsgi = somepackage.module',
'need-app = true',
], PythonSection(
params_python=dict(
# We'll run our app using virtualenv.
python_home='/home/idle/venv/',
search_path='/home/idle/apps/',
),
wsgi_module='somepackage.module',
embedded_plugins=None
))
# Embedded plugins = True
assert_lines('plugin = python', PythonSection(wsgi_module='somepackage.module'), assert_in=False)
| test_get_bundled_static_path | identifier_name |
test_nice.py | from os import environ
from uwsgiconf.presets.nice import Section, PythonSection
def test_nice_section(assert_lines):
assert_lines([
'env = LANG=en_US.UTF-8',
'workers = %k',
'die-on-term = true',
'vacuum = true',
'threads = 4',
], Section(threads=4))
assert_lines([
'logto',
], Section(), assert_in=False)
assert_lines([
'enable-threads = true',
'uid = www-data',
'gid = www-data',
'logto = /a/b.log',
], Section(threads=True, log_into='/a/b.log').configure_owner())
assert_lines([
'workers = 13',
'touch-reload', 'test_nice.py',
], Section(workers=13, touch_reload=__file__))
assert_lines([
'disable-write-exception = true',
'ignore-write-errors = true',
'ignore-sigpipe = true',
'log-master = true',
'threaded-logger = true',
], Section(log_dedicated=True, ignore_write_errors=True))
assert '%(headers) headers in %(hsize) bytes' in Section().get_log_format_default()
def test_get_bundled_static_path(assert_lines):
path = Section.get_bundled_static_path('503.html')
assert path.endswith('uwsgiconf/contrib/django/uwsgify/static/uwsgify/503.html')
def test_configure_https_redirect(assert_lines):
section = Section()
section.configure_https_redirect()
assert_lines(
'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
section
)
def test_configure_maintenance_mode(assert_lines, tmpdir):
section = Section()
section.configure_maintenance_mode('/watch/that/file', '/serve/this/file')
section.configure_maintenance_mode('/watch/that/file/also', 'http://pythonz.net')
assert_lines([
'route-if = exists:/watch/that/file static:/serve/this/file',
'route-if = exists:/watch/that/file/also redirect-302:http://pythonz.net',
], section)
afile = tmpdir.join('maintenance_file')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
], section)
assert_lines([
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section, assert_in=False)
# Create file
afile.write('')
section = Section()
section.configure_maintenance_mode(f'{afile}', 'app')
assert_lines([
f'env = UWSGICONF_MAINTENANCE={afile}',
f'touch-reload = {afile}',
'env = UWSGICONF_MAINTENANCE_INPLACE=1',
'wsgi = uwsgiconf.maintenance:app_maintenance',
], section)
assert environ['UWSGICONF_MAINTENANCE'] == f'{afile}'
assert environ['UWSGICONF_MAINTENANCE_INPLACE'] == '1'
section.configure_maintenance_mode(f'{afile}', 'app::mypack.here.there:myfunc')
assert_lines([
'wsgi = mypack.here.there:myfunc',
], section)
def test_configure_logging_json(assert_lines):
section = Section()
section.configure_logging_json()
assert_lines([
'logger-req = stdio:',
'log-format = %(method) %(uri) -> %(status)',
'log-req-encoder = json {"dt": "${strftime:%%Y-%%m-%%dT%%H:%%M:%%S%%z}", "src": "uwsgi.req"',
'log-req-encoder = nl',
'"src": "uwsgi.out"',
], section)
def test_configure_certbot_https(assert_lines, monkeypatch):
|
def test_nice_python(assert_lines):
assert_lines([
'plugin = python',
'pyhome = /home/idle/venv/\npythonpath = /home/idle/apps/',
'wsgi = somepackage.module',
'need-app = true',
], PythonSection(
params_python=dict(
# We'll run our app using virtualenv.
python_home='/home/idle/venv/',
search_path='/home/idle/apps/',
),
wsgi_module='somepackage.module',
embedded_plugins=None
))
# Embedded plugins = True
assert_lines('plugin = python', PythonSection(wsgi_module='somepackage.module'), assert_in=False)
| monkeypatch.setattr('pathlib.Path.exists', lambda self: True)
section = Section()
section.configure_certbot_https('mydomain.org', '/var/www/', address=':4443')
assert_lines([
'static-map2 = /.well-known/=/var/www/',
'https-socket = :4443,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem',
], section)
section = Section.bootstrap(['http://:80'])
section.configure_certbot_https('mydomain.org', '/var/www/', http_redirect=True)
assert_lines([
'shared-socket = :80',
'shared-socket = :443',
'http-socket = =0',
'https-socket = =1,/etc/letsencrypt/live/mydomain.org/fullchain.pem,'
'/etc/letsencrypt/live/mydomain.org/privkey.pem',
'route-if-not = eq:${HTTPS};on redirect-301:https://${HTTP_HOST}${REQUEST_URI}',
], section) | identifier_body |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn | () {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
}
| main | identifier_name |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() | {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
} | identifier_body | |
billow.rs | // example.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::billow::Billow;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() {
let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0);
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
| let n = ngen.get_value2d((x as f64), (y as f64));
let col = (n * 255.0) as u8;
let pixel = image::Luma(col);
imbuf.put_pixel(x, y, pixel);
}
}
let end = precise_time_s();
let fout = File::create(&Path::new("billow.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("billow.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
} | let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
| random_line_split |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store'; |
export function requestStateReducer(
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.shape |
typeof actions.requestFailure.shape |
typeof actions.clearErrors.shape
): RequestState {
switch (action.type) {
case actions.startRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: true
}
};
}
case actions.endRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: undefined
}
};
}
case actions.requestFailure.type: {
const { actionType, error } = action.payload;
return {
...state,
requesting: {
...state.requesting,
[actionType]: undefined
},
errors: {
...state.errors,
[actionType]: error
}
};
}
case actions.clearErrors.type: {
return {
...state,
errors: {}
};
}
default:
return state;
}
} | import { INITIAL_STATE } from './initialState'; | random_line_split |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store';
import { INITIAL_STATE } from './initialState';
export function requestStateReducer(
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.shape |
typeof actions.requestFailure.shape |
typeof actions.clearErrors.shape
): RequestState | {
switch (action.type) {
case actions.startRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: true
}
};
}
case actions.endRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: undefined
}
};
}
case actions.requestFailure.type: {
const { actionType, error } = action.payload;
return {
...state,
requesting: {
...state.requesting,
[actionType]: undefined
},
errors: {
...state.errors,
[actionType]: error
}
};
}
case actions.clearErrors.type: {
return {
...state,
errors: {}
};
}
default:
return state;
}
} | identifier_body | |
requestState.ts | import * as actions from 'src/actions/requestState';
import { RequestState } from 'src/store';
import { INITIAL_STATE } from './initialState';
export function | (
state: RequestState = INITIAL_STATE.requestState,
action:
typeof actions.startRequesting.shape |
typeof actions.endRequesting.shape |
typeof actions.requestFailure.shape |
typeof actions.clearErrors.shape
): RequestState {
switch (action.type) {
case actions.startRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: true
}
};
}
case actions.endRequesting.type: {
return {
...state,
requesting: {
...state.requesting,
[action.payload]: undefined
}
};
}
case actions.requestFailure.type: {
const { actionType, error } = action.payload;
return {
...state,
requesting: {
...state.requesting,
[actionType]: undefined
},
errors: {
...state.errors,
[actionType]: error
}
};
}
case actions.clearErrors.type: {
return {
...state,
errors: {}
};
}
default:
return state;
}
}
| requestStateReducer | identifier_name |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform methods
*/
@Pipe({ name: 'stringFormat' })
export class StringFormatPipe implements PipeTransform {
public transform(value: any, method: string, ...args: Array<any>): string |
}
| {
switch (method) {
case 'camelCase':
return camelCase(value);
case 'capitalize':
return capitalize(value);
case 'deburr':
return deburr(value);
case 'escape':
return escape(value);
case 'escapeRegExp':
return escapeRegExp(value);
case 'kebabCase':
return kebabCase(value);
case 'lowerCase':
return lowerCase(value);
case 'lowerFirst':
return lowerFirst(value);
case 'pad':
return (<any> pad)(value, ...args);
case 'padEnd':
return (<any> padEnd)(value, ...args);
case 'padStart':
return (<any> padStart)(value, ...args);
case 'snakeCase':
return snakeCase(value);
case 'startCase':
return startCase(value);
case 'truncate':
return (<any> truncate)(value, ...args);
case 'unescape':
return unescape(value);
case 'upperCase':
return upperCase(value);
case 'upperFirst':
return upperFirst(value);
default:
return value;
}
} | identifier_body |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform methods
*/
@Pipe({ name: 'stringFormat' })
export class StringFormatPipe implements PipeTransform {
public | (value: any, method: string, ...args: Array<any>): string {
switch (method) {
case 'camelCase':
return camelCase(value);
case 'capitalize':
return capitalize(value);
case 'deburr':
return deburr(value);
case 'escape':
return escape(value);
case 'escapeRegExp':
return escapeRegExp(value);
case 'kebabCase':
return kebabCase(value);
case 'lowerCase':
return lowerCase(value);
case 'lowerFirst':
return lowerFirst(value);
case 'pad':
return (<any> pad)(value, ...args);
case 'padEnd':
return (<any> padEnd)(value, ...args);
case 'padStart':
return (<any> padStart)(value, ...args);
case 'snakeCase':
return snakeCase(value);
case 'startCase':
return startCase(value);
case 'truncate':
return (<any> truncate)(value, ...args);
case 'unescape':
return unescape(value);
case 'upperCase':
return upperCase(value);
case 'upperFirst':
return upperFirst(value);
default:
return value;
}
}
}
| transform | identifier_name |
stringFormat.ts | import {
camelCase, capitalize, deburr, escape, escapeRegExp, kebabCase, lowerCase, lowerFirst, pad, padEnd, padStart,
snakeCase, startCase, truncate, unescape, upperCase, upperFirst
} from 'lodash';
import { Pipe, PipeTransform } from '@angular/core';
/**
* String format pipe, uses lodash string transform methods
*/
@Pipe({ name: 'stringFormat' })
export class StringFormatPipe implements PipeTransform {
public transform(value: any, method: string, ...args: Array<any>): string {
switch (method) {
case 'camelCase':
return camelCase(value);
case 'capitalize':
return capitalize(value);
case 'deburr':
return deburr(value);
case 'escape':
return escape(value);
case 'escapeRegExp':
return escapeRegExp(value);
case 'kebabCase':
return kebabCase(value);
case 'lowerCase':
return lowerCase(value);
case 'lowerFirst':
return lowerFirst(value);
case 'pad':
return (<any> pad)(value, ...args);
case 'padEnd':
return (<any> padEnd)(value, ...args);
case 'padStart':
return (<any> padStart)(value, ...args);
case 'snakeCase':
return snakeCase(value);
case 'startCase':
return startCase(value);
case 'truncate':
return (<any> truncate)(value, ...args);
case 'unescape':
return unescape(value);
case 'upperCase':
return upperCase(value);
case 'upperFirst':
return upperFirst(value);
default:
return value;
}
} | } | random_line_split | |
live_timers.rs | use std::collections::HashMap;
use platform::time::time_now;
use super::StartTime;
use super::Timing;
#[derive(Debug, Clone, PartialEq)]
pub struct LiveTimers {
timers: HashMap<String, StartTime>,
} |
impl LiveTimers {
pub fn new() -> LiveTimers {
LiveTimers { timers: HashMap::new() }
}
pub fn get_timers(&self) -> &HashMap<String, StartTime> {
&self.timers
}
pub fn start(&mut self, name: &str) -> StartTime {
let start_time = time_now();
self.timers.insert(name.to_string(), start_time.clone());
start_time
}
pub fn stop(&mut self, name: &str) -> Timing {
let stop_time = time_now();
let opt = self.timers.remove(name);
if opt.is_none() {
panic!("Tried to stop non-live timer: {:?}", name);
}
let start_time = opt.unwrap();
let duration = stop_time - start_time;
Timing::new(name, start_time, duration)
}
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.