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 |
---|---|---|---|---|
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleObject, JSContext, JSObject, Heap};
use std::default::Default;
/// Create the reflector for a new DOM object and yield ownership to the
/// reflector.
pub fn reflect_dom_object<T, U>(
obj: Box<T>,
global: &U,
wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>)
-> DomRoot<T>
where T: DomObject, U: DerivedFrom<GlobalScope>
{
let global_scope = global.upcast();
unsafe {
wrap_fn(global_scope.get_cx(), global_scope, obj)
}
}
/// A struct to store a reference to the reflector of a DOM object.
#[allow(unrooted_must_root)]
#[derive(MallocSizeOf)]
#[must_root]
// If you're renaming or moving this field, update the path in plugins::reflector as well
pub struct Reflector {
#[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
object: Heap<*mut JSObject>,
}
#[allow(unrooted_must_root)]
impl PartialEq for Reflector {
fn eq(&self, other: &Reflector) -> bool {
self.object.get() == other.object.get()
}
}
impl Reflector {
/// Get the reflector.
#[inline]
pub fn get_jsobject(&self) -> HandleObject {
// We're rooted, so it's safe to hand out a handle to object in Heap
unsafe { self.object.handle() }
}
/// Initialize the reflector. (May be called only once.)
pub fn set_jsobject(&mut self, object: *mut JSObject) {
assert!(self.object.get().is_null());
assert!(!object.is_null());
self.object.set(object);
}
/// Return a pointer to the memory location at which the JS reflector
/// object is stored. Used to root the reflector, as
/// required by the JSAPI rooting APIs.
pub fn rootable(&self) -> &Heap<*mut JSObject> {
&self.object
}
/// Create an uninitialized `Reflector`.
pub fn new() -> Reflector {
Reflector {
object: Heap::default(),
}
}
}
/// A trait to provide access to the `Reflector` for a DOM object.
pub trait DomObject: 'static {
/// Returns the receiver's reflector.
fn reflector(&self) -> &Reflector;
/// Returns the global scope of the realm that the DomObject was created in.
fn global(&self) -> DomRoot<GlobalScope> where Self: Sized {
GlobalScope::from_reflector(self)
}
} |
impl DomObject for Reflector {
fn reflector(&self) -> &Self {
self
}
}
/// A trait to initialize the `Reflector` for a DOM object.
pub trait MutDomObject: DomObject {
/// Initializes the Reflector
fn init_reflector(&mut self, obj: *mut JSObject);
}
impl MutDomObject for Reflector {
fn init_reflector(&mut self, obj: *mut JSObject) {
self.set_jsobject(obj)
}
} | random_line_split |
|
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleObject, JSContext, JSObject, Heap};
use std::default::Default;
/// Create the reflector for a new DOM object and yield ownership to the
/// reflector.
pub fn reflect_dom_object<T, U>(
obj: Box<T>,
global: &U,
wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>)
-> DomRoot<T>
where T: DomObject, U: DerivedFrom<GlobalScope>
{
let global_scope = global.upcast();
unsafe {
wrap_fn(global_scope.get_cx(), global_scope, obj)
}
}
/// A struct to store a reference to the reflector of a DOM object.
#[allow(unrooted_must_root)]
#[derive(MallocSizeOf)]
#[must_root]
// If you're renaming or moving this field, update the path in plugins::reflector as well
pub struct Reflector {
#[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
object: Heap<*mut JSObject>,
}
#[allow(unrooted_must_root)]
impl PartialEq for Reflector {
fn eq(&self, other: &Reflector) -> bool {
self.object.get() == other.object.get()
}
}
impl Reflector {
/// Get the reflector.
#[inline]
pub fn | (&self) -> HandleObject {
// We're rooted, so it's safe to hand out a handle to object in Heap
unsafe { self.object.handle() }
}
/// Initialize the reflector. (May be called only once.)
pub fn set_jsobject(&mut self, object: *mut JSObject) {
assert!(self.object.get().is_null());
assert!(!object.is_null());
self.object.set(object);
}
/// Return a pointer to the memory location at which the JS reflector
/// object is stored. Used to root the reflector, as
/// required by the JSAPI rooting APIs.
pub fn rootable(&self) -> &Heap<*mut JSObject> {
&self.object
}
/// Create an uninitialized `Reflector`.
pub fn new() -> Reflector {
Reflector {
object: Heap::default(),
}
}
}
/// A trait to provide access to the `Reflector` for a DOM object.
pub trait DomObject: 'static {
/// Returns the receiver's reflector.
fn reflector(&self) -> &Reflector;
/// Returns the global scope of the realm that the DomObject was created in.
fn global(&self) -> DomRoot<GlobalScope> where Self: Sized {
GlobalScope::from_reflector(self)
}
}
impl DomObject for Reflector {
fn reflector(&self) -> &Self {
self
}
}
/// A trait to initialize the `Reflector` for a DOM object.
pub trait MutDomObject: DomObject {
/// Initializes the Reflector
fn init_reflector(&mut self, obj: *mut JSObject);
}
impl MutDomObject for Reflector {
fn init_reflector(&mut self, obj: *mut JSObject) {
self.set_jsobject(obj)
}
}
| get_jsobject | identifier_name |
reflector.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! The `Reflector` struct.
use dom::bindings::conversions::DerivedFrom;
use dom::bindings::root::DomRoot;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleObject, JSContext, JSObject, Heap};
use std::default::Default;
/// Create the reflector for a new DOM object and yield ownership to the
/// reflector.
pub fn reflect_dom_object<T, U>(
obj: Box<T>,
global: &U,
wrap_fn: unsafe fn(*mut JSContext, &GlobalScope, Box<T>) -> DomRoot<T>)
-> DomRoot<T>
where T: DomObject, U: DerivedFrom<GlobalScope>
{
let global_scope = global.upcast();
unsafe {
wrap_fn(global_scope.get_cx(), global_scope, obj)
}
}
/// A struct to store a reference to the reflector of a DOM object.
#[allow(unrooted_must_root)]
#[derive(MallocSizeOf)]
#[must_root]
// If you're renaming or moving this field, update the path in plugins::reflector as well
pub struct Reflector {
#[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
object: Heap<*mut JSObject>,
}
#[allow(unrooted_must_root)]
impl PartialEq for Reflector {
fn eq(&self, other: &Reflector) -> bool {
self.object.get() == other.object.get()
}
}
impl Reflector {
/// Get the reflector.
#[inline]
pub fn get_jsobject(&self) -> HandleObject {
// We're rooted, so it's safe to hand out a handle to object in Heap
unsafe { self.object.handle() }
}
/// Initialize the reflector. (May be called only once.)
pub fn set_jsobject(&mut self, object: *mut JSObject) {
assert!(self.object.get().is_null());
assert!(!object.is_null());
self.object.set(object);
}
/// Return a pointer to the memory location at which the JS reflector
/// object is stored. Used to root the reflector, as
/// required by the JSAPI rooting APIs.
pub fn rootable(&self) -> &Heap<*mut JSObject> {
&self.object
}
/// Create an uninitialized `Reflector`.
pub fn new() -> Reflector {
Reflector {
object: Heap::default(),
}
}
}
/// A trait to provide access to the `Reflector` for a DOM object.
pub trait DomObject: 'static {
/// Returns the receiver's reflector.
fn reflector(&self) -> &Reflector;
/// Returns the global scope of the realm that the DomObject was created in.
fn global(&self) -> DomRoot<GlobalScope> where Self: Sized {
GlobalScope::from_reflector(self)
}
}
impl DomObject for Reflector {
fn reflector(&self) -> &Self {
self
}
}
/// A trait to initialize the `Reflector` for a DOM object.
pub trait MutDomObject: DomObject {
/// Initializes the Reflector
fn init_reflector(&mut self, obj: *mut JSObject);
}
impl MutDomObject for Reflector {
fn init_reflector(&mut self, obj: *mut JSObject) |
}
| {
self.set_jsobject(obj)
} | identifier_body |
app.js | angular.module('app', [ 'ngRoute', 'ui.select' ])
// Routes
.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/:steamId/trade-offers', {
templateUrl: 'trade-offers.html',
controller: 'TradeOffersController'
| templateUrl: 'trade-offer.html',
controller: 'TradeOfferController'
})
.when('/trade-offer-status', {
templateUrl: 'trade-offer-status.html',
controller: 'TradeOfferStatusController'
})
.otherwise({
redirectTo: '/'
});
})
// Controllers
.controller('HomeController', function($scope, $http) {
$http.get('/accounts').then(function(res) {
$scope.accounts = res.data;
});
})
.controller('TradeOffersController', function($scope, $http, $route) {
$scope.steamId = $route.current.params.steamId;
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId)).then(function(res) {
$scope.data = res.data;
});
})
.controller('TradeOfferController', function($scope, $http, $route) {
$scope.steamId = $route.current.params.steamId;
$scope.tradeOfferId = $route.current.params.tradeOfferId;
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId).replace(':tradeOfferId', $route.current.params.tradeOfferId)).then(function(res) {
$scope.offer = res.data.response.offer;
});
$scope.cancel = function() {
$http.get($route.current.originalPath.replace(':steamId', $route.current.params.steamId).replace(':tradeOfferId', $route.current.params.tradeOfferId) + '/cancel').then(function(res) {
$scope.cancelled = res.completed;
});
};
})
.controller('TradeOfferStatusController', function($scope, $http) {
$http.get('/accounts').then(function(res) {
$scope.accounts = [];
for (var account in res.data) {
$scope.accounts.push(res.data[account]);
}
});
$scope.steam64id = {};
$scope.generateEndpoint = function() {
$scope.endpoint = 'http://api.steampowered.com/IEconService/GetTradeOffer/v1?tradeofferid=' + $scope.tradeofferid + '&key=' + $scope.steam64id.selected.apiKey;
};
}); | })
.when('/:steamId/trade-offer/:tradeOfferId', {
| random_line_split |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
name: string;
safename: string;
options: Options;
projectFiles: boolean;
parameters: string[];
systemDirectory: string;
constructor(options: Options) {
super();
this.options = options;
this.width = 640;
this.height = 480;
this.sources = [];
this.libraries = [];
this.addSourceDirectory(path.join(options.kha, 'Sources'));
this.projectFiles = !options.noproject;
this.parameters = [];
// this.parameters = ['--macro kha.internal.GraphicsBuilder.build("' + this.backend().toLowerCase() + '")'];
this.addSourceDirectory(path.join(options.kha, 'Backends', this.backend()));
}
sysdir(): string {
return this.systemDirectory;
}
abstract backend(): string;
abstract haxeOptions(name: string, targetOptions: any, defines: Array<string>): any;
abstract async export(name: string, targetOptions: any, haxeOptions: any): Promise<void>;
setWidthAndHeight(width: number, height: number): void {
this.width = width;
this.height = height;
}
setName(name: string): void {
this.name = name;
this.safename = name.replace(/ /g, '-');
}
setSystemDirectory(systemDirectory: string): void {
this.systemDirectory = systemDirectory;
}
addShader(shader: string): void {
}
addSourceDirectory(path: string): void {
this.sources.push(path);
}
addLibrary(library: Library): void {
this.libraries.push(library);
}
removeSourceDirectory(path: string): void {
for (let i = 0; i < this.sources.length; ++i) {
if (this.sources[i] === path) {
this.sources.splice(i, 1);
return;
}
}
}
async copyImage(platform: string, from: string, to: string, options: any, cache: any): Promise<Array<string>> {
return [];
}
async copySound(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
| return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
} | return [];
}
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
| random_line_split |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
name: string;
safename: string;
options: Options;
projectFiles: boolean;
parameters: string[];
systemDirectory: string;
constructor(options: Options) {
super();
this.options = options;
this.width = 640;
this.height = 480;
this.sources = [];
this.libraries = [];
this.addSourceDirectory(path.join(options.kha, 'Sources'));
this.projectFiles = !options.noproject;
this.parameters = [];
// this.parameters = ['--macro kha.internal.GraphicsBuilder.build("' + this.backend().toLowerCase() + '")'];
this.addSourceDirectory(path.join(options.kha, 'Backends', this.backend()));
}
sysdir(): string {
return this.systemDirectory;
}
abstract backend(): string;
abstract haxeOptions(name: string, targetOptions: any, defines: Array<string>): any;
abstract async export(name: string, targetOptions: any, haxeOptions: any): Promise<void>;
setWidthAndHeight(width: number, height: number): void {
this.width = width;
this.height = height;
}
setName(name: string): void {
this.name = name;
this.safename = name.replace(/ /g, '-');
}
setSystemDirectory(systemDirectory: string): void {
this.systemDirectory = systemDirectory;
}
addShader(shader: string): void {
}
addSourceDirectory(path: string): void {
this.sources.push(path);
}
addLibrary(library: Library): void {
this.libraries.push(library);
}
removeSourceDirectory(path: string): void {
for (let i = 0; i < this.sources.length; ++i) |
}
async copyImage(platform: string, from: string, to: string, options: any, cache: any): Promise<Array<string>> {
return [];
}
async copySound(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
}
| {
if (this.sources[i] === path) {
this.sources.splice(i, 1);
return;
}
} | conditional_block |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
name: string;
safename: string;
options: Options;
projectFiles: boolean;
parameters: string[];
systemDirectory: string;
constructor(options: Options) {
super();
this.options = options;
this.width = 640;
this.height = 480;
this.sources = [];
this.libraries = [];
this.addSourceDirectory(path.join(options.kha, 'Sources'));
this.projectFiles = !options.noproject;
this.parameters = [];
// this.parameters = ['--macro kha.internal.GraphicsBuilder.build("' + this.backend().toLowerCase() + '")'];
this.addSourceDirectory(path.join(options.kha, 'Backends', this.backend()));
}
sysdir(): string {
return this.systemDirectory;
}
abstract backend(): string;
abstract haxeOptions(name: string, targetOptions: any, defines: Array<string>): any;
abstract async export(name: string, targetOptions: any, haxeOptions: any): Promise<void>;
setWidthAndHeight(width: number, height: number): void {
this.width = width;
this.height = height;
}
setName(name: string): void {
this.name = name;
this.safename = name.replace(/ /g, '-');
}
setSystemDirectory(systemDirectory: string): void {
this.systemDirectory = systemDirectory;
}
addShader(shader: string): void {
}
addSourceDirectory(path: string): void {
this.sources.push(path);
}
addLibrary(library: Library): void {
this.libraries.push(library);
}
removeSourceDirectory(path: string): void {
for (let i = 0; i < this.sources.length; ++i) {
if (this.sources[i] === path) {
this.sources.splice(i, 1);
return;
}
}
}
async copyImage(platform: string, from: string, to: string, options: any, cache: any): Promise<Array<string>> {
return [];
}
async | (platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
}
| copySound | identifier_name |
KhaExporter.ts | import * as path from 'path';
import {convert} from '../Converter';
import {Exporter} from './Exporter';
import {Options} from '../Options';
import {Library} from '../Project';
export abstract class KhaExporter extends Exporter {
width: number;
height: number;
sources: string[];
libraries: Library[];
name: string;
safename: string;
options: Options;
projectFiles: boolean;
parameters: string[];
systemDirectory: string;
constructor(options: Options) {
super();
this.options = options;
this.width = 640;
this.height = 480;
this.sources = [];
this.libraries = [];
this.addSourceDirectory(path.join(options.kha, 'Sources'));
this.projectFiles = !options.noproject;
this.parameters = [];
// this.parameters = ['--macro kha.internal.GraphicsBuilder.build("' + this.backend().toLowerCase() + '")'];
this.addSourceDirectory(path.join(options.kha, 'Backends', this.backend()));
}
sysdir(): string {
return this.systemDirectory;
}
abstract backend(): string;
abstract haxeOptions(name: string, targetOptions: any, defines: Array<string>): any;
abstract async export(name: string, targetOptions: any, haxeOptions: any): Promise<void>;
setWidthAndHeight(width: number, height: number): void {
this.width = width;
this.height = height;
}
setName(name: string): void {
this.name = name;
this.safename = name.replace(/ /g, '-');
}
setSystemDirectory(systemDirectory: string): void {
this.systemDirectory = systemDirectory;
}
addShader(shader: string): void {
}
addSourceDirectory(path: string): void {
this.sources.push(path);
}
addLibrary(library: Library): void {
this.libraries.push(library);
}
removeSourceDirectory(path: string): void {
for (let i = 0; i < this.sources.length; ++i) {
if (this.sources[i] === path) {
this.sources.splice(i, 1);
return;
}
}
}
async copyImage(platform: string, from: string, to: string, options: any, cache: any): Promise<Array<string>> {
return [];
}
async copySound(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyVideo(platform: string, from: string, to: string, options: any): Promise<Array<string>> |
async copyBlob(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return [];
}
async copyFont(platform: string, from: string, to: string, options: any): Promise<Array<string>> {
return await this.copyBlob(platform, from, to + '.ttf', options);
}
}
| {
return [];
} | identifier_body |
switch.js | /*
name: Switch
version: 0.1
description: On-off iPhone style switch button.
license: MooTools MIT-Style License (http://mootools.net/license.txt)
copyright: Valerio Proietti (http://mad4milk.net)
authors: Valerio Proietti (http://mad4milk.net)
requires: MooTools 1.2.5, Touch 0.1+ (http://github.com/kamicane/mootools-touch)
notes: ported to MooTools 1.11 with some modifications by Djamil Legato (w00fzIT [at] gmail.com)
notes: ported to MooTools 1.2.5 with some modifications by Stian Didriksen (stian [at] ninjaforge.com)
*/
var Switch = new Class({
Implements: [Options, Events],
options: {
target: '.iphone-checkbox-incl',
radius: 0,
duration: 250,
transition: Fx.Transitions.Sine.easeInOut,
focus: false
},
initialize: function (c, d) {
this.setOptions(d);
this.check = $(c) || false;
if (!this.check) {
return false;
}
this.container = new Element("div", {
'class': "ninja-iphone-incl-container"
});
this.sides = (new Element("div", {
'class': "ninja-iphone-incl-sides"
})).inject(this.container);
this.wrapper = (new Element("div", {
'class': "ninja-iphone-incl-wrapper"
})).inject(this.sides);
this.switcher = (new Element("div", {
'class': "ninja-iphone-incl-switch"
})).inject(this.sides.getFirst());
this.button = (new Element("div", {
'class': "ninja-iphone-incl-button"
})).inject(this.sides);
if (this.check.getParent().get('tag') == "label") {
this.container.inject(this.check.getParent(), "after");
this.check.getParent().inject(this.sides.getFirst()).setStyles({
position: "absolute",
left: "-100000px",
top: 0
});
} else {
this.container.inject(this.check, "after");
this.check.inject(this.sides.getFirst()).setStyles({
position: "absolute",
left: "-100000px",
top: 0
});
}
var f = this;
this.check.addEvents({
attach: this.attach.bind(this),
detach: this.detach.bind(this),
set: function (a) {
f.change(a, true);
}
});
this.height = this.sides.getStyle("height").toInt();
this.focused = false;
var g = this.button.getStyle("width").toInt(),
fullWidth = this.sides.getStyle("width").toInt();
this.min = this.options.radius;
this.max = fullWidth - g - this.min;
this.width = fullWidth - g;
this.height = this.height;
this.half = this.width / 2;
this.steps = this.options.duration / this.width;
this.state = !!this.check.checked;
this.change(this.state, true);
this.fx = new(Fx.Base)({
duration: this.options.duration,
transition: this.options.transition,
wait: false
});
this.fx.set = function (a) {
if (!$chk(a)) {
a = this.fx.now;
}
this.update(a);
}.bind(this);
this.fx.increase = this.fx.set;
this.drag = new Touch(this.button);
var h = function () {
if (!this.animating) {
this.toggle();
}
}.bind(this);
this.drag.addEvent("start", function (x) {
this.check.focus();
this.position = this.button.offsetLeft;
}.bind(this));
this.drag.addEvent("move", function (x) {
this.update(this.position + x);
}.bind(this));
this.drag.addEvent("end", function (x) {
var a = this.button.offsetLeft;
var b = a > this.half ? true : false;
this.change(b);
}.bind(this));
this.drag.addEvent("cancel", h);
this.switchButton = new Touch(this.switcher);
this.switchButton.addEvent("cancel", h);
this.switchButton.addEvent("start", function (e) {
this.check.focus();
}.bind(this));
return this;
},
attach: function () {
this.container.removeClass("disabled");
this.drag.attach();
this.switchButton.attach();
},
detach: function () {
this.container.addClass("disabled");
this.drag.detach();
this.switchButton.detach();
},
update: function (x) {
if (x < this.min) {
x = 0;
} else if (x > this.max) {
x = this.width;
}
this.switcher.style.backgroundPosition = x - this.width + "px center";
//this.switcher.style.left = x - this.width + "px";
this.button.style.left = x + "px";
this.updateSides(x);
},
updateSides: function (x) {
var a = "0 0";
var b = -this.height;
var c = {
off: "0 " + (this.focused && this.options.focus ? b * 6 : b * 3),
on: "0 " + (this.focused && this.options.focus ? b * 5 : b * 2)
};
if (x == 0) {
a = c.off + "px";
} else if (x == this.width) {
a = c.on + "px";
} else |
this.sides.style.backgroundPosition = a;
},
toggle: function () {
this.change(this.button.offsetLeft > this.half ? false : true);
},
change: function (a, b) {
if (typeof a == "string") {
a = a.toInt();
}
if (this.animating) {
return this;
}
if (b) {
this.set(a);
} else {
this.animate(a);
}
this.check.checked = a;
this.check.value = !a ? 0 : 1;
this.state = a;
this.check.fireEvent("onChange", a);
this.fireEvent("onChange", a);
return this;
},
set: function (a) {
if (typeof a == "string") {
a = a.toInt();
}
this.update(a ? this.width : 0);
},
animate: function (a) {
this.animating = true;
var b = this.button.offsetLeft,
to = a ? this.width : 0;
this.fx.options.duration = Math.abs(b - to) * this.steps;
this.drag.detach();
this.fx.stop().start(b, to).chain(function () {
this.drag.attach();
this.animating = false;
}.bind(this));
}
}); | {
a = "0 " + b * 4 + "px";
} | conditional_block |
switch.js | name: Switch
version: 0.1
description: On-off iPhone style switch button.
license: MooTools MIT-Style License (http://mootools.net/license.txt)
copyright: Valerio Proietti (http://mad4milk.net)
authors: Valerio Proietti (http://mad4milk.net)
requires: MooTools 1.2.5, Touch 0.1+ (http://github.com/kamicane/mootools-touch)
notes: ported to MooTools 1.11 with some modifications by Djamil Legato (w00fzIT [at] gmail.com)
notes: ported to MooTools 1.2.5 with some modifications by Stian Didriksen (stian [at] ninjaforge.com)
*/
var Switch = new Class({
Implements: [Options, Events],
options: {
target: '.iphone-checkbox-incl',
radius: 0,
duration: 250,
transition: Fx.Transitions.Sine.easeInOut,
focus: false
},
initialize: function (c, d) {
this.setOptions(d);
this.check = $(c) || false;
if (!this.check) {
return false;
}
this.container = new Element("div", {
'class': "ninja-iphone-incl-container"
});
this.sides = (new Element("div", {
'class': "ninja-iphone-incl-sides"
})).inject(this.container);
this.wrapper = (new Element("div", {
'class': "ninja-iphone-incl-wrapper"
})).inject(this.sides);
this.switcher = (new Element("div", {
'class': "ninja-iphone-incl-switch"
})).inject(this.sides.getFirst());
this.button = (new Element("div", {
'class': "ninja-iphone-incl-button"
})).inject(this.sides);
if (this.check.getParent().get('tag') == "label") {
this.container.inject(this.check.getParent(), "after");
this.check.getParent().inject(this.sides.getFirst()).setStyles({
position: "absolute",
left: "-100000px",
top: 0
});
} else {
this.container.inject(this.check, "after");
this.check.inject(this.sides.getFirst()).setStyles({
position: "absolute",
left: "-100000px",
top: 0
});
}
var f = this;
this.check.addEvents({
attach: this.attach.bind(this),
detach: this.detach.bind(this),
set: function (a) {
f.change(a, true);
}
});
this.height = this.sides.getStyle("height").toInt();
this.focused = false;
var g = this.button.getStyle("width").toInt(),
fullWidth = this.sides.getStyle("width").toInt();
this.min = this.options.radius;
this.max = fullWidth - g - this.min;
this.width = fullWidth - g;
this.height = this.height;
this.half = this.width / 2;
this.steps = this.options.duration / this.width;
this.state = !!this.check.checked;
this.change(this.state, true);
this.fx = new(Fx.Base)({
duration: this.options.duration,
transition: this.options.transition,
wait: false
});
this.fx.set = function (a) {
if (!$chk(a)) {
a = this.fx.now;
}
this.update(a);
}.bind(this);
this.fx.increase = this.fx.set;
this.drag = new Touch(this.button);
var h = function () {
if (!this.animating) {
this.toggle();
}
}.bind(this);
this.drag.addEvent("start", function (x) {
this.check.focus();
this.position = this.button.offsetLeft;
}.bind(this));
this.drag.addEvent("move", function (x) {
this.update(this.position + x);
}.bind(this));
this.drag.addEvent("end", function (x) {
var a = this.button.offsetLeft;
var b = a > this.half ? true : false;
this.change(b);
}.bind(this));
this.drag.addEvent("cancel", h);
this.switchButton = new Touch(this.switcher);
this.switchButton.addEvent("cancel", h);
this.switchButton.addEvent("start", function (e) {
this.check.focus();
}.bind(this));
return this;
},
attach: function () {
this.container.removeClass("disabled");
this.drag.attach();
this.switchButton.attach();
},
detach: function () {
this.container.addClass("disabled");
this.drag.detach();
this.switchButton.detach();
},
update: function (x) {
if (x < this.min) {
x = 0;
} else if (x > this.max) {
x = this.width;
}
this.switcher.style.backgroundPosition = x - this.width + "px center";
//this.switcher.style.left = x - this.width + "px";
this.button.style.left = x + "px";
this.updateSides(x);
},
updateSides: function (x) {
var a = "0 0";
var b = -this.height;
var c = {
off: "0 " + (this.focused && this.options.focus ? b * 6 : b * 3),
on: "0 " + (this.focused && this.options.focus ? b * 5 : b * 2)
};
if (x == 0) {
a = c.off + "px";
} else if (x == this.width) {
a = c.on + "px";
} else {
a = "0 " + b * 4 + "px";
}
this.sides.style.backgroundPosition = a;
},
toggle: function () {
this.change(this.button.offsetLeft > this.half ? false : true);
},
change: function (a, b) {
if (typeof a == "string") {
a = a.toInt();
}
if (this.animating) {
return this;
}
if (b) {
this.set(a);
} else {
this.animate(a);
}
this.check.checked = a;
this.check.value = !a ? 0 : 1;
this.state = a;
this.check.fireEvent("onChange", a);
this.fireEvent("onChange", a);
return this;
},
set: function (a) {
if (typeof a == "string") {
a = a.toInt();
}
this.update(a ? this.width : 0);
},
animate: function (a) {
this.animating = true;
var b = this.button.offsetLeft,
to = a ? this.width : 0;
this.fx.options.duration = Math.abs(b - to) * this.steps;
this.drag.detach();
this.fx.stop().start(b, to).chain(function () {
this.drag.attach();
this.animating = false;
}.bind(this));
}
}); | /* | random_line_split |
|
__init__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2007 Osmo Salomaa
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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. |
"""User-activatable actions for :class:`gaupol.Application`."""
from gaupol.actions.audio import * # noqa
from gaupol.actions.edit import * # noqa
from gaupol.actions.file import * # noqa
from gaupol.actions.help import * # noqa
from gaupol.actions.projects import * # noqa
from gaupol.actions.text import * # noqa
from gaupol.actions.tools import * # noqa
from gaupol.actions.video import * # noqa
from gaupol.actions.view import * # noqa
__all__ = tuple(x for x in dir() if x.endswith("Action")) | #
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. | random_line_split |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program 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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : kevintjuh93
*/
var status = -1;
function start(mode, type, selection) |
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0) {
qm.sendNext("What? You don't want the potion?");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendYesNo("Hm... Your expression tells me that the exercise didn't jog any memories. But don't you worry. They'll come back, eventually. Here, drink this potion and power up!\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0#\r\n#v2000022# 10 #t2000022#\r\n#v2000023# 10 #t2000023#\r\n\r\n#fUI/UIWindow.img/QuestIcon/8/0# 57 exp");
else if (status == 1) {
if(qm.isQuestCompleted(21012))
qm.dropMessage(1,"Unknown Error");
else if(qm.canHold(2000022) && qm.canHold(2000023)){
qm.gainExp(57);
qm.gainItem(2000022, 10);
qm.gainItem(2000023, 10);
qm.forceCompleteQuest();
qm.sendOk("#b(Even if you're really the hero everyone says you are... What good are you without any skills?)", 3);
qm.dispose();
}else
qm.dropMessage(1,"Your inventory is full");
qm.dispose();
}
} | {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that? You want to know how I knew who you were? That's easy. I eavesdropped on some people talking loudly next to me. I'm sure the rumor has spread through the entire island already. Everyone knows that you've returned!")
else if (status == 1) {
qm.sendNextPrev("Hm, how about trying out that sword? Wouldn't that bring back some memories? How about #bfighthing some monsters#k?");
} else if (status == 2) {
qm.sendAcceptDecline("Ah, I'm so sorry. I was so happy to have finally met you that I guess I got a little carried away. Whew, deep breaths. Deep breaths. Okay, I feel better now. But um...can I ask you a favor? Please?");
} else if (status == 3) {
qm.forceStartQuest();
qm.sendNext("It just so happens that there are a lot of #rTutorial Murus #knear here. How about defeating just #r3 #kof them? It could help you remember a thing or two.");
} else if (status == 4) {
qm.sendNextPrev("Ah, you've also forgotten how to use your skills? #bPlace skills in the quick slots for easy acces. #kYou can also place consumable items in the slots, so use the slots to your advantage.") ;
} else if (status == 5) {
qm.guideHint(17);
qm.dispose();
}
} | identifier_body |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program 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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : kevintjuh93
*/
var status = -1;
function start(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that? You want to know how I knew who you were? That's easy. I eavesdropped on some people talking loudly next to me. I'm sure the rumor has spread through the entire island already. Everyone knows that you've returned!")
else if (status == 1) {
qm.sendNextPrev("Hm, how about trying out that sword? Wouldn't that bring back some memories? How about #bfighthing some monsters#k?");
} else if (status == 2) {
qm.sendAcceptDecline("Ah, I'm so sorry. I was so happy to have finally met you that I guess I got a little carried away. Whew, deep breaths. Deep breaths. Okay, I feel better now. But um...can I ask you a favor? Please?");
} else if (status == 3) {
qm.forceStartQuest();
qm.sendNext("It just so happens that there are a lot of #rTutorial Murus #knear here. How about defeating just #r3 #kof them? It could help you remember a thing or two.");
} else if (status == 4) {
qm.sendNextPrev("Ah, you've also forgotten how to use your skills? #bPlace skills in the quick slots for easy acces. #kYou can also place consumable items in the slots, so use the slots to your advantage.") ;
} else if (status == 5) {
qm.guideHint(17);
qm.dispose();
}
}
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0) {
qm.sendNext("What? You don't want the potion?");
qm.dispose();
return;
}else{ | }
if (status == 0)
qm.sendYesNo("Hm... Your expression tells me that the exercise didn't jog any memories. But don't you worry. They'll come back, eventually. Here, drink this potion and power up!\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0#\r\n#v2000022# 10 #t2000022#\r\n#v2000023# 10 #t2000023#\r\n\r\n#fUI/UIWindow.img/QuestIcon/8/0# 57 exp");
else if (status == 1) {
if(qm.isQuestCompleted(21012))
qm.dropMessage(1,"Unknown Error");
else if(qm.canHold(2000022) && qm.canHold(2000023)){
qm.gainExp(57);
qm.gainItem(2000022, 10);
qm.gainItem(2000023, 10);
qm.forceCompleteQuest();
qm.sendOk("#b(Even if you're really the hero everyone says you are... What good are you without any skills?)", 3);
qm.dispose();
}else
qm.dropMessage(1,"Your inventory is full");
qm.dispose();
}
} | qm.dispose();
return;
} | random_line_split |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program 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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : kevintjuh93
*/
var status = -1;
function | (mode, type, selection) {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that? You want to know how I knew who you were? That's easy. I eavesdropped on some people talking loudly next to me. I'm sure the rumor has spread through the entire island already. Everyone knows that you've returned!")
else if (status == 1) {
qm.sendNextPrev("Hm, how about trying out that sword? Wouldn't that bring back some memories? How about #bfighthing some monsters#k?");
} else if (status == 2) {
qm.sendAcceptDecline("Ah, I'm so sorry. I was so happy to have finally met you that I guess I got a little carried away. Whew, deep breaths. Deep breaths. Okay, I feel better now. But um...can I ask you a favor? Please?");
} else if (status == 3) {
qm.forceStartQuest();
qm.sendNext("It just so happens that there are a lot of #rTutorial Murus #knear here. How about defeating just #r3 #kof them? It could help you remember a thing or two.");
} else if (status == 4) {
qm.sendNextPrev("Ah, you've also forgotten how to use your skills? #bPlace skills in the quick slots for easy acces. #kYou can also place consumable items in the slots, so use the slots to your advantage.") ;
} else if (status == 5) {
qm.guideHint(17);
qm.dispose();
}
}
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0) {
qm.sendNext("What? You don't want the potion?");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendYesNo("Hm... Your expression tells me that the exercise didn't jog any memories. But don't you worry. They'll come back, eventually. Here, drink this potion and power up!\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0#\r\n#v2000022# 10 #t2000022#\r\n#v2000023# 10 #t2000023#\r\n\r\n#fUI/UIWindow.img/QuestIcon/8/0# 57 exp");
else if (status == 1) {
if(qm.isQuestCompleted(21012))
qm.dropMessage(1,"Unknown Error");
else if(qm.canHold(2000022) && qm.canHold(2000023)){
qm.gainExp(57);
qm.gainItem(2000022, 10);
qm.gainItem(2000023, 10);
qm.forceCompleteQuest();
qm.sendOk("#b(Even if you're really the hero everyone says you are... What good are you without any skills?)", 3);
qm.dispose();
}else
qm.dropMessage(1,"Your inventory is full");
qm.dispose();
}
} | start | identifier_name |
21012.js | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program 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 version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : kevintjuh93
*/
var status = -1;
function start(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 2 && mode == 0) {
qm.sendOk("Hm... You don't think that would help? Think about it. It could help, you know...");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendNext("Welcome, hero! What's that? You want to know how I knew who you were? That's easy. I eavesdropped on some people talking loudly next to me. I'm sure the rumor has spread through the entire island already. Everyone knows that you've returned!")
else if (status == 1) {
qm.sendNextPrev("Hm, how about trying out that sword? Wouldn't that bring back some memories? How about #bfighthing some monsters#k?");
} else if (status == 2) {
qm.sendAcceptDecline("Ah, I'm so sorry. I was so happy to have finally met you that I guess I got a little carried away. Whew, deep breaths. Deep breaths. Okay, I feel better now. But um...can I ask you a favor? Please?");
} else if (status == 3) {
qm.forceStartQuest();
qm.sendNext("It just so happens that there are a lot of #rTutorial Murus #knear here. How about defeating just #r3 #kof them? It could help you remember a thing or two.");
} else if (status == 4) {
qm.sendNextPrev("Ah, you've also forgotten how to use your skills? #bPlace skills in the quick slots for easy acces. #kYou can also place consumable items in the slots, so use the slots to your advantage.") ;
} else if (status == 5) {
qm.guideHint(17);
qm.dispose();
}
}
function end(mode, type, selection) {
status++;
if (mode != 1) {
if(type == 1 && mode == 0) {
qm.sendNext("What? You don't want the potion?");
qm.dispose();
return;
}else{
qm.dispose();
return;
}
}
if (status == 0)
qm.sendYesNo("Hm... Your expression tells me that the exercise didn't jog any memories. But don't you worry. They'll come back, eventually. Here, drink this potion and power up!\r\n\r\n#fUI/UIWindow.img/QuestIcon/4/0#\r\n#v2000022# 10 #t2000022#\r\n#v2000023# 10 #t2000023#\r\n\r\n#fUI/UIWindow.img/QuestIcon/8/0# 57 exp");
else if (status == 1) |
} | {
if(qm.isQuestCompleted(21012))
qm.dropMessage(1,"Unknown Error");
else if(qm.canHold(2000022) && qm.canHold(2000023)){
qm.gainExp(57);
qm.gainItem(2000022, 10);
qm.gainItem(2000023, 10);
qm.forceCompleteQuest();
qm.sendOk("#b(Even if you're really the hero everyone says you are... What good are you without any skills?)", 3);
qm.dispose();
}else
qm.dropMessage(1,"Your inventory is full");
qm.dispose();
} | conditional_block |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We have to import these styles first to have them listed first in the final
// CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565
// The order is important: font files need to be first, with the subset after
// the full font file.
import 'fonts/inter.scss';
import 'fonts/inter-subset.scss';
import 'normalize.css/normalize.css';
import './styles.scss';
/* eslint-disable import/first */
import Routes from 'amo/components/Routes';
import ScrollToTop from 'amo/components/ScrollToTop';
import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage';
import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage';
import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage';
import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils';
import { addChangeListeners } from 'amo/addonManager';
import {
setClientApp as setClientAppAction,
setUserAgent as setUserAgentAction,
} from 'amo/reducers/api';
import { setInstallState } from 'amo/reducers/installations';
import { CLIENT_APP_ANDROID } from 'amo/constants';
import ErrorPage from 'amo/components/ErrorPage';
import translate from 'amo/i18n/translate';
import log from 'amo/logger';
import type { AppState } from 'amo/store';
import type { DispatchFunc } from 'amo/types/redux';
import type { InstalledAddon } from 'amo/reducers/installations';
import type { I18nType } from 'amo/types/i18n';
import type { ReactRouterLocationType } from 'amo/types/router';
/* eslint-enable import/first */
interface MozNavigator extends Navigator {
mozAddonManager?: Object;
}
type PropsFromState = {|
clientApp: string,
lang: string,
userAgent: string | null,
|};
type DefaultProps = {|
_addChangeListeners: (callback: Function, mozAddonManager: Object) => any,
_navigator: typeof navigator | null,
mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>,
userAgent: string | null,
|};
type Props = {|
...PropsFromState,
...DefaultProps,
handleGlobalEvent: () => void,
i18n: I18nType,
location: ReactRouterLocationType,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|};
export function getErrorPage(status: number | null): () => React.Node {
switch (status) {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
} | }
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNavigator).mozAddonManager,
userAgent: null,
};
componentDidMount() {
const {
_addChangeListeners,
_navigator,
handleGlobalEvent,
mozAddonManager,
setUserAgent,
userAgent,
} = this.props;
// Use addonManager.addChangeListener to setup and filter events.
_addChangeListeners(handleGlobalEvent, mozAddonManager);
// If userAgent isn't set in state it could be that we couldn't get one
// from the request headers on our first (server) request. If that's the
// case we try to load them from navigator.
if (!userAgent && _navigator && _navigator.userAgent) {
log.info(
'userAgent not in state on App load; using navigator.userAgent.',
);
setUserAgent(_navigator.userAgent);
}
}
componentDidUpdate() {
const { clientApp, location, setClientApp } = this.props;
const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath(
location.pathname,
);
if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) {
setClientApp(clientAppFromURL);
}
}
render(): React.Node {
const { clientApp, i18n, lang } = this.props;
const i18nValues = {
locale: lang,
};
let defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox (%(locale)s)'),
i18nValues,
);
let titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes. Helmet
// will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
if (clientApp === CLIENT_APP_ANDROID) {
defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox Android (%(locale)s)'),
i18nValues,
);
titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes.
// Helmet will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
}
return (
<NestedStatus code={200}>
<ScrollToTop>
<Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} />
<ErrorPage getErrorComponent={getErrorPage}>
<Routes />
</ErrorPage>
</ScrollToTop>
</NestedStatus>
);
}
}
export const mapStateToProps = (state: AppState): PropsFromState => ({
clientApp: state.api.clientApp,
lang: state.api.lang,
userAgent: state.api.userAgent,
});
export function mapDispatchToProps(dispatch: DispatchFunc): {|
handleGlobalEvent: (payload: InstalledAddon) => void,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|} {
return {
handleGlobalEvent(payload: InstalledAddon) {
dispatch(setInstallState(payload));
},
setClientApp(clientApp: string) {
dispatch(setClientAppAction(clientApp));
},
setUserAgent(userAgent: string) {
dispatch(setUserAgentAction(userAgent));
},
};
}
const App: React.ComponentType<Props> = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps),
translate(),
)(AppBase);
export default App; | random_line_split |
|
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We have to import these styles first to have them listed first in the final
// CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565
// The order is important: font files need to be first, with the subset after
// the full font file.
import 'fonts/inter.scss';
import 'fonts/inter-subset.scss';
import 'normalize.css/normalize.css';
import './styles.scss';
/* eslint-disable import/first */
import Routes from 'amo/components/Routes';
import ScrollToTop from 'amo/components/ScrollToTop';
import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage';
import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage';
import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage';
import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils';
import { addChangeListeners } from 'amo/addonManager';
import {
setClientApp as setClientAppAction,
setUserAgent as setUserAgentAction,
} from 'amo/reducers/api';
import { setInstallState } from 'amo/reducers/installations';
import { CLIENT_APP_ANDROID } from 'amo/constants';
import ErrorPage from 'amo/components/ErrorPage';
import translate from 'amo/i18n/translate';
import log from 'amo/logger';
import type { AppState } from 'amo/store';
import type { DispatchFunc } from 'amo/types/redux';
import type { InstalledAddon } from 'amo/reducers/installations';
import type { I18nType } from 'amo/types/i18n';
import type { ReactRouterLocationType } from 'amo/types/router';
/* eslint-enable import/first */
interface MozNavigator extends Navigator {
mozAddonManager?: Object;
}
type PropsFromState = {|
clientApp: string,
lang: string,
userAgent: string | null,
|};
type DefaultProps = {|
_addChangeListeners: (callback: Function, mozAddonManager: Object) => any,
_navigator: typeof navigator | null,
mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>,
userAgent: string | null,
|};
type Props = {|
...PropsFromState,
...DefaultProps,
handleGlobalEvent: () => void,
i18n: I18nType,
location: ReactRouterLocationType,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|};
export function getErrorPage(status: number | null): () => React.Node {
switch (status) |
}
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNavigator).mozAddonManager,
userAgent: null,
};
componentDidMount() {
const {
_addChangeListeners,
_navigator,
handleGlobalEvent,
mozAddonManager,
setUserAgent,
userAgent,
} = this.props;
// Use addonManager.addChangeListener to setup and filter events.
_addChangeListeners(handleGlobalEvent, mozAddonManager);
// If userAgent isn't set in state it could be that we couldn't get one
// from the request headers on our first (server) request. If that's the
// case we try to load them from navigator.
if (!userAgent && _navigator && _navigator.userAgent) {
log.info(
'userAgent not in state on App load; using navigator.userAgent.',
);
setUserAgent(_navigator.userAgent);
}
}
componentDidUpdate() {
const { clientApp, location, setClientApp } = this.props;
const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath(
location.pathname,
);
if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) {
setClientApp(clientAppFromURL);
}
}
render(): React.Node {
const { clientApp, i18n, lang } = this.props;
const i18nValues = {
locale: lang,
};
let defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox (%(locale)s)'),
i18nValues,
);
let titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes. Helmet
// will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
if (clientApp === CLIENT_APP_ANDROID) {
defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox Android (%(locale)s)'),
i18nValues,
);
titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes.
// Helmet will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
}
return (
<NestedStatus code={200}>
<ScrollToTop>
<Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} />
<ErrorPage getErrorComponent={getErrorPage}>
<Routes />
</ErrorPage>
</ScrollToTop>
</NestedStatus>
);
}
}
export const mapStateToProps = (state: AppState): PropsFromState => ({
clientApp: state.api.clientApp,
lang: state.api.lang,
userAgent: state.api.userAgent,
});
export function mapDispatchToProps(dispatch: DispatchFunc): {|
handleGlobalEvent: (payload: InstalledAddon) => void,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|} {
return {
handleGlobalEvent(payload: InstalledAddon) {
dispatch(setInstallState(payload));
},
setClientApp(clientApp: string) {
dispatch(setClientAppAction(clientApp));
},
setUserAgent(userAgent: string) {
dispatch(setUserAgentAction(userAgent));
},
};
}
const App: React.ComponentType<Props> = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps),
translate(),
)(AppBase);
export default App;
| {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
} | identifier_body |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We have to import these styles first to have them listed first in the final
// CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565
// The order is important: font files need to be first, with the subset after
// the full font file.
import 'fonts/inter.scss';
import 'fonts/inter-subset.scss';
import 'normalize.css/normalize.css';
import './styles.scss';
/* eslint-disable import/first */
import Routes from 'amo/components/Routes';
import ScrollToTop from 'amo/components/ScrollToTop';
import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage';
import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage';
import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage';
import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils';
import { addChangeListeners } from 'amo/addonManager';
import {
setClientApp as setClientAppAction,
setUserAgent as setUserAgentAction,
} from 'amo/reducers/api';
import { setInstallState } from 'amo/reducers/installations';
import { CLIENT_APP_ANDROID } from 'amo/constants';
import ErrorPage from 'amo/components/ErrorPage';
import translate from 'amo/i18n/translate';
import log from 'amo/logger';
import type { AppState } from 'amo/store';
import type { DispatchFunc } from 'amo/types/redux';
import type { InstalledAddon } from 'amo/reducers/installations';
import type { I18nType } from 'amo/types/i18n';
import type { ReactRouterLocationType } from 'amo/types/router';
/* eslint-enable import/first */
interface MozNavigator extends Navigator {
mozAddonManager?: Object;
}
type PropsFromState = {|
clientApp: string,
lang: string,
userAgent: string | null,
|};
type DefaultProps = {|
_addChangeListeners: (callback: Function, mozAddonManager: Object) => any,
_navigator: typeof navigator | null,
mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>,
userAgent: string | null,
|};
type Props = {|
...PropsFromState,
...DefaultProps,
handleGlobalEvent: () => void,
i18n: I18nType,
location: ReactRouterLocationType,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|};
export function getErrorPage(status: number | null): () => React.Node {
switch (status) {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
}
}
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNavigator).mozAddonManager,
userAgent: null,
};
componentDidMount() {
const {
_addChangeListeners,
_navigator,
handleGlobalEvent,
mozAddonManager,
setUserAgent,
userAgent,
} = this.props;
// Use addonManager.addChangeListener to setup and filter events.
_addChangeListeners(handleGlobalEvent, mozAddonManager);
// If userAgent isn't set in state it could be that we couldn't get one
// from the request headers on our first (server) request. If that's the
// case we try to load them from navigator.
if (!userAgent && _navigator && _navigator.userAgent) {
log.info(
'userAgent not in state on App load; using navigator.userAgent.',
);
setUserAgent(_navigator.userAgent);
}
}
componentDidUpdate() {
const { clientApp, location, setClientApp } = this.props;
const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath(
location.pathname,
);
if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) {
setClientApp(clientAppFromURL);
}
}
render(): React.Node {
const { clientApp, i18n, lang } = this.props;
const i18nValues = {
locale: lang,
};
let defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox (%(locale)s)'),
i18nValues,
);
let titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes. Helmet
// will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
if (clientApp === CLIENT_APP_ANDROID) {
| return (
<NestedStatus code={200}>
<ScrollToTop>
<Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} />
<ErrorPage getErrorComponent={getErrorPage}>
<Routes />
</ErrorPage>
</ScrollToTop>
</NestedStatus>
);
}
}
export const mapStateToProps = (state: AppState): PropsFromState => ({
clientApp: state.api.clientApp,
lang: state.api.lang,
userAgent: state.api.userAgent,
});
export function mapDispatchToProps(dispatch: DispatchFunc): {|
handleGlobalEvent: (payload: InstalledAddon) => void,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|} {
return {
handleGlobalEvent(payload: InstalledAddon) {
dispatch(setInstallState(payload));
},
setClientApp(clientApp: string) {
dispatch(setClientAppAction(clientApp));
},
setUserAgent(userAgent: string) {
dispatch(setUserAgentAction(userAgent));
},
};
}
const App: React.ComponentType<Props> = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps),
translate(),
)(AppBase);
export default App;
| defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox Android (%(locale)s)'),
i18nValues,
);
titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes.
// Helmet will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
}
| conditional_block |
index.js | /* @flow */
/* global Navigator, navigator */
import config from 'config';
import * as React from 'react';
import { Helmet } from 'react-helmet';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import NestedStatus from 'react-nested-status';
import { compose } from 'redux';
// We have to import these styles first to have them listed first in the final
// CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565
// The order is important: font files need to be first, with the subset after
// the full font file.
import 'fonts/inter.scss';
import 'fonts/inter-subset.scss';
import 'normalize.css/normalize.css';
import './styles.scss';
/* eslint-disable import/first */
import Routes from 'amo/components/Routes';
import ScrollToTop from 'amo/components/ScrollToTop';
import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage';
import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage';
import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage';
import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils';
import { addChangeListeners } from 'amo/addonManager';
import {
setClientApp as setClientAppAction,
setUserAgent as setUserAgentAction,
} from 'amo/reducers/api';
import { setInstallState } from 'amo/reducers/installations';
import { CLIENT_APP_ANDROID } from 'amo/constants';
import ErrorPage from 'amo/components/ErrorPage';
import translate from 'amo/i18n/translate';
import log from 'amo/logger';
import type { AppState } from 'amo/store';
import type { DispatchFunc } from 'amo/types/redux';
import type { InstalledAddon } from 'amo/reducers/installations';
import type { I18nType } from 'amo/types/i18n';
import type { ReactRouterLocationType } from 'amo/types/router';
/* eslint-enable import/first */
interface MozNavigator extends Navigator {
mozAddonManager?: Object;
}
type PropsFromState = {|
clientApp: string,
lang: string,
userAgent: string | null,
|};
type DefaultProps = {|
_addChangeListeners: (callback: Function, mozAddonManager: Object) => any,
_navigator: typeof navigator | null,
mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>,
userAgent: string | null,
|};
type Props = {|
...PropsFromState,
...DefaultProps,
handleGlobalEvent: () => void,
i18n: I18nType,
location: ReactRouterLocationType,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|};
export function getErrorPage(status: number | null): () => React.Node {
| (status) {
case 401:
return NotAuthorizedPage;
case 404:
return NotFoundPage;
case 500:
default:
return ServerErrorPage;
}
}
export class AppBase extends React.Component<Props> {
scheduledLogout: TimeoutID;
static defaultProps: DefaultProps = {
_addChangeListeners: addChangeListeners,
_navigator: typeof navigator !== 'undefined' ? navigator : null,
mozAddonManager: config.get('server')
? {}
: (navigator: MozNavigator).mozAddonManager,
userAgent: null,
};
componentDidMount() {
const {
_addChangeListeners,
_navigator,
handleGlobalEvent,
mozAddonManager,
setUserAgent,
userAgent,
} = this.props;
// Use addonManager.addChangeListener to setup and filter events.
_addChangeListeners(handleGlobalEvent, mozAddonManager);
// If userAgent isn't set in state it could be that we couldn't get one
// from the request headers on our first (server) request. If that's the
// case we try to load them from navigator.
if (!userAgent && _navigator && _navigator.userAgent) {
log.info(
'userAgent not in state on App load; using navigator.userAgent.',
);
setUserAgent(_navigator.userAgent);
}
}
componentDidUpdate() {
const { clientApp, location, setClientApp } = this.props;
const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath(
location.pathname,
);
if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) {
setClientApp(clientAppFromURL);
}
}
render(): React.Node {
const { clientApp, i18n, lang } = this.props;
const i18nValues = {
locale: lang,
};
let defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox (%(locale)s)'),
i18nValues,
);
let titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes. Helmet
// will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
if (clientApp === CLIENT_APP_ANDROID) {
defaultTitle = i18n.sprintf(
i18n.gettext('Add-ons for Firefox Android (%(locale)s)'),
i18nValues,
);
titleTemplate = i18n.sprintf(
i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'),
// We inject `%s` as a named argument to avoid localizer mistakes.
// Helmet will replace `%s` by the title supplied in other pages.
{ ...i18nValues, title: '%s' },
);
}
return (
<NestedStatus code={200}>
<ScrollToTop>
<Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} />
<ErrorPage getErrorComponent={getErrorPage}>
<Routes />
</ErrorPage>
</ScrollToTop>
</NestedStatus>
);
}
}
export const mapStateToProps = (state: AppState): PropsFromState => ({
clientApp: state.api.clientApp,
lang: state.api.lang,
userAgent: state.api.userAgent,
});
export function mapDispatchToProps(dispatch: DispatchFunc): {|
handleGlobalEvent: (payload: InstalledAddon) => void,
setClientApp: (clientApp: string) => void,
setUserAgent: (userAgent: string) => void,
|} {
return {
handleGlobalEvent(payload: InstalledAddon) {
dispatch(setInstallState(payload));
},
setClientApp(clientApp: string) {
dispatch(setClientAppAction(clientApp));
},
setUserAgent(userAgent: string) {
dispatch(setUserAgentAction(userAgent));
},
};
}
const App: React.ComponentType<Props> = compose(
withRouter,
connect(mapStateToProps, mapDispatchToProps),
translate(),
)(AppBase);
export default App;
| switch | identifier_name |
defaults-de_DE.js | /*!
* Bootstrap-select v1.13.15 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Bitte wählen...',
noneResultsText: 'Keine Ergebnisse für {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} Element ausgewählt' : '{0} Elemente ausgewählt';
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Limit erreicht ({n} Element max.)' : 'Limit erreicht ({n} Elemente max.)',
(numGroup == 1) ? 'Gruppen-Limit erreicht ({n} Element max.)' : 'Gruppen-Limit erreicht ({n} Elemente max.)'
| multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-de_DE.js.map | ];
},
selectAllText: 'Alles auswählen',
deselectAllText: 'Nichts auswählen',
| random_line_split |
defaults-de_DE.js | /*!
* Bootstrap-select v1.13.15 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else |
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Bitte wählen...',
noneResultsText: 'Keine Ergebnisse für {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? '{0} Element ausgewählt' : '{0} Elemente ausgewählt';
},
maxOptionsText: function (numAll, numGroup) {
return [
(numAll == 1) ? 'Limit erreicht ({n} Element max.)' : 'Limit erreicht ({n} Elemente max.)',
(numGroup == 1) ? 'Gruppen-Limit erreicht ({n} Element max.)' : 'Gruppen-Limit erreicht ({n} Elemente max.)'
];
},
selectAllText: 'Alles auswählen',
deselectAllText: 'Nichts auswählen',
multipleSeparator: ', '
};
})(jQuery);
}));
//# sourceMappingURL=defaults-de_DE.js.map | {
factory(root["jQuery"]);
} | conditional_block |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
'''
import qgis
import unittest
from utilities import getQgisTestApp, unitTestDataPath
from PyQt4.QtCore import QFileInfo, QDate, QDateTime
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapRenderer, QgsComposition, QgsComposerLabel, QgsFeatureRequest, QgsFeature, QgsExpression
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()
class TestQgsComposerLabel(unittest.TestCase):
def testCase(self):
|
def evaluation_test( self, mComposition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
expected = "__" + QDateTime.currentDateTime().toString( "dd" ) + "(ok)__"
assert mLabel.displayText() == expected
# $CURRENT_DATE() evaluation (inside an expression)
mLabel.setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" )
dd = QDate.currentDate().day()
expected = "__%d(ok)__" % (dd+1)
assert mLabel.displayText() == expected
# expression evaluation (without associated feature)
mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
assert mLabel.displayText() == "__[NAME_1]42__"
def feature_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setText( "[%\"NAME_1\"||'_ok'%]")
assert mLabel.displayText() == "Basse-Normandie_ok"
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
assert mLabel.displayText() == "Bretagne_ok"
# evaluation with local variables
locs = { "$test" : "OK" }
mLabel.setExpressionContext( feat, mVectorLayer, locs )
mLabel.setText( "[%\"NAME_1\"||$test%]" )
assert mLabel.displayText() == "BretagneOK"
def page_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
mComposition.setNumPages( 2 )
mLabel.setText( "[%$page||'/'||$numpages%]" )
assert mLabel.displayText() == "1/2"
# move the the second page and re-evaluate
mLabel.setItemPosition( 0, 320 )
assert mLabel.displayText() == "2/2"
# use setSpecialColumn
mLabel.setText( "[%$var1 + 1%]" )
QgsExpression.setSpecialColumn( "$var1", 41 )
assert mLabel.displayText() == "42"
QgsExpression.setSpecialColumn( "$var1", 99 )
assert mLabel.displayText() == "100"
QgsExpression.unsetSpecialColumn( "$var1" )
assert mLabel.displayText() == "[%$var1 + 1%]"
if __name__ == '__main__':
unittest.main()
| TEST_DATA_DIR = unitTestDataPath()
vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )
QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )
# create composition with composer map
mMapRenderer = QgsMapRenderer()
layerStringList = []
layerStringList.append( mVectorLayer.id() )
mMapRenderer.setLayerSet( layerStringList )
mMapRenderer.setProjectionsEnabled( False )
mComposition = QgsComposition( mMapRenderer )
mComposition.setPaperSize( 297, 210 )
mLabel = QgsComposerLabel( mComposition )
mComposition.addComposerLabel( mLabel )
self.evaluation_test( mComposition, mLabel )
self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
self.page_evaluation_test( mComposition, mLabel, mVectorLayer ) | identifier_body |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
'''
import qgis
import unittest
from utilities import getQgisTestApp, unitTestDataPath
from PyQt4.QtCore import QFileInfo, QDate, QDateTime
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapRenderer, QgsComposition, QgsComposerLabel, QgsFeatureRequest, QgsFeature, QgsExpression
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()
class TestQgsComposerLabel(unittest.TestCase):
def testCase(self):
TEST_DATA_DIR = unitTestDataPath()
vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )
QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )
# create composition with composer map
mMapRenderer = QgsMapRenderer()
layerStringList = []
layerStringList.append( mVectorLayer.id() )
mMapRenderer.setLayerSet( layerStringList )
mMapRenderer.setProjectionsEnabled( False )
mComposition = QgsComposition( mMapRenderer )
mComposition.setPaperSize( 297, 210 )
mLabel = QgsComposerLabel( mComposition )
mComposition.addComposerLabel( mLabel )
self.evaluation_test( mComposition, mLabel )
self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
self.page_evaluation_test( mComposition, mLabel, mVectorLayer )
def evaluation_test( self, mComposition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
expected = "__" + QDateTime.currentDateTime().toString( "dd" ) + "(ok)__"
assert mLabel.displayText() == expected
# $CURRENT_DATE() evaluation (inside an expression)
mLabel.setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" )
dd = QDate.currentDate().day()
expected = "__%d(ok)__" % (dd+1)
assert mLabel.displayText() == expected
# expression evaluation (without associated feature)
mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
assert mLabel.displayText() == "__[NAME_1]42__"
def feature_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setText( "[%\"NAME_1\"||'_ok'%]")
assert mLabel.displayText() == "Basse-Normandie_ok"
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
assert mLabel.displayText() == "Bretagne_ok"
# evaluation with local variables
locs = { "$test" : "OK" }
mLabel.setExpressionContext( feat, mVectorLayer, locs )
mLabel.setText( "[%\"NAME_1\"||$test%]" )
assert mLabel.displayText() == "BretagneOK"
def page_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
mComposition.setNumPages( 2 )
mLabel.setText( "[%$page||'/'||$numpages%]" )
assert mLabel.displayText() == "1/2"
# move the the second page and re-evaluate
mLabel.setItemPosition( 0, 320 )
assert mLabel.displayText() == "2/2"
# use setSpecialColumn
mLabel.setText( "[%$var1 + 1%]" )
QgsExpression.setSpecialColumn( "$var1", 41 )
assert mLabel.displayText() == "42"
QgsExpression.setSpecialColumn( "$var1", 99 )
assert mLabel.displayText() == "100"
QgsExpression.unsetSpecialColumn( "$var1" )
assert mLabel.displayText() == "[%$var1 + 1%]"
if __name__ == '__main__':
| unittest.main() | conditional_block |
|
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
'''
import qgis
import unittest
from utilities import getQgisTestApp, unitTestDataPath
from PyQt4.QtCore import QFileInfo, QDate, QDateTime
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapRenderer, QgsComposition, QgsComposerLabel, QgsFeatureRequest, QgsFeature, QgsExpression
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()
class TestQgsComposerLabel(unittest.TestCase):
def testCase(self):
TEST_DATA_DIR = unitTestDataPath()
vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )
QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )
# create composition with composer map
mMapRenderer = QgsMapRenderer()
layerStringList = []
layerStringList.append( mVectorLayer.id() )
mMapRenderer.setLayerSet( layerStringList )
mMapRenderer.setProjectionsEnabled( False )
mComposition = QgsComposition( mMapRenderer )
mComposition.setPaperSize( 297, 210 )
mLabel = QgsComposerLabel( mComposition )
mComposition.addComposerLabel( mLabel )
self.evaluation_test( mComposition, mLabel )
self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
self.page_evaluation_test( mComposition, mLabel, mVectorLayer )
def evaluation_test( self, mComposition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
expected = "__" + QDateTime.currentDateTime().toString( "dd" ) + "(ok)__"
assert mLabel.displayText() == expected
# $CURRENT_DATE() evaluation (inside an expression)
mLabel.setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" )
dd = QDate.currentDate().day()
expected = "__%d(ok)__" % (dd+1)
assert mLabel.displayText() == expected
# expression evaluation (without associated feature)
mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
assert mLabel.displayText() == "__[NAME_1]42__"
def | ( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setText( "[%\"NAME_1\"||'_ok'%]")
assert mLabel.displayText() == "Basse-Normandie_ok"
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
assert mLabel.displayText() == "Bretagne_ok"
# evaluation with local variables
locs = { "$test" : "OK" }
mLabel.setExpressionContext( feat, mVectorLayer, locs )
mLabel.setText( "[%\"NAME_1\"||$test%]" )
assert mLabel.displayText() == "BretagneOK"
def page_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
mComposition.setNumPages( 2 )
mLabel.setText( "[%$page||'/'||$numpages%]" )
assert mLabel.displayText() == "1/2"
# move the the second page and re-evaluate
mLabel.setItemPosition( 0, 320 )
assert mLabel.displayText() == "2/2"
# use setSpecialColumn
mLabel.setText( "[%$var1 + 1%]" )
QgsExpression.setSpecialColumn( "$var1", 41 )
assert mLabel.displayText() == "42"
QgsExpression.setSpecialColumn( "$var1", 99 )
assert mLabel.displayText() == "100"
QgsExpression.unsetSpecialColumn( "$var1" )
assert mLabel.displayText() == "[%$var1 + 1%]"
if __name__ == '__main__':
unittest.main()
| feature_evaluation_test | identifier_name |
test_qgscomposerlabel.py | # -*- coding: utf-8 -*-
'''
test_qgscomposerlabel.py
--------------------------------------
Date : Oct 2012
Copyright : (C) 2012 by Dr. Hugo Mercier
email : hugo dot mercier at oslandia dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
'''
import qgis
import unittest
from utilities import getQgisTestApp, unitTestDataPath
from PyQt4.QtCore import QFileInfo, QDate, QDateTime
from qgis.core import QgsVectorLayer, QgsMapLayerRegistry, QgsMapRenderer, QgsComposition, QgsComposerLabel, QgsFeatureRequest, QgsFeature, QgsExpression
QGISAPP, CANVAS, IFACE, PARENT = getQgisTestApp()
class TestQgsComposerLabel(unittest.TestCase):
def testCase(self):
TEST_DATA_DIR = unitTestDataPath()
vectorFileInfo = QFileInfo( TEST_DATA_DIR + "/france_parts.shp")
mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )
QgsMapLayerRegistry.instance().addMapLayers( [mVectorLayer] )
# create composition with composer map
mMapRenderer = QgsMapRenderer()
layerStringList = []
layerStringList.append( mVectorLayer.id() )
mMapRenderer.setLayerSet( layerStringList )
mMapRenderer.setProjectionsEnabled( False )
mComposition = QgsComposition( mMapRenderer )
mComposition.setPaperSize( 297, 210 )
mLabel = QgsComposerLabel( mComposition )
mComposition.addComposerLabel( mLabel )
self.evaluation_test( mComposition, mLabel )
self.feature_evaluation_test( mComposition, mLabel, mVectorLayer )
self.page_evaluation_test( mComposition, mLabel, mVectorLayer )
def evaluation_test( self, mComposition, mLabel ):
# $CURRENT_DATE evaluation
mLabel.setText( "__$CURRENT_DATE__" )
assert mLabel.displayText() == ( "__" + QDate.currentDate().toString() + "__" )
# $CURRENT_DATE() evaluation
mLabel.setText( "__$CURRENT_DATE(dd)(ok)__" )
expected = "__" + QDateTime.currentDateTime().toString( "dd" ) + "(ok)__"
assert mLabel.displayText() == expected
# $CURRENT_DATE() evaluation (inside an expression)
mLabel.setText( "__[%$CURRENT_DATE(dd) + 1%](ok)__" )
dd = QDate.currentDate().day()
expected = "__%d(ok)__" % (dd+1)
assert mLabel.displayText() == expected |
def feature_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
provider = mVectorLayer.dataProvider()
fi = provider.getFeatures( QgsFeatureRequest() )
feat = QgsFeature()
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
mLabel.setText( "[%\"NAME_1\"||'_ok'%]")
assert mLabel.displayText() == "Basse-Normandie_ok"
fi.nextFeature( feat )
mLabel.setExpressionContext( feat, mVectorLayer )
assert mLabel.displayText() == "Bretagne_ok"
# evaluation with local variables
locs = { "$test" : "OK" }
mLabel.setExpressionContext( feat, mVectorLayer, locs )
mLabel.setText( "[%\"NAME_1\"||$test%]" )
assert mLabel.displayText() == "BretagneOK"
def page_evaluation_test( self, mComposition, mLabel, mVectorLayer ):
mComposition.setNumPages( 2 )
mLabel.setText( "[%$page||'/'||$numpages%]" )
assert mLabel.displayText() == "1/2"
# move the the second page and re-evaluate
mLabel.setItemPosition( 0, 320 )
assert mLabel.displayText() == "2/2"
# use setSpecialColumn
mLabel.setText( "[%$var1 + 1%]" )
QgsExpression.setSpecialColumn( "$var1", 41 )
assert mLabel.displayText() == "42"
QgsExpression.setSpecialColumn( "$var1", 99 )
assert mLabel.displayText() == "100"
QgsExpression.unsetSpecialColumn( "$var1" )
assert mLabel.displayText() == "[%$var1 + 1%]"
if __name__ == '__main__':
unittest.main() |
# expression evaluation (without associated feature)
mLabel.setText( "__[%\"NAME_1\"%][%21*2%]__" )
assert mLabel.displayText() == "__[NAME_1]42__" | random_line_split |
sweetalert-tests.ts | /// <reference path="sweetalert.d.ts" />
// A basic message
swal("Here's a message!");
// A title with a text under
swal("Here's a message!", "It's pretty, isn't it?");
// A success message!
swal("Good job!", "You clicked the button!", "success");
// A warning message, with a function attached to the "Confirm"-button...
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function () {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
// ... and by passing a parameter, you can execute something else for "Cancel". | title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
// A message with a custom icon
swal({
title: "Sweet!",
text: "Here's a custom image.",
imageUrl: "images/thumbs-up.jpg"
});
// An HTML message
swal({
title: "HTML <small>Title</small>!",
text: "A custom <span style=\"color: #F8BB86\">html<span> message.",
html: true
});
// A message with auto close timer
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: false
});
// A replacement for the "prompt" function
swal({
title: "An input!",
text: "Write something interesting:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top"
},
function (inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false;
}
swal("Nice!", "You wrote: " + inputValue, "success");
}
);
swal.setDefaults({ confirmButtonColor: "#000000" });
swal.close();
swal.showInputError("Invalid email!"); | swal({ | random_line_split |
sweetalert-tests.ts | /// <reference path="sweetalert.d.ts" />
// A basic message
swal("Here's a message!");
// A title with a text under
swal("Here's a message!", "It's pretty, isn't it?");
// A success message!
swal("Good job!", "You clicked the button!", "success");
// A warning message, with a function attached to the "Confirm"-button...
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function () {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
});
// ... and by passing a parameter, you can execute something else for "Cancel".
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
cancelButtonText: "No, cancel plx!",
closeOnConfirm: false,
closeOnCancel: false
},
function (isConfirm) {
if (isConfirm) | else {
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
// A message with a custom icon
swal({
title: "Sweet!",
text: "Here's a custom image.",
imageUrl: "images/thumbs-up.jpg"
});
// An HTML message
swal({
title: "HTML <small>Title</small>!",
text: "A custom <span style=\"color: #F8BB86\">html<span> message.",
html: true
});
// A message with auto close timer
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: false
});
// A replacement for the "prompt" function
swal({
title: "An input!",
text: "Write something interesting:",
type: "input",
showCancelButton: true,
closeOnConfirm: false,
animation: "slide-from-top"
},
function (inputValue) {
if (inputValue === false) return false;
if (inputValue === "") {
swal.showInputError("You need to write something!");
return false;
}
swal("Nice!", "You wrote: " + inputValue, "success");
}
);
swal.setDefaults({ confirmButtonColor: "#000000" });
swal.close();
swal.showInputError("Invalid email!"); | {
swal("Deleted!", "Your imaginary file has been deleted.", "success");
} | conditional_block |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 <https://www.gnu.org/licenses/>.
#
import requests
from django.core.cache import cache
from weblate.logger import LOGGER
from weblate.utils.errors import report_error
from weblate.utils.version import USER_AGENT
def request(method, url, headers=None, **kwargs):
agent | f get_uri_error(uri):
"""Return error for fetching the URL or None if it works."""
if uri.startswith("https://nonexisting.weblate.org/"):
return "Non existing test URL"
cache_key = f"uri-check-{uri}"
cached = cache.get(cache_key)
if cached is True:
LOGGER.debug("URL check for %s, cached success", uri)
return None
if cached:
# The cache contains string here
LOGGER.debug("URL check for %s, cached failure", uri)
return cached
try:
with request("get", uri, stream=True):
cache.set(cache_key, True, 12 * 3600)
LOGGER.debug("URL check for %s, tested success", uri)
return None
except requests.exceptions.RequestException as error:
report_error(cause="URL check failed")
if getattr(error.response, "status_code", 0) == 429:
# Silently ignore rate limiting issues
return None
result = str(error)
cache.set(cache_key, result, 3600)
return result
| = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
de | identifier_body |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 <https://www.gnu.org/licenses/>.
#
import requests
from django.core.cache import cache
from weblate.logger import LOGGER
from weblate.utils.errors import report_error
from weblate.utils.version import USER_AGENT | agent = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
def get_uri_error(uri):
"""Return error for fetching the URL or None if it works."""
if uri.startswith("https://nonexisting.weblate.org/"):
return "Non existing test URL"
cache_key = f"uri-check-{uri}"
cached = cache.get(cache_key)
if cached is True:
LOGGER.debug("URL check for %s, cached success", uri)
return None
if cached:
# The cache contains string here
LOGGER.debug("URL check for %s, cached failure", uri)
return cached
try:
with request("get", uri, stream=True):
cache.set(cache_key, True, 12 * 3600)
LOGGER.debug("URL check for %s, tested success", uri)
return None
except requests.exceptions.RequestException as error:
report_error(cause="URL check failed")
if getattr(error.response, "status_code", 0) == 429:
# Silently ignore rate limiting issues
return None
result = str(error)
cache.set(cache_key, result, 3600)
return result |
def request(method, url, headers=None, **kwargs): | random_line_split |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 <https://www.gnu.org/licenses/>.
#
import requests
from django.core.cache import cache
from weblate.logger import LOGGER
from weblate.utils.errors import report_error
from weblate.utils.version import USER_AGENT
def reque | od, url, headers=None, **kwargs):
agent = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
def get_uri_error(uri):
"""Return error for fetching the URL or None if it works."""
if uri.startswith("https://nonexisting.weblate.org/"):
return "Non existing test URL"
cache_key = f"uri-check-{uri}"
cached = cache.get(cache_key)
if cached is True:
LOGGER.debug("URL check for %s, cached success", uri)
return None
if cached:
# The cache contains string here
LOGGER.debug("URL check for %s, cached failure", uri)
return cached
try:
with request("get", uri, stream=True):
cache.set(cache_key, True, 12 * 3600)
LOGGER.debug("URL check for %s, tested success", uri)
return None
except requests.exceptions.RequestException as error:
report_error(cause="URL check failed")
if getattr(error.response, "status_code", 0) == 429:
# Silently ignore rate limiting issues
return None
result = str(error)
cache.set(cache_key, result, 3600)
return result
| st(meth | identifier_name |
requests.py | #
# Copyright © 2012–2022 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 <https://www.gnu.org/licenses/>.
#
import requests
from django.core.cache import cache
from weblate.logger import LOGGER
from weblate.utils.errors import report_error
from weblate.utils.version import USER_AGENT
def request(method, url, headers=None, **kwargs):
agent = {"User-Agent": USER_AGENT}
if headers:
headers.update(agent)
else:
headers = agent
response = requests.request(method, url, headers=headers, **kwargs)
response.raise_for_status()
return response
def get_uri_error(uri):
"""Return error for fetching the URL or None if it works."""
if uri.startswith("https://nonexisting.weblate.org/"):
return "Non existing test URL"
cache_key = f"uri-check-{uri}"
cached = cache.get(cache_key)
if cached is True:
LOGGER.debug("URL check for %s, cached success", uri)
return None
if cached:
# The cache contains string here
LOGGER.debug("URL check for %s, cached failure", uri)
return cached
try:
with request("get", uri, stream=True):
cache.set(cache_key, True, 12 * 3600)
LOGGER.debug("URL check for %s, tested success", uri)
return None
except requests.exceptions.RequestException as error:
report_error(cause="URL check failed")
if getattr(error.response, "status_code", 0) == 429:
# Silently ignore rate limiting issues
retur | result = str(error)
cache.set(cache_key, result, 3600)
return result
| n None
| conditional_block |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn | (&mut self, s: &str) {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s)
);
s[c.len()..s.len()]
},
None => {
self.words.push(s[0..1].to_string());
s[1..s.len()]
}
};
self.add_chain(&next);
}
fn find(&self, s: &str) -> Option<String> {
for word in self.words {
if(word == s) {
Some(word.clone())
}
}
None
}
}
impl From<String> for LwzDict {
fn from(from: String) -> Self {
}
}
fn main() {
let sentence = env::args().nth(1).unwrap();
}
| add_chain | identifier_name |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn add_chain(&mut self, s: &str) {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s) | s[1..s.len()]
}
};
self.add_chain(&next);
}
fn find(&self, s: &str) -> Option<String> {
for word in self.words {
if(word == s) {
Some(word.clone())
}
}
None
}
}
impl From<String> for LwzDict {
fn from(from: String) -> Self {
}
}
fn main() {
let sentence = env::args().nth(1).unwrap();
} | );
s[c.len()..s.len()]
},
None => {
self.words.push(s[0..1].to_string()); | random_line_split |
main.rs | use std::env;
struct LwzDict {
words: Vec<String>
}
impl LwzDict {
pub fn add_chain(&mut self, s: &str) |
fn find(&self, s: &str) -> Option<String> {
for word in self.words {
if(word == s) {
Some(word.clone())
}
}
None
}
}
impl From<String> for LwzDict {
fn from(from: String) -> Self {
}
}
fn main() {
let sentence = env::args().nth(1).unwrap();
}
| {
if s.len() < 1 {
return;
}
let next = match self.find(s) {
Some(c) => {
self.words.push(
format!("{}{}", c, s)
);
s[c.len()..s.len()]
},
None => {
self.words.push(s[0..1].to_string());
s[1..s.len()]
}
};
self.add_chain(&next);
} | identifier_body |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateTimeInputComponent;
availableCultures: string[] =
[
'Czech (Czech Republic)', 'German (Germany)', 'English (Canada)', 'English (United States)', 'French (France)',
'Italian (Italy)', 'Japanese (Japan)', 'Hebrew (Israel)', 'Russian (Russia)', 'Croatian (Croatia)', 'Sanskrit (India)'
];
listOnSelect(event: any): void {
let index: number = event.args.index;
switch (index) {
case 0:
this.myDateTimeInput.culture('cs-CZ');
break;
case 1:
this.myDateTimeInput.culture('de-DE');
break;
case 2:
this.myDateTimeInput.culture('en-CA');
break;
case 3:
this.myDateTimeInput.culture('en-US');
break;
case 4:
this.myDateTimeInput.culture('fr-FR');
break;
case 5:
this.myDateTimeInput.culture('it-IT');
break;
case 6:
this.myDateTimeInput.culture('ja-JP');
break;
case 7:
this.myDateTimeInput.culture('he-IL');
break;
case 8:
this.myDateTimeInput.culture('ru-RU');
case 9:
this.myDateTimeInput.culture('hr');
break;
case 10:
this.myDateTimeInput.culture('sa-IN');
break; | }
} | } | random_line_split |
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateTimeInputComponent;
availableCultures: string[] =
[
'Czech (Czech Republic)', 'German (Germany)', 'English (Canada)', 'English (United States)', 'French (France)',
'Italian (Italy)', 'Japanese (Japan)', 'Hebrew (Israel)', 'Russian (Russia)', 'Croatian (Croatia)', 'Sanskrit (India)'
];
listOnSelect(event: any): void {
let index: num | ber = event.args.index;
switch (index) {
case 0:
this.myDateTimeInput.culture('cs-CZ');
break;
case 1:
this.myDateTimeInput.culture('de-DE');
break;
case 2:
this.myDateTimeInput.culture('en-CA');
break;
case 3:
this.myDateTimeInput.culture('en-US');
break;
case 4:
this.myDateTimeInput.culture('fr-FR');
break;
case 5:
this.myDateTimeInput.culture('it-IT');
break;
case 6:
this.myDateTimeInput.culture('ja-JP');
break;
case 7:
this.myDateTimeInput.culture('he-IL');
break;
case 8:
this.myDateTimeInput.culture('ru-RU');
case 9:
this.myDateTimeInput.culture('hr');
break;
case 10:
this.myDateTimeInput.culture('sa-IN');
break;
}
}
} | identifier_body |
|
app.component.ts | import { Component, ViewChild } from '@angular/core';
import { jqxDateTimeInputComponent } from '../../../jqwidgets-ts/angular_jqxdatetimeinput';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('myDateTimeInput') myDateTimeInput; jqxDateTimeInputComponent;
availableCultures: string[] =
[
'Czech (Czech Republic)', 'German (Germany)', 'English (Canada)', 'English (United States)', 'French (France)',
'Italian (Italy)', 'Japanese (Japan)', 'Hebrew (Israel)', 'Russian (Russia)', 'Croatian (Croatia)', 'Sanskrit (India)'
];
listOnSelect(event: any) | let index: number = event.args.index;
switch (index) {
case 0:
this.myDateTimeInput.culture('cs-CZ');
break;
case 1:
this.myDateTimeInput.culture('de-DE');
break;
case 2:
this.myDateTimeInput.culture('en-CA');
break;
case 3:
this.myDateTimeInput.culture('en-US');
break;
case 4:
this.myDateTimeInput.culture('fr-FR');
break;
case 5:
this.myDateTimeInput.culture('it-IT');
break;
case 6:
this.myDateTimeInput.culture('ja-JP');
break;
case 7:
this.myDateTimeInput.culture('he-IL');
break;
case 8:
this.myDateTimeInput.culture('ru-RU');
case 9:
this.myDateTimeInput.culture('hr');
break;
case 10:
this.myDateTimeInput.culture('sa-IN');
break;
}
}
} | : void {
| identifier_name |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import dnf.const
import dnf.util
import libdnf.repo
import logging
import os
import sys
import time
import warnings
# :api loggers are: 'dnf', 'dnf.plugin', 'dnf.rpm'
SUPERCRITICAL = 100 # do not use this for logging
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
DDEBUG = 8
SUBDEBUG = 6
TRACE = 4
def only_once(func):
"""Method decorator turning the method into noop on second or later calls."""
def noop(*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno >= self.max_level:
return 0
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the default
3 : logging.DEBUG,
4 : logging.DEBUG,
5 : logging.DEBUG,
6 : logging.DEBUG, # verbose value
}
def _cfg_verbose_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _VERBOSE_VAL_MAPPING.get(cfg_errval, DDEBUG)
# Both the DNF default and the verbose default are WARNING. Note that ERROR has
# no specific level.
_ERR_VAL_MAPPING = {
0: SUPERCRITICAL,
1: logging.CRITICAL,
2: logging.ERROR
}
def _cfg_err_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _ERR_VAL_MAPPING.get(cfg_errval, logging.WARNING)
def _create_filehandler(logfile):
if not os.path.exists(logfile):
dnf.util.ensure_dir(os.path.dirname(logfile))
dnf.util.touch(logfile)
# By default, make logfiles readable by the user (so the reporting ABRT
# user can attach root logfiles).
os.chmod(logfile, 0o644)
handler = logging.FileHandler(logfile)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s",
"%Y-%m-%dT%H:%M:%SZ")
formatter.converter = time.gmtime
handler.setFormatter(formatter)
return handler
def _paint_mark(logger):
logger.log(INFO, dnf.const.LOG_MARKER)
class Logging(object):
def __init__(self):
self.stdout_handler = self.stderr_handler = None
@only_once
def _presetup(self):
logging.addLevelName(DDEBUG, "DDEBUG")
logging.addLevelName(SUBDEBUG, "SUBDEBUG")
logging.addLevelName(TRACE, "TRACE")
logger_dnf = logging.getLogger("dnf")
logger_dnf.setLevel(TRACE)
# setup stdout
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(INFO)
stdout.addFilter(_MaxLevelFilter(logging.WARNING))
logger_dnf.addHandler(stdout)
self.stdout_handler = stdout
# setup stderr
stderr = logging.StreamHandler(sys.stderr)
stderr.setLevel(WARNING)
logger_dnf.addHandler(stderr)
self.stderr_handler = stderr
@only_once
def _setup(self, verbose_level, error_level, logdir):
self._presetup()
logger_dnf = logging.getLogger("dnf")
# setup file logger
logfile = os.path.join(logdir, dnf.const.LOG)
handler = _create_filehandler(logfile)
logger_dnf.addHandler(handler)
# temporarily turn off stdout/stderr handlers:
self.stdout_handler.setLevel(SUPERCRITICAL)
self.stderr_handler.setLevel(SUPERCRITICAL)
# put the marker in the file now:
_paint_mark(logger_dnf)
# setup Python warnings
logging.captureWarnings(True)
logger_warnings = logging.getLogger("py.warnings")
logger_warnings.addHandler(self.stderr_handler)
logger_warnings.addHandler(handler)
lr_logfile = os.path.join(logdir, dnf.const.LOG_LIBREPO)
libdnf.repo.LibrepoLog.addHandler(lr_logfile, verbose_level <= DEBUG)
# setup RPM callbacks logger
logger_rpm = logging.getLogger("dnf.rpm")
logger_rpm.propagate = False
logger_rpm.setLevel(SUBDEBUG)
logfile = os.path.join(logdir, dnf.const.LOG_RPM)
handler = _create_filehandler(logfile)
logger_rpm.addHandler(self.stdout_handler)
logger_rpm.addHandler(self.stderr_handler)
logger_rpm.addHandler(handler)
_paint_mark(logger_rpm)
# bring std handlers to the preferred level
self.stdout_handler.setLevel(verbose_level)
self.stderr_handler.setLevel(error_level)
logging.raiseExceptions = False
def _setup_from_dnf_conf(self, conf):
verbose_level_r = _cfg_verbose_val2level(conf.debuglevel)
error_level_r = _cfg_err_val2level(conf.errorlevel)
logdir = conf.logdir
return self._setup(verbose_level_r, error_level_r, logdir)
class Timer(object):
def __init__(self, what):
self.what = what
self.start = time.time()
def __call__(self):
diff = time.time() - self.start | logging.getLogger("dnf").log(DDEBUG, msg)
_LIBDNF_TO_DNF_LOGLEVEL_MAPPING = {
libdnf.utils.Logger.Level_CRITICAL: CRITICAL,
libdnf.utils.Logger.Level_ERROR: ERROR,
libdnf.utils.Logger.Level_WARNING: WARNING,
libdnf.utils.Logger.Level_NOTICE: INFO,
libdnf.utils.Logger.Level_INFO: INFO,
libdnf.utils.Logger.Level_DEBUG: DEBUG,
libdnf.utils.Logger.Level_TRACE: TRACE
}
class LibdnfLoggerCB(libdnf.utils.Logger):
def __init__(self):
super(LibdnfLoggerCB, self).__init__()
self._logger = logging.getLogger("dnf")
def write(self, source, *args):
"""Log message.
source -- integer, defines origin (libdnf, librepo, ...) of message, 0 - unknown
"""
if len(args) == 2:
level, message = args
elif len(args) == 4:
time, pid, level, message = args
self._logger.log(_LIBDNF_TO_DNF_LOGLEVEL_MAPPING[level], message)
libdnfLoggerCB = LibdnfLoggerCB()
libdnf.utils.Log.setLogger(libdnfLoggerCB) | msg = 'timer: %s: %d ms' % (self.what, diff * 1000) | random_line_split |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import dnf.const
import dnf.util
import libdnf.repo
import logging
import os
import sys
import time
import warnings
# :api loggers are: 'dnf', 'dnf.plugin', 'dnf.rpm'
SUPERCRITICAL = 100 # do not use this for logging
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
DDEBUG = 8
SUBDEBUG = 6
TRACE = 4
def only_once(func):
"""Method decorator turning the method into noop on second or later calls."""
def noop(*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno >= self.max_level:
|
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the default
3 : logging.DEBUG,
4 : logging.DEBUG,
5 : logging.DEBUG,
6 : logging.DEBUG, # verbose value
}
def _cfg_verbose_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _VERBOSE_VAL_MAPPING.get(cfg_errval, DDEBUG)
# Both the DNF default and the verbose default are WARNING. Note that ERROR has
# no specific level.
_ERR_VAL_MAPPING = {
0: SUPERCRITICAL,
1: logging.CRITICAL,
2: logging.ERROR
}
def _cfg_err_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _ERR_VAL_MAPPING.get(cfg_errval, logging.WARNING)
def _create_filehandler(logfile):
if not os.path.exists(logfile):
dnf.util.ensure_dir(os.path.dirname(logfile))
dnf.util.touch(logfile)
# By default, make logfiles readable by the user (so the reporting ABRT
# user can attach root logfiles).
os.chmod(logfile, 0o644)
handler = logging.FileHandler(logfile)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s",
"%Y-%m-%dT%H:%M:%SZ")
formatter.converter = time.gmtime
handler.setFormatter(formatter)
return handler
def _paint_mark(logger):
logger.log(INFO, dnf.const.LOG_MARKER)
class Logging(object):
def __init__(self):
self.stdout_handler = self.stderr_handler = None
@only_once
def _presetup(self):
logging.addLevelName(DDEBUG, "DDEBUG")
logging.addLevelName(SUBDEBUG, "SUBDEBUG")
logging.addLevelName(TRACE, "TRACE")
logger_dnf = logging.getLogger("dnf")
logger_dnf.setLevel(TRACE)
# setup stdout
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(INFO)
stdout.addFilter(_MaxLevelFilter(logging.WARNING))
logger_dnf.addHandler(stdout)
self.stdout_handler = stdout
# setup stderr
stderr = logging.StreamHandler(sys.stderr)
stderr.setLevel(WARNING)
logger_dnf.addHandler(stderr)
self.stderr_handler = stderr
@only_once
def _setup(self, verbose_level, error_level, logdir):
self._presetup()
logger_dnf = logging.getLogger("dnf")
# setup file logger
logfile = os.path.join(logdir, dnf.const.LOG)
handler = _create_filehandler(logfile)
logger_dnf.addHandler(handler)
# temporarily turn off stdout/stderr handlers:
self.stdout_handler.setLevel(SUPERCRITICAL)
self.stderr_handler.setLevel(SUPERCRITICAL)
# put the marker in the file now:
_paint_mark(logger_dnf)
# setup Python warnings
logging.captureWarnings(True)
logger_warnings = logging.getLogger("py.warnings")
logger_warnings.addHandler(self.stderr_handler)
logger_warnings.addHandler(handler)
lr_logfile = os.path.join(logdir, dnf.const.LOG_LIBREPO)
libdnf.repo.LibrepoLog.addHandler(lr_logfile, verbose_level <= DEBUG)
# setup RPM callbacks logger
logger_rpm = logging.getLogger("dnf.rpm")
logger_rpm.propagate = False
logger_rpm.setLevel(SUBDEBUG)
logfile = os.path.join(logdir, dnf.const.LOG_RPM)
handler = _create_filehandler(logfile)
logger_rpm.addHandler(self.stdout_handler)
logger_rpm.addHandler(self.stderr_handler)
logger_rpm.addHandler(handler)
_paint_mark(logger_rpm)
# bring std handlers to the preferred level
self.stdout_handler.setLevel(verbose_level)
self.stderr_handler.setLevel(error_level)
logging.raiseExceptions = False
def _setup_from_dnf_conf(self, conf):
verbose_level_r = _cfg_verbose_val2level(conf.debuglevel)
error_level_r = _cfg_err_val2level(conf.errorlevel)
logdir = conf.logdir
return self._setup(verbose_level_r, error_level_r, logdir)
class Timer(object):
def __init__(self, what):
self.what = what
self.start = time.time()
def __call__(self):
diff = time.time() - self.start
msg = 'timer: %s: %d ms' % (self.what, diff * 1000)
logging.getLogger("dnf").log(DDEBUG, msg)
_LIBDNF_TO_DNF_LOGLEVEL_MAPPING = {
libdnf.utils.Logger.Level_CRITICAL: CRITICAL,
libdnf.utils.Logger.Level_ERROR: ERROR,
libdnf.utils.Logger.Level_WARNING: WARNING,
libdnf.utils.Logger.Level_NOTICE: INFO,
libdnf.utils.Logger.Level_INFO: INFO,
libdnf.utils.Logger.Level_DEBUG: DEBUG,
libdnf.utils.Logger.Level_TRACE: TRACE
}
class LibdnfLoggerCB(libdnf.utils.Logger):
def __init__(self):
super(LibdnfLoggerCB, self).__init__()
self._logger = logging.getLogger("dnf")
def write(self, source, *args):
"""Log message.
source -- integer, defines origin (libdnf, librepo, ...) of message, 0 - unknown
"""
if len(args) == 2:
level, message = args
elif len(args) == 4:
time, pid, level, message = args
self._logger.log(_LIBDNF_TO_DNF_LOGLEVEL_MAPPING[level], message)
libdnfLoggerCB = LibdnfLoggerCB()
libdnf.utils.Log.setLogger(libdnfLoggerCB)
| return 0 | conditional_block |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import dnf.const
import dnf.util
import libdnf.repo
import logging
import os
import sys
import time
import warnings
# :api loggers are: 'dnf', 'dnf.plugin', 'dnf.rpm'
SUPERCRITICAL = 100 # do not use this for logging
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
DDEBUG = 8
SUBDEBUG = 6
TRACE = 4
def only_once(func):
|
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno >= self.max_level:
return 0
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the default
3 : logging.DEBUG,
4 : logging.DEBUG,
5 : logging.DEBUG,
6 : logging.DEBUG, # verbose value
}
def _cfg_verbose_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _VERBOSE_VAL_MAPPING.get(cfg_errval, DDEBUG)
# Both the DNF default and the verbose default are WARNING. Note that ERROR has
# no specific level.
_ERR_VAL_MAPPING = {
0: SUPERCRITICAL,
1: logging.CRITICAL,
2: logging.ERROR
}
def _cfg_err_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _ERR_VAL_MAPPING.get(cfg_errval, logging.WARNING)
def _create_filehandler(logfile):
if not os.path.exists(logfile):
dnf.util.ensure_dir(os.path.dirname(logfile))
dnf.util.touch(logfile)
# By default, make logfiles readable by the user (so the reporting ABRT
# user can attach root logfiles).
os.chmod(logfile, 0o644)
handler = logging.FileHandler(logfile)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s",
"%Y-%m-%dT%H:%M:%SZ")
formatter.converter = time.gmtime
handler.setFormatter(formatter)
return handler
def _paint_mark(logger):
logger.log(INFO, dnf.const.LOG_MARKER)
class Logging(object):
def __init__(self):
self.stdout_handler = self.stderr_handler = None
@only_once
def _presetup(self):
logging.addLevelName(DDEBUG, "DDEBUG")
logging.addLevelName(SUBDEBUG, "SUBDEBUG")
logging.addLevelName(TRACE, "TRACE")
logger_dnf = logging.getLogger("dnf")
logger_dnf.setLevel(TRACE)
# setup stdout
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(INFO)
stdout.addFilter(_MaxLevelFilter(logging.WARNING))
logger_dnf.addHandler(stdout)
self.stdout_handler = stdout
# setup stderr
stderr = logging.StreamHandler(sys.stderr)
stderr.setLevel(WARNING)
logger_dnf.addHandler(stderr)
self.stderr_handler = stderr
@only_once
def _setup(self, verbose_level, error_level, logdir):
self._presetup()
logger_dnf = logging.getLogger("dnf")
# setup file logger
logfile = os.path.join(logdir, dnf.const.LOG)
handler = _create_filehandler(logfile)
logger_dnf.addHandler(handler)
# temporarily turn off stdout/stderr handlers:
self.stdout_handler.setLevel(SUPERCRITICAL)
self.stderr_handler.setLevel(SUPERCRITICAL)
# put the marker in the file now:
_paint_mark(logger_dnf)
# setup Python warnings
logging.captureWarnings(True)
logger_warnings = logging.getLogger("py.warnings")
logger_warnings.addHandler(self.stderr_handler)
logger_warnings.addHandler(handler)
lr_logfile = os.path.join(logdir, dnf.const.LOG_LIBREPO)
libdnf.repo.LibrepoLog.addHandler(lr_logfile, verbose_level <= DEBUG)
# setup RPM callbacks logger
logger_rpm = logging.getLogger("dnf.rpm")
logger_rpm.propagate = False
logger_rpm.setLevel(SUBDEBUG)
logfile = os.path.join(logdir, dnf.const.LOG_RPM)
handler = _create_filehandler(logfile)
logger_rpm.addHandler(self.stdout_handler)
logger_rpm.addHandler(self.stderr_handler)
logger_rpm.addHandler(handler)
_paint_mark(logger_rpm)
# bring std handlers to the preferred level
self.stdout_handler.setLevel(verbose_level)
self.stderr_handler.setLevel(error_level)
logging.raiseExceptions = False
def _setup_from_dnf_conf(self, conf):
verbose_level_r = _cfg_verbose_val2level(conf.debuglevel)
error_level_r = _cfg_err_val2level(conf.errorlevel)
logdir = conf.logdir
return self._setup(verbose_level_r, error_level_r, logdir)
class Timer(object):
def __init__(self, what):
self.what = what
self.start = time.time()
def __call__(self):
diff = time.time() - self.start
msg = 'timer: %s: %d ms' % (self.what, diff * 1000)
logging.getLogger("dnf").log(DDEBUG, msg)
_LIBDNF_TO_DNF_LOGLEVEL_MAPPING = {
libdnf.utils.Logger.Level_CRITICAL: CRITICAL,
libdnf.utils.Logger.Level_ERROR: ERROR,
libdnf.utils.Logger.Level_WARNING: WARNING,
libdnf.utils.Logger.Level_NOTICE: INFO,
libdnf.utils.Logger.Level_INFO: INFO,
libdnf.utils.Logger.Level_DEBUG: DEBUG,
libdnf.utils.Logger.Level_TRACE: TRACE
}
class LibdnfLoggerCB(libdnf.utils.Logger):
def __init__(self):
super(LibdnfLoggerCB, self).__init__()
self._logger = logging.getLogger("dnf")
def write(self, source, *args):
"""Log message.
source -- integer, defines origin (libdnf, librepo, ...) of message, 0 - unknown
"""
if len(args) == 2:
level, message = args
elif len(args) == 4:
time, pid, level, message = args
self._logger.log(_LIBDNF_TO_DNF_LOGLEVEL_MAPPING[level], message)
libdnfLoggerCB = LibdnfLoggerCB()
libdnf.utils.Log.setLogger(libdnfLoggerCB)
| """Method decorator turning the method into noop on second or later calls."""
def noop(*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song | identifier_body |
logging.py | # logging.py
# DNF Logging Subsystem.
#
# Copyright (C) 2013-2016 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties 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, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
from __future__ import absolute_import
from __future__ import unicode_literals
import dnf.exceptions
import dnf.const
import dnf.util
import libdnf.repo
import logging
import os
import sys
import time
import warnings
# :api loggers are: 'dnf', 'dnf.plugin', 'dnf.rpm'
SUPERCRITICAL = 100 # do not use this for logging
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
DDEBUG = 8
SUBDEBUG = 6
TRACE = 4
def only_once(func):
"""Method decorator turning the method into noop on second or later calls."""
def | (*_args, **_kwargs):
pass
def swan_song(self, *args, **kwargs):
func(self, *args, **kwargs)
setattr(self, func.__name__, noop)
return swan_song
class _MaxLevelFilter(object):
def __init__(self, max_level):
self.max_level = max_level
def filter(self, record):
if record.levelno >= self.max_level:
return 0
return 1
_VERBOSE_VAL_MAPPING = {
0 : SUPERCRITICAL,
1 : logging.INFO,
2 : logging.INFO, # the default
3 : logging.DEBUG,
4 : logging.DEBUG,
5 : logging.DEBUG,
6 : logging.DEBUG, # verbose value
}
def _cfg_verbose_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _VERBOSE_VAL_MAPPING.get(cfg_errval, DDEBUG)
# Both the DNF default and the verbose default are WARNING. Note that ERROR has
# no specific level.
_ERR_VAL_MAPPING = {
0: SUPERCRITICAL,
1: logging.CRITICAL,
2: logging.ERROR
}
def _cfg_err_val2level(cfg_errval):
assert 0 <= cfg_errval <= 10
return _ERR_VAL_MAPPING.get(cfg_errval, logging.WARNING)
def _create_filehandler(logfile):
if not os.path.exists(logfile):
dnf.util.ensure_dir(os.path.dirname(logfile))
dnf.util.touch(logfile)
# By default, make logfiles readable by the user (so the reporting ABRT
# user can attach root logfiles).
os.chmod(logfile, 0o644)
handler = logging.FileHandler(logfile)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s",
"%Y-%m-%dT%H:%M:%SZ")
formatter.converter = time.gmtime
handler.setFormatter(formatter)
return handler
def _paint_mark(logger):
logger.log(INFO, dnf.const.LOG_MARKER)
class Logging(object):
def __init__(self):
self.stdout_handler = self.stderr_handler = None
@only_once
def _presetup(self):
logging.addLevelName(DDEBUG, "DDEBUG")
logging.addLevelName(SUBDEBUG, "SUBDEBUG")
logging.addLevelName(TRACE, "TRACE")
logger_dnf = logging.getLogger("dnf")
logger_dnf.setLevel(TRACE)
# setup stdout
stdout = logging.StreamHandler(sys.stdout)
stdout.setLevel(INFO)
stdout.addFilter(_MaxLevelFilter(logging.WARNING))
logger_dnf.addHandler(stdout)
self.stdout_handler = stdout
# setup stderr
stderr = logging.StreamHandler(sys.stderr)
stderr.setLevel(WARNING)
logger_dnf.addHandler(stderr)
self.stderr_handler = stderr
@only_once
def _setup(self, verbose_level, error_level, logdir):
self._presetup()
logger_dnf = logging.getLogger("dnf")
# setup file logger
logfile = os.path.join(logdir, dnf.const.LOG)
handler = _create_filehandler(logfile)
logger_dnf.addHandler(handler)
# temporarily turn off stdout/stderr handlers:
self.stdout_handler.setLevel(SUPERCRITICAL)
self.stderr_handler.setLevel(SUPERCRITICAL)
# put the marker in the file now:
_paint_mark(logger_dnf)
# setup Python warnings
logging.captureWarnings(True)
logger_warnings = logging.getLogger("py.warnings")
logger_warnings.addHandler(self.stderr_handler)
logger_warnings.addHandler(handler)
lr_logfile = os.path.join(logdir, dnf.const.LOG_LIBREPO)
libdnf.repo.LibrepoLog.addHandler(lr_logfile, verbose_level <= DEBUG)
# setup RPM callbacks logger
logger_rpm = logging.getLogger("dnf.rpm")
logger_rpm.propagate = False
logger_rpm.setLevel(SUBDEBUG)
logfile = os.path.join(logdir, dnf.const.LOG_RPM)
handler = _create_filehandler(logfile)
logger_rpm.addHandler(self.stdout_handler)
logger_rpm.addHandler(self.stderr_handler)
logger_rpm.addHandler(handler)
_paint_mark(logger_rpm)
# bring std handlers to the preferred level
self.stdout_handler.setLevel(verbose_level)
self.stderr_handler.setLevel(error_level)
logging.raiseExceptions = False
def _setup_from_dnf_conf(self, conf):
verbose_level_r = _cfg_verbose_val2level(conf.debuglevel)
error_level_r = _cfg_err_val2level(conf.errorlevel)
logdir = conf.logdir
return self._setup(verbose_level_r, error_level_r, logdir)
class Timer(object):
def __init__(self, what):
self.what = what
self.start = time.time()
def __call__(self):
diff = time.time() - self.start
msg = 'timer: %s: %d ms' % (self.what, diff * 1000)
logging.getLogger("dnf").log(DDEBUG, msg)
_LIBDNF_TO_DNF_LOGLEVEL_MAPPING = {
libdnf.utils.Logger.Level_CRITICAL: CRITICAL,
libdnf.utils.Logger.Level_ERROR: ERROR,
libdnf.utils.Logger.Level_WARNING: WARNING,
libdnf.utils.Logger.Level_NOTICE: INFO,
libdnf.utils.Logger.Level_INFO: INFO,
libdnf.utils.Logger.Level_DEBUG: DEBUG,
libdnf.utils.Logger.Level_TRACE: TRACE
}
class LibdnfLoggerCB(libdnf.utils.Logger):
def __init__(self):
super(LibdnfLoggerCB, self).__init__()
self._logger = logging.getLogger("dnf")
def write(self, source, *args):
"""Log message.
source -- integer, defines origin (libdnf, librepo, ...) of message, 0 - unknown
"""
if len(args) == 2:
level, message = args
elif len(args) == 4:
time, pid, level, message = args
self._logger.log(_LIBDNF_TO_DNF_LOGLEVEL_MAPPING[level], message)
libdnfLoggerCB = LibdnfLoggerCB()
libdnf.utils.Log.setLogger(libdnfLoggerCB)
| noop | identifier_name |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy; | const VERSION: &'static str = "1.7.1";
fn main() {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = Vec::new();
let mut handle = Easy::new();
handle
.url(&format!(
"https://github.com/apache/kudu/archive/{}.tar.gz",
VERSION
)).expect("failed to configure Kudu tarball URL");
handle
.follow_location(true)
.expect("failed to configure follow location");
{
let mut transfer = handle.transfer();
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).expect("failed to write download data");
transfer
.perform()
.expect("failed to download Kudu source tarball");
}
Archive::new(GzDecoder::new(Cursor::new(data)))
.unpack(target)
.expect("failed to unpack Kudu source tarball");
}
prost_build::Config::new()
.service_generator(Box::new(krpc_build::KrpcServiceGenerator))
.compile_protos(
&[
dir.join("src/kudu/client/client.proto"),
dir.join("src/kudu/consensus/metadata.proto"),
dir.join("src/kudu/master/master.proto"),
dir.join("src/kudu/rpc/rpc_header.proto"),
dir.join("src/kudu/tools/tool.proto"),
dir.join("src/kudu/tserver/tserver_service.proto"),
],
&[dir.join("src")],
).unwrap();
} | use flate2::bufread::GzDecoder;
use tar::Archive;
| random_line_split |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn | () {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = Vec::new();
let mut handle = Easy::new();
handle
.url(&format!(
"https://github.com/apache/kudu/archive/{}.tar.gz",
VERSION
)).expect("failed to configure Kudu tarball URL");
handle
.follow_location(true)
.expect("failed to configure follow location");
{
let mut transfer = handle.transfer();
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).expect("failed to write download data");
transfer
.perform()
.expect("failed to download Kudu source tarball");
}
Archive::new(GzDecoder::new(Cursor::new(data)))
.unpack(target)
.expect("failed to unpack Kudu source tarball");
}
prost_build::Config::new()
.service_generator(Box::new(krpc_build::KrpcServiceGenerator))
.compile_protos(
&[
dir.join("src/kudu/client/client.proto"),
dir.join("src/kudu/consensus/metadata.proto"),
dir.join("src/kudu/master/master.proto"),
dir.join("src/kudu/rpc/rpc_header.proto"),
dir.join("src/kudu/tools/tool.proto"),
dir.join("src/kudu/tserver/tserver_service.proto"),
],
&[dir.join("src")],
).unwrap();
}
| main | identifier_name |
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn main() | {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() {
let mut data = Vec::new();
let mut handle = Easy::new();
handle
.url(&format!(
"https://github.com/apache/kudu/archive/{}.tar.gz",
VERSION
)).expect("failed to configure Kudu tarball URL");
handle
.follow_location(true)
.expect("failed to configure follow location");
{
let mut transfer = handle.transfer();
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).expect("failed to write download data");
transfer
.perform()
.expect("failed to download Kudu source tarball");
}
Archive::new(GzDecoder::new(Cursor::new(data)))
.unpack(target)
.expect("failed to unpack Kudu source tarball");
}
prost_build::Config::new()
.service_generator(Box::new(krpc_build::KrpcServiceGenerator))
.compile_protos(
&[
dir.join("src/kudu/client/client.proto"),
dir.join("src/kudu/consensus/metadata.proto"),
dir.join("src/kudu/master/master.proto"),
dir.join("src/kudu/rpc/rpc_header.proto"),
dir.join("src/kudu/tools/tool.proto"),
dir.join("src/kudu/tserver/tserver_service.proto"),
],
&[dir.join("src")],
).unwrap();
} | identifier_body |
|
build.rs | extern crate curl;
extern crate env_logger;
extern crate flate2;
extern crate krpc_build;
extern crate prost_build;
extern crate tar;
use std::env;
use std::io::Cursor;
use std::path::PathBuf;
use curl::easy::Easy;
use flate2::bufread::GzDecoder;
use tar::Archive;
const VERSION: &'static str = "1.7.1";
fn main() {
env_logger::init();
let target = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR environment variable not set"));
let dir = target.join(format!("kudu-{}", VERSION));
// Download the Kudu source tarball.
if !dir.exists() |
prost_build::Config::new()
.service_generator(Box::new(krpc_build::KrpcServiceGenerator))
.compile_protos(
&[
dir.join("src/kudu/client/client.proto"),
dir.join("src/kudu/consensus/metadata.proto"),
dir.join("src/kudu/master/master.proto"),
dir.join("src/kudu/rpc/rpc_header.proto"),
dir.join("src/kudu/tools/tool.proto"),
dir.join("src/kudu/tserver/tserver_service.proto"),
],
&[dir.join("src")],
).unwrap();
}
| {
let mut data = Vec::new();
let mut handle = Easy::new();
handle
.url(&format!(
"https://github.com/apache/kudu/archive/{}.tar.gz",
VERSION
)).expect("failed to configure Kudu tarball URL");
handle
.follow_location(true)
.expect("failed to configure follow location");
{
let mut transfer = handle.transfer();
transfer
.write_function(|new_data| {
data.extend_from_slice(new_data);
Ok(new_data.len())
}).expect("failed to write download data");
transfer
.perform()
.expect("failed to download Kudu source tarball");
}
Archive::new(GzDecoder::new(Cursor::new(data)))
.unpack(target)
.expect("failed to unpack Kudu source tarball");
} | conditional_block |
deleteFile.json.js | //This script is to delete a resource within the node
var deleteFile = exports;
deleteFile.handle = function(req, res, pathInfo, resource) {
const filename = pathInfo.parameters.name || pathInfo.parameters.filename;
if (filename == undefined)
{
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The url-parameter [name] is not set. This parameter defines the filename within the selected resource.");
res.end();
}
else if (!resource.isAuthorized("delete"))
{
res.writeHead(401, {"Content-Type": "text/plain; charset=utf-8"});
res.write("User is not authorized to delete here files and resources.");
res.end();
}
else
{
resource.fileExists(filename).then(function() {
return resource.deleteFile(filename);
}).then(function() {
return resource.getFiles(true);
}).then(function(fileList){ | res.end();
}).fail(function() {
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The resource [" + filename + "] does not exists within [" + resource.path + "]");
res.end();
});
}
}; | res.writeHead(200, {"Content-Type": "application/json; charset=utf-8"});
res.write(JSON.stringify(fileList)); | random_line_split |
deleteFile.json.js | //This script is to delete a resource within the node
var deleteFile = exports;
deleteFile.handle = function(req, res, pathInfo, resource) {
const filename = pathInfo.parameters.name || pathInfo.parameters.filename;
if (filename == undefined)
|
else if (!resource.isAuthorized("delete"))
{
res.writeHead(401, {"Content-Type": "text/plain; charset=utf-8"});
res.write("User is not authorized to delete here files and resources.");
res.end();
}
else
{
resource.fileExists(filename).then(function() {
return resource.deleteFile(filename);
}).then(function() {
return resource.getFiles(true);
}).then(function(fileList){
res.writeHead(200, {"Content-Type": "application/json; charset=utf-8"});
res.write(JSON.stringify(fileList));
res.end();
}).fail(function() {
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The resource [" + filename + "] does not exists within [" + resource.path + "]");
res.end();
});
}
};
| {
res.writeHead(500, {"Content-Type": "text/plain; charset=utf-8"});
res.write("The url-parameter [name] is not set. This parameter defines the filename within the selected resource.");
res.end();
} | conditional_block |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from pyven.utils.parallelizer import Parallelizer
from pyven.exceptions.exception import PyvenException
class Step(object):
LOCAL_REPO = None
WORKSPACE = None
PROJECTS = []
def __init__(self, verbose=False):
self.verbose = verbose
self.name = None
self.checker = None
self.status = pyven.constants.STATUS[2]
@staticmethod
def log_delimiter(path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = function(self)
if ok:
self.status = pyven.constants.STATUS[0]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : SUCCESSFUL')
Step.log_delimiter()
else:
self.status = pyven.constants.STATUS[1]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : FAILED')
Step.log_delimiter()
return ok
return _intern
@staticmethod
def error_checks(function):
def _intern(self, project):
ok = True
Logger.set_format(project)
try:
try:
if project.path != os.getcwd():
if not os.path.isdir(project.path):
raise PyvenException('Subproject path does not exist : ' + project.path)
tic = time.time()
ok = function(self, project)
toc = time.time()
Logger.get().info('Step time : ' + str(round(toc - tic, 3)) + ' seconds')
except PyvenException as e:
self.checker.errors.append(e.args)
ok = False
finally:
Logger.set_format()
return ok
return _intern
@step
def _process_parallel(self):
self.checker.status = pyven.constants.STATUS[2]
threads = []
for project in Step.PROJECTS:
threads.append(Thread(target=self._process, args=(project,)))
parallelizer = Parallelizer(threads, self.nb_threads)
parallelizer.run()
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if project.status in pyven.constants.STATUS[1:]:
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
@step
def _process_sequential(self):
self.checker.status = pyven.constants.STATUS[2]
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if not self._process(project):
|
return self.status == pyven.constants.STATUS[0]
def process(self):
raise NotImplementedError('Step process method not implemented')
def report_status(self):
if self.status == pyven.constants.STATUS[0]:
return Success()
elif self.status == pyven.constants.STATUS[1]:
return Failure()
else:
return Unknown()
def _process(self, project):
raise NotImplementedError
def reportables(self):
raise NotImplementedError
def content(self):
raise NotImplementedError
def report(self):
return self.status != pyven.constants.STATUS[2]
def title(self):
return Title(self.name) | self.status = pyven.constants.STATUS[1] | conditional_block |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from pyven.utils.parallelizer import Parallelizer
from pyven.exceptions.exception import PyvenException
class Step(object):
LOCAL_REPO = None
WORKSPACE = None
PROJECTS = []
def __init__(self, verbose=False):
|
@staticmethod
def log_delimiter(path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = function(self)
if ok:
self.status = pyven.constants.STATUS[0]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : SUCCESSFUL')
Step.log_delimiter()
else:
self.status = pyven.constants.STATUS[1]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : FAILED')
Step.log_delimiter()
return ok
return _intern
@staticmethod
def error_checks(function):
def _intern(self, project):
ok = True
Logger.set_format(project)
try:
try:
if project.path != os.getcwd():
if not os.path.isdir(project.path):
raise PyvenException('Subproject path does not exist : ' + project.path)
tic = time.time()
ok = function(self, project)
toc = time.time()
Logger.get().info('Step time : ' + str(round(toc - tic, 3)) + ' seconds')
except PyvenException as e:
self.checker.errors.append(e.args)
ok = False
finally:
Logger.set_format()
return ok
return _intern
@step
def _process_parallel(self):
self.checker.status = pyven.constants.STATUS[2]
threads = []
for project in Step.PROJECTS:
threads.append(Thread(target=self._process, args=(project,)))
parallelizer = Parallelizer(threads, self.nb_threads)
parallelizer.run()
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if project.status in pyven.constants.STATUS[1:]:
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
@step
def _process_sequential(self):
self.checker.status = pyven.constants.STATUS[2]
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if not self._process(project):
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
def process(self):
raise NotImplementedError('Step process method not implemented')
def report_status(self):
if self.status == pyven.constants.STATUS[0]:
return Success()
elif self.status == pyven.constants.STATUS[1]:
return Failure()
else:
return Unknown()
def _process(self, project):
raise NotImplementedError
def reportables(self):
raise NotImplementedError
def content(self):
raise NotImplementedError
def report(self):
return self.status != pyven.constants.STATUS[2]
def title(self):
return Title(self.name) | self.verbose = verbose
self.name = None
self.checker = None
self.status = pyven.constants.STATUS[2] | identifier_body |
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from pyven.utils.parallelizer import Parallelizer
from pyven.exceptions.exception import PyvenException
class Step(object):
LOCAL_REPO = None
WORKSPACE = None
PROJECTS = []
def __init__(self, verbose=False):
self.verbose = verbose
self.name = None
self.checker = None
self.status = pyven.constants.STATUS[2]
@staticmethod
def log_delimiter(path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = function(self)
if ok:
self.status = pyven.constants.STATUS[0]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : SUCCESSFUL')
Step.log_delimiter()
else:
self.status = pyven.constants.STATUS[1]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : FAILED')
Step.log_delimiter()
return ok
return _intern
@staticmethod
def error_checks(function):
def _intern(self, project):
ok = True
Logger.set_format(project)
try:
try:
if project.path != os.getcwd():
if not os.path.isdir(project.path):
raise PyvenException('Subproject path does not exist : ' + project.path)
tic = time.time()
ok = function(self, project)
toc = time.time()
Logger.get().info('Step time : ' + str(round(toc - tic, 3)) + ' seconds')
except PyvenException as e:
self.checker.errors.append(e.args)
ok = False
finally:
Logger.set_format()
return ok
return _intern
@step
def _process_parallel(self):
self.checker.status = pyven.constants.STATUS[2]
threads = []
for project in Step.PROJECTS:
threads.append(Thread(target=self._process, args=(project,)))
parallelizer = Parallelizer(threads, self.nb_threads)
parallelizer.run()
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if project.status in pyven.constants.STATUS[1:]:
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
@step
def _process_sequential(self):
self.checker.status = pyven.constants.STATUS[2]
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if not self._process(project):
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
def process(self):
raise NotImplementedError('Step process method not implemented')
def report_status(self):
if self.status == pyven.constants.STATUS[0]:
return Success()
elif self.status == pyven.constants.STATUS[1]:
return Failure()
else:
return Unknown()
def _process(self, project):
raise NotImplementedError
def reportables(self):
raise NotImplementedError
def content(self):
raise NotImplementedError
def report(self):
return self.status != pyven.constants.STATUS[2]
| def title(self):
return Title(self.name) | random_line_split |
|
step.py | import os, time
from threading import Thread
from pyven.logging.logger import Logger
import pyven.constants
from pyven.reporting.content.success import Success
from pyven.reporting.content.failure import Failure
from pyven.reporting.content.unknown import Unknown
from pyven.reporting.content.title import Title
from pyven.utils.parallelizer import Parallelizer
from pyven.exceptions.exception import PyvenException
class Step(object):
LOCAL_REPO = None
WORKSPACE = None
PROJECTS = []
def __init__(self, verbose=False):
self.verbose = verbose
self.name = None
self.checker = None
self.status = pyven.constants.STATUS[2]
@staticmethod
def | (path=None):
Logger.get().info('===================================')
def step(function):
def _intern(self):
Step.log_delimiter()
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : STARTING')
ok = function(self)
if ok:
self.status = pyven.constants.STATUS[0]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : SUCCESSFUL')
Step.log_delimiter()
else:
self.status = pyven.constants.STATUS[1]
Logger.get().info('STEP ' + self.name.replace('_', ' ').upper() + ' : FAILED')
Step.log_delimiter()
return ok
return _intern
@staticmethod
def error_checks(function):
def _intern(self, project):
ok = True
Logger.set_format(project)
try:
try:
if project.path != os.getcwd():
if not os.path.isdir(project.path):
raise PyvenException('Subproject path does not exist : ' + project.path)
tic = time.time()
ok = function(self, project)
toc = time.time()
Logger.get().info('Step time : ' + str(round(toc - tic, 3)) + ' seconds')
except PyvenException as e:
self.checker.errors.append(e.args)
ok = False
finally:
Logger.set_format()
return ok
return _intern
@step
def _process_parallel(self):
self.checker.status = pyven.constants.STATUS[2]
threads = []
for project in Step.PROJECTS:
threads.append(Thread(target=self._process, args=(project,)))
parallelizer = Parallelizer(threads, self.nb_threads)
parallelizer.run()
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if project.status in pyven.constants.STATUS[1:]:
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
@step
def _process_sequential(self):
self.checker.status = pyven.constants.STATUS[2]
self.status = pyven.constants.STATUS[0]
for project in Step.PROJECTS:
if not self._process(project):
self.status = pyven.constants.STATUS[1]
return self.status == pyven.constants.STATUS[0]
def process(self):
raise NotImplementedError('Step process method not implemented')
def report_status(self):
if self.status == pyven.constants.STATUS[0]:
return Success()
elif self.status == pyven.constants.STATUS[1]:
return Failure()
else:
return Unknown()
def _process(self, project):
raise NotImplementedError
def reportables(self):
raise NotImplementedError
def content(self):
raise NotImplementedError
def report(self):
return self.status != pyven.constants.STATUS[2]
def title(self):
return Title(self.name) | log_delimiter | identifier_name |
generate-mod.rs | // Modules generated by transparent proc macros still acts as barriers for names (issue #50504).
// aux-build:generate-mod.rs
extern crate generate_mod;
struct FromOutside;
generate_mod::check!(); //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `Outer` in this scope
#[generate_mod::check_attr] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterAttr` in this scope
struct S;
#[derive(generate_mod::CheckDerive)] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterDerive` in this scope
//~| WARN this was previously accepted
//~| WARN this was previously accepted
struct Z;
fn inner_block() {
#[derive(generate_mod::CheckDerive)] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterDerive` in this scope
//~| WARN this was previously accepted
//~| WARN this was previously accepted
struct | ;
}
#[derive(generate_mod::CheckDeriveLint)] // OK, lint is suppressed
struct W;
fn main() {}
| InnerZ | identifier_name |
generate-mod.rs | // Modules generated by transparent proc macros still acts as barriers for names (issue #50504).
// aux-build:generate-mod.rs
| struct FromOutside;
generate_mod::check!(); //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `Outer` in this scope
#[generate_mod::check_attr] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterAttr` in this scope
struct S;
#[derive(generate_mod::CheckDerive)] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterDerive` in this scope
//~| WARN this was previously accepted
//~| WARN this was previously accepted
struct Z;
fn inner_block() {
#[derive(generate_mod::CheckDerive)] //~ ERROR cannot find type `FromOutside` in this scope
//~| ERROR cannot find type `OuterDerive` in this scope
//~| WARN this was previously accepted
//~| WARN this was previously accepted
struct InnerZ;
}
#[derive(generate_mod::CheckDeriveLint)] // OK, lint is suppressed
struct W;
fn main() {} | extern crate generate_mod;
| random_line_split |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, 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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import logging # pylint: disable=W0611
import bz2
from twisted.protocols.basic import Int32StringReceiver
from common import common_file
class NetworkEvents(Int32StringReceiver):
"""
Process the network events for the server
"""
# init is called on every connection
def __init__(self, users):
self.MAX_LENGTH = 32000000 # pylint: disable=C0103
self.cpu_use_table = {}
# server info
self.users = users
self.user_host_name = None
self.user_ip_addy = None
self.user_user_name = None
self.user_verified = 0
def connectionMade(self):
"""
Network connection made from client so ask for ident
"""
logging.info('Got Connection')
self.sendString('IDENT')
def connectionLost(self, reason):
"""
Network connection dropped so remove client
"""
logging.info('Lost Connection')
if self.users.has_key(self.user_user_name):
del self.users[self.user_user_name]
def stringReceived(self, data):
"""
Message received from client
"""
msg = None
message_words = data.split(' ')
logging.info('GOT Data: %s', data)
logging.info('Message: %s', message_words[0])
if message_words[0] == "VALIDATE":
# have to create the self.player data so network knows how to send data back
self.user_host_name = message_words[1]
self.user_ip_addy = str(self.transport.getPeer()).split('\'')[1]
self.user_user_name = message_words[1]
self.users[message_words[1]] = self
logging.info("user: %s %s", self.user_host_name, self.user_ip_addy)
# user commands
elif message_words[0] == "LOGIN":
pass
elif message_words[0] == "KODI_LOG":
common_file.com_file_save_data(
'./log_debug/Kodi', bz2.decompress(message_words[1]), False, True, '.log')
| msg = "UNKNOWN_TYPE"
if msg is not None:
logging.info("should be sending data")
self.send_single_user(msg)
def send_single_user(self, message):
"""
Send message to single user
"""
for user_host_name, protocol in self.users.iteritems(): # pylint: disable=W0612
if protocol == self:
logging.info('send single: %s', message)
protocol.sendString(message.encode("utf8"))
break
def send_all_users(self, message):
"""
Send message to all users
"""
for user_host_name, protocol in self.users.iteritems():
if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8")) | elif message_words[0] == "DEBUG_LOG":
common_file.com_file_save_data(
'./log_debug/Debug', bz2.decompress(message_words[1]), False, True, '.log')
else:
logging.error("UNKNOWN TYPE: %s", message_words[0])
| random_line_split |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, 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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import logging # pylint: disable=W0611
import bz2
from twisted.protocols.basic import Int32StringReceiver
from common import common_file
class NetworkEvents(Int32StringReceiver):
"""
Process the network events for the server
"""
# init is called on every connection
def __init__(self, users):
self.MAX_LENGTH = 32000000 # pylint: disable=C0103
self.cpu_use_table = {}
# server info
self.users = users
self.user_host_name = None
self.user_ip_addy = None
self.user_user_name = None
self.user_verified = 0
def connectionMade(self):
"""
Network connection made from client so ask for ident
"""
logging.info('Got Connection')
self.sendString('IDENT')
def connectionLost(self, reason):
"""
Network connection dropped so remove client
"""
logging.info('Lost Connection')
if self.users.has_key(self.user_user_name):
del self.users[self.user_user_name]
def stringReceived(self, data):
"""
Message received from client
"""
msg = None
message_words = data.split(' ')
logging.info('GOT Data: %s', data)
logging.info('Message: %s', message_words[0])
if message_words[0] == "VALIDATE":
# have to create the self.player data so network knows how to send data back
self.user_host_name = message_words[1]
self.user_ip_addy = str(self.transport.getPeer()).split('\'')[1]
self.user_user_name = message_words[1]
self.users[message_words[1]] = self
logging.info("user: %s %s", self.user_host_name, self.user_ip_addy)
# user commands
elif message_words[0] == "LOGIN":
pass
elif message_words[0] == "KODI_LOG":
common_file.com_file_save_data(
'./log_debug/Kodi', bz2.decompress(message_words[1]), False, True, '.log')
elif message_words[0] == "DEBUG_LOG":
common_file.com_file_save_data(
'./log_debug/Debug', bz2.decompress(message_words[1]), False, True, '.log')
else:
logging.error("UNKNOWN TYPE: %s", message_words[0])
msg = "UNKNOWN_TYPE"
if msg is not None:
logging.info("should be sending data")
self.send_single_user(msg)
def send_single_user(self, message):
"""
Send message to single user
"""
for user_host_name, protocol in self.users.iteritems(): # pylint: disable=W0612
if protocol == self:
logging.info('send single: %s', message)
protocol.sendString(message.encode("utf8"))
break
def send_all_users(self, message):
| """
Send message to all users
"""
for user_host_name, protocol in self.users.iteritems():
if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8")) | identifier_body |
|
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, 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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import logging # pylint: disable=W0611
import bz2
from twisted.protocols.basic import Int32StringReceiver
from common import common_file
class NetworkEvents(Int32StringReceiver):
"""
Process the network events for the server
"""
# init is called on every connection
def __init__(self, users):
self.MAX_LENGTH = 32000000 # pylint: disable=C0103
self.cpu_use_table = {}
# server info
self.users = users
self.user_host_name = None
self.user_ip_addy = None
self.user_user_name = None
self.user_verified = 0
def connectionMade(self):
"""
Network connection made from client so ask for ident
"""
logging.info('Got Connection')
self.sendString('IDENT')
def connectionLost(self, reason):
"""
Network connection dropped so remove client
"""
logging.info('Lost Connection')
if self.users.has_key(self.user_user_name):
del self.users[self.user_user_name]
def | (self, data):
"""
Message received from client
"""
msg = None
message_words = data.split(' ')
logging.info('GOT Data: %s', data)
logging.info('Message: %s', message_words[0])
if message_words[0] == "VALIDATE":
# have to create the self.player data so network knows how to send data back
self.user_host_name = message_words[1]
self.user_ip_addy = str(self.transport.getPeer()).split('\'')[1]
self.user_user_name = message_words[1]
self.users[message_words[1]] = self
logging.info("user: %s %s", self.user_host_name, self.user_ip_addy)
# user commands
elif message_words[0] == "LOGIN":
pass
elif message_words[0] == "KODI_LOG":
common_file.com_file_save_data(
'./log_debug/Kodi', bz2.decompress(message_words[1]), False, True, '.log')
elif message_words[0] == "DEBUG_LOG":
common_file.com_file_save_data(
'./log_debug/Debug', bz2.decompress(message_words[1]), False, True, '.log')
else:
logging.error("UNKNOWN TYPE: %s", message_words[0])
msg = "UNKNOWN_TYPE"
if msg is not None:
logging.info("should be sending data")
self.send_single_user(msg)
def send_single_user(self, message):
"""
Send message to single user
"""
for user_host_name, protocol in self.users.iteritems(): # pylint: disable=W0612
if protocol == self:
logging.info('send single: %s', message)
protocol.sendString(message.encode("utf8"))
break
def send_all_users(self, message):
"""
Send message to all users
"""
for user_host_name, protocol in self.users.iteritems():
if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8"))
| stringReceived | identifier_name |
network_base_string_weblog.py | '''
Copyright (C) 2016 Quinn D Granfor <[email protected]>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, 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 version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import absolute_import, division, print_function, unicode_literals
import logging # pylint: disable=W0611
import bz2
from twisted.protocols.basic import Int32StringReceiver
from common import common_file
class NetworkEvents(Int32StringReceiver):
"""
Process the network events for the server
"""
# init is called on every connection
def __init__(self, users):
self.MAX_LENGTH = 32000000 # pylint: disable=C0103
self.cpu_use_table = {}
# server info
self.users = users
self.user_host_name = None
self.user_ip_addy = None
self.user_user_name = None
self.user_verified = 0
def connectionMade(self):
"""
Network connection made from client so ask for ident
"""
logging.info('Got Connection')
self.sendString('IDENT')
def connectionLost(self, reason):
"""
Network connection dropped so remove client
"""
logging.info('Lost Connection')
if self.users.has_key(self.user_user_name):
del self.users[self.user_user_name]
def stringReceived(self, data):
"""
Message received from client
"""
msg = None
message_words = data.split(' ')
logging.info('GOT Data: %s', data)
logging.info('Message: %s', message_words[0])
if message_words[0] == "VALIDATE":
# have to create the self.player data so network knows how to send data back
self.user_host_name = message_words[1]
self.user_ip_addy = str(self.transport.getPeer()).split('\'')[1]
self.user_user_name = message_words[1]
self.users[message_words[1]] = self
logging.info("user: %s %s", self.user_host_name, self.user_ip_addy)
# user commands
elif message_words[0] == "LOGIN":
pass
elif message_words[0] == "KODI_LOG":
common_file.com_file_save_data(
'./log_debug/Kodi', bz2.decompress(message_words[1]), False, True, '.log')
elif message_words[0] == "DEBUG_LOG":
common_file.com_file_save_data(
'./log_debug/Debug', bz2.decompress(message_words[1]), False, True, '.log')
else:
logging.error("UNKNOWN TYPE: %s", message_words[0])
msg = "UNKNOWN_TYPE"
if msg is not None:
logging.info("should be sending data")
self.send_single_user(msg)
def send_single_user(self, message):
"""
Send message to single user
"""
for user_host_name, protocol in self.users.iteritems(): # pylint: disable=W0612
if protocol == self:
logging.info('send single: %s', message)
protocol.sendString(message.encode("utf8"))
break
def send_all_users(self, message):
"""
Send message to all users
"""
for user_host_name, protocol in self.users.iteritems():
| if self.users[user_host_name].user_verified == 1:
logging.info('send all: %s', message)
protocol.sendString(message.encode("utf8")) | conditional_block |
|
functions.ts | 'use strict';
export var t = function appendText(e: HTMLElement, text: string, doc: HTMLDocument) {
return e.appendChild(doc.createTextNode(text));
}
export var tst = function appendTest() {
/* global window */
return window.document.body && (window.document.body.insertAdjacentElement);
} | e.appendChild(node);
return node;
}
export var aens = function alternateAppendNs(e: HTMLElement, name: string, ns: string, doc: HTMLDocument) {
var node = doc.createElementNS(ns, name);
e.appendChild(node);
return node;
}
export var e = function appendElement(e: HTMLElement, name: string, doc: HTMLDocument) {
var node = doc.createElement(name);
e.insertAdjacentElement('beforeEnd', node);
return node;
}
export var ens = function appendElementNs(e: HTMLElement, name: string, ns: string, doc: HTMLDocument) {
var node = doc.createElementNS(ns, name);
e.insertAdjacentElement('beforeEnd', node);
return node;
} | export var ae = function alternateAppend(e:HTMLElement, name: string, doc: HTMLDocument) {
var node = doc.createElement(name); | random_line_split |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn get_input() -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_springdroid(state: &mut ProgramState, script: &str) -> DroidResult {
let inputs = script.lines()
.map(|line| line.trim())
.filter(|line| line.len() > 0 && line.chars().next().unwrap() != '#')
.flat_map(|instruction| instruction.chars().chain(iter::once('\n')))
.map(|c| c as i64);
let (outputs, _) = run_program_with_inputs(state, inputs);
match outputs.last() {
Some(&x) if x > u8::max_value() as i64 => {
DroidResult::Success(x)
},
_ => {
DroidResult::Fail(
outputs.iter()
.map(|&c| c as u8 as char)
.fold(String::new(), |mut acc, c| {
acc.push(c);
acc
})
)
}
}
}
fn main() {
let input = get_input().unwrap();
let program = input.split(',')
.filter_map(|x| x.trim().parse::<i64>().ok())
.collect::<Vec<_>>();
let springscript = "
# There's a hole in ABC
NOT A J
NOT J J
AND B J
AND C J
NOT J J
# and D is not a hole
AND D J
WALK
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 1: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
let springscript = "
# (
# E and I are not holes
OR E J
AND I J
# )
| # E and F are not holes
OR E T
AND F T
# )
OR T J
OR H J
# (
# There's a hole in ABC
NOT A T
NOT T T
AND B T
AND C T
NOT T T
# and D is not a hole
AND D T
# )
AND T J
RUN
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 2: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
} | # ( | random_line_split |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn | () -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_springdroid(state: &mut ProgramState, script: &str) -> DroidResult {
let inputs = script.lines()
.map(|line| line.trim())
.filter(|line| line.len() > 0 && line.chars().next().unwrap() != '#')
.flat_map(|instruction| instruction.chars().chain(iter::once('\n')))
.map(|c| c as i64);
let (outputs, _) = run_program_with_inputs(state, inputs);
match outputs.last() {
Some(&x) if x > u8::max_value() as i64 => {
DroidResult::Success(x)
},
_ => {
DroidResult::Fail(
outputs.iter()
.map(|&c| c as u8 as char)
.fold(String::new(), |mut acc, c| {
acc.push(c);
acc
})
)
}
}
}
fn main() {
let input = get_input().unwrap();
let program = input.split(',')
.filter_map(|x| x.trim().parse::<i64>().ok())
.collect::<Vec<_>>();
let springscript = "
# There's a hole in ABC
NOT A J
NOT J J
AND B J
AND C J
NOT J J
# and D is not a hole
AND D J
WALK
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 1: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
let springscript = "
# (
# E and I are not holes
OR E J
AND I J
# )
# (
# E and F are not holes
OR E T
AND F T
# )
OR T J
OR H J
# (
# There's a hole in ABC
NOT A T
NOT T T
AND B T
AND C T
NOT T T
# and D is not a hole
AND D T
# )
AND T J
RUN
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 2: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
}
| get_input | identifier_name |
21.rs | use std::fs::File;
use std::io::prelude::*;
use std::iter;
mod intcode;
use intcode::*;
#[derive(Debug, Clone)]
enum DroidResult {
Fail(String),
Success(i64)
}
fn get_input() -> std::io::Result<String> {
let mut file = File::open("21.txt")?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn run_springdroid(state: &mut ProgramState, script: &str) -> DroidResult {
let inputs = script.lines()
.map(|line| line.trim())
.filter(|line| line.len() > 0 && line.chars().next().unwrap() != '#')
.flat_map(|instruction| instruction.chars().chain(iter::once('\n')))
.map(|c| c as i64);
let (outputs, _) = run_program_with_inputs(state, inputs);
match outputs.last() {
Some(&x) if x > u8::max_value() as i64 => | ,
_ => {
DroidResult::Fail(
outputs.iter()
.map(|&c| c as u8 as char)
.fold(String::new(), |mut acc, c| {
acc.push(c);
acc
})
)
}
}
}
fn main() {
let input = get_input().unwrap();
let program = input.split(',')
.filter_map(|x| x.trim().parse::<i64>().ok())
.collect::<Vec<_>>();
let springscript = "
# There's a hole in ABC
NOT A J
NOT J J
AND B J
AND C J
NOT J J
# and D is not a hole
AND D J
WALK
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 1: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
let springscript = "
# (
# E and I are not holes
OR E J
AND I J
# )
# (
# E and F are not holes
OR E T
AND F T
# )
OR T J
OR H J
# (
# There's a hole in ABC
NOT A T
NOT T T
AND B T
AND C T
NOT T T
# and D is not a hole
AND D T
# )
AND T J
RUN
";
let result = run_springdroid(&mut ProgramState::new(program.clone()), springscript);
match result {
DroidResult::Success(x) => println!("Part 2: {}", x),
DroidResult::Fail(msg) => println!("Failure: {}", msg)
}
}
| {
DroidResult::Success(x)
} | conditional_block |
dont_promote_unstable_const_fn.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
const fn foo() -> u32 { 42 }
fn meh() -> u32 { 42 }
const fn bar() -> u32 { foo() } //~ ERROR `foo` is not yet stable as a const fn
fn a() {
let _: &'static u32 = &foo(); //~ ERROR does not live long enough
}
fn | () {
let _: &'static u32 = &meh(); //~ ERROR does not live long enough
let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not live long enough
}
| main | identifier_name |
dont_promote_unstable_const_fn.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
const fn foo() -> u32 { 42 }
fn meh() -> u32 { 42 }
const fn bar() -> u32 { foo() } //~ ERROR `foo` is not yet stable as a const fn
fn a() {
let _: &'static u32 = &foo(); //~ ERROR does not live long enough
}
fn main() {
let _: &'static u32 = &meh(); //~ ERROR does not live long enough | let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not live long enough
} | random_line_split |
|
dont_promote_unstable_const_fn.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// 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.
#![unstable(feature = "humans",
reason = "who ever let humans program computers,
we're apparently really bad at it",
issue = "0")]
#![feature(rustc_const_unstable, const_fn)]
#![feature(staged_api)]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature="foo")]
const fn foo() -> u32 { 42 }
fn meh() -> u32 { 42 }
const fn bar() -> u32 | //~ ERROR `foo` is not yet stable as a const fn
fn a() {
let _: &'static u32 = &foo(); //~ ERROR does not live long enough
}
fn main() {
let _: &'static u32 = &meh(); //~ ERROR does not live long enough
let x: &'static _ = &std::time::Duration::from_millis(42).subsec_millis();
//~^ ERROR does not live long enough
}
| { foo() } | identifier_body |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.ne.y + (corners.se.y - corners.ne.y) / 2
];
};
// Taken from: http://stackoverflow.com/a/5835212/4068492
function getRectScreenCoords(rect) {
var svg = findParentSVG(rect); | var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
function findParentSVG(node) {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
} | var pt = svg.createSVGPoint(); | random_line_split |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.ne.y + (corners.se.y - corners.ne.y) / 2
];
};
// Taken from: http://stackoverflow.com/a/5835212/4068492
function getRectScreenCoords(rect) {
var svg = findParentSVG(rect);
var pt = svg.createSVGPoint();
var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
function findParentSVG(node) | {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
} | identifier_body |
|
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.ne.y + (corners.se.y - corners.ne.y) / 2
];
};
// Taken from: http://stackoverflow.com/a/5835212/4068492
function getRectScreenCoords(rect) {
var svg = findParentSVG(rect);
var pt = svg.createSVGPoint();
var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
function | (node) {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else {
return findParentSVG(parentNode);
}
}
| findParentSVG | identifier_name |
get_rect_center.js | 'use strict';
/**
* Get the screen coordinates of the center of
* an SVG rectangle node.
*
* @param {rect} rect svg <rect> node
*/
module.exports = function getRectCenter(rect) {
var corners = getRectScreenCoords(rect);
return [
corners.nw.x + (corners.ne.x - corners.nw.x) / 2,
corners.ne.y + (corners.se.y - corners.ne.y) / 2
];
};
// Taken from: http://stackoverflow.com/a/5835212/4068492
function getRectScreenCoords(rect) {
var svg = findParentSVG(rect);
var pt = svg.createSVGPoint();
var corners = {};
var matrix = rect.getScreenCTM();
pt.x = rect.x.animVal.value;
pt.y = rect.y.animVal.value;
corners.nw = pt.matrixTransform(matrix);
pt.x += rect.width.animVal.value;
corners.ne = pt.matrixTransform(matrix);
pt.y += rect.height.animVal.value;
corners.se = pt.matrixTransform(matrix);
pt.x -= rect.width.animVal.value;
corners.sw = pt.matrixTransform(matrix);
return corners;
}
function findParentSVG(node) {
var parentNode = node.parentNode;
if(parentNode.tagName === 'svg') {
return parentNode;
} else |
}
| {
return findParentSVG(parentNode);
} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Dmitry Vyukov.
*/
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
#[cfg(stage0)]
use core::prelude::v1::*;
use alloc::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped
Data(T),
/// The queue is empty
Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> { }
unsafe impl<T: Send> Sync for Queue<T> { }
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn test_full() {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => |
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move|| {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {},
Data(_) => { i += 1 }
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
}
| {} | conditional_block |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Dmitry Vyukov.
*/
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
#[cfg(stage0)]
use core::prelude::v1::*;
use alloc::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped
Data(T),
/// The queue is empty
Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> { }
unsafe impl<T: Send> Sync for Queue<T> { }
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> |
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn test_full() {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move|| {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {},
Data(_) => { i += 1 }
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
}
| {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
} | identifier_body |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Dmitry Vyukov.
*/
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
#[cfg(stage0)]
use core::prelude::v1::*;
use alloc::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped
Data(T),
/// The queue is empty
Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> { }
unsafe impl<T: Send> Sync for Queue<T> { }
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> {
Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn | (&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn test_full() {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move|| {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {},
Data(_) => { i += 1 }
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
}
| pop | identifier_name |
mpsc_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY DMITRY VYUKOV "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 DMITRY VYUKOV 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Dmitry Vyukov.
*/
//! A mostly lock-free multi-producer, single consumer queue.
//!
//! This module contains an implementation of a concurrent MPSC queue. This
//! queue can be used to share data between threads, and is also used as the
//! building block of channels in rust.
//!
//! Note that the current implementation of this queue has a caveat of the `pop`
//! method, and see the method for more information about it. Due to this
//! caveat, this queue may not be appropriate for all use-cases.
// http://www.1024cores.net/home/lock-free-algorithms
// /queues/non-intrusive-mpsc-node-based-queue
pub use self::PopResult::*;
#[cfg(stage0)]
use core::prelude::v1::*;
use alloc::boxed::Box;
use core::ptr;
use core::cell::UnsafeCell;
use sync::atomic::{AtomicPtr, Ordering};
/// A result of the `pop` function.
pub enum PopResult<T> {
/// Some data has been popped
Data(T),
/// The queue is empty
Empty,
/// The queue is in an inconsistent state. Popping data should succeed, but
/// some pushers have yet to make enough progress in order allow a pop to
/// succeed. It is recommended that a pop() occur "in the near future" in
/// order to see if the sender has made progress or not
Inconsistent,
}
struct Node<T> {
next: AtomicPtr<Node<T>>,
value: Option<T>,
}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: AtomicPtr<Node<T>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T: Send> Send for Queue<T> { }
unsafe impl<T: Send> Sync for Queue<T> { } | Box::into_raw(box Node {
next: AtomicPtr::new(ptr::null_mut()),
value: v,
})
}
}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
Queue {
head: AtomicPtr::new(stub),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
pub fn push(&self, t: T) {
unsafe {
let n = Node::new(Some(t));
let prev = self.head.swap(n, Ordering::AcqRel);
(*prev).next.store(n, Ordering::Release);
}
}
/// Pops some data from this queue.
///
/// Note that the current implementation means that this function cannot
/// return `Option<T>`. It is possible for this queue to be in an
/// inconsistent state where many pushes have succeeded and completely
/// finished, but pops cannot return `Some(t)`. This inconsistent state
/// happens when a pusher is pre-empted at an inopportune moment.
///
/// This inconsistent state means that this queue does indeed have data, but
/// it does not currently have access to it at this time.
pub fn pop(&self) -> PopResult<T> {
unsafe {
let tail = *self.tail.get();
let next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let ret = (*next).value.take().unwrap();
let _: Box<Node<T>> = Box::from_raw(tail);
return Data(ret);
}
if self.head.load(Ordering::Acquire) == tail {Empty} else {Inconsistent}
}
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
unsafe {
let mut cur = *self.tail.get();
while !cur.is_null() {
let next = (*cur).next.load(Ordering::Relaxed);
let _: Box<Node<T>> = Box::from_raw(cur);
cur = next;
}
}
}
}
#[cfg(test)]
mod tests {
use prelude::v1::*;
use sync::mpsc::channel;
use super::{Queue, Data, Empty, Inconsistent};
use sync::Arc;
use thread;
#[test]
fn test_full() {
let q: Queue<Box<_>> = Queue::new();
q.push(box 1);
q.push(box 2);
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
Empty => {}
Inconsistent | Data(..) => panic!()
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move|| {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
Empty | Inconsistent => {},
Data(_) => { i += 1 }
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
} |
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> { | random_line_split |
chips-autocomplete-example.ts | import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
/**
* @title Chips Autocomplete
*/
@Component({
selector: 'chips-autocomplete-example',
templateUrl: 'chips-autocomplete-example.html',
styleUrls: ['chips-autocomplete-example.css'],
})
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
separatorKeysCodes: number[] = [ENTER, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string[]>;
fruits: string[] = ['Lemon'];
allFruits: string[] = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
add(event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) |
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}
}
| {
this.fruits.splice(index, 1);
} | conditional_block |
chips-autocomplete-example.ts | import {COMMA, ENTER} from '@angular/cdk/keycodes';
import {Component, ElementRef, ViewChild} from '@angular/core';
import {FormControl} from '@angular/forms';
import {MatAutocompleteSelectedEvent, MatAutocomplete} from '@angular/material/autocomplete';
import {MatChipInputEvent} from '@angular/material/chips';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
/**
* @title Chips Autocomplete
*/
@Component({
selector: 'chips-autocomplete-example',
templateUrl: 'chips-autocomplete-example.html',
styleUrls: ['chips-autocomplete-example.css'],
})
export class ChipsAutocompleteExample {
visible = true;
selectable = true;
removable = true;
separatorKeysCodes: number[] = [ENTER, COMMA];
fruitCtrl = new FormControl();
filteredFruits: Observable<string[]>;
fruits: string[] = ['Lemon'];
allFruits: string[] = ['Apple', 'Lemon', 'Lime', 'Orange', 'Strawberry'];
@ViewChild('fruitInput') fruitInput: ElementRef<HTMLInputElement>;
@ViewChild('auto') matAutocomplete: MatAutocomplete;
constructor() {
this.filteredFruits = this.fruitCtrl.valueChanges.pipe(
startWith(null),
map((fruit: string | null) => fruit ? this._filter(fruit) : this.allFruits.slice()));
}
| (event: MatChipInputEvent): void {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim()) {
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
remove(fruit: string): void {
const index = this.fruits.indexOf(fruit);
if (index >= 0) {
this.fruits.splice(index, 1);
}
}
selected(event: MatAutocompleteSelectedEvent): void {
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.allFruits.filter(fruit => fruit.toLowerCase().indexOf(filterValue) === 0);
}
}
| add | identifier_name |
record.ts | /*-----------------------------------------------------------------------------
| Copyright (c) 2014-2018, PhosphorJS Contributors
|
| Distributed under the terms of the BSD 3-Clause License.
|
| The full license is in the file LICENSE, distributed with this software.
|----------------------------------------------------------------------------*/
import {
Schema
} from './schema';
/**
* A type alias for a datastore record.
*/
export
type Record<S extends Schema> = Record.Base<S> & Record.Value<S>;
/**
* The namespace for the `Record` type statics.
*/
export
namespace Record {
/**
* A type alias for the record base type.
*/
export
type Base<S extends Schema> = {
/**
* The unique id of the record.
*/
readonly $id: string;
/**
* @internal
*
* The metadata for the record.
*/
readonly '@@metadata': Metadata<S>;
};
/**
* A type alias for the record value type.
*/
export
type Value<S extends Schema> = {
readonly [N in keyof S['fields']]: S['fields'][N]['ValueType'];
};
/**
* A type alias for the record update type.
*/
export
type Update<S extends Schema> = {
readonly [N in keyof S['fields']]?: S['fields'][N]['UpdateType'];
};
/**
* A type alias for the record change type.
*/
export
type Change<S extends Schema> = {
readonly [N in keyof S['fields']]?: S['fields'][N]['ChangeType'];
};
/**
* A type alias for the record patch type.
*/
export
type Patch<S extends Schema> = {
readonly [N in keyof S['fields']]?: S['fields'][N]['PatchType'];
};
/**
* @internal
*
* A type alias for the record metadata type.
*/
export
type Metadata<S extends Schema> = {
readonly [N in keyof S['fields']]: S['fields'][N]['MetadataType'];
};
/**
* @internal
*
* A type alias for the record mutable change type. | */
export
type MutableChange<S extends Schema> = {
[N in keyof S['fields']]?: S['fields'][N]['ChangeType'];
};
/**
* @internal
*
* A type alias for the record mutable patch type.
*/
export
type MutablePatch<S extends Schema> = {
[N in keyof S['fields']]?: S['fields'][N]['PatchType'];
};
} | random_line_split |
|
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundColor: mainBackgroundColor
});
var queHeight = Ti.Platform.displayCaps.platformHeight / 6;
var pushButtonView = Ti.UI.createImageView({
image: "/images/push_button_250_250.png",
zIndex: 999
});
self.add(pushButtonView);
var resetButtonView = Ti.UI.createImageView({
image: "/images/reset.jpg",
top: 10,
right: 10,
width: 50,
height: 50,
zIndex: 999
});
self.add(resetButtonView);
var queIndex = 0;
pushButtonView.addEventListener("click", function(e) {
if (queIndex < 6) {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queValue);
var options = {
queIndex: queIndex,
queHeight: queHeight,
backgroundColor: mainBackgroundColor
}
var queView = createQueView(queValue, options);
self.add(queView);
} else if (queIndex == 6) { // if que == 6, xin hao dong
// xin hao dong
var haoDong = Math.floor(Math.random() * 6);
highlightHao(haoDong);
// reverse que lai, doc tu duoi len
queWholeValue.reverse();
// add hao dong vao queWholeValue
queWholeValue.push(haoDong);
console.log(queWholeValue.toString());
// xin xong, chuyen sang window khac
self.hide();
var queWindow = new QueDetailWindow({
data: queWholeValue
});
queWindow.open();
}
queIndex++;
});
resetButtonView.addEventListener("click", function(e) {
queWholeValue = [];
queIndex = 0;
removeAllQueViews(self);
queViewArray = [];
});
return self;
}
function createQueView(queValue, options) |
function removeAllQueViews(window) {
for( var i = 0; i < queViewArray.length; i++) {
var _queView = queViewArray[i];
window.remove(_queView);
}
}
function highlightHao(index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView;
| {
var queIndex = options["queIndex"];
var queHeight = options["queHeight"] * 90 / 100;
var backgroundColor = options["backgroundColor"];
var _queView = Ti.UI.createView({
top: queHeight * queIndex,
height: queHeight,
width: "100%",
borderColor: backgroundColor,
borderWidth: 5,
borderRadius: 20,
backgroundColor: queValue == 1 ? "black" : "white"
});
queViewArray.push(_queView);
return _queView;
} | identifier_body |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundColor: mainBackgroundColor
});
var queHeight = Ti.Platform.displayCaps.platformHeight / 6;
var pushButtonView = Ti.UI.createImageView({
image: "/images/push_button_250_250.png",
zIndex: 999
});
self.add(pushButtonView);
var resetButtonView = Ti.UI.createImageView({
image: "/images/reset.jpg",
top: 10,
right: 10,
width: 50,
height: 50,
zIndex: 999
});
self.add(resetButtonView);
var queIndex = 0;
pushButtonView.addEventListener("click", function(e) {
if (queIndex < 6) | else if (queIndex == 6) { // if que == 6, xin hao dong
// xin hao dong
var haoDong = Math.floor(Math.random() * 6);
highlightHao(haoDong);
// reverse que lai, doc tu duoi len
queWholeValue.reverse();
// add hao dong vao queWholeValue
queWholeValue.push(haoDong);
console.log(queWholeValue.toString());
// xin xong, chuyen sang window khac
self.hide();
var queWindow = new QueDetailWindow({
data: queWholeValue
});
queWindow.open();
}
queIndex++;
});
resetButtonView.addEventListener("click", function(e) {
queWholeValue = [];
queIndex = 0;
removeAllQueViews(self);
queViewArray = [];
});
return self;
}
function createQueView(queValue, options) {
var queIndex = options["queIndex"];
var queHeight = options["queHeight"] * 90 / 100;
var backgroundColor = options["backgroundColor"];
var _queView = Ti.UI.createView({
top: queHeight * queIndex,
height: queHeight,
width: "100%",
borderColor: backgroundColor,
borderWidth: 5,
borderRadius: 20,
backgroundColor: queValue == 1 ? "black" : "white"
});
queViewArray.push(_queView);
return _queView;
}
function removeAllQueViews(window) {
for( var i = 0; i < queViewArray.length; i++) {
var _queView = queViewArray[i];
window.remove(_queView);
}
}
function highlightHao(index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView;
| {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queValue);
var options = {
queIndex: queIndex,
queHeight: queHeight,
backgroundColor: mainBackgroundColor
}
var queView = createQueView(queValue, options);
self.add(queView);
} | conditional_block |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundColor: mainBackgroundColor
});
var queHeight = Ti.Platform.displayCaps.platformHeight / 6;
var pushButtonView = Ti.UI.createImageView({
image: "/images/push_button_250_250.png",
zIndex: 999
});
self.add(pushButtonView);
var resetButtonView = Ti.UI.createImageView({
image: "/images/reset.jpg",
top: 10,
right: 10,
width: 50,
height: 50,
zIndex: 999
});
self.add(resetButtonView);
var queIndex = 0;
pushButtonView.addEventListener("click", function(e) {
if (queIndex < 6) {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queValue);
var options = {
queIndex: queIndex,
queHeight: queHeight,
backgroundColor: mainBackgroundColor
}
var queView = createQueView(queValue, options);
self.add(queView);
} else if (queIndex == 6) { // if que == 6, xin hao dong
// xin hao dong
var haoDong = Math.floor(Math.random() * 6);
highlightHao(haoDong);
// reverse que lai, doc tu duoi len
queWholeValue.reverse();
// add hao dong vao queWholeValue
queWholeValue.push(haoDong);
console.log(queWholeValue.toString());
// xin xong, chuyen sang window khac
self.hide();
var queWindow = new QueDetailWindow({
data: queWholeValue
});
queWindow.open();
}
queIndex++;
});
resetButtonView.addEventListener("click", function(e) {
queWholeValue = [];
queIndex = 0;
removeAllQueViews(self);
queViewArray = [];
});
return self;
}
function createQueView(queValue, options) {
var queIndex = options["queIndex"];
var queHeight = options["queHeight"] * 90 / 100;
var backgroundColor = options["backgroundColor"];
var _queView = Ti.UI.createView({
top: queHeight * queIndex,
height: queHeight,
width: "100%",
borderColor: backgroundColor,
borderWidth: 5,
borderRadius: 20,
backgroundColor: queValue == 1 ? "black" : "white"
});
queViewArray.push(_queView);
return _queView;
}
function removeAllQueViews(window) {
for( var i = 0; i < queViewArray.length; i++) {
var _queView = queViewArray[i];
window.remove(_queView);
}
}
function | (index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView;
| highlightHao | identifier_name |
FirstView.js | //FirstView Component Constructor
var queViewArray = [];
function FirstView() {
var QueDetailWindow = require('ui/common/QueDetailWindow');
var mainBackgroundColor = "gray";
var queWholeValue = [];
//create object instance, a parasitic subclass of Observable
var self = Ti.UI.createView({
backgroundColor: mainBackgroundColor
});
var queHeight = Ti.Platform.displayCaps.platformHeight / 6;
var pushButtonView = Ti.UI.createImageView({
image: "/images/push_button_250_250.png",
zIndex: 999
});
self.add(pushButtonView);
var resetButtonView = Ti.UI.createImageView({ | top: 10,
right: 10,
width: 50,
height: 50,
zIndex: 999
});
self.add(resetButtonView);
var queIndex = 0;
pushButtonView.addEventListener("click", function(e) {
if (queIndex < 6) {
var queValue = Math.random() >= 0.5 ? 1 : 0;
console.log(queValue);
queWholeValue.push(queValue);
var options = {
queIndex: queIndex,
queHeight: queHeight,
backgroundColor: mainBackgroundColor
}
var queView = createQueView(queValue, options);
self.add(queView);
} else if (queIndex == 6) { // if que == 6, xin hao dong
// xin hao dong
var haoDong = Math.floor(Math.random() * 6);
highlightHao(haoDong);
// reverse que lai, doc tu duoi len
queWholeValue.reverse();
// add hao dong vao queWholeValue
queWholeValue.push(haoDong);
console.log(queWholeValue.toString());
// xin xong, chuyen sang window khac
self.hide();
var queWindow = new QueDetailWindow({
data: queWholeValue
});
queWindow.open();
}
queIndex++;
});
resetButtonView.addEventListener("click", function(e) {
queWholeValue = [];
queIndex = 0;
removeAllQueViews(self);
queViewArray = [];
});
return self;
}
function createQueView(queValue, options) {
var queIndex = options["queIndex"];
var queHeight = options["queHeight"] * 90 / 100;
var backgroundColor = options["backgroundColor"];
var _queView = Ti.UI.createView({
top: queHeight * queIndex,
height: queHeight,
width: "100%",
borderColor: backgroundColor,
borderWidth: 5,
borderRadius: 20,
backgroundColor: queValue == 1 ? "black" : "white"
});
queViewArray.push(_queView);
return _queView;
}
function removeAllQueViews(window) {
for( var i = 0; i < queViewArray.length; i++) {
var _queView = queViewArray[i];
window.remove(_queView);
}
}
function highlightHao(index) {
var _queView = queViewArray[index];
_queView.backgroundColor = "#900";
}
module.exports = FirstView; | image: "/images/reset.jpg", | random_line_split |
login.test.js | import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetchMock from 'fetch-mock';
import {
fetchLogin,
testing,
} from './login';
const mockStore = configureMockStore([thunk]);
beforeEach(() => {
fetchMock.restore();
});
test('fetch login with success', done => {
fetchMock.post(`${testing.base_url}/auth/login/`, {
status: 200,
body: {success: true},
});
const store = mockStore();
const expectedActions = [
testing.fetchLoginSuccess(),
];
const email = "[email protected]"; | done();
});
});
test('fetch login failure', done => {
fetchMock.post(`${testing.base_url}/auth/login/`, {
status: 401,
body: {},
});
const store = mockStore();
const expectedActions = [
testing.fetchLoginFailure(),
];
const email = "[email protected]";
const password = "pippo";
return store.dispatch(fetchLogin(email, password))
.then(() => {
expect(store.getActions()).toEqual(expectedActions);
done();
});
}); | const password = "pippo";
return store.dispatch(fetchLogin(email, password))
.then(() => {
expect(store.getActions()).toEqual(expectedActions); | random_line_split |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self, *args, **kwargs):
super(TailF, self).__init__(*args, **kwargs)
self.prev_file_size = -1
self.prev_mod_time = -1
def run(self, edit):
self.view.set_read_only(True)
t = threading.Thread(target=self.thread_handler)
TAILF_VIEWS.add(self.view.id())
self.view.set_status(STATUS_KEY, 'TailF mode')
t.start()
def thread_handler(self):
while True:
if self.view.id() in TAILF_VIEWS:
if self.view.file_name() is None:
sublime.error_message('File not save on disk')
return
else:
file_stat = os.stat(self.view.file_name())
new_size = file_stat[stat.ST_SIZE]
new_mod_time = file_stat[stat.ST_MTIME]
if (new_mod_time > self.prev_mod_time or
new_size != self.prev_file_size):
self.view.run_command('update_file')
self.view.run_command('move_to',
args={'to': 'eof', 'extend': False})
self.prev_file_size = new_size
self.prev_mod_time = new_mod_time
time.sleep(self.view.settings().get('tailf_pull_rate'))
else:
|
def description(self):
return 'Starts monitoring file on disk'
class StopTailF(sublime_plugin.TextCommand):
'''
Stop monitoring file command.
'''
def run(self, edit):
TAILF_VIEWS.remove(self.view.id())
# restore view to previous state
self.view.set_read_only(False)
self.view.set_scratch(False)
self.view.erase_status(STATUS_KEY)
def description(self):
return 'Stops monitoring file on disk'
class UpdateFile(sublime_plugin.TextCommand):
'''
Reloads content of the file and replaces view content with it.
'''
def run(self, edit):
read_only = self.view.is_read_only()
self.view.set_read_only(False)
with io.open(self.view.file_name(), 'r', encoding='utf-8-sig') as f:
content = f.read()
whole_file = sublime.Region(0, self.view.size())
self.view.replace(edit, whole_file, content)
self.view.set_read_only(read_only)
# don't ask user if he want's to save changes to disk
self.view.set_scratch(True)
class TailFEventListener(sublime_plugin.EventListener):
'''
Listener that removes files from monitored files once file is
about to be closed.
'''
def on_pre_close(self, view):
if view.id() in TAILF_VIEWS:
TAILF_VIEWS.remove(view.id())
| return | conditional_block |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self, *args, **kwargs):
super(TailF, self).__init__(*args, **kwargs)
self.prev_file_size = -1
self.prev_mod_time = -1
def run(self, edit):
self.view.set_read_only(True)
t = threading.Thread(target=self.thread_handler)
TAILF_VIEWS.add(self.view.id())
self.view.set_status(STATUS_KEY, 'TailF mode')
t.start()
def thread_handler(self):
while True:
if self.view.id() in TAILF_VIEWS: | return
else:
file_stat = os.stat(self.view.file_name())
new_size = file_stat[stat.ST_SIZE]
new_mod_time = file_stat[stat.ST_MTIME]
if (new_mod_time > self.prev_mod_time or
new_size != self.prev_file_size):
self.view.run_command('update_file')
self.view.run_command('move_to',
args={'to': 'eof', 'extend': False})
self.prev_file_size = new_size
self.prev_mod_time = new_mod_time
time.sleep(self.view.settings().get('tailf_pull_rate'))
else:
return
def description(self):
return 'Starts monitoring file on disk'
class StopTailF(sublime_plugin.TextCommand):
'''
Stop monitoring file command.
'''
def run(self, edit):
TAILF_VIEWS.remove(self.view.id())
# restore view to previous state
self.view.set_read_only(False)
self.view.set_scratch(False)
self.view.erase_status(STATUS_KEY)
def description(self):
return 'Stops monitoring file on disk'
class UpdateFile(sublime_plugin.TextCommand):
'''
Reloads content of the file and replaces view content with it.
'''
def run(self, edit):
read_only = self.view.is_read_only()
self.view.set_read_only(False)
with io.open(self.view.file_name(), 'r', encoding='utf-8-sig') as f:
content = f.read()
whole_file = sublime.Region(0, self.view.size())
self.view.replace(edit, whole_file, content)
self.view.set_read_only(read_only)
# don't ask user if he want's to save changes to disk
self.view.set_scratch(True)
class TailFEventListener(sublime_plugin.EventListener):
'''
Listener that removes files from monitored files once file is
about to be closed.
'''
def on_pre_close(self, view):
if view.id() in TAILF_VIEWS:
TAILF_VIEWS.remove(view.id()) | if self.view.file_name() is None:
sublime.error_message('File not save on disk') | random_line_split |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def __init__(self, *args, **kwargs):
super(TailF, self).__init__(*args, **kwargs)
self.prev_file_size = -1
self.prev_mod_time = -1
def run(self, edit):
self.view.set_read_only(True)
t = threading.Thread(target=self.thread_handler)
TAILF_VIEWS.add(self.view.id())
self.view.set_status(STATUS_KEY, 'TailF mode')
t.start()
def thread_handler(self):
while True:
if self.view.id() in TAILF_VIEWS:
if self.view.file_name() is None:
sublime.error_message('File not save on disk')
return
else:
file_stat = os.stat(self.view.file_name())
new_size = file_stat[stat.ST_SIZE]
new_mod_time = file_stat[stat.ST_MTIME]
if (new_mod_time > self.prev_mod_time or
new_size != self.prev_file_size):
self.view.run_command('update_file')
self.view.run_command('move_to',
args={'to': 'eof', 'extend': False})
self.prev_file_size = new_size
self.prev_mod_time = new_mod_time
time.sleep(self.view.settings().get('tailf_pull_rate'))
else:
return
def description(self):
return 'Starts monitoring file on disk'
class StopTailF(sublime_plugin.TextCommand):
'''
Stop monitoring file command.
'''
def run(self, edit):
TAILF_VIEWS.remove(self.view.id())
# restore view to previous state
self.view.set_read_only(False)
self.view.set_scratch(False)
self.view.erase_status(STATUS_KEY)
def description(self):
return 'Stops monitoring file on disk'
class UpdateFile(sublime_plugin.TextCommand):
'''
Reloads content of the file and replaces view content with it.
'''
def run(self, edit):
|
class TailFEventListener(sublime_plugin.EventListener):
'''
Listener that removes files from monitored files once file is
about to be closed.
'''
def on_pre_close(self, view):
if view.id() in TAILF_VIEWS:
TAILF_VIEWS.remove(view.id())
| read_only = self.view.is_read_only()
self.view.set_read_only(False)
with io.open(self.view.file_name(), 'r', encoding='utf-8-sig') as f:
content = f.read()
whole_file = sublime.Region(0, self.view.size())
self.view.replace(edit, whole_file, content)
self.view.set_read_only(read_only)
# don't ask user if he want's to save changes to disk
self.view.set_scratch(True) | identifier_body |
tailf.py | import os
import io
import stat
import time
import threading
import sublime
import sublime_plugin
# Set of IDs of view that are being monitored.
TAILF_VIEWS = set()
STATUS_KEY = 'tailf'
class TailF(sublime_plugin.TextCommand):
'''
Start monitoring file in `tail -f` line style.
'''
def | (self, *args, **kwargs):
super(TailF, self).__init__(*args, **kwargs)
self.prev_file_size = -1
self.prev_mod_time = -1
def run(self, edit):
self.view.set_read_only(True)
t = threading.Thread(target=self.thread_handler)
TAILF_VIEWS.add(self.view.id())
self.view.set_status(STATUS_KEY, 'TailF mode')
t.start()
def thread_handler(self):
while True:
if self.view.id() in TAILF_VIEWS:
if self.view.file_name() is None:
sublime.error_message('File not save on disk')
return
else:
file_stat = os.stat(self.view.file_name())
new_size = file_stat[stat.ST_SIZE]
new_mod_time = file_stat[stat.ST_MTIME]
if (new_mod_time > self.prev_mod_time or
new_size != self.prev_file_size):
self.view.run_command('update_file')
self.view.run_command('move_to',
args={'to': 'eof', 'extend': False})
self.prev_file_size = new_size
self.prev_mod_time = new_mod_time
time.sleep(self.view.settings().get('tailf_pull_rate'))
else:
return
def description(self):
return 'Starts monitoring file on disk'
class StopTailF(sublime_plugin.TextCommand):
'''
Stop monitoring file command.
'''
def run(self, edit):
TAILF_VIEWS.remove(self.view.id())
# restore view to previous state
self.view.set_read_only(False)
self.view.set_scratch(False)
self.view.erase_status(STATUS_KEY)
def description(self):
return 'Stops monitoring file on disk'
class UpdateFile(sublime_plugin.TextCommand):
'''
Reloads content of the file and replaces view content with it.
'''
def run(self, edit):
read_only = self.view.is_read_only()
self.view.set_read_only(False)
with io.open(self.view.file_name(), 'r', encoding='utf-8-sig') as f:
content = f.read()
whole_file = sublime.Region(0, self.view.size())
self.view.replace(edit, whole_file, content)
self.view.set_read_only(read_only)
# don't ask user if he want's to save changes to disk
self.view.set_scratch(True)
class TailFEventListener(sublime_plugin.EventListener):
'''
Listener that removes files from monitored files once file is
about to be closed.
'''
def on_pre_close(self, view):
if view.id() in TAILF_VIEWS:
TAILF_VIEWS.remove(view.id())
| __init__ | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(proc_macro)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(try_from)]
#![feature(untagged_unions)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(script_plugins)]
extern crate angle;
extern crate app_units;
extern crate atomic_refcell;
extern crate audio_video_metadata;
#[macro_use]
extern crate bitflags;
extern crate bluetooth_traits;
extern crate byteorder;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate deny_public_fields;
extern crate devtools_traits;
extern crate dom_struct;
#[macro_use]
extern crate domobject_derive;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate html5ever;
#[macro_use] extern crate html5ever_atoms;
#[macro_use]
extern crate hyper;
extern crate hyper_serde;
extern crate image;
extern crate ipc_channel;
#[macro_use]
extern crate js;
#[macro_use]
extern crate jstraceable_derive;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate parking_lot;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate range;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde;
#[macro_use] extern crate servo_atoms;
extern crate servo_config;
extern crate servo_geometry;
extern crate servo_rand;
extern crate servo_url;
extern crate smallvec;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
extern crate url;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate webvr_traits;
extern crate xml5ever;
mod body;
pub mod clipboard_provider;
mod devtools;
pub mod document_loader;
#[macro_use]
mod dom;
pub mod fetch;
mod layout_image;
pub mod layout_wrapper;
mod mem;
mod microtask;
mod network_listener;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod serviceworker_manager;
mod serviceworkerjob;
mod stylesheet_loader;
mod task_source;
pub mod test;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::proxyhandler;
use script_traits::SWManagerSenders;
use serviceworker_manager::ServiceWorkerManager;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn | () {}
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
}
| perform_platform_specific_initialization | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(proc_macro)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(try_from)]
#![feature(untagged_unions)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(script_plugins)]
extern crate angle;
extern crate app_units; | #[macro_use]
extern crate bitflags;
extern crate bluetooth_traits;
extern crate byteorder;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate deny_public_fields;
extern crate devtools_traits;
extern crate dom_struct;
#[macro_use]
extern crate domobject_derive;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate html5ever;
#[macro_use] extern crate html5ever_atoms;
#[macro_use]
extern crate hyper;
extern crate hyper_serde;
extern crate image;
extern crate ipc_channel;
#[macro_use]
extern crate js;
#[macro_use]
extern crate jstraceable_derive;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate parking_lot;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate range;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde;
#[macro_use] extern crate servo_atoms;
extern crate servo_config;
extern crate servo_geometry;
extern crate servo_rand;
extern crate servo_url;
extern crate smallvec;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
extern crate url;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate webvr_traits;
extern crate xml5ever;
mod body;
pub mod clipboard_provider;
mod devtools;
pub mod document_loader;
#[macro_use]
mod dom;
pub mod fetch;
mod layout_image;
pub mod layout_wrapper;
mod mem;
mod microtask;
mod network_listener;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod serviceworker_manager;
mod serviceworkerjob;
mod stylesheet_loader;
mod task_source;
pub mod test;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::proxyhandler;
use script_traits::SWManagerSenders;
use serviceworker_manager::ServiceWorkerManager;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
pub fn init() {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
} | extern crate atomic_refcell;
extern crate audio_video_metadata; | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(box_syntax)]
#![feature(conservative_impl_trait)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(mpsc_select)]
#![feature(nonzero)]
#![feature(on_unimplemented)]
#![feature(optin_builtin_traits)]
#![feature(plugin)]
#![feature(proc_macro)]
#![feature(slice_patterns)]
#![feature(stmt_expr_attributes)]
#![feature(try_from)]
#![feature(untagged_unions)]
#![deny(unsafe_code)]
#![allow(non_snake_case)]
#![doc = "The script crate contains all matters DOM."]
#![plugin(script_plugins)]
extern crate angle;
extern crate app_units;
extern crate atomic_refcell;
extern crate audio_video_metadata;
#[macro_use]
extern crate bitflags;
extern crate bluetooth_traits;
extern crate byteorder;
extern crate canvas_traits;
extern crate caseless;
extern crate cookie as cookie_rs;
extern crate core;
#[macro_use] extern crate cssparser;
#[macro_use] extern crate deny_public_fields;
extern crate devtools_traits;
extern crate dom_struct;
#[macro_use]
extern crate domobject_derive;
extern crate encoding;
extern crate euclid;
extern crate fnv;
extern crate gfx_traits;
extern crate heapsize;
#[macro_use] extern crate heapsize_derive;
extern crate html5ever;
#[macro_use] extern crate html5ever_atoms;
#[macro_use]
extern crate hyper;
extern crate hyper_serde;
extern crate image;
extern crate ipc_channel;
#[macro_use]
extern crate js;
#[macro_use]
extern crate jstraceable_derive;
extern crate libc;
#[macro_use]
extern crate log;
#[macro_use]
extern crate mime;
extern crate mime_guess;
extern crate msg;
extern crate net_traits;
extern crate num_traits;
extern crate offscreen_gl_context;
extern crate open;
extern crate parking_lot;
extern crate phf;
#[macro_use]
extern crate profile_traits;
extern crate range;
extern crate ref_filter_map;
extern crate ref_slice;
extern crate regex;
extern crate rustc_serialize;
extern crate script_layout_interface;
extern crate script_traits;
extern crate selectors;
extern crate serde;
#[macro_use] extern crate servo_atoms;
extern crate servo_config;
extern crate servo_geometry;
extern crate servo_rand;
extern crate servo_url;
extern crate smallvec;
#[macro_use]
extern crate style;
extern crate style_traits;
extern crate time;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
extern crate tinyfiledialogs;
extern crate url;
extern crate uuid;
extern crate webrender_traits;
extern crate websocket;
extern crate webvr_traits;
extern crate xml5ever;
mod body;
pub mod clipboard_provider;
mod devtools;
pub mod document_loader;
#[macro_use]
mod dom;
pub mod fetch;
mod layout_image;
pub mod layout_wrapper;
mod mem;
mod microtask;
mod network_listener;
pub mod script_runtime;
#[allow(unsafe_code)]
pub mod script_thread;
mod serviceworker_manager;
mod serviceworkerjob;
mod stylesheet_loader;
mod task_source;
pub mod test;
pub mod textinput;
mod timers;
mod unpremultiplytable;
mod webdriver_handlers;
use dom::bindings::codegen::RegisterBindings;
use dom::bindings::proxyhandler;
use script_traits::SWManagerSenders;
use serviceworker_manager::ServiceWorkerManager;
#[cfg(target_os = "linux")]
#[allow(unsafe_code)]
fn perform_platform_specific_initialization() {
use std::mem;
// 4096 is default max on many linux systems
const MAX_FILE_LIMIT: libc::rlim_t = 4096;
// Bump up our number of file descriptors to save us from impending doom caused by an onslaught
// of iframes.
unsafe {
let mut rlim: libc::rlimit = mem::uninitialized();
match libc::getrlimit(libc::RLIMIT_NOFILE, &mut rlim) {
0 => {
if rlim.rlim_cur >= MAX_FILE_LIMIT {
// we have more than enough
return;
}
rlim.rlim_cur = match rlim.rlim_max {
libc::RLIM_INFINITY => MAX_FILE_LIMIT,
_ => {
if rlim.rlim_max < MAX_FILE_LIMIT {
rlim.rlim_max
} else {
MAX_FILE_LIMIT
}
}
};
match libc::setrlimit(libc::RLIMIT_NOFILE, &rlim) {
0 => (),
_ => warn!("Failed to set file count limit"),
};
},
_ => warn!("Failed to get file count limit"),
};
}
}
#[cfg(not(target_os = "linux"))]
fn perform_platform_specific_initialization() {}
pub fn init_service_workers(sw_senders: SWManagerSenders) {
// Spawn the service worker manager passing the constellation sender
ServiceWorkerManager::spawn_manager(sw_senders);
}
#[allow(unsafe_code)]
pub fn init() | {
unsafe {
proxyhandler::init();
// Create the global vtables used by the (generated) DOM
// bindings to implement JS proxies.
RegisterBindings::RegisterProxyHandlers();
}
perform_platform_specific_initialization();
} | identifier_body |
|
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ['CO2', 'ppm', 'mdi:cloud'],
'pressure': ['Pressure', 'mbar', 'mdi:gauge'],
'noise': ['Noise', 'dB', 'mdi:volume-high'],
'humidity': ['Humidity', '%', 'mdi:water-percent']
}
CONF_SECRET_KEY = 'secret_key'
ATTR_MODULE = 'modules'
# Return cached results if last scan was less then this time ago
# NetAtmo Data is uploaded to server every 10mn
# so this time should not be under
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SECRET_KEY]},
_LOGGER):
return None
import lnetatmo
authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None),
config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each module
for module_name, monitored_conditions in config[ATTR_MODULE].items():
# Test if module exist """
if module_name not in data.get_module_names():
_LOGGER.error('Module name: "%s" not found', module_name)
continue
# Only create sensor for monitored """
for variable in monitored_conditions:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(
NetAtmoSensor(data, module_name, variable))
except KeyError:
pass
add_devices(dev)
# pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """
def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name,
SENSOR_TYPES[sensor_type][0])
self.netatmo_data = netatmo_data
self.module_name = module_name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def | (self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """
return self._unit_of_measurement
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """
self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name]
if self.type == 'temperature':
self._state = round(data['Temperature'], 1)
elif self.type == 'humidity':
self._state = data['Humidity']
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
def __init__(self, auth):
self.auth = auth
self.data = None
def get_module_names(self):
""" Return all module available on the API as a list. """
self.update()
return self.data.keys()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600)
| name | identifier_name |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ['CO2', 'ppm', 'mdi:cloud'],
'pressure': ['Pressure', 'mbar', 'mdi:gauge'],
'noise': ['Noise', 'dB', 'mdi:volume-high'],
'humidity': ['Humidity', '%', 'mdi:water-percent']
}
CONF_SECRET_KEY = 'secret_key'
ATTR_MODULE = 'modules'
# Return cached results if last scan was less then this time ago
# NetAtmo Data is uploaded to server every 10mn
# so this time should not be under
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SECRET_KEY]},
_LOGGER):
return None
import lnetatmo
| config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each module
for module_name, monitored_conditions in config[ATTR_MODULE].items():
# Test if module exist """
if module_name not in data.get_module_names():
_LOGGER.error('Module name: "%s" not found', module_name)
continue
# Only create sensor for monitored """
for variable in monitored_conditions:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(
NetAtmoSensor(data, module_name, variable))
except KeyError:
pass
add_devices(dev)
# pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """
def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name,
SENSOR_TYPES[sensor_type][0])
self.netatmo_data = netatmo_data
self.module_name = module_name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def name(self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """
return self._unit_of_measurement
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """
self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name]
if self.type == 'temperature':
self._state = round(data['Temperature'], 1)
elif self.type == 'humidity':
self._state = data['Humidity']
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
def __init__(self, auth):
self.auth = auth
self.data = None
def get_module_names(self):
""" Return all module available on the API as a list. """
self.update()
return self.data.keys()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600) | authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None), | random_line_split |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ['CO2', 'ppm', 'mdi:cloud'],
'pressure': ['Pressure', 'mbar', 'mdi:gauge'],
'noise': ['Noise', 'dB', 'mdi:volume-high'],
'humidity': ['Humidity', '%', 'mdi:water-percent']
}
CONF_SECRET_KEY = 'secret_key'
ATTR_MODULE = 'modules'
# Return cached results if last scan was less then this time ago
# NetAtmo Data is uploaded to server every 10mn
# so this time should not be under
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SECRET_KEY]},
_LOGGER):
return None
import lnetatmo
authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None),
config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each module
for module_name, monitored_conditions in config[ATTR_MODULE].items():
# Test if module exist """
if module_name not in data.get_module_names():
_LOGGER.error('Module name: "%s" not found', module_name)
continue
# Only create sensor for monitored """
for variable in monitored_conditions:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(
NetAtmoSensor(data, module_name, variable))
except KeyError:
pass
add_devices(dev)
# pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """
def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name,
SENSOR_TYPES[sensor_type][0])
self.netatmo_data = netatmo_data
self.module_name = module_name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def name(self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """
return self._unit_of_measurement
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """
self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name]
if self.type == 'temperature':
self._state = round(data['Temperature'], 1)
elif self.type == 'humidity':
|
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
def __init__(self, auth):
self.auth = auth
self.data = None
def get_module_names(self):
""" Return all module available on the API as a list. """
self.update()
return self.data.keys()
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600)
| self._state = data['Humidity'] | conditional_block |
netatmo.py | """
homeassistant.components.sensor.netatmo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NetAtmo Weather Service service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.netatmo/
"""
import logging
from datetime import timedelta
from homeassistant.components.sensor import DOMAIN
from homeassistant.const import (
CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME, TEMP_CELCIUS)
from homeassistant.helpers import validate_config
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
REQUIREMENTS = [
'https://github.com/HydrelioxGitHub/netatmo-api-python/archive/'
'43ff238a0122b0939a0dc4e8836b6782913fb6e2.zip'
'#lnetatmo==0.4.0']
_LOGGER = logging.getLogger(__name__)
SENSOR_TYPES = {
'temperature': ['Temperature', TEMP_CELCIUS, 'mdi:thermometer'],
'co2': ['CO2', 'ppm', 'mdi:cloud'],
'pressure': ['Pressure', 'mbar', 'mdi:gauge'],
'noise': ['Noise', 'dB', 'mdi:volume-high'],
'humidity': ['Humidity', '%', 'mdi:water-percent']
}
CONF_SECRET_KEY = 'secret_key'
ATTR_MODULE = 'modules'
# Return cached results if last scan was less then this time ago
# NetAtmo Data is uploaded to server every 10mn
# so this time should not be under
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=600)
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Get the NetAtmo sensor. """
if not validate_config({DOMAIN: config},
{DOMAIN: [CONF_API_KEY,
CONF_USERNAME,
CONF_PASSWORD,
CONF_SECRET_KEY]},
_LOGGER):
return None
import lnetatmo
authorization = lnetatmo.ClientAuth(config.get(CONF_API_KEY, None),
config.get(CONF_SECRET_KEY, None),
config.get(CONF_USERNAME, None),
config.get(CONF_PASSWORD, None))
if not authorization:
_LOGGER.error(
"Connection error "
"Please check your settings for NatAtmo API.")
return False
data = NetAtmoData(authorization)
dev = []
try:
# Iterate each module
for module_name, monitored_conditions in config[ATTR_MODULE].items():
# Test if module exist """
if module_name not in data.get_module_names():
_LOGGER.error('Module name: "%s" not found', module_name)
continue
# Only create sensor for monitored """
for variable in monitored_conditions:
if variable not in SENSOR_TYPES:
_LOGGER.error('Sensor type: "%s" does not exist', variable)
else:
dev.append(
NetAtmoSensor(data, module_name, variable))
except KeyError:
pass
add_devices(dev)
# pylint: disable=too-few-public-methods
class NetAtmoSensor(Entity):
""" Implements a NetAtmo sensor. """
def __init__(self, netatmo_data, module_name, sensor_type):
self._name = "NetAtmo {} {}".format(module_name,
SENSOR_TYPES[sensor_type][0])
self.netatmo_data = netatmo_data
self.module_name = module_name
self.type = sensor_type
self._state = None
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self.update()
@property
def name(self):
return self._name
@property
def icon(self):
return SENSOR_TYPES[self.type][2]
@property
def state(self):
""" Returns the state of the device. """
return self._state
@property
def unit_of_measurement(self):
""" Unit of measurement of this entity, if any. """
return self._unit_of_measurement
# pylint: disable=too-many-branches
def update(self):
""" Gets the latest data from NetAtmo API and updates the states. """
self.netatmo_data.update()
data = self.netatmo_data.data[self.module_name]
if self.type == 'temperature':
self._state = round(data['Temperature'], 1)
elif self.type == 'humidity':
self._state = data['Humidity']
elif self.type == 'noise':
self._state = data['Noise']
elif self.type == 'co2':
self._state = data['CO2']
elif self.type == 'pressure':
self._state = round(data['Pressure'], 1)
class NetAtmoData(object):
""" Gets the latest data from NetAtmo. """
def __init__(self, auth):
self.auth = auth
self.data = None
def get_module_names(self):
|
@Throttle(MIN_TIME_BETWEEN_UPDATES)
def update(self):
""" Call the NetAtmo API to update the data. """
import lnetatmo
# Gets the latest data from NetAtmo. """
dev_list = lnetatmo.DeviceList(self.auth)
self.data = dev_list.lastData(exclude=3600)
| """ Return all module available on the API as a list. """
self.update()
return self.data.keys() | identifier_body |
proto.spec.ts | import Long from "long";
import { ClientTransaction } from "../../src/byzcoin";
import { DataBody, DataHeader, TxResult } from "../../src/byzcoin/proto";
import {
AddTxRequest, CreateGenesisBlock,
} from "../../src/byzcoin/proto/requests";
import Darc from "../../src/darc/darc";
describe("ByzCoin Proto Tests", () => {
it("should handle create genesis block messages", () => {
const req = new CreateGenesisBlock({
blockInterval: Long.fromNumber(1),
genesisDarc: new Darc(),
maxBlockSize: 42,
});
expect(req.genesisDarc).toBeDefined(); |
expect(new CreateGenesisBlock()).toBeDefined();
});
it("should handle add tx request messages", () => {
const req = new AddTxRequest({ skipchainID: Buffer.from([1, 2, 3]) });
expect(req.skipchainID).toEqual(Buffer.from([1, 2, 3]));
expect(new AddTxRequest()).toBeDefined();
});
it("should instantiate DataBody", () => {
const obj = new DataBody();
expect(obj.txResults).toEqual([]);
const obj2 = new DataBody({ txResults: [] });
// @ts-ignore
expect(obj2.txresults).toEqual([]);
});
it("should instantiate DataHeader", () => {
const dh = new DataHeader();
expect(dh.trieRoot).toEqual(Buffer.from([]));
const dh2 = new DataHeader({
clientTransactionHash: Buffer.from([1, 2, 3]),
stateChangeHash: Buffer.from([7, 8, 9]),
trieRoot: Buffer.from([4, 5, 6]),
});
// @ts-ignore
expect(dh2.clienttransactionhash).toEqual(Buffer.from([1, 2, 3]));
// @ts-ignore
expect(dh2.statechangehash).toEqual(Buffer.from([7, 8, 9]));
// @ts-ignore
expect(dh2.trieroot).toEqual(Buffer.from([4, 5, 6]));
});
it("should instantiate a transaction result", () => {
const tr = new TxResult();
expect(tr.clientTransaction).toBeUndefined();
const tr2 = new TxResult({ clientTransaction: new ClientTransaction() });
// @ts-ignore
expect(tr2.clienttransaction).toBeDefined();
});
}); | expect(req.blockInterval.toNumber()).toBe(1);
expect(req.maxBlockSize).toBe(42); | random_line_split |
target-apply.ts | import * as clc from "cli-color";
import { Command } from "../command";
import { logger } from "../logger";
import * as requireConfig from "../requireConfig";
import * as utils from "../utils";
import { FirebaseError } from "../error";
export default new Command("target:apply <type> <name> <resources...>")
.description("apply a deploy target to a resource")
.before(requireConfig)
.action((type, name, resources, options) => {
if (!options.project) {
throw new FirebaseError(
`Must have an active project to set deploy targets. Try ${clc.bold("firebase use --add")}`
);
}
const changes = options.rc.applyTarget(options.project, type, name, resources);
| );
for (const change of changes) {
utils.logWarning(
`Previous target ${clc.bold(change.target)} removed from ${clc.bold(change.resource)}`
);
}
logger.info();
logger.info(`Updated: ${name} (${options.rc.target(options.project, type, name).join(",")})`);
}); | utils.logSuccess(
`Applied ${type} target ${clc.bold(name)} to ${clc.bold(resources.join(", "))}` | random_line_split |
target-apply.ts | import * as clc from "cli-color";
import { Command } from "../command";
import { logger } from "../logger";
import * as requireConfig from "../requireConfig";
import * as utils from "../utils";
import { FirebaseError } from "../error";
export default new Command("target:apply <type> <name> <resources...>")
.description("apply a deploy target to a resource")
.before(requireConfig)
.action((type, name, resources, options) => {
if (!options.project) |
const changes = options.rc.applyTarget(options.project, type, name, resources);
utils.logSuccess(
`Applied ${type} target ${clc.bold(name)} to ${clc.bold(resources.join(", "))}`
);
for (const change of changes) {
utils.logWarning(
`Previous target ${clc.bold(change.target)} removed from ${clc.bold(change.resource)}`
);
}
logger.info();
logger.info(`Updated: ${name} (${options.rc.target(options.project, type, name).join(",")})`);
});
| {
throw new FirebaseError(
`Must have an active project to set deploy targets. Try ${clc.bold("firebase use --add")}`
);
} | conditional_block |
input_state.rs | use std::vec::Vec;
use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: false, up: false, down: false,
enter: false, cancel: false,
}
}
pub fn press(&mut self, op: Operation) -> &mut Self {
self.update(op, true)
}
pub fn release(&mut self, op: Operation) -> &mut Self {
self.update(op, false)
}
fn update(&mut self, op: Operation, value: bool) -> &mut Self {
match op {
Operation::Move(dir) => match dir {
Direction::Left => self.left = value,
Direction::Right => self.right = value,
Direction::Up => self.up = value,
Direction::Down => self.down = value,
},
Operation::Enter => self.enter = value,
Operation::Cancel => self.cancel = value,
_ => {}
}
self
}
pub fn vec(&self) -> Vec<Operation> {
let mut states = Vec::new();
if self.left { states.push(Operation::Move(Direction::Left)); }
if self.right { states.push(Operation::Move(Direction::Right)); }
if self.up { states.push(Operation::Move(Direction::Up)); }
if self.down { states.push(Operation::Move(Direction::Down)); }
if self.enter |
if self.cancel { states.push(Operation::Cancel); }
states
}
}
| { states.push(Operation::Enter); } | conditional_block |
input_state.rs | use std::vec::Vec;
use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: false, up: false, down: false,
enter: false, cancel: false,
}
}
pub fn press(&mut self, op: Operation) -> &mut Self {
self.update(op, true)
}
pub fn | (&mut self, op: Operation) -> &mut Self {
self.update(op, false)
}
fn update(&mut self, op: Operation, value: bool) -> &mut Self {
match op {
Operation::Move(dir) => match dir {
Direction::Left => self.left = value,
Direction::Right => self.right = value,
Direction::Up => self.up = value,
Direction::Down => self.down = value,
},
Operation::Enter => self.enter = value,
Operation::Cancel => self.cancel = value,
_ => {}
}
self
}
pub fn vec(&self) -> Vec<Operation> {
let mut states = Vec::new();
if self.left { states.push(Operation::Move(Direction::Left)); }
if self.right { states.push(Operation::Move(Direction::Right)); }
if self.up { states.push(Operation::Move(Direction::Up)); }
if self.down { states.push(Operation::Move(Direction::Down)); }
if self.enter { states.push(Operation::Enter); }
if self.cancel { states.push(Operation::Cancel); }
states
}
}
| release | identifier_name |
input_state.rs | use std::vec::Vec; | use operation::{ Operation, Direction, };
pub struct InputState {
pub left: bool,
pub right: bool,
pub up: bool,
pub down: bool,
pub enter: bool,
pub cancel: bool,
}
impl InputState {
pub fn new() -> InputState {
InputState {
left: false, right: false, up: false, down: false,
enter: false, cancel: false,
}
}
pub fn press(&mut self, op: Operation) -> &mut Self {
self.update(op, true)
}
pub fn release(&mut self, op: Operation) -> &mut Self {
self.update(op, false)
}
fn update(&mut self, op: Operation, value: bool) -> &mut Self {
match op {
Operation::Move(dir) => match dir {
Direction::Left => self.left = value,
Direction::Right => self.right = value,
Direction::Up => self.up = value,
Direction::Down => self.down = value,
},
Operation::Enter => self.enter = value,
Operation::Cancel => self.cancel = value,
_ => {}
}
self
}
pub fn vec(&self) -> Vec<Operation> {
let mut states = Vec::new();
if self.left { states.push(Operation::Move(Direction::Left)); }
if self.right { states.push(Operation::Move(Direction::Right)); }
if self.up { states.push(Operation::Move(Direction::Up)); }
if self.down { states.push(Operation::Move(Direction::Down)); }
if self.enter { states.push(Operation::Enter); }
if self.cancel { states.push(Operation::Cancel); }
states
}
} | random_line_split |
|
spatial_reference.rs | extern crate gdal; |
fn run() -> Result<(), gdal::errors::Error> {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_ref2 = SpatialRef::from_wkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",7030]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",6326]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",4326]]")?;
println!(
"Spatial ref from wkt to proj4:\n{:?}\n",
spatial_ref2.to_proj4()?
);
let spatial_ref3 = SpatialRef::from_definition("urn:ogc:def:crs:EPSG:6.3:26986")?;
println!(
"Spatial ref from ogc naming to wkt:\n{:?}\n",
spatial_ref3.to_wkt()?
);
let spatial_ref4 = SpatialRef::from_epsg(4326)?;
println!(
"Spatial ref from epsg code to wkt:\n{:?}\n",
spatial_ref4.to_wkt()?
);
println!(
"Spatial ref from epsg code to pretty wkt:\n{:?}\n",
spatial_ref4.to_pretty_wkt()?
);
println!(
"Comparison between identical SRS : {:?}\n",
spatial_ref2 == spatial_ref4
);
let htransform = CoordTransform::new(&spatial_ref2, &spatial_ref1)?;
let mut xs = [23.43, 23.50];
let mut ys = [37.58, 37.70];
println!("Before transformation :\n{:?} {:?}", xs, ys);
htransform.transform_coords(&mut xs, &mut ys, &mut [0.0, 0.0])?;
println!("After transformation :\n{:?} {:?}\n", xs, ys);
let geom = Geometry::from_wkt(
"POLYGON((23.43 37.58, 23.43 40.0, 25.29 40.0, 25.29 37.58, 23.43 37.58))",
)?;
println!("Polygon before transformation:\n{:?}\n", geom.wkt()?);
geom.transform(&htransform)?;
println!("Polygon after transformation:\n{:?}\n", geom.wkt()?);
let spatial_ref5 = SpatialRef::from_epsg(4326)?;
println!("To wkt: {:?}", spatial_ref5.to_wkt());
spatial_ref5.morph_to_esri()?;
println!("To esri wkt: {:?}", spatial_ref5.to_wkt());
println!("To xml: {:?}", spatial_ref5.to_xml());
Ok(())
}
fn main() {
run().unwrap();
} |
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry; | random_line_split |
spatial_reference.rs | extern crate gdal;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
fn | () -> Result<(), gdal::errors::Error> {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_ref2 = SpatialRef::from_wkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",7030]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",6326]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",4326]]")?;
println!(
"Spatial ref from wkt to proj4:\n{:?}\n",
spatial_ref2.to_proj4()?
);
let spatial_ref3 = SpatialRef::from_definition("urn:ogc:def:crs:EPSG:6.3:26986")?;
println!(
"Spatial ref from ogc naming to wkt:\n{:?}\n",
spatial_ref3.to_wkt()?
);
let spatial_ref4 = SpatialRef::from_epsg(4326)?;
println!(
"Spatial ref from epsg code to wkt:\n{:?}\n",
spatial_ref4.to_wkt()?
);
println!(
"Spatial ref from epsg code to pretty wkt:\n{:?}\n",
spatial_ref4.to_pretty_wkt()?
);
println!(
"Comparison between identical SRS : {:?}\n",
spatial_ref2 == spatial_ref4
);
let htransform = CoordTransform::new(&spatial_ref2, &spatial_ref1)?;
let mut xs = [23.43, 23.50];
let mut ys = [37.58, 37.70];
println!("Before transformation :\n{:?} {:?}", xs, ys);
htransform.transform_coords(&mut xs, &mut ys, &mut [0.0, 0.0])?;
println!("After transformation :\n{:?} {:?}\n", xs, ys);
let geom = Geometry::from_wkt(
"POLYGON((23.43 37.58, 23.43 40.0, 25.29 40.0, 25.29 37.58, 23.43 37.58))",
)?;
println!("Polygon before transformation:\n{:?}\n", geom.wkt()?);
geom.transform(&htransform)?;
println!("Polygon after transformation:\n{:?}\n", geom.wkt()?);
let spatial_ref5 = SpatialRef::from_epsg(4326)?;
println!("To wkt: {:?}", spatial_ref5.to_wkt());
spatial_ref5.morph_to_esri()?;
println!("To esri wkt: {:?}", spatial_ref5.to_wkt());
println!("To xml: {:?}", spatial_ref5.to_xml());
Ok(())
}
fn main() {
run().unwrap();
}
| run | identifier_name |
spatial_reference.rs | extern crate gdal;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::Geometry;
fn run() -> Result<(), gdal::errors::Error> |
fn main() {
run().unwrap();
}
| {
let spatial_ref1 = SpatialRef::from_proj4(
"+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs",
)?;
println!(
"Spatial ref from proj4 to wkt:\n{:?}\n",
spatial_ref1.to_wkt()?
);
let spatial_ref2 = SpatialRef::from_wkt("GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",7030]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",6326]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",8901]],UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",9108]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",4326]]")?;
println!(
"Spatial ref from wkt to proj4:\n{:?}\n",
spatial_ref2.to_proj4()?
);
let spatial_ref3 = SpatialRef::from_definition("urn:ogc:def:crs:EPSG:6.3:26986")?;
println!(
"Spatial ref from ogc naming to wkt:\n{:?}\n",
spatial_ref3.to_wkt()?
);
let spatial_ref4 = SpatialRef::from_epsg(4326)?;
println!(
"Spatial ref from epsg code to wkt:\n{:?}\n",
spatial_ref4.to_wkt()?
);
println!(
"Spatial ref from epsg code to pretty wkt:\n{:?}\n",
spatial_ref4.to_pretty_wkt()?
);
println!(
"Comparison between identical SRS : {:?}\n",
spatial_ref2 == spatial_ref4
);
let htransform = CoordTransform::new(&spatial_ref2, &spatial_ref1)?;
let mut xs = [23.43, 23.50];
let mut ys = [37.58, 37.70];
println!("Before transformation :\n{:?} {:?}", xs, ys);
htransform.transform_coords(&mut xs, &mut ys, &mut [0.0, 0.0])?;
println!("After transformation :\n{:?} {:?}\n", xs, ys);
let geom = Geometry::from_wkt(
"POLYGON((23.43 37.58, 23.43 40.0, 25.29 40.0, 25.29 37.58, 23.43 37.58))",
)?;
println!("Polygon before transformation:\n{:?}\n", geom.wkt()?);
geom.transform(&htransform)?;
println!("Polygon after transformation:\n{:?}\n", geom.wkt()?);
let spatial_ref5 = SpatialRef::from_epsg(4326)?;
println!("To wkt: {:?}", spatial_ref5.to_wkt());
spatial_ref5.morph_to_esri()?;
println!("To esri wkt: {:?}", spatial_ref5.to_wkt());
println!("To xml: {:?}", spatial_ref5.to_xml());
Ok(())
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.