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 |
|---|---|---|---|---|
fn_must_use.rs | // check-pass
#![warn(unused_must_use)]
#[derive(PartialEq, Eq)]
struct MyStruct {
n: usize,
}
impl MyStruct {
#[must_use]
fn need_to_use_this_method_value(&self) -> usize {
self.n
}
#[must_use]
fn need_to_use_this_associated_function_value() -> isize {
-1
}
}
trait EvenNature {
#[must_use = "no side effects"]
fn is_even(&self) -> bool;
}
impl EvenNature for MyStruct {
fn is_even(&self) -> bool {
self.n % 2 == 0
}
}
trait Replaceable {
fn replace(&mut self, substitute: usize) -> usize;
}
impl Replaceable for MyStruct {
// ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
// method won't work; the attribute should be on the method signature in
// the trait's definition.
#[must_use]
fn replace(&mut self, substitute: usize) -> usize {
let previously = self.n;
self.n = substitute;
previously
}
}
#[must_use = "it's important"]
fn ne | -> bool {
false
}
fn main() {
need_to_use_this_value(); //~ WARN unused return value
let mut m = MyStruct { n: 2 };
let n = MyStruct { n: 3 };
m.need_to_use_this_method_value(); //~ WARN unused return value
m.is_even(); // trait method!
//~^ WARN unused return value
MyStruct::need_to_use_this_associated_function_value();
//~^ WARN unused return value
m.replace(3); // won't warn (annotation needs to be in trait definition)
// comparison methods are `must_use`
2.eq(&3); //~ WARN unused return value
m.eq(&n); //~ WARN unused return value
// lint includes comparison operators
2 == 3; //~ WARN unused comparison
m == n; //~ WARN unused comparison
}
| ed_to_use_this_value() | identifier_name |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
|
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
output(prev)
prev = tokens
output(prev)
| count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1 | identifier_body |
fixes.py | #!/usr/bin/env python
import sys
| tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
output(prev)
prev = tokens
output(prev) | def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'): | random_line_split |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def balance_quotes(tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
|
output(prev)
| output(prev)
prev = tokens | conditional_block |
fixes.py | #!/usr/bin/env python
import sys
def fix_terminator(tokens):
if not tokens:
return
last = tokens[-1]
if last not in ('.', '?', '!') and last.endswith('.'):
tokens[-1] = last[:-1]
tokens.append('.')
def | (tokens):
count = tokens.count("'")
if not count:
return
processed = 0
for i, token in enumerate(tokens):
if token == "'":
if processed % 2 == 0 and (i == 0 or processed != count - 1):
tokens[i] = "`"
processed += 1
def output(tokens):
if not tokens:
return
# fix_terminator(tokens)
balance_quotes(tokens)
print ' '.join(tokens)
prev = None
for line in sys.stdin:
tokens = line.split()
if len(tokens) == 1 and tokens[0] in ('"', "'", ')', ']'):
prev.append(tokens[0])
else:
output(prev)
prev = tokens
output(prev)
| balance_quotes | identifier_name |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
| fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
} | fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
| random_line_split |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn can_hold(&self, other: &Rectangle) -> bool |
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
| {
self.width > other.width && self.height > other.height
} | identifier_body |
main.rs | #[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn | (&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
}
| can_hold | identifier_name |
unit.tests.js | (function () {
window._paddingsTest = function () {
var test = function (padding) {
for (var len = 0; len <= 32; len++) {
var initialArray = random.default.getUint8Array(len);
var padded = padding.pad(initialArray, 16, random.default);
var padCount = padding.unpad(padded);
if (padCount == -1) {
console.log('Failed! 1');
return;
}
var unpadded = padded.subarray(0, padded.length - padCount);
if (initialArray.length != unpadded.length) {
console.log('Failed! 2');
return;
}
for (var i = 0; i < len; i++)
if (initialArray[i] != unpadded[i]) {
console.log('Failed! 3');
return;
}
}
console.log('passed');
};
console.log('ANSI X.923 test');
test(paddings['ANSI X.923']);
console.log('ISO 10126 test');
test(paddings['ISO 10126']);
console.log('PKCS7 test');
test(paddings['PKCS7']);
console.log('ISO/IEC 7816-4 test');
test(paddings['ISO/IEC 7816-4']);
};
var a40 = [25, 215, 226, 12, 106, 44, 159, 200, 49, 56, 86, 185, 11, 129, 90, 44, 125, 56, 126, 161, 114, 118, 212, 181, 23, 207, 189, 3, 55, 60, 7, 51, 5, 40, 199, 63, 151, 19, 88, 63];
window._md2Test = function () {
var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.md2.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], '8350e5a3e24c153df2275c9f80692773');
result &= test([255], '0797438d0baf3d71b7194ab3c71746b6');
result &= test(a40, '92183ec96932db4a26396b23d4df87a3');
console.log(result ? 'Passed' : 'Failed');
};
window._md4Test = function () {
var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.md4.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], '31d6cfe0d16ae931b73c59d7e0c089c0');
result &= test([255], '82c167af8e345bd055487af8d2b540c9');
result &= test(a40, 'c146aadc86111c7de36c7f319fa8a15d');
| var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.md5.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], 'd41d8cd98f00b204e9800998ecf8427e');
result &= test([255], '00594fd4f42ba43fc1ca0427a0576295');
result &= test(a40, '332f73d56f380cea8ab0d51e855bac41');
console.log(result ? 'Passed' : 'Failed');
}
window._sha1Test = function () {
var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.sha1.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], 'da39a3ee5e6b4b0d3255bfef95601890afd80709');
result &= test([255], '85e53271e14006f0265921d02d4d736cdc580b0b');
result &= test(a40, '7a4ce8e483c6fb3460501e660fb164a4d2928c57');
console.log(result ? 'Passed' : 'Failed');
};
window._sha2Test = function () {
var test = function (bytes, ver, hex) {
if (ver == 224)
return bh.byteArrayToHex(hashAlgorithms.sha224.computeHash(bytes)) == hex;
if (ver == 256)
return bh.byteArrayToHex(hashAlgorithms.sha256.computeHash(bytes)) == hex;
if (ver == 384)
return bh.byteArrayToHex(hashAlgorithms.sha384.computeHash(bytes)) == hex;
if (ver == 512)
return bh.byteArrayToHex(hashAlgorithms.sha512.computeHash(bytes)) == hex;
};
console.log('SHA-224');
var result = true;
result &= test([], 224, 'd14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f');
result &= test([255], 224, 'e33f9d75e6ae1369dbabf81b96b4591ae46bba30b591a6b6c62542b5');
result &= test(a40, 224, '4beabeb77adf912c2270c455dd215f818662c0d61b85508c7def6a73');
console.log(result ? 'Passed' : 'Failed');
console.log('SHA-256');
var result = true;
result &= test([], 256, 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
result &= test([255], 256, 'a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89');
result &= test(a40, 256, '9792f39846b22bee11dbaa2a34014141c90cb4ef2f2c16dc83a48b0456f4705d');
console.log(result ? 'Passed' : 'Failed');
console.log('SHA-384');
var result = true;
result &= test([], 384, '38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b');
result &= test([255], 384, '43950796d9883503655e35b5190aee687a2dd99f265012625b95753978e4efff3e8414d178a6e2318480d8eb6ddee643');
result &= test(a40, 384, '1fde9ca46c6d627edfbda629ce47e9101e803674e9156f9706d7a9406e5fe1c91e981e4276b37c78ce8c329b4a30a765');
console.log(result ? 'Passed' : 'Failed');
console.log('SHA-512');
var result = true;
result &= test([], 512, 'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e');
result &= test([255], 512, '6700df6600b118ab0432715a7e8a68b0bf37cdf4adaf0fb9e2b3ebe04ad19c7032cbad55e932792af360bafaa09962e2e690652bc075b2dad0c30688ba2f31a3');
result &= test([97, 98, 99], 512, 'ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f');
test(a40, 512, 'a8e64de4f5fa72e7a1a1bee705d87acc50748a810482a088535e53ad741ed68fb0c7cb08035802f63d466ba629b13823705db763f5ec043918f20c2266c0a783');
console.log(result ? 'Passed' : 'Failed');
};
window._ripemd160Test = function () {
var test = function (bytes, hex) {
return bh.byteArrayToHex(hashAlgorithms.ripemd160.computeHash(bytes)) == hex;
};
var result = true;
result &= test([], '9c1185a5c5e9fc54612808977ee8f548b2258d31');
result &= test([255], '2c0c45d3ecab80fe060e5f1d7057cd2f8de5e557');
result &= test(a40, '7b78ec9d05702f000dbb1d88c2c941795b4f62bd');
console.log(result ? 'Passed' : 'Failed');
};
window._hashAlgoTest = function () {
console.log('md2'); _md2Test();
console.log('md4'); _md4Test();
console.log('md5'); _md5Test();
console.log('sha1'); _sha1Test();
_sha2Test();
console.log('ripemd160'); _ripemd160Test();
};
})(); | console.log(result ? 'Passed' : 'Failed');
};
window._md5Test = function () { | random_line_split |
jstree-tests.ts |
// gets version of lib
var version: string = $.jstree.version;
// create new instance
var instance1: JSTree = $('div').jstree();
$('div').jstree('open_node', '#branch');
// get existing reference
var existingReference: JSTree = $.jstree.reference('sds');
// advanced tree creation
var advancedTree = $("#briefcasetree").jstree({
plugins: ['contextmenu', 'dnd', 'state', 'types', 'unique'],
core: {
check_callback: true,
data: {
cache: false,
url: 'Briefcase/GetProjectTree',
async: true,
type: 'GET',
dataType: 'json'
}
},
types: {
max_depth: -2,
max_children: -2,
valid_children: ['root_folder_all', 'root_folder'],
types: {
root_folder_all: {
valid_children: ['sub_folder_all'],
start_drag: false,
move_node: false,
delete_node: false,
remove: false
},
sub_folder_all: {
valid_children: ['sub_folder_all', 'saved_all'],
start_drag: false,
move_node: false,
delete_node: false,
remove: false
},
saved_all: {
valid_children: [],
start_drag: false,
move_node: false,
delete_node: false,
remove: false
},
root_folder: {
valid_children: ['sub_folder'],
start_drag: false,
move_node: false,
delete_node: false,
remove: false
},
sub_folder: {
valid_children: ['sub_folder', 'saved_single']
},
saved_single: {
valid_children: 'none'
}
}
}
});
var a = $('a').jstree();
// test search node
a.search('test', false, true);
//test redraw node
a.redraw_node($('#node1'), false, false, false);
//test clear buffer
a.clear_buffer();
//tree with new unique plugin parameters
var treeWithUnique = $('#treeWithUnique').jstree({
unique: {
case_sensitive: true,
duplicate: (name: string, counter: number): string => {
return name + ' ( ' + counter.toString() + ' )';
}
}
});
// tree with new core properties
var treeWithNewCoreProperties = $('#treeWithNewCoreProperties').jstree({
core: {
worker: true,
force_text: true,
}
});
// tree with new checkbox properties
var treeWithNewCheckboxProperties = $('#treeWithNewCheckboxProperties').jstree({
checkbox: {
cascade: '',
tie_selection: true
}
});
var tree = $('a').jstree();
tree.move_node('a', 'b', 0, (node: any, new_par: any, pos: any) => { }, true, true);
tree.copy_node('a', 'b', 0, (node: any, new_par: any, pos: any) => { }, true, true);
// #10271 jstree - get_path params not marked to be optional
tree.get_path('nodeId');
tree.get_path('nodeId', '/'); |
var coreThemes: JSTreeStaticDefaultsCoreThemes = {
ellipsis:true
};
// tree with new theme elipsis
var treeWithNewCoreProperties = $('#treeWithNewEllipsisProperties').jstree({
core: {
themes: coreThemes
}
}); | tree.get_path('nodeId', '/', true);
| random_line_split |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Inject,
NgZone,
Provider,
ViewEncapsulation
} from '@angular/core';
import {
MAT_MENU_DEFAULT_OPTIONS,
MAT_MENU_PANEL,
MAT_MENU_SCROLL_STRATEGY,
MatMenu as BaseMatMenu,
matMenuAnimations,
MatMenuDefaultOptions,
} from '@angular/material/menu';
/** @docs-private */
export function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** @docs-private */
export const MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER: Provider = {
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_MENU_SCROLL_STRATEGY_FACTORY,
};
@Component({
selector: 'mat-menu',
templateUrl: 'menu.html',
styleUrls: ['menu.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'matMenu',
animations: [
matMenuAnimations.transformMenu,
matMenuAnimations.fadeInItems
],
providers: [
{provide: MAT_MENU_PANEL, useExisting: MatMenu},
{provide: BaseMatMenu, useExisting: MatMenu},
]
})
export class MatMenu extends BaseMatMenu {
constructor(_elementRef: ElementRef<HTMLElement>,
_ngZone: NgZone,
@Inject(MAT_MENU_DEFAULT_OPTIONS) _defaultOptions: MatMenuDefaultOptions) {
super(_elementRef, _ngZone, _defaultOptions);
}
| (_depth: number) {
// TODO(crisbeto): MDC's styles come with elevation already and we haven't mapped our mixins
// to theirs. Disable the elevation stacking for now until everything has been mapped.
// The following unit tests should be re-enabled:
// - should not remove mat-elevation class from overlay when panelClass is changed
// - should increase the sub-menu elevation based on its depth
// - should update the elevation when the same menu is opened at a different depth
// - should not increase the elevation if the user specified a custom one
}
}
| setElevation | identifier_name |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Inject,
NgZone,
Provider,
ViewEncapsulation
} from '@angular/core';
import {
MAT_MENU_DEFAULT_OPTIONS,
MAT_MENU_PANEL,
MAT_MENU_SCROLL_STRATEGY,
MatMenu as BaseMatMenu,
matMenuAnimations,
MatMenuDefaultOptions,
} from '@angular/material/menu';
/** @docs-private */
export function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** @docs-private */
export const MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER: Provider = {
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_MENU_SCROLL_STRATEGY_FACTORY,
};
@Component({
selector: 'mat-menu', | exportAs: 'matMenu',
animations: [
matMenuAnimations.transformMenu,
matMenuAnimations.fadeInItems
],
providers: [
{provide: MAT_MENU_PANEL, useExisting: MatMenu},
{provide: BaseMatMenu, useExisting: MatMenu},
]
})
export class MatMenu extends BaseMatMenu {
constructor(_elementRef: ElementRef<HTMLElement>,
_ngZone: NgZone,
@Inject(MAT_MENU_DEFAULT_OPTIONS) _defaultOptions: MatMenuDefaultOptions) {
super(_elementRef, _ngZone, _defaultOptions);
}
setElevation(_depth: number) {
// TODO(crisbeto): MDC's styles come with elevation already and we haven't mapped our mixins
// to theirs. Disable the elevation stacking for now until everything has been mapped.
// The following unit tests should be re-enabled:
// - should not remove mat-elevation class from overlay when panelClass is changed
// - should increase the sub-menu elevation based on its depth
// - should update the elevation when the same menu is opened at a different depth
// - should not increase the elevation if the user specified a custom one
}
} | templateUrl: 'menu.html',
styleUrls: ['menu.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None, | random_line_split |
menu.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Overlay, ScrollStrategy} from '@angular/cdk/overlay';
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Inject,
NgZone,
Provider,
ViewEncapsulation
} from '@angular/core';
import {
MAT_MENU_DEFAULT_OPTIONS,
MAT_MENU_PANEL,
MAT_MENU_SCROLL_STRATEGY,
MatMenu as BaseMatMenu,
matMenuAnimations,
MatMenuDefaultOptions,
} from '@angular/material/menu';
/** @docs-private */
export function MAT_MENU_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** @docs-private */
export const MAT_MENU_SCROLL_STRATEGY_FACTORY_PROVIDER: Provider = {
provide: MAT_MENU_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_MENU_SCROLL_STRATEGY_FACTORY,
};
@Component({
selector: 'mat-menu',
templateUrl: 'menu.html',
styleUrls: ['menu.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
exportAs: 'matMenu',
animations: [
matMenuAnimations.transformMenu,
matMenuAnimations.fadeInItems
],
providers: [
{provide: MAT_MENU_PANEL, useExisting: MatMenu},
{provide: BaseMatMenu, useExisting: MatMenu},
]
})
export class MatMenu extends BaseMatMenu {
constructor(_elementRef: ElementRef<HTMLElement>,
_ngZone: NgZone,
@Inject(MAT_MENU_DEFAULT_OPTIONS) _defaultOptions: MatMenuDefaultOptions) |
setElevation(_depth: number) {
// TODO(crisbeto): MDC's styles come with elevation already and we haven't mapped our mixins
// to theirs. Disable the elevation stacking for now until everything has been mapped.
// The following unit tests should be re-enabled:
// - should not remove mat-elevation class from overlay when panelClass is changed
// - should increase the sub-menu elevation based on its depth
// - should update the elevation when the same menu is opened at a different depth
// - should not increase the elevation if the user specified a custom one
}
}
| {
super(_elementRef, _ngZone, _defaultOptions);
} | identifier_body |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} ) |
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit() | f = o.open(login_page, p)
data = f.read() | random_line_split |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
|
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
| print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg | identifier_body |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def parse_bugtrackerpage(url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
|
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
| print soup.findAll('a',{'id': 'next'})
count += 1
pages = True | conditional_block |
unassignedbugs.py | #!/usr/bin/env python2
import urllib2
import urllib
from BeautifulSoup import BeautifulSoup
import smtplib
import ConfigParser
# Retreive user information
config = ConfigParser.ConfigParser()
config.read('config.cfg')
user = config.get('data','user')
password = config.get('data','password')
fromaddr = config.get('data','fromaddr')
toaddr = config.get('data','toaddr')
smtpserver = config.get('data','smtp_server')
login_page='https://bugs.archlinux.org/index.php?do=authenticate'
# Create message
msg = "To: %s \nFrom: %s \nSubject: Bug Mail\n\n" % (toaddr,fromaddr)
msg += 'Unassigned bugs \n\n'
# build opener with HTTPCookieProcessor
o = urllib2.build_opener( urllib2.HTTPCookieProcessor() )
urllib2.install_opener( o )
p = urllib.urlencode( { 'user_name': user, 'password': password, 'remember_login' : 'on',} )
f = o.open(login_page, p)
data = f.read()
# Archlinux
url = "https://bugs.archlinux.org/index.php?string=&project=1&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
# Community
url2= "https://bugs.archlinux.org/index.php?string=&project=5&search_name=&type%5B%5D=&sev%5B%5D=&pri%5B%5D=&due%5B%5D=0&reported%5B%5D=&cat%5B%5D=&status%5B%5D=1&percent%5B%5D=&opened=&dev=&closed=&duedatefrom=&duedateto=&changedfrom=&changedto=&openedfrom=&openedto=&closedfrom=&closedto=&do=index"
def | (url,count=1):
print url
# open bugtracker / parse
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
data = soup.findAll('td',{'class':'task_id'})
msg = ""
pages = False
# Is there another page with unassigned bugs
if soup.findAll('a',{'id': 'next' }) == []:
page = False
else:
print soup.findAll('a',{'id': 'next'})
count += 1
pages = True
print count
# print all found bugs
for f in data:
title = f.a['title'].replace('Assigned |','')
title = f.a['title'].replace('| 0%','')
msg += '* [https://bugs.archlinux.org/task/%s FS#%s] %s \n' % (f.a.string,f.a.string,title)
if pages == True:
new = "%s&pagenum=%s" % (url,count)
msg += parse_bugtrackerpage(new,count)
return msg
msg += '\n\nArchlinux: \n\n'
msg += parse_bugtrackerpage(url)
msg += '\n\nCommunity: \n\n'
msg += parse_bugtrackerpage(url2)
msg = msg.encode("utf8")
# send mail
server = smtplib.SMTP(smtpserver)
server.sendmail(fromaddr, toaddr,msg)
server.quit()
| parse_bugtrackerpage | identifier_name |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#![warn(missing_docs)]
// Clippy lints, some should be disabled incrementally
#![allow(
clippy::assertions_on_constants,
clippy::bind_instead_of_map,
clippy::blocks_in_if_conditions,
clippy::clone_on_copy,
clippy::collapsible_if,
clippy::explicit_counter_loop,
clippy::field_reassign_with_default,
clippy::float_cmp,
clippy::into_iter_on_ref,
clippy::len_zero,
clippy::let_and_return,
clippy::map_clone,
clippy::map_collect_result_unit,
clippy::match_like_matches_macro,
clippy::match_ref_pats,
clippy::module_inception,
clippy::needless_lifetimes,
clippy::needless_range_loop,
clippy::needless_return,
clippy::new_without_default,
clippy::or_fun_call,
clippy::ptr_arg,
clippy::redundant_clone,
clippy::redundant_field_names,
clippy::redundant_static_lifetimes,
clippy::redundant_pattern_matching,
clippy::redundant_closure,
clippy::single_match,
clippy::stable_sort_primitive,
clippy::type_complexity,
clippy::unit_arg,
clippy::unnecessary_unwrap,
clippy::useless_format,
clippy::zero_prefixed_literal
)]
//! DataFusion is an extensible query execution framework that uses
//! [Apache Arrow](https://arrow.apache.org) as its in-memory format.
//!
//! DataFusion supports both an SQL and a DataFrame API for building logical query plans
//! as well as a query optimizer and execution engine capable of parallel execution
//! against partitioned data sources (CSV and Parquet) using threads.
//!
//! Below is an example of how to execute a query against a CSV using [`DataFrames`](dataframe::DataFrame):
//!
//! ```rust
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! // create the dataframe
//! let df = ctx.read_csv("tests/example.csv", CsvReadOptions::new())?;
//!
//! // create a plan
//! let df = df.filter(col("a").lt_eq(col("b")))?
//! .aggregate(vec![col("a")], vec![min(col("b"))])?
//! .limit(100)?;
//!
//! // execute the plan
//! let results: Vec<RecordBatch> = df.collect().await?;
//! # Ok(())
//! # }
//! ```
//! | //! ```
//! # use datafusion::prelude::*;
//! # use datafusion::error::Result;
//! # use arrow::record_batch::RecordBatch;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<()> {
//! let mut ctx = ExecutionContext::new();
//!
//! ctx.register_csv("example", "tests/example.csv", CsvReadOptions::new())?;
//!
//! // create a plan
//! let df = ctx.sql("SELECT a, MIN(b) FROM example GROUP BY a LIMIT 100")?;
//!
//! // execute the plan
//! let results: Vec<RecordBatch> = df.collect().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Parse, Plan, Optimize, Execute
//!
//! DataFusion is a fully fledged query engine capable of performing complex operations.
//! Specifically, when DataFusion receives an SQL query, there are different steps
//! that it passes through until a result is obtained. Broadly, they are:
//!
//! 1. The string is parsed to an Abstract syntax tree (AST) using [sqlparser](https://docs.rs/sqlparser/0.6.1/sqlparser/).
//! 2. The planner [`SqlToRel`](sql::planner::SqlToRel) converts logical expressions on the AST to logical expressions [`Expr`s](logical_plan::Expr).
//! 3. The planner [`SqlToRel`](sql::planner::SqlToRel) converts logical nodes on the AST to a [`LogicalPlan`](logical_plan::LogicalPlan).
//! 4. [`OptimizerRules`](optimizer::optimizer::OptimizerRule) are applied to the [`LogicalPlan`](logical_plan::LogicalPlan) to optimize it.
//! 5. The [`LogicalPlan`](logical_plan::LogicalPlan) is converted to an [`ExecutionPlan`](physical_plan::ExecutionPlan) by a [`PhysicalPlanner`](physical_plan::PhysicalPlanner)
//! 6. The [`ExecutionPlan`](physical_plan::ExecutionPlan) is executed against data through the [`ExecutionContext`](execution::context::ExecutionContext)
//!
//! With a [`DataFrame`](dataframe::DataFrame) API, steps 1-3 are not used as the DataFrame builds the [`LogicalPlan`](logical_plan::LogicalPlan) directly.
//!
//! Phases 1-5 are typically cheap when compared to phase 6, and thus DataFusion puts a
//! lot of effort to ensure that phase 6 runs efficiently and without errors.
//!
//! DataFusion's planning is divided in two main parts: logical planning and physical planning.
//!
//! ### Logical plan
//!
//! Logical planning yields [`logical plans`](logical_plan::LogicalPlan) and [`logical expressions`](logical_plan::Expr).
//! These are [`Schema`](arrow::datatypes::Schema)-aware traits that represent statements whose result is independent of how it should physically be executed.
//!
//! A [`LogicalPlan`](logical_plan::LogicalPlan) is a Direct Asyclic graph of other [`LogicalPlan`s](logical_plan::LogicalPlan) and each node contains logical expressions ([`Expr`s](logical_plan::Expr)).
//! All of these are located in [`logical_plan`](logical_plan).
//!
//! ### Physical plan
//!
//! A Physical plan ([`ExecutionPlan`](physical_plan::ExecutionPlan)) is a plan that can be executed against data.
//! Contrarily to a logical plan, the physical plan has concrete information about how the calculation
//! should be performed (e.g. what Rust functions are used) and how data should be loaded into memory.
//!
//! [`ExecutionPlan`](physical_plan::ExecutionPlan) uses the Arrow format as its in-memory representation of data, through the [arrow] crate.
//! We recommend going through [its documentation](arrow) for details on how the data is physically represented.
//!
//! A [`ExecutionPlan`](physical_plan::ExecutionPlan) is composed by nodes (implement the trait [`ExecutionPlan`](physical_plan::ExecutionPlan)),
//! and each node is composed by physical expressions ([`PhysicalExpr`](physical_plan::PhysicalExpr))
//! or aggreagate expressions ([`AggregateExpr`](physical_plan::AggregateExpr)).
//! All of these are located in the module [`physical_plan`](physical_plan).
//!
//! Broadly speaking,
//!
//! * an [`ExecutionPlan`](physical_plan::ExecutionPlan) receives a partition number and asyncronosly returns
//! an iterator over [`RecordBatch`](arrow::record_batch::RecordBatch)
//! (a node-specific struct that implements [`RecordBatchReader`](arrow::record_batch::RecordBatchReader))
//! * a [`PhysicalExpr`](physical_plan::PhysicalExpr) receives a [`RecordBatch`](arrow::record_batch::RecordBatch)
//! and returns an [`Array`](arrow::array::Array)
//! * an [`AggregateExpr`](physical_plan::AggregateExpr) receives [`RecordBatch`es](arrow::record_batch::RecordBatch)
//! and returns a [`RecordBatch`](arrow::record_batch::RecordBatch) of a single row(*)
//!
//! (*) Technically, it aggregates the results on each partition and then merges the results into a single partition.
//!
//! The following physical nodes are currently implemented:
//!
//! * Projection: [`ProjectionExec`](physical_plan::projection::ProjectionExec)
//! * Filter: [`FilterExec`](physical_plan::filter::FilterExec)
//! * Hash and Grouped aggregations: [`HashAggregateExec`](physical_plan::hash_aggregate::HashAggregateExec)
//! * Sort: [`SortExec`](physical_plan::sort::SortExec)
//! * Merge (partitions): [`MergeExec`](physical_plan::merge::MergeExec)
//! * Limit: [`LocalLimitExec`](physical_plan::limit::LocalLimitExec) and [`GlobalLimitExec`](physical_plan::limit::GlobalLimitExec)
//! * Scan a CSV: [`CsvExec`](physical_plan::csv::CsvExec)
//! * Scan a Parquet: [`ParquetExec`](physical_plan::parquet::ParquetExec)
//! * Scan from memory: [`MemoryExec`](physical_plan::memory::MemoryExec)
//! * Explain the plan: [`ExplainExec`](physical_plan::explain::ExplainExec)
//!
//! ## Customize
//!
//! DataFusion allows users to
//! * extend the planner to use user-defined logical and physical nodes ([`QueryPlanner`](execution::context::QueryPlanner))
//! * declare and use user-defined scalar functions ([`ScalarUDF`](physical_plan::udf::ScalarUDF))
//! * declare and use user-defined aggregate functions ([`AggregateUDF`](physical_plan::udaf::AggregateUDF))
//!
//! you can find examples of each of them in examples section.
extern crate arrow;
extern crate sqlparser;
pub mod dataframe;
pub mod datasource;
pub mod error;
pub mod execution;
pub mod logical_plan;
pub mod optimizer;
pub mod physical_plan;
pub mod prelude;
pub mod scalar;
pub mod sql;
pub mod variable;
#[cfg(test)]
pub mod test; | //! and how to execute a query against a CSV using SQL:
//! | random_line_split |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT),
});
this.connected = false;
}
public async query(query: string, args?: any[]): Promise<IDatabaseRow[]> {
let result: QueryResult;
await this.connectIfNecessary();
try {
result = await this.client.query(query, args);
} catch(postgresError) {
console.error(postgresError);
throw new DatabaseServiceError('Database query failed', postgresError);
}
return result.rows;
}
public async bulkInsert(tableName: string, columnNames: string[], rows: any[][]): Promise<IDatabaseRow[]> {
const rowsPerInsert = 1000;
const query = `insert into ${tableName} (${columnNames.join()}) values`;
let allReturnedRows: any[] = [];
for (let i = 0; i < rows.length; i += rowsPerInsert) {
const rowSlice = rows.slice(i, i + rowsPerInsert);
const placeholders: string[] = [];
const values: any[] = [];
let counter = 1;
for (const row of rowSlice) {
placeholders.push(`(${row.map(() => `$${counter++}`).join()})`);
for (const value of row) {
values.push(value);
}
}
const fullQuery = `${query} ${placeholders.join()} returning *`;
const returnedRows = await this.query(fullQuery, values);
allReturnedRows = allReturnedRows.concat(returnedRows);
}
return allReturnedRows;
}
private async connectIfNecessary() {
if (!this.connected) {
try {
await this.client.connect();
} catch(postgresError) {
throw new DatabaseServiceError('Could not connect to database', postgresError);
}
this.connected = true;
}
}
}
export const databaseService = new DatabaseService();
enum ErrorType {
NotNullViolation,
UniqueViolation,
Other,
}
export class DatabaseServiceError extends Error {
public readonly type: ErrorType;
public readonly table: string | undefined;
public readonly column: string | undefined;
public readonly constraint: string | undefined;
constructor(message: string, postgresError: any) {
super(message);
switch (postgresError.code) {
case '23502':
this.type = ErrorType.NotNullViolation;
break;
case '23505':
this.type = ErrorType.UniqueViolation;
break;
default:
this.type = ErrorType.Other;
break;
}
this.table = postgresError.table;
this.column = postgresError.column;
this.constraint = postgresError.constraint;
}
public isNotNullViolationOnColumn(table: string, column: string): boolean {
if (this.type === ErrorType.NotNullViolation
&& this.table === table && this.column === column) | else {
return false;
}
}
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
}
| {
return true;
} | conditional_block |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT),
});
this.connected = false;
}
public async query(query: string, args?: any[]): Promise<IDatabaseRow[]> {
let result: QueryResult;
await this.connectIfNecessary();
try {
result = await this.client.query(query, args);
} catch(postgresError) {
console.error(postgresError);
throw new DatabaseServiceError('Database query failed', postgresError);
}
return result.rows;
}
public async bulkInsert(tableName: string, columnNames: string[], rows: any[][]): Promise<IDatabaseRow[]> {
const rowsPerInsert = 1000;
const query = `insert into ${tableName} (${columnNames.join()}) values`;
let allReturnedRows: any[] = [];
for (let i = 0; i < rows.length; i += rowsPerInsert) {
const rowSlice = rows.slice(i, i + rowsPerInsert);
const placeholders: string[] = [];
const values: any[] = [];
let counter = 1;
for (const row of rowSlice) {
placeholders.push(`(${row.map(() => `$${counter++}`).join()})`);
for (const value of row) {
values.push(value);
}
}
const fullQuery = `${query} ${placeholders.join()} returning *`;
const returnedRows = await this.query(fullQuery, values);
allReturnedRows = allReturnedRows.concat(returnedRows);
}
return allReturnedRows;
}
private async connectIfNecessary() {
if (!this.connected) {
try {
await this.client.connect();
} catch(postgresError) {
throw new DatabaseServiceError('Could not connect to database', postgresError);
}
this.connected = true;
}
}
}
export const databaseService = new DatabaseService();
enum ErrorType {
NotNullViolation,
UniqueViolation,
Other,
}
export class DatabaseServiceError extends Error {
public readonly type: ErrorType;
public readonly table: string | undefined;
public readonly column: string | undefined;
public readonly constraint: string | undefined;
constructor(message: string, postgresError: any) {
super(message);
switch (postgresError.code) {
case '23502':
this.type = ErrorType.NotNullViolation;
break;
case '23505':
this.type = ErrorType.UniqueViolation;
break;
default:
this.type = ErrorType.Other;
break;
}
this.table = postgresError.table;
this.column = postgresError.column;
this.constraint = postgresError.constraint;
}
public isNotNullViolationOnColumn(table: string, column: string): boolean |
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
}
| {
if (this.type === ErrorType.NotNullViolation
&& this.table === table && this.column === column) {
return true;
} else {
return false;
}
} | identifier_body |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT),
});
this.connected = false;
}
public async query(query: string, args?: any[]): Promise<IDatabaseRow[]> {
let result: QueryResult;
await this.connectIfNecessary();
try {
result = await this.client.query(query, args);
} catch(postgresError) {
console.error(postgresError);
throw new DatabaseServiceError('Database query failed', postgresError);
}
return result.rows;
}
public async bulkInsert(tableName: string, columnNames: string[], rows: any[][]): Promise<IDatabaseRow[]> {
const rowsPerInsert = 1000;
const query = `insert into ${tableName} (${columnNames.join()}) values`;
let allReturnedRows: any[] = [];
for (let i = 0; i < rows.length; i += rowsPerInsert) {
const rowSlice = rows.slice(i, i + rowsPerInsert);
const placeholders: string[] = [];
const values: any[] = [];
let counter = 1;
for (const row of rowSlice) {
placeholders.push(`(${row.map(() => `$${counter++}`).join()})`);
for (const value of row) {
values.push(value);
}
}
const fullQuery = `${query} ${placeholders.join()} returning *`;
const returnedRows = await this.query(fullQuery, values);
allReturnedRows = allReturnedRows.concat(returnedRows);
}
return allReturnedRows;
}
private async connectIfNecessary() {
if (!this.connected) {
try {
await this.client.connect();
} catch(postgresError) {
throw new DatabaseServiceError('Could not connect to database', postgresError);
}
this.connected = true;
}
}
}
export const databaseService = new DatabaseService();
enum ErrorType {
NotNullViolation,
UniqueViolation,
Other,
}
export class DatabaseServiceError extends Error {
public readonly type: ErrorType;
public readonly table: string | undefined;
public readonly column: string | undefined;
public readonly constraint: string | undefined;
| (message: string, postgresError: any) {
super(message);
switch (postgresError.code) {
case '23502':
this.type = ErrorType.NotNullViolation;
break;
case '23505':
this.type = ErrorType.UniqueViolation;
break;
default:
this.type = ErrorType.Other;
break;
}
this.table = postgresError.table;
this.column = postgresError.column;
this.constraint = postgresError.constraint;
}
public isNotNullViolationOnColumn(table: string, column: string): boolean {
if (this.type === ErrorType.NotNullViolation
&& this.table === table && this.column === column) {
return true;
} else {
return false;
}
}
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
}
| constructor | identifier_name |
DatabaseService.ts | import { Client, QueryResult } from 'pg';
export interface IDatabaseRow {
[columnName: string]: any;
}
class DatabaseService {
private readonly client: Client;
private connected: boolean = false;
constructor() {
this.client = new Client({
user: process.env.DATABASE_USERNAME,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME,
host: process.env.DATABASE_HOST,
port: Number(process.env.DATABASE_PORT),
});
this.connected = false;
}
public async query(query: string, args?: any[]): Promise<IDatabaseRow[]> {
let result: QueryResult;
await this.connectIfNecessary();
try {
result = await this.client.query(query, args);
} catch(postgresError) {
console.error(postgresError);
throw new DatabaseServiceError('Database query failed', postgresError);
}
return result.rows; | }
public async bulkInsert(tableName: string, columnNames: string[], rows: any[][]): Promise<IDatabaseRow[]> {
const rowsPerInsert = 1000;
const query = `insert into ${tableName} (${columnNames.join()}) values`;
let allReturnedRows: any[] = [];
for (let i = 0; i < rows.length; i += rowsPerInsert) {
const rowSlice = rows.slice(i, i + rowsPerInsert);
const placeholders: string[] = [];
const values: any[] = [];
let counter = 1;
for (const row of rowSlice) {
placeholders.push(`(${row.map(() => `$${counter++}`).join()})`);
for (const value of row) {
values.push(value);
}
}
const fullQuery = `${query} ${placeholders.join()} returning *`;
const returnedRows = await this.query(fullQuery, values);
allReturnedRows = allReturnedRows.concat(returnedRows);
}
return allReturnedRows;
}
private async connectIfNecessary() {
if (!this.connected) {
try {
await this.client.connect();
} catch(postgresError) {
throw new DatabaseServiceError('Could not connect to database', postgresError);
}
this.connected = true;
}
}
}
export const databaseService = new DatabaseService();
enum ErrorType {
NotNullViolation,
UniqueViolation,
Other,
}
export class DatabaseServiceError extends Error {
public readonly type: ErrorType;
public readonly table: string | undefined;
public readonly column: string | undefined;
public readonly constraint: string | undefined;
constructor(message: string, postgresError: any) {
super(message);
switch (postgresError.code) {
case '23502':
this.type = ErrorType.NotNullViolation;
break;
case '23505':
this.type = ErrorType.UniqueViolation;
break;
default:
this.type = ErrorType.Other;
break;
}
this.table = postgresError.table;
this.column = postgresError.column;
this.constraint = postgresError.constraint;
}
public isNotNullViolationOnColumn(table: string, column: string): boolean {
if (this.type === ErrorType.NotNullViolation
&& this.table === table && this.column === column) {
return true;
} else {
return false;
}
}
public isUniqueViolationOnConstraint(constraint: string): boolean {
if (this.type === ErrorType.UniqueViolation && this.constraint === constraint) {
return true;
} else {
return false;
}
}
} | random_line_split | |
express.ts | import grant from 'grant';
import session from 'express-session';
import { Request, Response, NextFunction } from 'express';
import { createDebug } from '@feathersjs/commons';
import { Application } from '@feathersjs/feathers';
import { AuthenticationResult } from '@feathersjs/authentication';
import {
Application as ExpressApplication,
original as originalExpress
} from '@feathersjs/express';
import { OauthSetupSettings } from './utils';
import { OAuthStrategy } from './strategy';
const grantInstance = grant.express();
const debug = createDebug('@feathersjs/authentication-oauth/express');
declare module 'express-session' {
interface SessionData {
redirect: string;
accessToken: string;
query: { [key: string]: any };
grant: { [key: string]: any };
headers: { [key: string]: any };
}
}
export default (options: OauthSetupSettings) => {
return (feathersApp: Application) => {
const { authService, linkStrategy } = options;
const app = feathersApp as ExpressApplication;
const config = app.get('grant');
if (!config) {
debug('No grant configuration found, skipping Express oAuth setup');
return;
}
const { prefix } = config.defaults;
const expressSession = options.expressSession || session({
secret: Math.random().toString(36).substring(7),
saveUninitialized: true,
resave: true
});
const grantApp = grantInstance(config);
const authApp = originalExpress();
authApp.use(expressSession);
authApp.get('/:name', (req: Request, _res: Response, next: NextFunction) => {
const { feathers_token, redirect, ...query } = req.query;
if (feathers_token) {
debug('Got feathers_token query parameter to link accounts', feathers_token);
req.session.accessToken = feathers_token as string;
}
req.session.redirect = redirect as string;
req.session.query = query;
req.session.headers = req.headers;
req.session.save((err: any) => {
if (err) {
next(`Error storing session: ${err}`);
} else {
next();
}
});
});
authApp.get('/:name/authenticate', async (req: Request, res: Response, next: NextFunction) => {
const { name } = req.params ;
const { accessToken, grant, query = {}, redirect, headers } = req.session;
const service = app.defaultAuthentication(authService);
const [ strategy ] = service.getStrategies(name) as OAuthStrategy[];
const params = {
...req.feathers,
authStrategies: [ name ],
authentication: accessToken ? {
strategy: linkStrategy,
accessToken
} : null,
query,
redirect,
headers
};
const sendResponse = async (data: AuthenticationResult|Error) => {
try {
const redirect = await strategy.getRedirect(data, params);
if (redirect !== null) {
res.redirect(redirect);
} else if (data instanceof Error) {
throw data;
} else {
res.json(data);
}
} catch (error: any) {
debug('oAuth error', error);
next(error);
}
};
try {
const payload = config.defaults.transport === 'session' ?
grant.response : req.query;
const authentication = {
strategy: name,
...payload
};
await new Promise<void>((resolve, reject) => {
if (!req.session.destroy) {
req.session = null;
resolve();
}
req.session.destroy((err: any) => err ? reject(err) : resolve());
});
debug(`Calling ${authService}.create authentication with strategy ${name}`);
const authResult = await service.create(authentication, params); | debug('Successful oAuth authentication, sending response');
await sendResponse(authResult);
} catch (error: any) {
debug('Received oAuth authentication error', error.stack);
await sendResponse(error);
}
});
authApp.use(grantApp);
app.set('grant', grantApp.config);
app.use(prefix, authApp);
};
}; | random_line_split | |
express.ts | import grant from 'grant';
import session from 'express-session';
import { Request, Response, NextFunction } from 'express';
import { createDebug } from '@feathersjs/commons';
import { Application } from '@feathersjs/feathers';
import { AuthenticationResult } from '@feathersjs/authentication';
import {
Application as ExpressApplication,
original as originalExpress
} from '@feathersjs/express';
import { OauthSetupSettings } from './utils';
import { OAuthStrategy } from './strategy';
const grantInstance = grant.express();
const debug = createDebug('@feathersjs/authentication-oauth/express');
declare module 'express-session' {
interface SessionData {
redirect: string;
accessToken: string;
query: { [key: string]: any };
grant: { [key: string]: any };
headers: { [key: string]: any };
}
}
export default (options: OauthSetupSettings) => {
return (feathersApp: Application) => {
const { authService, linkStrategy } = options;
const app = feathersApp as ExpressApplication;
const config = app.get('grant');
if (!config) {
debug('No grant configuration found, skipping Express oAuth setup');
return;
}
const { prefix } = config.defaults;
const expressSession = options.expressSession || session({
secret: Math.random().toString(36).substring(7),
saveUninitialized: true,
resave: true
});
const grantApp = grantInstance(config);
const authApp = originalExpress();
authApp.use(expressSession);
authApp.get('/:name', (req: Request, _res: Response, next: NextFunction) => {
const { feathers_token, redirect, ...query } = req.query;
if (feathers_token) {
debug('Got feathers_token query parameter to link accounts', feathers_token);
req.session.accessToken = feathers_token as string;
}
req.session.redirect = redirect as string;
req.session.query = query;
req.session.headers = req.headers;
req.session.save((err: any) => {
if (err) {
next(`Error storing session: ${err}`);
} else {
next();
}
});
});
authApp.get('/:name/authenticate', async (req: Request, res: Response, next: NextFunction) => {
const { name } = req.params ;
const { accessToken, grant, query = {}, redirect, headers } = req.session;
const service = app.defaultAuthentication(authService);
const [ strategy ] = service.getStrategies(name) as OAuthStrategy[];
const params = {
...req.feathers,
authStrategies: [ name ],
authentication: accessToken ? {
strategy: linkStrategy,
accessToken
} : null,
query,
redirect,
headers
};
const sendResponse = async (data: AuthenticationResult|Error) => {
try {
const redirect = await strategy.getRedirect(data, params);
if (redirect !== null) {
res.redirect(redirect);
} else if (data instanceof Error) | else {
res.json(data);
}
} catch (error: any) {
debug('oAuth error', error);
next(error);
}
};
try {
const payload = config.defaults.transport === 'session' ?
grant.response : req.query;
const authentication = {
strategy: name,
...payload
};
await new Promise<void>((resolve, reject) => {
if (!req.session.destroy) {
req.session = null;
resolve();
}
req.session.destroy((err: any) => err ? reject(err) : resolve());
});
debug(`Calling ${authService}.create authentication with strategy ${name}`);
const authResult = await service.create(authentication, params);
debug('Successful oAuth authentication, sending response');
await sendResponse(authResult);
} catch (error: any) {
debug('Received oAuth authentication error', error.stack);
await sendResponse(error);
}
});
authApp.use(grantApp);
app.set('grant', grantApp.config);
app.use(prefix, authApp);
};
};
| {
throw data;
} | conditional_block |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
"""
NOPRINT = (None, KeyboardInterrupt)
def __init__(self, **defaults):
super(TracebackCompat, self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
self._register_patch(traceback, key, getattr(self, key))
#def __exit__(self, etype, evalue, tb):
#if etype not in self.NOPRINT:
#self.print_exception(etype, evalue, tb)
#super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=None, **options):
options["limit"] = \
getattr(sys, "tracebacklimit", None) if limit is None else limit
_options = self.defaults.copy()
_options.update(options)
return XTraceback(etype, value, tb, **_options)
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
# late binding here may cause problems where there is no sys i.e. on
# google app engine but it is required for cases where sys.stderr is
# rebound i.e. under nose
if file is None and hasattr(sys, "stderr"):
|
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options)
return xtb.format_tb()
@functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only()
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
options["limit"] = limit
return "".join(self.format_exception(*sys.exc_info(), **options))
@functools.wraps(traceback.print_tb)
def print_tb(self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._print_factory(etype, value, tb, limit, file, **options)
xtb.print_exception()
@functools.wraps(traceback.print_exc)
def print_exc(self, limit=None, file=None, **options):
options["limit"] = limit
options["file"] = file
self.print_exception(*sys.exc_info(), **options)
| file = sys.stderr | conditional_block |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
"""
NOPRINT = (None, KeyboardInterrupt)
def __init__(self, **defaults):
super(TracebackCompat, self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
self._register_patch(traceback, key, getattr(self, key))
#def __exit__(self, etype, evalue, tb):
#if etype not in self.NOPRINT:
#self.print_exception(etype, evalue, tb)
#super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=None, **options):
options["limit"] = \
getattr(sys, "tracebacklimit", None) if limit is None else limit
_options = self.defaults.copy()
_options.update(options)
return XTraceback(etype, value, tb, **_options)
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
# late binding here may cause problems where there is no sys i.e. on
# google app engine but it is required for cases where sys.stderr is
# rebound i.e. under nose
if file is None and hasattr(sys, "stderr"):
file = sys.stderr
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options)
return xtb.format_tb()
@functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
|
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
options["limit"] = limit
return "".join(self.format_exception(*sys.exc_info(), **options))
@functools.wraps(traceback.print_tb)
def print_tb(self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._print_factory(etype, value, tb, limit, file, **options)
xtb.print_exception()
@functools.wraps(traceback.print_exc)
def print_exc(self, limit=None, file=None, **options):
options["limit"] = limit
options["file"] = file
self.print_exception(*sys.exc_info(), **options)
| xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only() | identifier_body |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
"""
NOPRINT = (None, KeyboardInterrupt)
def __init__(self, **defaults):
super(TracebackCompat, self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
self._register_patch(traceback, key, getattr(self, key))
#def __exit__(self, etype, evalue, tb):
#if etype not in self.NOPRINT:
#self.print_exception(etype, evalue, tb)
#super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=None, **options):
options["limit"] = \
getattr(sys, "tracebacklimit", None) if limit is None else limit
_options = self.defaults.copy()
_options.update(options)
return XTraceback(etype, value, tb, **_options)
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
# late binding here may cause problems where there is no sys i.e. on
# google app engine but it is required for cases where sys.stderr is
# rebound i.e. under nose
if file is None and hasattr(sys, "stderr"):
file = sys.stderr
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options) | @functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only()
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
options["limit"] = limit
return "".join(self.format_exception(*sys.exc_info(), **options))
@functools.wraps(traceback.print_tb)
def print_tb(self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._print_factory(etype, value, tb, limit, file, **options)
xtb.print_exception()
@functools.wraps(traceback.print_exc)
def print_exc(self, limit=None, file=None, **options):
options["limit"] = limit
options["file"] = file
self.print_exception(*sys.exc_info(), **options) | return xtb.format_tb()
| random_line_split |
tracebackcompat.py | import functools
import sys
import traceback
from stacked import Stacked
from .xtraceback import XTraceback
class TracebackCompat(Stacked):
"""
A context manager that patches the stdlib traceback module
Functions in the traceback module that exist as a method of this class are
replaced with equivalents that use XTraceback.
:cvar NOPRINT: Exception types that we don't print for (includes None)
:type NOPRINT: tuple
:ivar defaults: Default options to apply to XTracebacks created by this
instance
:type defaults: dict
"""
NOPRINT = (None, KeyboardInterrupt)
def __init__(self, **defaults):
super(TracebackCompat, self).__init__()
self.defaults = defaults
# register patches for methods that wrap traceback functions
for key in dir(traceback):
if hasattr(self, key):
self._register_patch(traceback, key, getattr(self, key))
#def __exit__(self, etype, evalue, tb):
#if etype not in self.NOPRINT:
#self.print_exception(etype, evalue, tb)
#super(TracebackCompat, self).__exit__(etype, evalue, tb)
def _factory(self, etype, value, tb, limit=None, **options):
options["limit"] = \
getattr(sys, "tracebacklimit", None) if limit is None else limit
_options = self.defaults.copy()
_options.update(options)
return XTraceback(etype, value, tb, **_options)
def _print_factory(self, etype, value, tb, limit=None, file=None,
**options):
# late binding here may cause problems where there is no sys i.e. on
# google app engine but it is required for cases where sys.stderr is
# rebound i.e. under nose
if file is None and hasattr(sys, "stderr"):
file = sys.stderr
options["stream"] = file
return self._factory(etype, value, tb, limit, **options)
@functools.wraps(traceback.format_tb)
def format_tb(self, tb, limit=None, **options):
xtb = self._factory(None, None, tb, limit, **options)
return xtb.format_tb()
@functools.wraps(traceback.format_exception_only)
def format_exception_only(self, etype, value, **options):
xtb = self._factory(etype, value, None, **options)
return xtb.format_exception_only()
@functools.wraps(traceback.format_exception)
def format_exception(self, etype, value, tb, limit=None, **options):
xtb = self._factory(etype, value, tb, limit, **options)
return xtb.format_exception()
@functools.wraps(traceback.format_exc)
def format_exc(self, limit=None, **options):
options["limit"] = limit
return "".join(self.format_exception(*sys.exc_info(), **options))
@functools.wraps(traceback.print_tb)
def | (self, tb, limit=None, file=None, **options):
xtb = self._print_factory(None, None, tb, limit, file, **options)
xtb.print_tb()
@functools.wraps(traceback.print_exception)
def print_exception(self, etype, value, tb, limit=None, file=None,
**options):
xtb = self._print_factory(etype, value, tb, limit, file, **options)
xtb.print_exception()
@functools.wraps(traceback.print_exc)
def print_exc(self, limit=None, file=None, **options):
options["limit"] = limit
options["file"] = file
self.print_exception(*sys.exc_info(), **options)
| print_tb | identifier_name |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use cssparser::{Parser, RGBA};
use euclid::{TypedScale, Size2D, TypedSize2D};
use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues;
use selectors::parser::SelectorParseErrorKind;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::{CSSPixel, DevicePixel, ToCss, ParseError};
use style_traits::viewport::ViewportConstraints;
use values::computed::{self, ToComputedValue};
use values::computed::font::FontSize;
use values::specified;
/// A device is a structure that represents the current media a given document
/// is displayed in.
///
/// This is the struct against which media queries are evaluated.
#[derive(MallocSizeOf)]
pub struct Device {
/// The current media type used by de device.
media_type: MediaType,
/// The current viewport size, in CSS pixels.
viewport_size: TypedSize2D<f32, CSSPixel>,
/// The current device pixel ratio, from CSS pixels to device pixels.
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
/// The font size of the root element
/// This is set when computing the style of the root
/// element, and used for rem units in other elements
///
/// When computing the style of the root element, there can't be any
/// other style being computed at the same time, given we need the style of
/// the parent to compute everything else. So it is correct to just use
/// a relaxed atomic here.
#[ignore_malloc_size_of = "Pure stack type"]
root_font_size: AtomicIsize,
/// Whether any styles computed in the document relied on the root font-size
/// by using rem units.
#[ignore_malloc_size_of = "Pure stack type"]
used_root_font_size: AtomicBool,
/// Whether any styles computed in the document relied on the viewport size.
#[ignore_malloc_size_of = "Pure stack type"]
used_viewport_units: AtomicBool,
}
impl Device {
/// Trivially construct a new `Device`.
pub fn new(
media_type: MediaType,
viewport_size: TypedSize2D<f32, CSSPixel>,
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>
) -> Device {
Device {
media_type,
viewport_size,
device_pixel_ratio,
// FIXME(bz): Seems dubious?
root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize),
used_root_font_size: AtomicBool::new(false),
used_viewport_units: AtomicBool::new(false),
}
}
/// Return the default computed values for this device.
pub fn default_computed_values(&self) -> &ComputedValues {
// FIXME(bz): This isn't really right, but it's no more wrong
// than what we used to do. See
// https://github.com/servo/servo/issues/14773 for fixing it properly.
ComputedValues::initial_values()
}
/// Get the font size of the root element (for rem)
pub fn root_font_size(&self) -> Au {
self.used_root_font_size.store(true, Ordering::Relaxed);
Au::new(self.root_font_size.load(Ordering::Relaxed) as i32)
}
/// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed)
}
/// Sets the body text color for the "inherit color from body" quirk.
///
/// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk>
pub fn set_body_text_color(&self, _color: RGBA) {
// Servo doesn't implement this quirk (yet)
}
/// Returns whether we ever looked up the root font size of the Device.
pub fn used_root_font_size(&self) -> bool {
self.used_root_font_size.load(Ordering::Relaxed)
}
/// Returns the viewport size of the current device in app units, needed,
/// among other things, to resolve viewport units.
#[inline]
pub fn au_viewport_size(&self) -> Size2D<Au> {
Size2D::new(Au::from_f32_px(self.viewport_size.width),
Au::from_f32_px(self.viewport_size.height))
}
/// Like the above, but records that we've used viewport units.
pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> {
self.used_viewport_units.store(true, Ordering::Relaxed);
self.au_viewport_size()
}
/// Whether viewport units were used since the last device change.
pub fn used_viewport_units(&self) -> bool {
self.used_viewport_units.load(Ordering::Relaxed)
}
/// Returns the device pixel ratio.
pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> {
self.device_pixel_ratio
}
/// Take into account a viewport rule taken from the stylesheets.
pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) {
self.viewport_size = constraints.size;
}
/// Return the media type of the current device.
pub fn media_type(&self) -> MediaType {
self.media_type.clone()
}
/// Returns whether document colors are enabled.
pub fn use_document_colors(&self) -> bool {
true
}
/// Returns the default background color.
pub fn default_background_color(&self) -> RGBA {
RGBA::new(255, 255, 255, 255)
}
}
/// A expression kind servo understands and parses.
///
/// Only `pub` for unit testing, please don't use it directly!
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum ExpressionKind {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
impl Expression { | /// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
/// Only supports width and width ranges for now.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let name = input.expect_ident_cloned()?;
input.expect_colon()?;
// TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => {
ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?))
},
"max-width" => {
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?))
},
"width" => {
ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?))
},
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone())))
}))
})
}
/// Evaluate this expression and return whether it matches the current
/// device.
pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
let viewport_size = device.au_viewport_size();
let value = viewport_size.width;
match self.0 {
ExpressionKind::Width(ref range) => {
match range.to_computed_range(device, quirks_mode) {
Range::Min(ref width) => { value >= *width },
Range::Max(ref width) => { value <= *width },
Range::Eq(ref width) => { value == *width },
}
}
}
}
}
impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
let (s, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l),
ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l),
ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l),
};
dest.write_str(s)?;
l.to_css(dest)?;
dest.write_char(')')
}
}
/// An enumeration that represents a ranged value.
///
/// Only public for testing, implementation details of `Expression` may change
/// for Stylo.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum Range<T> {
/// At least the inner value.
Min(T),
/// At most the inner value.
Max(T),
/// Exactly the inner value.
Eq(T),
}
impl Range<specified::Length> {
fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
match *self {
Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))),
Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))),
Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context)))
}
})
}
} | random_line_split | |
media_queries.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/. */
//! Servo's media-query device and expression representation.
use app_units::Au;
use context::QuirksMode;
use cssparser::{Parser, RGBA};
use euclid::{TypedScale, Size2D, TypedSize2D};
use media_queries::MediaType;
use parser::ParserContext;
use properties::ComputedValues;
use selectors::parser::SelectorParseErrorKind;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering};
use style_traits::{CSSPixel, DevicePixel, ToCss, ParseError};
use style_traits::viewport::ViewportConstraints;
use values::computed::{self, ToComputedValue};
use values::computed::font::FontSize;
use values::specified;
/// A device is a structure that represents the current media a given document
/// is displayed in.
///
/// This is the struct against which media queries are evaluated.
#[derive(MallocSizeOf)]
pub struct Device {
/// The current media type used by de device.
media_type: MediaType,
/// The current viewport size, in CSS pixels.
viewport_size: TypedSize2D<f32, CSSPixel>,
/// The current device pixel ratio, from CSS pixels to device pixels.
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>,
/// The font size of the root element
/// This is set when computing the style of the root
/// element, and used for rem units in other elements
///
/// When computing the style of the root element, there can't be any
/// other style being computed at the same time, given we need the style of
/// the parent to compute everything else. So it is correct to just use
/// a relaxed atomic here.
#[ignore_malloc_size_of = "Pure stack type"]
root_font_size: AtomicIsize,
/// Whether any styles computed in the document relied on the root font-size
/// by using rem units.
#[ignore_malloc_size_of = "Pure stack type"]
used_root_font_size: AtomicBool,
/// Whether any styles computed in the document relied on the viewport size.
#[ignore_malloc_size_of = "Pure stack type"]
used_viewport_units: AtomicBool,
}
impl Device {
/// Trivially construct a new `Device`.
pub fn new(
media_type: MediaType,
viewport_size: TypedSize2D<f32, CSSPixel>,
device_pixel_ratio: TypedScale<f32, CSSPixel, DevicePixel>
) -> Device {
Device {
media_type,
viewport_size,
device_pixel_ratio,
// FIXME(bz): Seems dubious?
root_font_size: AtomicIsize::new(FontSize::medium().size().0 as isize),
used_root_font_size: AtomicBool::new(false),
used_viewport_units: AtomicBool::new(false),
}
}
/// Return the default computed values for this device.
pub fn default_computed_values(&self) -> &ComputedValues {
// FIXME(bz): This isn't really right, but it's no more wrong
// than what we used to do. See
// https://github.com/servo/servo/issues/14773 for fixing it properly.
ComputedValues::initial_values()
}
/// Get the font size of the root element (for rem)
pub fn root_font_size(&self) -> Au {
self.used_root_font_size.store(true, Ordering::Relaxed);
Au::new(self.root_font_size.load(Ordering::Relaxed) as i32)
}
/// Set the font size of the root element (for rem)
pub fn set_root_font_size(&self, size: Au) {
self.root_font_size.store(size.0 as isize, Ordering::Relaxed)
}
/// Sets the body text color for the "inherit color from body" quirk.
///
/// <https://quirks.spec.whatwg.org/#the-tables-inherit-color-from-body-quirk>
pub fn set_body_text_color(&self, _color: RGBA) {
// Servo doesn't implement this quirk (yet)
}
/// Returns whether we ever looked up the root font size of the Device.
pub fn used_root_font_size(&self) -> bool {
self.used_root_font_size.load(Ordering::Relaxed)
}
/// Returns the viewport size of the current device in app units, needed,
/// among other things, to resolve viewport units.
#[inline]
pub fn au_viewport_size(&self) -> Size2D<Au> {
Size2D::new(Au::from_f32_px(self.viewport_size.width),
Au::from_f32_px(self.viewport_size.height))
}
/// Like the above, but records that we've used viewport units.
pub fn au_viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> {
self.used_viewport_units.store(true, Ordering::Relaxed);
self.au_viewport_size()
}
/// Whether viewport units were used since the last device change.
pub fn used_viewport_units(&self) -> bool {
self.used_viewport_units.load(Ordering::Relaxed)
}
/// Returns the device pixel ratio.
pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> {
self.device_pixel_ratio
}
/// Take into account a viewport rule taken from the stylesheets.
pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) {
self.viewport_size = constraints.size;
}
/// Return the media type of the current device.
pub fn media_type(&self) -> MediaType {
self.media_type.clone()
}
/// Returns whether document colors are enabled.
pub fn use_document_colors(&self) -> bool {
true
}
/// Returns the default background color.
pub fn default_background_color(&self) -> RGBA {
RGBA::new(255, 255, 255, 255)
}
}
/// A expression kind servo understands and parses.
///
/// Only `pub` for unit testing, please don't use it directly!
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum | {
/// <http://dev.w3.org/csswg/mediaqueries-3/#width>
Width(Range<specified::Length>),
}
/// A single expression a per:
///
/// <http://dev.w3.org/csswg/mediaqueries-3/#media1>
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub struct Expression(pub ExpressionKind);
impl Expression {
/// The kind of expression we're, just for unit testing.
///
/// Eventually this will become servo-only.
pub fn kind_for_testing(&self) -> &ExpressionKind {
&self.0
}
/// Parse a media expression of the form:
///
/// ```
/// (media-feature: media-value)
/// ```
///
/// Only supports width and width ranges for now.
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Self, ParseError<'i>> {
input.expect_parenthesis_block()?;
input.parse_nested_block(|input| {
let name = input.expect_ident_cloned()?;
input.expect_colon()?;
// TODO: Handle other media features
Ok(Expression(match_ignore_ascii_case! { &name,
"min-width" => {
ExpressionKind::Width(Range::Min(specified::Length::parse_non_negative(context, input)?))
},
"max-width" => {
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?))
},
"width" => {
ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?))
},
_ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone())))
}))
})
}
/// Evaluate this expression and return whether it matches the current
/// device.
pub fn matches(&self, device: &Device, quirks_mode: QuirksMode) -> bool {
let viewport_size = device.au_viewport_size();
let value = viewport_size.width;
match self.0 {
ExpressionKind::Width(ref range) => {
match range.to_computed_range(device, quirks_mode) {
Range::Min(ref width) => { value >= *width },
Range::Max(ref width) => { value <= *width },
Range::Eq(ref width) => { value == *width },
}
}
}
}
}
impl ToCss for Expression {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result
where W: fmt::Write,
{
let (s, l) = match self.0 {
ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l),
ExpressionKind::Width(Range::Max(ref l)) => ("(max-width: ", l),
ExpressionKind::Width(Range::Eq(ref l)) => ("(width: ", l),
};
dest.write_str(s)?;
l.to_css(dest)?;
dest.write_char(')')
}
}
/// An enumeration that represents a ranged value.
///
/// Only public for testing, implementation details of `Expression` may change
/// for Stylo.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
pub enum Range<T> {
/// At least the inner value.
Min(T),
/// At most the inner value.
Max(T),
/// Exactly the inner value.
Eq(T),
}
impl Range<specified::Length> {
fn to_computed_range(&self, device: &Device, quirks_mode: QuirksMode) -> Range<Au> {
computed::Context::for_media_query_evaluation(device, quirks_mode, |context| {
match *self {
Range::Min(ref width) => Range::Min(Au::from(width.to_computed_value(&context))),
Range::Max(ref width) => Range::Max(Au::from(width.to_computed_value(&context))),
Range::Eq(ref width) => Range::Eq(Au::from(width.to_computed_value(&context)))
}
})
}
}
| ExpressionKind | identifier_name |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
from gettext import gettext as _
import gettext
class StatsTipster(QWidget):
def __init__(self, mainWindows):
QWidget.__init__(self)
uic.loadUi(directory + "/../ui/stats_tipster.ui", self)
gettext.textdomain("betcon")
gettext.bindtextdomain("betcon", "../lang/mo" + mainWindows.lang)
gettext.bindtextdomain("betcon", "/usr/share/locale" + mainWindows.lang)
self.mainWindows = mainWindows
self.mainWindows.setWindowTitle(_("Stats Tipsters") + " | Betcon v" + mainWindows.version)
self.translate()
try:
self.initData()
except Exception:
print(_("Error trying to load the data."))
self.setEnabled(False)
self.cmbYear.activated.connect(self.updateMonths)
self.cmbMonth.activated.connect(self.updateTree)
def translate(self):
header = [_("Tipster"), _("Sport"), _("Bets"), _("Success"), _("Money Bet"), _("Profit"), _("Stake"), _("Quota")]
self.treeMonth.setHeaderLabels(header)
self.treeTotal.setHeaderLabels(header)
self.lblYear.setText(_("Year"))
self.lblMonth.setText(_("Month"))
self.lblTotalMonth.setText(_("Total of the month"))
self.lblTotal.setText(_("Totals"))
def initData(self):
self.years, self.months = LibStats.getYears()
self.cmbYear.addItems(self.years.keys())
firstKey = next(iter(self.years))
self.cmbMonth.addItems(self.getMonths(firstKey))
data = LibStats.getTipster()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeTotal.addTopLevelItems(items)
self.updateMonths()
def updateMonths(self):
year = self.cmbYear.currentText()
self.cmbMonth.clear()
self.cmbMonth.addItems(self.getMonths(year))
self.updateTree()
def updateTree(self):
|
def getMonths(self, year):
sMonths =[]
for i in self.years[year]:
sMonths.append(self.months[i])
return sMonths
| year = self.cmbYear.currentText()
sMonth = self.cmbMonth.currentText()
month = key_from_value(self.months, sMonth)
data = LibStats.getTipster(year, month)
self.treeMonth.clear()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeMonth.addTopLevelItems(items) | identifier_body |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
from gettext import gettext as _
import gettext
class StatsTipster(QWidget):
def __init__(self, mainWindows):
QWidget.__init__(self)
uic.loadUi(directory + "/../ui/stats_tipster.ui", self)
gettext.textdomain("betcon")
gettext.bindtextdomain("betcon", "../lang/mo" + mainWindows.lang)
gettext.bindtextdomain("betcon", "/usr/share/locale" + mainWindows.lang)
self.mainWindows = mainWindows
self.mainWindows.setWindowTitle(_("Stats Tipsters") + " | Betcon v" + mainWindows.version)
self.translate()
try:
self.initData()
except Exception:
print(_("Error trying to load the data."))
self.setEnabled(False)
self.cmbYear.activated.connect(self.updateMonths)
self.cmbMonth.activated.connect(self.updateTree)
def translate(self):
header = [_("Tipster"), _("Sport"), _("Bets"), _("Success"), _("Money Bet"), _("Profit"), _("Stake"), _("Quota")]
self.treeMonth.setHeaderLabels(header)
self.treeTotal.setHeaderLabels(header)
self.lblYear.setText(_("Year"))
self.lblMonth.setText(_("Month"))
self.lblTotalMonth.setText(_("Total of the month"))
self.lblTotal.setText(_("Totals"))
def initData(self):
self.years, self.months = LibStats.getYears()
self.cmbYear.addItems(self.years.keys())
firstKey = next(iter(self.years))
self.cmbMonth.addItems(self.getMonths(firstKey))
data = LibStats.getTipster()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeTotal.addTopLevelItems(items)
self.updateMonths()
def updateMonths(self):
year = self.cmbYear.currentText()
self.cmbMonth.clear()
self.cmbMonth.addItems(self.getMonths(year))
self.updateTree()
def updateTree(self):
year = self.cmbYear.currentText()
sMonth = self.cmbMonth.currentText()
month = key_from_value(self.months, sMonth)
data = LibStats.getTipster(year, month)
self.treeMonth.clear()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeMonth.addTopLevelItems(items) | sMonths.append(self.months[i])
return sMonths |
def getMonths(self, year):
sMonths =[]
for i in self.years[year]: | random_line_split |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
from gettext import gettext as _
import gettext
class StatsTipster(QWidget):
def __init__(self, mainWindows):
QWidget.__init__(self)
uic.loadUi(directory + "/../ui/stats_tipster.ui", self)
gettext.textdomain("betcon")
gettext.bindtextdomain("betcon", "../lang/mo" + mainWindows.lang)
gettext.bindtextdomain("betcon", "/usr/share/locale" + mainWindows.lang)
self.mainWindows = mainWindows
self.mainWindows.setWindowTitle(_("Stats Tipsters") + " | Betcon v" + mainWindows.version)
self.translate()
try:
self.initData()
except Exception:
print(_("Error trying to load the data."))
self.setEnabled(False)
self.cmbYear.activated.connect(self.updateMonths)
self.cmbMonth.activated.connect(self.updateTree)
def translate(self):
header = [_("Tipster"), _("Sport"), _("Bets"), _("Success"), _("Money Bet"), _("Profit"), _("Stake"), _("Quota")]
self.treeMonth.setHeaderLabels(header)
self.treeTotal.setHeaderLabels(header)
self.lblYear.setText(_("Year"))
self.lblMonth.setText(_("Month"))
self.lblTotalMonth.setText(_("Total of the month"))
self.lblTotal.setText(_("Totals"))
def | (self):
self.years, self.months = LibStats.getYears()
self.cmbYear.addItems(self.years.keys())
firstKey = next(iter(self.years))
self.cmbMonth.addItems(self.getMonths(firstKey))
data = LibStats.getTipster()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeTotal.addTopLevelItems(items)
self.updateMonths()
def updateMonths(self):
year = self.cmbYear.currentText()
self.cmbMonth.clear()
self.cmbMonth.addItems(self.getMonths(year))
self.updateTree()
def updateTree(self):
year = self.cmbYear.currentText()
sMonth = self.cmbMonth.currentText()
month = key_from_value(self.months, sMonth)
data = LibStats.getTipster(year, month)
self.treeMonth.clear()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeMonth.addTopLevelItems(items)
def getMonths(self, year):
sMonths =[]
for i in self.years[year]:
sMonths.append(self.months[i])
return sMonths
| initData | identifier_name |
stats_tipster.py | import sys, os, inspect
from PyQt5.QtWidgets import QWidget, QTreeWidgetItem
from PyQt5 import uic
directory = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
sys.path.append(directory + "/lib")
from libstats import LibStats
from func_aux import paint_row, key_from_value
from gettext import gettext as _
import gettext
class StatsTipster(QWidget):
def __init__(self, mainWindows):
QWidget.__init__(self)
uic.loadUi(directory + "/../ui/stats_tipster.ui", self)
gettext.textdomain("betcon")
gettext.bindtextdomain("betcon", "../lang/mo" + mainWindows.lang)
gettext.bindtextdomain("betcon", "/usr/share/locale" + mainWindows.lang)
self.mainWindows = mainWindows
self.mainWindows.setWindowTitle(_("Stats Tipsters") + " | Betcon v" + mainWindows.version)
self.translate()
try:
self.initData()
except Exception:
print(_("Error trying to load the data."))
self.setEnabled(False)
self.cmbYear.activated.connect(self.updateMonths)
self.cmbMonth.activated.connect(self.updateTree)
def translate(self):
header = [_("Tipster"), _("Sport"), _("Bets"), _("Success"), _("Money Bet"), _("Profit"), _("Stake"), _("Quota")]
self.treeMonth.setHeaderLabels(header)
self.treeTotal.setHeaderLabels(header)
self.lblYear.setText(_("Year"))
self.lblMonth.setText(_("Month"))
self.lblTotalMonth.setText(_("Total of the month"))
self.lblTotal.setText(_("Totals"))
def initData(self):
self.years, self.months = LibStats.getYears()
self.cmbYear.addItems(self.years.keys())
firstKey = next(iter(self.years))
self.cmbMonth.addItems(self.getMonths(firstKey))
data = LibStats.getTipster()
items = []
for i in data:
|
self.treeTotal.addTopLevelItems(items)
self.updateMonths()
def updateMonths(self):
year = self.cmbYear.currentText()
self.cmbMonth.clear()
self.cmbMonth.addItems(self.getMonths(year))
self.updateTree()
def updateTree(self):
year = self.cmbYear.currentText()
sMonth = self.cmbMonth.currentText()
month = key_from_value(self.months, sMonth)
data = LibStats.getTipster(year, month)
self.treeMonth.clear()
items = []
for i in data:
item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item)
self.treeMonth.addTopLevelItems(items)
def getMonths(self, year):
sMonths =[]
for i in self.years[year]:
sMonths.append(self.months[i])
return sMonths
| item = QTreeWidgetItem(i)
item = paint_row(item, i[5])
items.append(item) | conditional_block |
Font.js | lychee.define('Font').exports(function(lychee) {
var Class = function(spriteOrImages, settings) {
this.settings = lychee.extend({}, this.defaults, settings);
if (this.settings.kerning > this.settings.spacing) {
this.settings.kerning = this.settings.spacing;
}
this.__cache = {};
this.__images = null;
this.__sprite = null;
if (Object.prototype.toString.call(spriteOrImages) === '[object Array]') {
this.__images = spriteOrImages;
} else {
this.__sprite = spriteOrImages;
}
this.__init();
};
Class.prototype = {
defaults: {
// default charset from 32-126
charset: ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~',
baseline: 0,
spacing: 0,
kerning: 0,
map: null
},
__init: function() {
// Single Image Mode
if (this.__images !== null) {
this.__initImages();
// Sprite Image Mode
} else if (this.__sprite !== null) {
if (Object.prototype.toString.call(this.settings.map) === '[object Array]') {
var test = this.settings.map[0];
if (Object.prototype.toString.call(test) === '[object Object]') {
this.__initSpriteXY();
} else if (typeof test === 'number') {
this.__initSpriteX();
}
}
}
},
__initImages: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var image = this.__images[c] || null;
if (image === null) continue;
var chr = {
id: this.settings.charset[c],
image: image,
width: image.width,
height: image.height,
x: 0,
y: 0
};
this.__cache[chr.id] = chr;
}
},
__initSpriteX: function() {
var offset = this.settings.spacing;
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var chr = {
id: this.settings.charset[c],
width: this.settings.map[c] + this.settings.spacing * 2,
height: this.__sprite.height,
real: this.settings.map[c],
x: offset - this.settings.spacing,
y: 0
};
offset += chr.width;
this.__cache[chr.id] = chr; |
}
},
__initSpriteXY: function() {
for (var c = 0, l = this.settings.charset.length; c < l; c++) {
var frame = this.settings.map[c];
var chr = {
id: this.settings.charset[c],
width: frame.width + this.settings.spacing * 2,
height: frame.height,
real: frame.width,
x: frame.x - this.settings.spacing,
y: frame.y
};
this.__cache[chr.id] = chr;
}
},
get: function(id) {
if (this.__cache[id] !== undefined) {
return this.__cache[id];
}
return null;
},
getSettings: function() {
return this.settings;
},
getSprite: function() {
return this.__sprite;
}
};
return Class;
}); | random_line_split | |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { MainThreadTunnelServiceShape, IExtHostContext, MainContext, ExtHostContext, ExtHostTunnelServiceShape, CandidatePortSource, PortAttributesProviderSelector } from 'vs/workbench/api/common/extHost.protocol';
import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { CandidatePort, IRemoteExplorerService, makeAddress, PORT_AUTO_FORWARD_SETTING, PORT_AUTO_SOURCE_SETTING, PORT_AUTO_SOURCE_SETTING_OUTPUT, PORT_AUTO_SOURCE_SETTING_PROCESS, TunnelSource } from 'vs/workbench/services/remote/common/remoteExplorerService';
import { ITunnelProvider, ITunnelService, TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions, RemoteTunnel, isPortPrivileged, ProvidedPortAttributes, PortAttributesProvider, TunnelProtocol } from 'vs/platform/remote/common/tunnel';
import { Disposable } from 'vs/base/common/lifecycle';
import type { TunnelDescription } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService } from 'vs/platform/log/common/log';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
@extHostNamedCustomer(MainContext.MainThreadTunnelService)
export class MainThreadTunnelService extends Disposable implements MainThreadTunnelServiceShape, PortAttributesProvider {
private readonly _proxy: ExtHostTunnelServiceShape;
private elevateionRetry: boolean = false;
private portsAttributesProviders: Map<number, PortAttributesProviderSelector> = new Map();
constructor(
extHostContext: IExtHostContext,
@IRemoteExplorerService private readonly remoteExplorerService: IRemoteExplorerService,
@ITunnelService private readonly tunnelService: ITunnelService,
@INotificationService private readonly notificationService: INotificationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService
) {
super();
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTunnelService);
this._register(tunnelService.onTunnelOpened(() => this._proxy.$onDidTunnelsChange()));
this._register(tunnelService.onTunnelClosed(() => this._proxy.$onDidTunnelsChange()));
}
private processFindingEnabled(): boolean {
return (!!this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING) || this.tunnelService.hasTunnelProvider)
&& (this.configurationService.getValue(PORT_AUTO_SOURCE_SETTING) === PORT_AUTO_SOURCE_SETTING_PROCESS);
}
async $setRemoteTunnelService(processId: number): Promise<void> {
this.remoteExplorerService.namedProcesses.set(processId, 'Code Extension Host');
if (this.remoteExplorerService.portsFeaturesEnabled) {
this._proxy.$registerCandidateFinder(this.processFindingEnabled());
} else {
this._register(this.remoteExplorerService.onEnabledPortsFeatures(() => this._proxy.$registerCandidateFinder(this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING)))); | }
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_SETTING) || e.affectsConfiguration(PORT_AUTO_SOURCE_SETTING)) {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}
}));
this._register(this.tunnelService.onAddedTunnelProvider(() => {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}));
}
private _alreadyRegistered: boolean = false;
async $registerPortsAttributesProvider(selector: PortAttributesProviderSelector, providerHandle: number): Promise<void> {
this.portsAttributesProviders.set(providerHandle, selector);
if (!this._alreadyRegistered) {
this.remoteExplorerService.tunnelModel.addAttributesProvider(this);
this._alreadyRegistered = true;
}
}
async $unregisterPortsAttributesProvider(providerHandle: number): Promise<void> {
this.portsAttributesProviders.delete(providerHandle);
}
async providePortAttributes(ports: number[], pid: number | undefined, commandLine: string | undefined, token: CancellationToken): Promise<ProvidedPortAttributes[]> {
if (this.portsAttributesProviders.size === 0) {
return [];
}
// Check all the selectors to make sure it's worth going to the extension host.
const appropriateHandles = Array.from(this.portsAttributesProviders.entries()).filter(entry => {
const selector = entry[1];
const portRange = selector.portRange;
const portInRange = portRange ? ports.some(port => portRange[0] <= port && port < portRange[1]) : true;
const pidMatches = !selector.pid || (selector.pid === pid);
const commandMatches = !selector.commandMatcher || (commandLine && (commandLine.match(selector.commandMatcher)));
return portInRange && pidMatches && commandMatches;
}).map(entry => entry[0]);
if (appropriateHandles.length === 0) {
return [];
}
return this._proxy.$providePortAttributes(appropriateHandles, ports, pid, commandLine, token);
}
async $openTunnel(tunnelOptions: TunnelOptions, source: string): Promise<TunnelDto | undefined> {
const tunnel = await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: false
});
if (tunnel) {
if (!this.elevateionRetry
&& (tunnelOptions.localAddressPort !== undefined)
&& (tunnel.tunnelLocalPort !== undefined)
&& isPortPrivileged(tunnelOptions.localAddressPort)
&& (tunnel.tunnelLocalPort !== tunnelOptions.localAddressPort)
&& this.tunnelService.canElevate) {
this.elevationPrompt(tunnelOptions, tunnel, source);
}
return TunnelDto.fromServiceTunnel(tunnel);
}
return undefined;
}
private async elevationPrompt(tunnelOptions: TunnelOptions, tunnel: RemoteTunnel, source: string) {
return this.notificationService.prompt(Severity.Info,
nls.localize('remote.tunnel.openTunnel', "The extension {0} has forwarded port {1}. You'll need to run as superuser to use port {2} locally.", source, tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort),
[{
label: nls.localize('remote.tunnelsView.elevationButton', "Use Port {0} as Sudo...", tunnel.tunnelRemotePort),
run: async () => {
this.elevateionRetry = true;
await this.remoteExplorerService.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort });
await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: true
});
this.elevateionRetry = false;
}
}]);
}
async $closeTunnel(remote: { host: string, port: number }): Promise<void> {
return this.remoteExplorerService.close(remote);
}
async $getTunnels(): Promise<TunnelDescription[]> {
return (await this.tunnelService.tunnels).map(tunnel => {
return {
remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
localAddress: tunnel.localAddress,
privacy: tunnel.privacy,
protocol: tunnel.protocol
};
});
}
async $onFoundNewCandidates(candidates: CandidatePort[]): Promise<void> {
this.remoteExplorerService.onFoundNewCandidates(candidates);
}
async $setTunnelProvider(features?: TunnelProviderFeatures): Promise<void> {
const tunnelProvider: ITunnelProvider = {
forwardPort: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => {
const forward = this._proxy.$forwardPort(tunnelOptions, tunnelCreationOptions);
return forward.then(tunnel => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) New tunnel established by tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
if (!tunnel) {
return undefined;
}
return {
tunnelRemotePort: tunnel.remoteAddress.port,
tunnelRemoteHost: tunnel.remoteAddress.host,
localAddress: typeof tunnel.localAddress === 'string' ? tunnel.localAddress : makeAddress(tunnel.localAddress.host, tunnel.localAddress.port),
tunnelLocalPort: typeof tunnel.localAddress !== 'string' ? tunnel.localAddress.port : undefined,
public: tunnel.public,
privacy: tunnel.privacy,
protocol: tunnel.protocol ?? TunnelProtocol.Http,
dispose: async (silent?: boolean) => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) Closing tunnel from tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
return this._proxy.$closeTunnel({ host: tunnel.remoteAddress.host, port: tunnel.remoteAddress.port }, silent);
}
};
});
}
};
this.tunnelService.setTunnelProvider(tunnelProvider);
if (features) {
this.tunnelService.setTunnelFeatures(features);
}
}
async $setCandidateFilter(): Promise<void> {
this.remoteExplorerService.setCandidateFilter((candidates: CandidatePort[]): Promise<CandidatePort[]> => {
return this._proxy.$applyCandidateFilter(candidates);
});
}
async $setCandidatePortSource(source: CandidatePortSource): Promise<void> {
// Must wait for the remote environment before trying to set settings there.
this.remoteAgentService.getEnvironment().then(() => {
switch (source) {
case CandidatePortSource.None: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPorts': false } }]);
break;
}
case CandidatePortSource.Output: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPortsSource': PORT_AUTO_SOURCE_SETTING_OUTPUT } }]);
break;
}
default: // Do nothing, the defaults for these settings should be used.
}
}).catch(() => {
// The remote failed to get setup. Errors from that area will already be surfaced to the user.
});
}
} | random_line_split | |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { MainThreadTunnelServiceShape, IExtHostContext, MainContext, ExtHostContext, ExtHostTunnelServiceShape, CandidatePortSource, PortAttributesProviderSelector } from 'vs/workbench/api/common/extHost.protocol';
import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { CandidatePort, IRemoteExplorerService, makeAddress, PORT_AUTO_FORWARD_SETTING, PORT_AUTO_SOURCE_SETTING, PORT_AUTO_SOURCE_SETTING_OUTPUT, PORT_AUTO_SOURCE_SETTING_PROCESS, TunnelSource } from 'vs/workbench/services/remote/common/remoteExplorerService';
import { ITunnelProvider, ITunnelService, TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions, RemoteTunnel, isPortPrivileged, ProvidedPortAttributes, PortAttributesProvider, TunnelProtocol } from 'vs/platform/remote/common/tunnel';
import { Disposable } from 'vs/base/common/lifecycle';
import type { TunnelDescription } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService } from 'vs/platform/log/common/log';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
@extHostNamedCustomer(MainContext.MainThreadTunnelService)
export class MainThreadTunnelService extends Disposable implements MainThreadTunnelServiceShape, PortAttributesProvider {
private readonly _proxy: ExtHostTunnelServiceShape;
private elevateionRetry: boolean = false;
private portsAttributesProviders: Map<number, PortAttributesProviderSelector> = new Map();
constructor(
extHostContext: IExtHostContext,
@IRemoteExplorerService private readonly remoteExplorerService: IRemoteExplorerService,
@ITunnelService private readonly tunnelService: ITunnelService,
@INotificationService private readonly notificationService: INotificationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService
) {
super();
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTunnelService);
this._register(tunnelService.onTunnelOpened(() => this._proxy.$onDidTunnelsChange()));
this._register(tunnelService.onTunnelClosed(() => this._proxy.$onDidTunnelsChange()));
}
private processFindingEnabled(): boolean {
return (!!this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING) || this.tunnelService.hasTunnelProvider)
&& (this.configurationService.getValue(PORT_AUTO_SOURCE_SETTING) === PORT_AUTO_SOURCE_SETTING_PROCESS);
}
async $setRemoteTunnelService(processId: number): Promise<void> {
this.remoteExplorerService.namedProcesses.set(processId, 'Code Extension Host');
if (this.remoteExplorerService.portsFeaturesEnabled) {
this._proxy.$registerCandidateFinder(this.processFindingEnabled());
} else {
this._register(this.remoteExplorerService.onEnabledPortsFeatures(() => this._proxy.$registerCandidateFinder(this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING))));
}
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_SETTING) || e.affectsConfiguration(PORT_AUTO_SOURCE_SETTING)) {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}
}));
this._register(this.tunnelService.onAddedTunnelProvider(() => {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}));
}
private _alreadyRegistered: boolean = false;
async $registerPortsAttributesProvider(selector: PortAttributesProviderSelector, providerHandle: number): Promise<void> {
this.portsAttributesProviders.set(providerHandle, selector);
if (!this._alreadyRegistered) {
this.remoteExplorerService.tunnelModel.addAttributesProvider(this);
this._alreadyRegistered = true;
}
}
async $unregisterPortsAttributesProvider(providerHandle: number): Promise<void> {
this.portsAttributesProviders.delete(providerHandle);
}
async providePortAttributes(ports: number[], pid: number | undefined, commandLine: string | undefined, token: CancellationToken): Promise<ProvidedPortAttributes[]> {
if (this.portsAttributesProviders.size === 0) {
return [];
}
// Check all the selectors to make sure it's worth going to the extension host.
const appropriateHandles = Array.from(this.portsAttributesProviders.entries()).filter(entry => {
const selector = entry[1];
const portRange = selector.portRange;
const portInRange = portRange ? ports.some(port => portRange[0] <= port && port < portRange[1]) : true;
const pidMatches = !selector.pid || (selector.pid === pid);
const commandMatches = !selector.commandMatcher || (commandLine && (commandLine.match(selector.commandMatcher)));
return portInRange && pidMatches && commandMatches;
}).map(entry => entry[0]);
if (appropriateHandles.length === 0) {
return [];
}
return this._proxy.$providePortAttributes(appropriateHandles, ports, pid, commandLine, token);
}
async $openTunnel(tunnelOptions: TunnelOptions, source: string): Promise<TunnelDto | undefined> {
const tunnel = await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: false
});
if (tunnel) {
if (!this.elevateionRetry
&& (tunnelOptions.localAddressPort !== undefined)
&& (tunnel.tunnelLocalPort !== undefined)
&& isPortPrivileged(tunnelOptions.localAddressPort)
&& (tunnel.tunnelLocalPort !== tunnelOptions.localAddressPort)
&& this.tunnelService.canElevate) {
this.elevationPrompt(tunnelOptions, tunnel, source);
}
return TunnelDto.fromServiceTunnel(tunnel);
}
return undefined;
}
private async elevationPrompt(tunnelOptions: TunnelOptions, tunnel: RemoteTunnel, source: string) {
return this.notificationService.prompt(Severity.Info,
nls.localize('remote.tunnel.openTunnel', "The extension {0} has forwarded port {1}. You'll need to run as superuser to use port {2} locally.", source, tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort),
[{
label: nls.localize('remote.tunnelsView.elevationButton', "Use Port {0} as Sudo...", tunnel.tunnelRemotePort),
run: async () => {
this.elevateionRetry = true;
await this.remoteExplorerService.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort });
await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: true
});
this.elevateionRetry = false;
}
}]);
}
async $closeTunnel(remote: { host: string, port: number }): Promise<void> {
return this.remoteExplorerService.close(remote);
}
async $getTunnels(): Promise<TunnelDescription[]> |
async $onFoundNewCandidates(candidates: CandidatePort[]): Promise<void> {
this.remoteExplorerService.onFoundNewCandidates(candidates);
}
async $setTunnelProvider(features?: TunnelProviderFeatures): Promise<void> {
const tunnelProvider: ITunnelProvider = {
forwardPort: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => {
const forward = this._proxy.$forwardPort(tunnelOptions, tunnelCreationOptions);
return forward.then(tunnel => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) New tunnel established by tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
if (!tunnel) {
return undefined;
}
return {
tunnelRemotePort: tunnel.remoteAddress.port,
tunnelRemoteHost: tunnel.remoteAddress.host,
localAddress: typeof tunnel.localAddress === 'string' ? tunnel.localAddress : makeAddress(tunnel.localAddress.host, tunnel.localAddress.port),
tunnelLocalPort: typeof tunnel.localAddress !== 'string' ? tunnel.localAddress.port : undefined,
public: tunnel.public,
privacy: tunnel.privacy,
protocol: tunnel.protocol ?? TunnelProtocol.Http,
dispose: async (silent?: boolean) => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) Closing tunnel from tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
return this._proxy.$closeTunnel({ host: tunnel.remoteAddress.host, port: tunnel.remoteAddress.port }, silent);
}
};
});
}
};
this.tunnelService.setTunnelProvider(tunnelProvider);
if (features) {
this.tunnelService.setTunnelFeatures(features);
}
}
async $setCandidateFilter(): Promise<void> {
this.remoteExplorerService.setCandidateFilter((candidates: CandidatePort[]): Promise<CandidatePort[]> => {
return this._proxy.$applyCandidateFilter(candidates);
});
}
async $setCandidatePortSource(source: CandidatePortSource): Promise<void> {
// Must wait for the remote environment before trying to set settings there.
this.remoteAgentService.getEnvironment().then(() => {
switch (source) {
case CandidatePortSource.None: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPorts': false } }]);
break;
}
case CandidatePortSource.Output: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPortsSource': PORT_AUTO_SOURCE_SETTING_OUTPUT } }]);
break;
}
default: // Do nothing, the defaults for these settings should be used.
}
}).catch(() => {
// The remote failed to get setup. Errors from that area will already be surfaced to the user.
});
}
}
| {
return (await this.tunnelService.tunnels).map(tunnel => {
return {
remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
localAddress: tunnel.localAddress,
privacy: tunnel.privacy,
protocol: tunnel.protocol
};
});
} | identifier_body |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { MainThreadTunnelServiceShape, IExtHostContext, MainContext, ExtHostContext, ExtHostTunnelServiceShape, CandidatePortSource, PortAttributesProviderSelector } from 'vs/workbench/api/common/extHost.protocol';
import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { CandidatePort, IRemoteExplorerService, makeAddress, PORT_AUTO_FORWARD_SETTING, PORT_AUTO_SOURCE_SETTING, PORT_AUTO_SOURCE_SETTING_OUTPUT, PORT_AUTO_SOURCE_SETTING_PROCESS, TunnelSource } from 'vs/workbench/services/remote/common/remoteExplorerService';
import { ITunnelProvider, ITunnelService, TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions, RemoteTunnel, isPortPrivileged, ProvidedPortAttributes, PortAttributesProvider, TunnelProtocol } from 'vs/platform/remote/common/tunnel';
import { Disposable } from 'vs/base/common/lifecycle';
import type { TunnelDescription } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService } from 'vs/platform/log/common/log';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
@extHostNamedCustomer(MainContext.MainThreadTunnelService)
export class MainThreadTunnelService extends Disposable implements MainThreadTunnelServiceShape, PortAttributesProvider {
private readonly _proxy: ExtHostTunnelServiceShape;
private elevateionRetry: boolean = false;
private portsAttributesProviders: Map<number, PortAttributesProviderSelector> = new Map();
constructor(
extHostContext: IExtHostContext,
@IRemoteExplorerService private readonly remoteExplorerService: IRemoteExplorerService,
@ITunnelService private readonly tunnelService: ITunnelService,
@INotificationService private readonly notificationService: INotificationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService
) {
super();
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTunnelService);
this._register(tunnelService.onTunnelOpened(() => this._proxy.$onDidTunnelsChange()));
this._register(tunnelService.onTunnelClosed(() => this._proxy.$onDidTunnelsChange()));
}
private processFindingEnabled(): boolean {
return (!!this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING) || this.tunnelService.hasTunnelProvider)
&& (this.configurationService.getValue(PORT_AUTO_SOURCE_SETTING) === PORT_AUTO_SOURCE_SETTING_PROCESS);
}
async $setRemoteTunnelService(processId: number): Promise<void> {
this.remoteExplorerService.namedProcesses.set(processId, 'Code Extension Host');
if (this.remoteExplorerService.portsFeaturesEnabled) {
this._proxy.$registerCandidateFinder(this.processFindingEnabled());
} else {
this._register(this.remoteExplorerService.onEnabledPortsFeatures(() => this._proxy.$registerCandidateFinder(this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING))));
}
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_SETTING) || e.affectsConfiguration(PORT_AUTO_SOURCE_SETTING)) {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}
}));
this._register(this.tunnelService.onAddedTunnelProvider(() => {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}));
}
private _alreadyRegistered: boolean = false;
async $registerPortsAttributesProvider(selector: PortAttributesProviderSelector, providerHandle: number): Promise<void> {
this.portsAttributesProviders.set(providerHandle, selector);
if (!this._alreadyRegistered) {
this.remoteExplorerService.tunnelModel.addAttributesProvider(this);
this._alreadyRegistered = true;
}
}
async | (providerHandle: number): Promise<void> {
this.portsAttributesProviders.delete(providerHandle);
}
async providePortAttributes(ports: number[], pid: number | undefined, commandLine: string | undefined, token: CancellationToken): Promise<ProvidedPortAttributes[]> {
if (this.portsAttributesProviders.size === 0) {
return [];
}
// Check all the selectors to make sure it's worth going to the extension host.
const appropriateHandles = Array.from(this.portsAttributesProviders.entries()).filter(entry => {
const selector = entry[1];
const portRange = selector.portRange;
const portInRange = portRange ? ports.some(port => portRange[0] <= port && port < portRange[1]) : true;
const pidMatches = !selector.pid || (selector.pid === pid);
const commandMatches = !selector.commandMatcher || (commandLine && (commandLine.match(selector.commandMatcher)));
return portInRange && pidMatches && commandMatches;
}).map(entry => entry[0]);
if (appropriateHandles.length === 0) {
return [];
}
return this._proxy.$providePortAttributes(appropriateHandles, ports, pid, commandLine, token);
}
async $openTunnel(tunnelOptions: TunnelOptions, source: string): Promise<TunnelDto | undefined> {
const tunnel = await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: false
});
if (tunnel) {
if (!this.elevateionRetry
&& (tunnelOptions.localAddressPort !== undefined)
&& (tunnel.tunnelLocalPort !== undefined)
&& isPortPrivileged(tunnelOptions.localAddressPort)
&& (tunnel.tunnelLocalPort !== tunnelOptions.localAddressPort)
&& this.tunnelService.canElevate) {
this.elevationPrompt(tunnelOptions, tunnel, source);
}
return TunnelDto.fromServiceTunnel(tunnel);
}
return undefined;
}
private async elevationPrompt(tunnelOptions: TunnelOptions, tunnel: RemoteTunnel, source: string) {
return this.notificationService.prompt(Severity.Info,
nls.localize('remote.tunnel.openTunnel', "The extension {0} has forwarded port {1}. You'll need to run as superuser to use port {2} locally.", source, tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort),
[{
label: nls.localize('remote.tunnelsView.elevationButton', "Use Port {0} as Sudo...", tunnel.tunnelRemotePort),
run: async () => {
this.elevateionRetry = true;
await this.remoteExplorerService.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort });
await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: true
});
this.elevateionRetry = false;
}
}]);
}
async $closeTunnel(remote: { host: string, port: number }): Promise<void> {
return this.remoteExplorerService.close(remote);
}
async $getTunnels(): Promise<TunnelDescription[]> {
return (await this.tunnelService.tunnels).map(tunnel => {
return {
remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
localAddress: tunnel.localAddress,
privacy: tunnel.privacy,
protocol: tunnel.protocol
};
});
}
async $onFoundNewCandidates(candidates: CandidatePort[]): Promise<void> {
this.remoteExplorerService.onFoundNewCandidates(candidates);
}
async $setTunnelProvider(features?: TunnelProviderFeatures): Promise<void> {
const tunnelProvider: ITunnelProvider = {
forwardPort: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => {
const forward = this._proxy.$forwardPort(tunnelOptions, tunnelCreationOptions);
return forward.then(tunnel => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) New tunnel established by tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
if (!tunnel) {
return undefined;
}
return {
tunnelRemotePort: tunnel.remoteAddress.port,
tunnelRemoteHost: tunnel.remoteAddress.host,
localAddress: typeof tunnel.localAddress === 'string' ? tunnel.localAddress : makeAddress(tunnel.localAddress.host, tunnel.localAddress.port),
tunnelLocalPort: typeof tunnel.localAddress !== 'string' ? tunnel.localAddress.port : undefined,
public: tunnel.public,
privacy: tunnel.privacy,
protocol: tunnel.protocol ?? TunnelProtocol.Http,
dispose: async (silent?: boolean) => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) Closing tunnel from tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
return this._proxy.$closeTunnel({ host: tunnel.remoteAddress.host, port: tunnel.remoteAddress.port }, silent);
}
};
});
}
};
this.tunnelService.setTunnelProvider(tunnelProvider);
if (features) {
this.tunnelService.setTunnelFeatures(features);
}
}
async $setCandidateFilter(): Promise<void> {
this.remoteExplorerService.setCandidateFilter((candidates: CandidatePort[]): Promise<CandidatePort[]> => {
return this._proxy.$applyCandidateFilter(candidates);
});
}
async $setCandidatePortSource(source: CandidatePortSource): Promise<void> {
// Must wait for the remote environment before trying to set settings there.
this.remoteAgentService.getEnvironment().then(() => {
switch (source) {
case CandidatePortSource.None: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPorts': false } }]);
break;
}
case CandidatePortSource.Output: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPortsSource': PORT_AUTO_SOURCE_SETTING_OUTPUT } }]);
break;
}
default: // Do nothing, the defaults for these settings should be used.
}
}).catch(() => {
// The remote failed to get setup. Errors from that area will already be surfaced to the user.
});
}
}
| $unregisterPortsAttributesProvider | identifier_name |
mainThreadTunnelService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import { MainThreadTunnelServiceShape, IExtHostContext, MainContext, ExtHostContext, ExtHostTunnelServiceShape, CandidatePortSource, PortAttributesProviderSelector } from 'vs/workbench/api/common/extHost.protocol';
import { TunnelDto } from 'vs/workbench/api/common/extHostTunnelService';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { CandidatePort, IRemoteExplorerService, makeAddress, PORT_AUTO_FORWARD_SETTING, PORT_AUTO_SOURCE_SETTING, PORT_AUTO_SOURCE_SETTING_OUTPUT, PORT_AUTO_SOURCE_SETTING_PROCESS, TunnelSource } from 'vs/workbench/services/remote/common/remoteExplorerService';
import { ITunnelProvider, ITunnelService, TunnelCreationOptions, TunnelProviderFeatures, TunnelOptions, RemoteTunnel, isPortPrivileged, ProvidedPortAttributes, PortAttributesProvider, TunnelProtocol } from 'vs/platform/remote/common/tunnel';
import { Disposable } from 'vs/base/common/lifecycle';
import type { TunnelDescription } from 'vs/platform/remote/common/remoteAuthorityResolver';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { ILogService } from 'vs/platform/log/common/log';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Registry } from 'vs/platform/registry/common/platform';
import { IConfigurationRegistry, Extensions as ConfigurationExtensions } from 'vs/platform/configuration/common/configurationRegistry';
@extHostNamedCustomer(MainContext.MainThreadTunnelService)
export class MainThreadTunnelService extends Disposable implements MainThreadTunnelServiceShape, PortAttributesProvider {
private readonly _proxy: ExtHostTunnelServiceShape;
private elevateionRetry: boolean = false;
private portsAttributesProviders: Map<number, PortAttributesProviderSelector> = new Map();
constructor(
extHostContext: IExtHostContext,
@IRemoteExplorerService private readonly remoteExplorerService: IRemoteExplorerService,
@ITunnelService private readonly tunnelService: ITunnelService,
@INotificationService private readonly notificationService: INotificationService,
@IConfigurationService private readonly configurationService: IConfigurationService,
@ILogService private readonly logService: ILogService,
@IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService
) {
super();
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTunnelService);
this._register(tunnelService.onTunnelOpened(() => this._proxy.$onDidTunnelsChange()));
this._register(tunnelService.onTunnelClosed(() => this._proxy.$onDidTunnelsChange()));
}
private processFindingEnabled(): boolean {
return (!!this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING) || this.tunnelService.hasTunnelProvider)
&& (this.configurationService.getValue(PORT_AUTO_SOURCE_SETTING) === PORT_AUTO_SOURCE_SETTING_PROCESS);
}
async $setRemoteTunnelService(processId: number): Promise<void> {
this.remoteExplorerService.namedProcesses.set(processId, 'Code Extension Host');
if (this.remoteExplorerService.portsFeaturesEnabled) | else {
this._register(this.remoteExplorerService.onEnabledPortsFeatures(() => this._proxy.$registerCandidateFinder(this.configurationService.getValue(PORT_AUTO_FORWARD_SETTING))));
}
this._register(this.configurationService.onDidChangeConfiguration(async (e) => {
if (e.affectsConfiguration(PORT_AUTO_FORWARD_SETTING) || e.affectsConfiguration(PORT_AUTO_SOURCE_SETTING)) {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}
}));
this._register(this.tunnelService.onAddedTunnelProvider(() => {
return this._proxy.$registerCandidateFinder(this.processFindingEnabled());
}));
}
private _alreadyRegistered: boolean = false;
async $registerPortsAttributesProvider(selector: PortAttributesProviderSelector, providerHandle: number): Promise<void> {
this.portsAttributesProviders.set(providerHandle, selector);
if (!this._alreadyRegistered) {
this.remoteExplorerService.tunnelModel.addAttributesProvider(this);
this._alreadyRegistered = true;
}
}
async $unregisterPortsAttributesProvider(providerHandle: number): Promise<void> {
this.portsAttributesProviders.delete(providerHandle);
}
async providePortAttributes(ports: number[], pid: number | undefined, commandLine: string | undefined, token: CancellationToken): Promise<ProvidedPortAttributes[]> {
if (this.portsAttributesProviders.size === 0) {
return [];
}
// Check all the selectors to make sure it's worth going to the extension host.
const appropriateHandles = Array.from(this.portsAttributesProviders.entries()).filter(entry => {
const selector = entry[1];
const portRange = selector.portRange;
const portInRange = portRange ? ports.some(port => portRange[0] <= port && port < portRange[1]) : true;
const pidMatches = !selector.pid || (selector.pid === pid);
const commandMatches = !selector.commandMatcher || (commandLine && (commandLine.match(selector.commandMatcher)));
return portInRange && pidMatches && commandMatches;
}).map(entry => entry[0]);
if (appropriateHandles.length === 0) {
return [];
}
return this._proxy.$providePortAttributes(appropriateHandles, ports, pid, commandLine, token);
}
async $openTunnel(tunnelOptions: TunnelOptions, source: string): Promise<TunnelDto | undefined> {
const tunnel = await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: false
});
if (tunnel) {
if (!this.elevateionRetry
&& (tunnelOptions.localAddressPort !== undefined)
&& (tunnel.tunnelLocalPort !== undefined)
&& isPortPrivileged(tunnelOptions.localAddressPort)
&& (tunnel.tunnelLocalPort !== tunnelOptions.localAddressPort)
&& this.tunnelService.canElevate) {
this.elevationPrompt(tunnelOptions, tunnel, source);
}
return TunnelDto.fromServiceTunnel(tunnel);
}
return undefined;
}
private async elevationPrompt(tunnelOptions: TunnelOptions, tunnel: RemoteTunnel, source: string) {
return this.notificationService.prompt(Severity.Info,
nls.localize('remote.tunnel.openTunnel', "The extension {0} has forwarded port {1}. You'll need to run as superuser to use port {2} locally.", source, tunnelOptions.remoteAddress.port, tunnelOptions.localAddressPort),
[{
label: nls.localize('remote.tunnelsView.elevationButton', "Use Port {0} as Sudo...", tunnel.tunnelRemotePort),
run: async () => {
this.elevateionRetry = true;
await this.remoteExplorerService.close({ host: tunnel.tunnelRemoteHost, port: tunnel.tunnelRemotePort });
await this.remoteExplorerService.forward({
remote: tunnelOptions.remoteAddress,
local: tunnelOptions.localAddressPort,
name: tunnelOptions.label,
source: {
source: TunnelSource.Extension,
description: source
},
elevateIfNeeded: true
});
this.elevateionRetry = false;
}
}]);
}
async $closeTunnel(remote: { host: string, port: number }): Promise<void> {
return this.remoteExplorerService.close(remote);
}
async $getTunnels(): Promise<TunnelDescription[]> {
return (await this.tunnelService.tunnels).map(tunnel => {
return {
remoteAddress: { port: tunnel.tunnelRemotePort, host: tunnel.tunnelRemoteHost },
localAddress: tunnel.localAddress,
privacy: tunnel.privacy,
protocol: tunnel.protocol
};
});
}
async $onFoundNewCandidates(candidates: CandidatePort[]): Promise<void> {
this.remoteExplorerService.onFoundNewCandidates(candidates);
}
async $setTunnelProvider(features?: TunnelProviderFeatures): Promise<void> {
const tunnelProvider: ITunnelProvider = {
forwardPort: (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions) => {
const forward = this._proxy.$forwardPort(tunnelOptions, tunnelCreationOptions);
return forward.then(tunnel => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) New tunnel established by tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
if (!tunnel) {
return undefined;
}
return {
tunnelRemotePort: tunnel.remoteAddress.port,
tunnelRemoteHost: tunnel.remoteAddress.host,
localAddress: typeof tunnel.localAddress === 'string' ? tunnel.localAddress : makeAddress(tunnel.localAddress.host, tunnel.localAddress.port),
tunnelLocalPort: typeof tunnel.localAddress !== 'string' ? tunnel.localAddress.port : undefined,
public: tunnel.public,
privacy: tunnel.privacy,
protocol: tunnel.protocol ?? TunnelProtocol.Http,
dispose: async (silent?: boolean) => {
this.logService.trace(`ForwardedPorts: (MainThreadTunnelService) Closing tunnel from tunnel provider: ${tunnel?.remoteAddress.host}:${tunnel?.remoteAddress.port}`);
return this._proxy.$closeTunnel({ host: tunnel.remoteAddress.host, port: tunnel.remoteAddress.port }, silent);
}
};
});
}
};
this.tunnelService.setTunnelProvider(tunnelProvider);
if (features) {
this.tunnelService.setTunnelFeatures(features);
}
}
async $setCandidateFilter(): Promise<void> {
this.remoteExplorerService.setCandidateFilter((candidates: CandidatePort[]): Promise<CandidatePort[]> => {
return this._proxy.$applyCandidateFilter(candidates);
});
}
async $setCandidatePortSource(source: CandidatePortSource): Promise<void> {
// Must wait for the remote environment before trying to set settings there.
this.remoteAgentService.getEnvironment().then(() => {
switch (source) {
case CandidatePortSource.None: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPorts': false } }]);
break;
}
case CandidatePortSource.Output: {
Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration)
.registerDefaultConfigurations([{ overrides: { 'remote.autoForwardPortsSource': PORT_AUTO_SOURCE_SETTING_OUTPUT } }]);
break;
}
default: // Do nothing, the defaults for these settings should be used.
}
}).catch(() => {
// The remote failed to get setup. Errors from that area will already be surfaced to the user.
});
}
}
| {
this._proxy.$registerCandidateFinder(this.processFindingEnabled());
} | conditional_block |
pl.js | /* | copy: 'Kopiuj',
copyError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne kopiowanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+C.',
cut: 'Wytnij',
cutError: 'Ustawienia bezpieczeństwa Twojej przeglądarki nie pozwalają na automatyczne wycinanie tekstu. Użyj skrótu klawiszowego Ctrl/Cmd+X.',
paste: 'Wklej',
pasteArea: 'Obszar wklejania',
pasteMsg: 'Wklej tekst w poniższym polu, używając skrótu klawiaturowego (<STRONG>Ctrl/Cmd+V</STRONG>), i kliknij <STRONG>OK</STRONG>.',
securityMsg: 'Zabezpieczenia przeglądarki uniemożliwiają wklejenie danych bezpośrednio do edytora. Proszę ponownie wkleić dane w tym oknie.',
title: 'Wklej'
} ); | Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'pl', { | random_line_split |
schema.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import {
GraphQLBoolean,
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
} from 'graphql';
import {
connectionArgs,
connectionDefinitions,
connectionFromArray,
fromGlobalId,
globalIdField,
mutationWithClientMutationId,
nodeDefinitions,
} from 'graphql-relay';
import {
Game,
HidingSpot,
checkHidingSpotForTreasure,
getGame,
getHidingSpot,
getHidingSpots,
getTurnsRemaining,
} from './database';
var {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
var {type, id} = fromGlobalId(globalId);
if (type === 'Game') {
return getGame(id);
} else if (type === 'HidingSpot') {
return getHidingSpot(id);
} else {
return null;
}
},
(obj) => {
if (obj instanceof Game) {
return gameType;
} else if (obj instanceof HidingSpot) | else {
return null;
}
}
);
var gameType = new GraphQLObjectType({
name: 'Game',
description: 'A treasure search game',
fields: () => ({
id: globalIdField('Game'),
hidingSpots: {
type: hidingSpotConnection,
description: 'Places where treasure might be hidden',
args: connectionArgs,
resolve: (game, args) => connectionFromArray(getHidingSpots(), args),
},
turnsRemaining: {
type: GraphQLInt,
description: 'The number of turns a player has left to find the treasure',
resolve: () => getTurnsRemaining(),
},
}),
interfaces: [nodeInterface],
});
var hidingSpotType = new GraphQLObjectType({
name: 'HidingSpot',
description: 'A place where you might find treasure',
fields: () => ({
id: globalIdField('HidingSpot'),
hasBeenChecked: {
type: GraphQLBoolean,
description: 'True this spot has already been checked for treasure',
resolve: (hidingSpot) => hidingSpot.hasBeenChecked,
},
hasTreasure: {
type: GraphQLBoolean,
description: 'True if this hiding spot holds treasure',
resolve: (hidingSpot) => {
if (hidingSpot.hasBeenChecked) {
return hidingSpot.hasTreasure;
} else {
return null; // Shh... it's a secret!
}
},
},
}),
interfaces: [nodeInterface],
});
var {connectionType: hidingSpotConnection} =
connectionDefinitions({name: 'HidingSpot', nodeType: hidingSpotType});
var queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
game: {
type: gameType,
resolve: () => getGame(),
},
}),
});
var CheckHidingSpotForTreasureMutation = mutationWithClientMutationId({
name: 'CheckHidingSpotForTreasure',
inputFields: {
id: { type: new GraphQLNonNull(GraphQLID) },
},
outputFields: {
hidingSpot: {
type: hidingSpotType,
resolve: ({localHidingSpotId}) => getHidingSpot(localHidingSpotId),
},
game: {
type: gameType,
resolve: () => getGame(),
},
},
mutateAndGetPayload: ({id}) => {
var localHidingSpotId = fromGlobalId(id).id;
checkHidingSpotForTreasure(localHidingSpotId);
return {localHidingSpotId};
},
});
var mutationType = new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
checkHidingSpotForTreasure: CheckHidingSpotForTreasureMutation,
}),
});
/**
* Finally, we construct our schema (whose starting query type is the query
* type we defined above) and export it.
*/
export var Schema = new GraphQLSchema({
query: queryType,
mutation: mutationType
});
| {
return hidingSpotType;
} | conditional_block |
schema.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import {
GraphQLBoolean,
GraphQLFloat,
GraphQLID,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
} from 'graphql';
import {
connectionArgs,
connectionDefinitions,
connectionFromArray,
fromGlobalId,
globalIdField,
mutationWithClientMutationId,
nodeDefinitions,
} from 'graphql-relay';
import {
Game,
HidingSpot,
checkHidingSpotForTreasure,
getGame,
getHidingSpot,
getHidingSpots,
getTurnsRemaining,
} from './database';
var {nodeInterface, nodeField} = nodeDefinitions(
(globalId) => {
var {type, id} = fromGlobalId(globalId);
if (type === 'Game') {
return getGame(id);
} else if (type === 'HidingSpot') {
return getHidingSpot(id);
} else {
return null;
}
},
(obj) => {
if (obj instanceof Game) {
return gameType;
} else if (obj instanceof HidingSpot) {
return hidingSpotType;
} else {
return null;
}
}
);
var gameType = new GraphQLObjectType({
name: 'Game',
description: 'A treasure search game',
fields: () => ({
id: globalIdField('Game'),
hidingSpots: {
type: hidingSpotConnection,
description: 'Places where treasure might be hidden',
args: connectionArgs,
resolve: (game, args) => connectionFromArray(getHidingSpots(), args),
},
turnsRemaining: {
type: GraphQLInt,
description: 'The number of turns a player has left to find the treasure',
resolve: () => getTurnsRemaining(),
},
}),
interfaces: [nodeInterface],
});
var hidingSpotType = new GraphQLObjectType({
name: 'HidingSpot',
description: 'A place where you might find treasure',
fields: () => ({
id: globalIdField('HidingSpot'),
hasBeenChecked: {
type: GraphQLBoolean,
description: 'True this spot has already been checked for treasure',
resolve: (hidingSpot) => hidingSpot.hasBeenChecked,
},
hasTreasure: {
type: GraphQLBoolean,
description: 'True if this hiding spot holds treasure',
resolve: (hidingSpot) => {
if (hidingSpot.hasBeenChecked) {
return hidingSpot.hasTreasure;
} else {
return null; // Shh... it's a secret!
}
},
},
}),
interfaces: [nodeInterface],
});
var {connectionType: hidingSpotConnection} =
connectionDefinitions({name: 'HidingSpot', nodeType: hidingSpotType});
var queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
game: {
type: gameType,
resolve: () => getGame(),
},
}),
});
var CheckHidingSpotForTreasureMutation = mutationWithClientMutationId({ | name: 'CheckHidingSpotForTreasure',
inputFields: {
id: { type: new GraphQLNonNull(GraphQLID) },
},
outputFields: {
hidingSpot: {
type: hidingSpotType,
resolve: ({localHidingSpotId}) => getHidingSpot(localHidingSpotId),
},
game: {
type: gameType,
resolve: () => getGame(),
},
},
mutateAndGetPayload: ({id}) => {
var localHidingSpotId = fromGlobalId(id).id;
checkHidingSpotForTreasure(localHidingSpotId);
return {localHidingSpotId};
},
});
var mutationType = new GraphQLObjectType({
name: 'Mutation',
fields: () => ({
checkHidingSpotForTreasure: CheckHidingSpotForTreasureMutation,
}),
});
/**
* Finally, we construct our schema (whose starting query type is the query
* type we defined above) and export it.
*/
export var Schema = new GraphQLSchema({
query: queryType,
mutation: mutationType
}); | random_line_split | |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package 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.
"""
from ceph_radosgw.rgw_client import RGWClient
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from rest_framework import status
from sysutils.database_utils import make_default_admin
import json
import mock
class RGWClientTestCase(TestCase):
@staticmethod
def _mock_settings(Settings_mock):
Settings_mock.RGW_API_HOST = 'host'
Settings_mock.RGW_API_PORT = 42
Settings_mock.RGW_API_SCHEME = 'https'
Settings_mock.RGW_API_ADMIN_RESOURCE = 'ADMIN_RESOURCE'
Settings_mock.RGW_API_USER_ID = 'USER_ID'
Settings_mock.RGW_API_ACCESS_KEY = 'ak'
Settings_mock.RGW_API_SECRET_KEY = 'sk'
@mock.patch('ceph_radosgw.rgw_client.Settings')
def test_load_settings(self, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
RGWClient._load_settings() # Also test import of awsauth.S3Auth
self.assertEqual(RGWClient._host, 'host')
self.assertEqual(RGWClient._port, 42)
self.assertEqual(RGWClient._ssl, True)
self.assertEqual(RGWClient._ADMIN_PATH, 'ADMIN_RESOURCE')
self.assertEqual(RGWClient._SYSTEM_USERID, 'USER_ID')
instance = RGWClient._user_instances[RGWClient._SYSTEM_USERID]
self.assertEqual(instance.userid, 'USER_ID')
@mock.patch('ceph_radosgw.views.Settings')
def test_user_delete(self, Settings_mock):
|
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_delete(self, filter_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [4, 8, 15, 16, 23, 42]
response = self.client.delete('/api/ceph_radosgw/bucket/delete?bucket=test01')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the bucket', response.data['detail'])
@mock.patch('ceph_radosgw.rgw_client.Settings')
@mock.patch('ceph_radosgw.views.proxy_view')
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_get(self, filter_mock, proxy_view_mock, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
proxy_view_mock.return_value = HttpResponse(json.dumps({
'owner': 'floyd',
'bucket': 'my_data'
}))
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [0, 8, 15]
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test01')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertTrue(content['is_referenced'])
filter_mock.return_value = []
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test02')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertFalse(content['is_referenced'])
| make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
Settings_mock.RGW_API_USER_ID = 'admin'
response = self.client.delete('/api/ceph_radosgw/user/delete?uid=admin')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the user', response.data['detail']) | identifier_body |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package 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.
"""
from ceph_radosgw.rgw_client import RGWClient
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from rest_framework import status
from sysutils.database_utils import make_default_admin
import json
import mock
class RGWClientTestCase(TestCase):
@staticmethod
def _mock_settings(Settings_mock):
Settings_mock.RGW_API_HOST = 'host'
Settings_mock.RGW_API_PORT = 42
Settings_mock.RGW_API_SCHEME = 'https'
Settings_mock.RGW_API_ADMIN_RESOURCE = 'ADMIN_RESOURCE'
Settings_mock.RGW_API_USER_ID = 'USER_ID'
Settings_mock.RGW_API_ACCESS_KEY = 'ak'
Settings_mock.RGW_API_SECRET_KEY = 'sk'
@mock.patch('ceph_radosgw.rgw_client.Settings')
def test_load_settings(self, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
RGWClient._load_settings() # Also test import of awsauth.S3Auth
self.assertEqual(RGWClient._host, 'host')
self.assertEqual(RGWClient._port, 42)
self.assertEqual(RGWClient._ssl, True)
self.assertEqual(RGWClient._ADMIN_PATH, 'ADMIN_RESOURCE')
self.assertEqual(RGWClient._SYSTEM_USERID, 'USER_ID')
instance = RGWClient._user_instances[RGWClient._SYSTEM_USERID]
self.assertEqual(instance.userid, 'USER_ID')
@mock.patch('ceph_radosgw.views.Settings')
def test_user_delete(self, Settings_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
Settings_mock.RGW_API_USER_ID = 'admin'
response = self.client.delete('/api/ceph_radosgw/user/delete?uid=admin')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the user', response.data['detail'])
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_delete(self, filter_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [4, 8, 15, 16, 23, 42]
response = self.client.delete('/api/ceph_radosgw/bucket/delete?bucket=test01')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the bucket', response.data['detail'])
@mock.patch('ceph_radosgw.rgw_client.Settings')
@mock.patch('ceph_radosgw.views.proxy_view')
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_get(self, filter_mock, proxy_view_mock, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
proxy_view_mock.return_value = HttpResponse(json.dumps({ | 'bucket': 'my_data'
}))
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [0, 8, 15]
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test01')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertTrue(content['is_referenced'])
filter_mock.return_value = []
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test02')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertFalse(content['is_referenced']) | 'owner': 'floyd', | random_line_split |
tests.py | """
* Copyright (c) 2017 SUSE LLC
*
* openATTIC 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; version 2.
*
* This package 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.
"""
from ceph_radosgw.rgw_client import RGWClient
from django.conf import settings
from django.http import HttpResponse
from django.test import TestCase
from rest_framework import status
from sysutils.database_utils import make_default_admin
import json
import mock
class RGWClientTestCase(TestCase):
@staticmethod
def _mock_settings(Settings_mock):
Settings_mock.RGW_API_HOST = 'host'
Settings_mock.RGW_API_PORT = 42
Settings_mock.RGW_API_SCHEME = 'https'
Settings_mock.RGW_API_ADMIN_RESOURCE = 'ADMIN_RESOURCE'
Settings_mock.RGW_API_USER_ID = 'USER_ID'
Settings_mock.RGW_API_ACCESS_KEY = 'ak'
Settings_mock.RGW_API_SECRET_KEY = 'sk'
@mock.patch('ceph_radosgw.rgw_client.Settings')
def test_load_settings(self, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
RGWClient._load_settings() # Also test import of awsauth.S3Auth
self.assertEqual(RGWClient._host, 'host')
self.assertEqual(RGWClient._port, 42)
self.assertEqual(RGWClient._ssl, True)
self.assertEqual(RGWClient._ADMIN_PATH, 'ADMIN_RESOURCE')
self.assertEqual(RGWClient._SYSTEM_USERID, 'USER_ID')
instance = RGWClient._user_instances[RGWClient._SYSTEM_USERID]
self.assertEqual(instance.userid, 'USER_ID')
@mock.patch('ceph_radosgw.views.Settings')
def | (self, Settings_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
Settings_mock.RGW_API_USER_ID = 'admin'
response = self.client.delete('/api/ceph_radosgw/user/delete?uid=admin')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the user', response.data['detail'])
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_delete(self, filter_mock):
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [4, 8, 15, 16, 23, 42]
response = self.client.delete('/api/ceph_radosgw/bucket/delete?bucket=test01')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Can not delete the bucket', response.data['detail'])
@mock.patch('ceph_radosgw.rgw_client.Settings')
@mock.patch('ceph_radosgw.views.proxy_view')
@mock.patch('ceph_nfs.models.GaneshaExport.objects.filter')
def test_bucket_get(self, filter_mock, proxy_view_mock, Settings_mock):
RGWClientTestCase._mock_settings(Settings_mock)
proxy_view_mock.return_value = HttpResponse(json.dumps({
'owner': 'floyd',
'bucket': 'my_data'
}))
make_default_admin()
self.assertTrue(self.client.login(username=settings.OAUSER, password='openattic'))
filter_mock.return_value = [0, 8, 15]
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test01')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertTrue(content['is_referenced'])
filter_mock.return_value = []
response = self.client.get('/api/ceph_radosgw/bucket/get?bucket=test02')
content = json.loads(response.content)
self.assertIn('is_referenced', content)
self.assertFalse(content['is_referenced'])
| test_user_delete | identifier_name |
inMemoryRowModel.d.ts | // Type definitions for ag-grid v4.1.5
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
import { RowNode } from "../../entities/rowNode";
import { IInMemoryRowModel } from "../../interfaces/iInMemoryRowModel";
export declare class | implements IInMemoryRowModel {
private gridOptionsWrapper;
private columnController;
private filterManager;
private $scope;
private selectionController;
private eventService;
private context;
private filterStage;
private sortStage;
private flattenStage;
private groupStage;
private aggregationStage;
private allRows;
private rowsAfterGroup;
private rowsAfterFilter;
private rowsAfterSort;
private rowsToDisplay;
init(): void;
getType(): string;
refreshModel(step: number, fromIndex?: any, groupState?: any): void;
isEmpty(): boolean;
isRowsToRender(): boolean;
setDatasource(datasource: any): void;
getTopLevelNodes(): RowNode[];
getRow(index: number): RowNode;
getVirtualRowCount(): number;
getRowCount(): number;
getRowIndexAtPixel(pixelToMatch: number): number;
private isRowInPixel(rowNode, pixelToMatch);
getRowCombinedHeight(): number;
forEachNode(callback: Function): void;
forEachNodeAfterFilter(callback: Function): void;
forEachNodeAfterFilterAndSort(callback: Function): void;
private recursivelyWalkNodesAndCallback(nodes, callback, recursionType, index);
doAggregate(): void;
expandOrCollapseAll(expand: boolean): void;
private doSort();
private doRowGrouping(groupState);
private restoreGroupState(groupState);
private doFilter();
setRowData(rowData: any[], refresh: boolean, firstId?: number): void;
private getGroupState();
private createRowNodesFromData(rowData, firstId?);
private doRowsToDisplay();
}
| InMemoryRowModel | identifier_name |
inMemoryRowModel.d.ts | // Type definitions for ag-grid v4.1.5
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ceolter/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
import { RowNode } from "../../entities/rowNode";
import { IInMemoryRowModel } from "../../interfaces/iInMemoryRowModel";
export declare class InMemoryRowModel implements IInMemoryRowModel {
private gridOptionsWrapper;
private columnController;
private filterManager;
private $scope;
private selectionController;
private eventService;
private context;
private filterStage;
private sortStage;
private flattenStage;
private groupStage;
private aggregationStage;
private allRows;
private rowsAfterGroup;
private rowsAfterFilter;
private rowsAfterSort;
private rowsToDisplay;
init(): void;
getType(): string;
refreshModel(step: number, fromIndex?: any, groupState?: any): void;
isEmpty(): boolean;
isRowsToRender(): boolean;
setDatasource(datasource: any): void;
getTopLevelNodes(): RowNode[]; | getRowIndexAtPixel(pixelToMatch: number): number;
private isRowInPixel(rowNode, pixelToMatch);
getRowCombinedHeight(): number;
forEachNode(callback: Function): void;
forEachNodeAfterFilter(callback: Function): void;
forEachNodeAfterFilterAndSort(callback: Function): void;
private recursivelyWalkNodesAndCallback(nodes, callback, recursionType, index);
doAggregate(): void;
expandOrCollapseAll(expand: boolean): void;
private doSort();
private doRowGrouping(groupState);
private restoreGroupState(groupState);
private doFilter();
setRowData(rowData: any[], refresh: boolean, firstId?: number): void;
private getGroupState();
private createRowNodesFromData(rowData, firstId?);
private doRowsToDisplay();
} | getRow(index: number): RowNode;
getVirtualRowCount(): number;
getRowCount(): number; | random_line_split |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
// Returns number of items "removed", which on success is 0 or 1.
// 0 - item with that id wasn't in the cart
// 1 - item was changed.
// You can't remove an item more than once from a cart.
export default async function | (
account_id: string,
id: number
): Promise<number> {
if (!isValidUUID(account_id)) {
throw Error("account_id is invalid");
}
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
}
| removeFromCart | identifier_name |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
// Returns number of items "removed", which on success is 0 or 1.
// 0 - item with that id wasn't in the cart
// 1 - item was changed.
// You can't remove an item more than once from a cart.
export default async function removeFromCart(
account_id: string,
id: number
): Promise<number> {
if (!isValidUUID(account_id)) |
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
}
| {
throw Error("account_id is invalid");
} | conditional_block |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
// we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
// Returns number of items "removed", which on success is 0 or 1.
// 0 - item with that id wasn't in the cart
// 1 - item was changed.
// You can't remove an item more than once from a cart.
export default async function removeFromCart(
account_id: string,
id: number
): Promise<number> | {
if (!isValidUUID(account_id)) {
throw Error("account_id is invalid");
}
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
} | identifier_body | |
remove.ts | /*
Remove an item from the given user's shopping cart.
*/
import { isValidUUID } from "@cocalc/util/misc";
import getPool from "@cocalc/database/pool";
| // we include the account_id to ensure here and in the query below
// to ensure there is an error if user A tries to delete an item
// from user B's shopping cart.
// Returns number of items "removed", which on success is 0 or 1.
// 0 - item with that id wasn't in the cart
// 1 - item was changed.
// You can't remove an item more than once from a cart.
export default async function removeFromCart(
account_id: string,
id: number
): Promise<number> {
if (!isValidUUID(account_id)) {
throw Error("account_id is invalid");
}
const pool = getPool();
const { rowCount } = await pool.query(
"UPDATE shopping_cart_items SET removed=NOW() WHERE account_id=$1 AND id=$2 AND removed IS NULL AND purchased IS NULL",
[account_id, id]
);
return rowCount;
} | random_line_split | |
test.rs | // Copyright 2013 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.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr |
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
} | identifier_body |
test.rs | // Copyright 2013 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.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn | () -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| next_test_ip6 | identifier_name |
test.rs | // Copyright 2013 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.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) | else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases {
if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
}
| {
env::temp_dir().join(string)
} | conditional_block |
test.rs | // Copyright 2013 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.
//! Various utility functions useful for writing I/O tests
use prelude::v1::*;
use env;
use libc;
use std::old_io::net::ip::*;
use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
/// Get a port number, starting at 9600, for use in tests
pub fn next_test_port() -> u16 {
static NEXT_OFFSET: AtomicUsize = ATOMIC_USIZE_INIT;
base_port() + NEXT_OFFSET.fetch_add(1, Ordering::Relaxed) as u16
}
// iOS has a pretty long tmpdir path which causes pipe creation
// to like: invalid argument: path must be smaller than SUN_LEN
fn next_test_unix_socket() -> String {
static COUNT: AtomicUsize = ATOMIC_USIZE_INIT;
// base port and pid are an attempt to be unique between multiple
// test-runners of different configurations running on one
// buildbot, the count is to be unique within this executable.
format!("rust-test-unix-path-{}-{}-{}",
base_port(),
unsafe {libc::getpid()},
COUNT.fetch_add(1, Ordering::Relaxed))
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(not(target_os = "ios"))]
pub fn next_test_unix() -> Path {
let string = next_test_unix_socket();
if cfg!(unix) {
env::temp_dir().join(string)
} else {
Path::new(format!("{}{}", r"\\.\pipe\", string))
}
}
/// Get a temporary path which could be the location of a unix socket
#[cfg(target_os = "ios")]
pub fn next_test_unix() -> Path {
Path::new(format!("/var/tmp/{}", next_test_unix_socket()))
}
/// Get a unique IPv4 localhost:port pair starting at 9600
pub fn next_test_ip4() -> SocketAddr {
SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
}
/// Get a unique IPv6 localhost:port pair starting at 9600
pub fn next_test_ip6() -> SocketAddr {
SocketAddr { ip: Ipv6Addr(0, 0, 0, 0, 0, 0, 0, 1), port: next_test_port() }
}
/*
XXX: Welcome to MegaHack City.
The bots run multiple builds at the same time, and these builds
all want to use ports. This function figures out which workspace
it is running in and assigns a port range based on it.
*/
fn base_port() -> u16 {
let base = 9600u16;
let range = 1000u16;
let bases = [
("32-opt", base + range * 1),
("32-nopt", base + range * 2),
("64-opt", base + range * 3),
("64-nopt", base + range * 4),
("64-opt-vg", base + range * 5),
("all-opt", base + range * 6),
("snap3", base + range * 7),
("dist", base + range * 8)
];
// FIXME (#9639): This needs to handle non-utf8 paths
let path = env::current_dir().unwrap();
let path_s = path.as_str().unwrap();
let mut final_base = base;
for &(dir, base) in &bases { | if path_s.contains(dir) {
final_base = base;
break;
}
}
return final_base;
}
/// Raises the file descriptor limit when running tests if necessary
pub fn raise_fd_limit() {
unsafe { darwin_fd_limit::raise_fd_limit() }
}
/// darwin_fd_limit exists to work around an issue where launchctl on Mac OS X defaults the rlimit
/// maxfiles to 256/unlimited. The default soft limit of 256 ends up being far too low for our
/// multithreaded scheduler testing, depending on the number of cores available.
///
/// This fixes issue #7772.
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[allow(non_camel_case_types)]
mod darwin_fd_limit {
use libc;
type rlim_t = libc::uint64_t;
#[repr(C)]
struct rlimit {
rlim_cur: rlim_t,
rlim_max: rlim_t
}
extern {
// name probably doesn't need to be mut, but the C function doesn't specify const
fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint,
oldp: *mut libc::c_void, oldlenp: *mut libc::size_t,
newp: *mut libc::c_void, newlen: libc::size_t) -> libc::c_int;
fn getrlimit(resource: libc::c_int, rlp: *mut rlimit) -> libc::c_int;
fn setrlimit(resource: libc::c_int, rlp: *const rlimit) -> libc::c_int;
}
static CTL_KERN: libc::c_int = 1;
static KERN_MAXFILESPERPROC: libc::c_int = 29;
static RLIMIT_NOFILE: libc::c_int = 8;
pub unsafe fn raise_fd_limit() {
// The strategy here is to fetch the current resource limits, read the kern.maxfilesperproc
// sysctl value, and bump the soft resource limit for maxfiles up to the sysctl value.
use ptr::null_mut;
use mem::size_of_val;
use os::last_os_error;
// Fetch the kern.maxfilesperproc value
let mut mib: [libc::c_int; 2] = [CTL_KERN, KERN_MAXFILESPERPROC];
let mut maxfiles: libc::c_int = 0;
let mut size: libc::size_t = size_of_val(&maxfiles) as libc::size_t;
if sysctl(&mut mib[0], 2, &mut maxfiles as *mut libc::c_int as *mut libc::c_void, &mut size,
null_mut(), 0) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling sysctl: {}", err);
}
// Fetch the current resource limits
let mut rlim = rlimit{rlim_cur: 0, rlim_max: 0};
if getrlimit(RLIMIT_NOFILE, &mut rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling getrlimit: {}", err);
}
// Bump the soft limit to the smaller of kern.maxfilesperproc and the hard limit
rlim.rlim_cur = ::cmp::min(maxfiles as rlim_t, rlim.rlim_max);
// Set our newly-increased resource limit
if setrlimit(RLIMIT_NOFILE, &rlim) != 0 {
let err = last_os_error();
panic!("raise_fd_limit: error calling setrlimit: {}", err);
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
mod darwin_fd_limit {
pub unsafe fn raise_fd_limit() {}
} | random_line_split | |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO |
# Context manager for capturing stdout output. See
# https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._bytesio = BytesIO()
return self
def __exit__(self, *args):
self.extend(self._bytesio.getvalue().decode('UTF-8').splitlines())
del self._bytesio # free up some memory
sys.stdout = self._stdout
class FixedOffset(tzinfo):
def __init__(self, offset_hours):
self.__offset = timedelta(hours=offset_hours)
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return 'FixedOffset'
def dst(self, dt):
return timedelta(0)
def fetch_title(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_TITLE, filters)
def fetch_stream_url(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_URL, filters)
def fetch_episode_pages(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_EPISODE_PAGES, filters)
def fetch_metadata(url, filters=StreamFilters(), meta_language=None):
return json.loads('\n'.join(
fetch(url, StreamAction.PRINT_METADATA, filters, meta_language)))
def fetch(url, action, filters, meta_language=None):
io = IOContext(destdir='/tmp/', metadata_language=meta_language,
x_forwarded_for=random_elisa_ipv4())
httpclient = HttpClient(io)
title_formatter = TitleFormatter()
with Capturing() as output:
res = execute_action(url,
action,
io,
httpclient,
title_formatter,
stream_filters = filters)
assert res == RD_SUCCESS
return output | from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter | random_line_split |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO
from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter
# Context manager for capturing stdout output. See
# https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._bytesio = BytesIO()
return self
def __exit__(self, *args):
self.extend(self._bytesio.getvalue().decode('UTF-8').splitlines())
del self._bytesio # free up some memory
sys.stdout = self._stdout
class FixedOffset(tzinfo):
def __init__(self, offset_hours):
self.__offset = timedelta(hours=offset_hours)
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return 'FixedOffset'
def dst(self, dt):
return timedelta(0)
def fetch_title(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_TITLE, filters)
def fetch_stream_url(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_URL, filters)
def fetch_episode_pages(url, filters=StreamFilters()):
|
def fetch_metadata(url, filters=StreamFilters(), meta_language=None):
return json.loads('\n'.join(
fetch(url, StreamAction.PRINT_METADATA, filters, meta_language)))
def fetch(url, action, filters, meta_language=None):
io = IOContext(destdir='/tmp/', metadata_language=meta_language,
x_forwarded_for=random_elisa_ipv4())
httpclient = HttpClient(io)
title_formatter = TitleFormatter()
with Capturing() as output:
res = execute_action(url,
action,
io,
httpclient,
title_formatter,
stream_filters = filters)
assert res == RD_SUCCESS
return output
| return fetch(url, StreamAction.PRINT_EPISODE_PAGES, filters) | identifier_body |
utils.py | import sys
import json
from datetime import timedelta, tzinfo
from io import BytesIO
from yledl import execute_action, StreamFilters, IOContext, StreamAction, RD_SUCCESS
from yledl.io import random_elisa_ipv4
from yledl.http import HttpClient
from yledl.titleformatter import TitleFormatter
# Context manager for capturing stdout output. See
# https://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._bytesio = BytesIO()
return self
def __exit__(self, *args):
self.extend(self._bytesio.getvalue().decode('UTF-8').splitlines())
del self._bytesio # free up some memory
sys.stdout = self._stdout
class FixedOffset(tzinfo):
def __init__(self, offset_hours):
self.__offset = timedelta(hours=offset_hours)
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return 'FixedOffset'
def dst(self, dt):
return timedelta(0)
def fetch_title(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_TITLE, filters)
def fetch_stream_url(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_STREAM_URL, filters)
def fetch_episode_pages(url, filters=StreamFilters()):
return fetch(url, StreamAction.PRINT_EPISODE_PAGES, filters)
def fetch_metadata(url, filters=StreamFilters(), meta_language=None):
return json.loads('\n'.join(
fetch(url, StreamAction.PRINT_METADATA, filters, meta_language)))
def | (url, action, filters, meta_language=None):
io = IOContext(destdir='/tmp/', metadata_language=meta_language,
x_forwarded_for=random_elisa_ipv4())
httpclient = HttpClient(io)
title_formatter = TitleFormatter()
with Capturing() as output:
res = execute_action(url,
action,
io,
httpclient,
title_formatter,
stream_filters = filters)
assert res == RD_SUCCESS
return output
| fetch | identifier_name |
deriving-span-Zero-tuple-struct.rs | // Copyright 2014 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.
// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py'
#![feature(struct_variant)]
extern crate rand;
struct Error;
#[deriving(Zero)] //~ ERROR failed to find an implementation
struct Struct(
Error //~ ERROR
//~^ ERROR failed to find an implementation
//~^^ ERROR type `Error` does not implement any method in scope
);
fn | () {}
| main | identifier_name |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
from argparse import SUPPRESS, ArgumentParser
from django.conf import settings
from django.core import management
import syspath_override # noqa
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.zing/zing.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.template'
# Python 2+3 support for input()
if sys.version_info[0] < 3:
input = raw_input
def add_help_to_parser(parser):
parser.add_help = True
parser.add_argument("-h", "--help",
action="help", default=SUPPRESS,
help="Show this help message and exit")
def init_settings(settings_filepath, template_filename,
db="sqlite", db_name="dbs/zing.db", db_user="",
db_password="", db_host="", db_port=""):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
:param db: Database engine to use
(default=sqlite, choices=[mysql, postgresql]).
:param db_name: Database name (default: zingdb) or path to database file
if using sqlite (default: dbs/zing.db)
:param db_user: Name of the database user. Not used with sqlite.
:param db_password: Password for the database user. Not used with sqlite.
:param db_host: Database host. Defaults to localhost. Not used with sqlite.
:param db_port: Database port. Defaults to backend default. Not used with
sqlite.
"""
from base64 import b64encode
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if db == "sqlite":
db_name = "working_path('%s')" % (db_name or "dbs/zing.db")
db_user = db_password = db_host = db_port = "''"
else:
db_name = "'%s'" % (db_name or "zingdb")
db_user = "'%s'" % (db_user or "zing")
db_password = "'%s'" % db_password
db_host = "'%s'" % db_host
db_port = "'%s'" % db_port
db_module = {
'sqlite': 'sqlite3',
'mysql': 'mysql',
'postgresql': 'postgresql',
}[db]
context = {
"default_key": ("'%s'"
% b64encode(os.urandom(KEY_LENGTH)).decode("utf-8")),
"db_engine": "'django.db.backends.%s'" % db_module,
"db_name": db_name,
"db_user": db_user,
"db_password": db_password,
"db_host": db_host,
"db_port": db_port,
}
with open(settings_filepath, 'w') as settings:
with open(template_filename) as template:
settings.write(
(template.read().decode("utf8") % context).encode("utf8"))
def init_command(parser, settings_template, args):
"""Parse and run the `init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param settings_template: Template file for initializing settings from.
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_to_parser(parser)
parser.add_argument("--db",
default="sqlite",
choices=['sqlite', 'mysql', 'postgresql'],
help=(u"Use the specified database backend (default: "
u"%(default)s)."))
parser.add_argument("--db-name", default="",
help=(u"Database name (default: 'zingdb') or path "
u"to database file if using sqlite (default: "
u"'%s/dbs/zing.db')" % src_dir))
parser.add_argument("--db-user", default="",
help=(u"Name of the database user. Not used with "
u"sqlite."))
parser.add_argument("--db-host", default="",
help=(u"Database host. Defaults to localhost. Not "
u"used with sqlite."))
parser.add_argument("--db-port", default="",
help=(u"Database port. Defaults to backend default. "
u"Not used with sqlite."))
args, remainder_ = parser.parse_known_args(args)
config_path = os.path.expanduser(args.config)
if os.path.exists(config_path):
resp = None
if args.noinput:
resp = 'n'
else:
resp = input("File already exists at %r, overwrite? [Ny] "
% config_path).lower()
if resp not in ("y", "yes"):
print("File already exists, not overwriting.")
exit(2)
try:
init_settings(config_path, settings_template,
db=args.db, db_name=args.db_name, db_user=args.db_user,
db_host=args.db_host, db_port=args.db_port)
except (IOError, OSError) as e:
raise e.__class__('Unable to write default settings file to %r'
% config_path)
if args.db in ['mysql', 'postgresql']:
print("Configuration file created at %r. Your database password is "
"not currently set . You may want to update the database "
"settings now" % config_path)
else:
print("Configuration file created at %r" % config_path)
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode may conflict with jobs "
"that are dispatched to your workers.\n\n"
"It is safer to stop any workers before using "
"synchronous commands.\n\n")
if noinput:
print("Warning: %s" % redis_warning)
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
print("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
q['ASYNC'] = False
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(
os.path.abspath(os.path.expanduser(config_path),))
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print(u"Configuration file does not exist at %r or "
u"%r environment variable has not been set.\n"
u"Use '%s init' to initialize the configuration file." %
(config_path, settings_envvar, runner_name))
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
""" | # This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_args(sys.argv[1:])
parser.add_argument(
"--config",
default=default_settings_path,
help=u"Use the specified configuration file.",
)
parser.add_argument(
"--noinput",
action="store_true",
default=False,
help=u"Never prompt for input",
)
parser.add_argument(
"--no-rq",
action="store_true",
default=False,
help=(u"Run all jobs in a single process, without "
"using rq workers"),
)
# Parse the init command by hand to prevent raising a SystemExit while
# parsing
args_provided = [c for c in sys.argv[1:] if not c.startswith("-")]
if args_provided and args_provided[0] == "init":
init_command(parser, settings_template, sys.argv[1:])
sys.exit(0)
args, remainder = parser.parse_known_args(sys.argv[1:])
# Configure settings from args.config path
configure_app(project=project, config_path=args.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
# If no CACHES backend set tell user and exit. This prevents raising
# ImproperlyConfigured error on trying to run any commands
# NB: it may be possible to remove this when #4006 is fixed
caches = settings.CACHES.keys()
if "stats" not in caches or "redis" not in caches:
sys.stdout.write("\nYou need to configure the CACHES setting, "
"or to use the defaults remove CACHES from %s\n\n"
"Once you have fixed the CACHES setting you should "
"run 'zing check' again\n\n"
% args.config)
sys.exit(2)
# Set synchronous mode
if args.no_rq:
set_sync_mode(args.noinput)
# Print the help message for "--help"
if len(remainder) == 1 and remainder[0] in ["-h", "--help"]:
add_help_to_parser(parser)
parser.parse_known_args(sys.argv[1:])
command = [runner_name] + remainder
# Respect the noinput flag
if args.noinput:
command += ["--noinput"]
management.execute_from_command_line(command)
sys.exit(0)
def get_version():
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version as django_version
return ('Zing %s (Django %s, Translate Toolkit %s)' %
(__version__, django_version(), tt_version.sver))
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='zing',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main() | runner_name = os.path.basename(sys.argv[0])
| random_line_split |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
from argparse import SUPPRESS, ArgumentParser
from django.conf import settings
from django.core import management
import syspath_override # noqa
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.zing/zing.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.template'
# Python 2+3 support for input()
if sys.version_info[0] < 3:
input = raw_input
def add_help_to_parser(parser):
parser.add_help = True
parser.add_argument("-h", "--help",
action="help", default=SUPPRESS,
help="Show this help message and exit")
def init_settings(settings_filepath, template_filename,
db="sqlite", db_name="dbs/zing.db", db_user="",
db_password="", db_host="", db_port=""):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
:param db: Database engine to use
(default=sqlite, choices=[mysql, postgresql]).
:param db_name: Database name (default: zingdb) or path to database file
if using sqlite (default: dbs/zing.db)
:param db_user: Name of the database user. Not used with sqlite.
:param db_password: Password for the database user. Not used with sqlite.
:param db_host: Database host. Defaults to localhost. Not used with sqlite.
:param db_port: Database port. Defaults to backend default. Not used with
sqlite.
"""
from base64 import b64encode
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if db == "sqlite":
db_name = "working_path('%s')" % (db_name or "dbs/zing.db")
db_user = db_password = db_host = db_port = "''"
else:
db_name = "'%s'" % (db_name or "zingdb")
db_user = "'%s'" % (db_user or "zing")
db_password = "'%s'" % db_password
db_host = "'%s'" % db_host
db_port = "'%s'" % db_port
db_module = {
'sqlite': 'sqlite3',
'mysql': 'mysql',
'postgresql': 'postgresql',
}[db]
context = {
"default_key": ("'%s'"
% b64encode(os.urandom(KEY_LENGTH)).decode("utf-8")),
"db_engine": "'django.db.backends.%s'" % db_module,
"db_name": db_name,
"db_user": db_user,
"db_password": db_password,
"db_host": db_host,
"db_port": db_port,
}
with open(settings_filepath, 'w') as settings:
with open(template_filename) as template:
settings.write(
(template.read().decode("utf8") % context).encode("utf8"))
def init_command(parser, settings_template, args):
"""Parse and run the `init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param settings_template: Template file for initializing settings from.
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_to_parser(parser)
parser.add_argument("--db",
default="sqlite",
choices=['sqlite', 'mysql', 'postgresql'],
help=(u"Use the specified database backend (default: "
u"%(default)s)."))
parser.add_argument("--db-name", default="",
help=(u"Database name (default: 'zingdb') or path "
u"to database file if using sqlite (default: "
u"'%s/dbs/zing.db')" % src_dir))
parser.add_argument("--db-user", default="",
help=(u"Name of the database user. Not used with "
u"sqlite."))
parser.add_argument("--db-host", default="",
help=(u"Database host. Defaults to localhost. Not "
u"used with sqlite."))
parser.add_argument("--db-port", default="",
help=(u"Database port. Defaults to backend default. "
u"Not used with sqlite."))
args, remainder_ = parser.parse_known_args(args)
config_path = os.path.expanduser(args.config)
if os.path.exists(config_path):
resp = None
if args.noinput:
resp = 'n'
else:
resp = input("File already exists at %r, overwrite? [Ny] "
% config_path).lower()
if resp not in ("y", "yes"):
print("File already exists, not overwriting.")
exit(2)
try:
init_settings(config_path, settings_template,
db=args.db, db_name=args.db_name, db_user=args.db_user,
db_host=args.db_host, db_port=args.db_port)
except (IOError, OSError) as e:
raise e.__class__('Unable to write default settings file to %r'
% config_path)
if args.db in ['mysql', 'postgresql']:
print("Configuration file created at %r. Your database password is "
"not currently set . You may want to update the database "
"settings now" % config_path)
else:
print("Configuration file created at %r" % config_path)
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode may conflict with jobs "
"that are dispatched to your workers.\n\n"
"It is safer to stop any workers before using "
"synchronous commands.\n\n")
if noinput:
|
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
print("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
q['ASYNC'] = False
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(
os.path.abspath(os.path.expanduser(config_path),))
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print(u"Configuration file does not exist at %r or "
u"%r environment variable has not been set.\n"
u"Use '%s init' to initialize the configuration file." %
(config_path, settings_envvar, runner_name))
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
runner_name = os.path.basename(sys.argv[0])
# This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_args(sys.argv[1:])
parser.add_argument(
"--config",
default=default_settings_path,
help=u"Use the specified configuration file.",
)
parser.add_argument(
"--noinput",
action="store_true",
default=False,
help=u"Never prompt for input",
)
parser.add_argument(
"--no-rq",
action="store_true",
default=False,
help=(u"Run all jobs in a single process, without "
"using rq workers"),
)
# Parse the init command by hand to prevent raising a SystemExit while
# parsing
args_provided = [c for c in sys.argv[1:] if not c.startswith("-")]
if args_provided and args_provided[0] == "init":
init_command(parser, settings_template, sys.argv[1:])
sys.exit(0)
args, remainder = parser.parse_known_args(sys.argv[1:])
# Configure settings from args.config path
configure_app(project=project, config_path=args.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
# If no CACHES backend set tell user and exit. This prevents raising
# ImproperlyConfigured error on trying to run any commands
# NB: it may be possible to remove this when #4006 is fixed
caches = settings.CACHES.keys()
if "stats" not in caches or "redis" not in caches:
sys.stdout.write("\nYou need to configure the CACHES setting, "
"or to use the defaults remove CACHES from %s\n\n"
"Once you have fixed the CACHES setting you should "
"run 'zing check' again\n\n"
% args.config)
sys.exit(2)
# Set synchronous mode
if args.no_rq:
set_sync_mode(args.noinput)
# Print the help message for "--help"
if len(remainder) == 1 and remainder[0] in ["-h", "--help"]:
add_help_to_parser(parser)
parser.parse_known_args(sys.argv[1:])
command = [runner_name] + remainder
# Respect the noinput flag
if args.noinput:
command += ["--noinput"]
management.execute_from_command_line(command)
sys.exit(0)
def get_version():
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version as django_version
return ('Zing %s (Django %s, Translate Toolkit %s)' %
(__version__, django_version(), tt_version.sver))
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='zing',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| print("Warning: %s" % redis_warning) | conditional_block |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
from argparse import SUPPRESS, ArgumentParser
from django.conf import settings
from django.core import management
import syspath_override # noqa
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.zing/zing.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.template'
# Python 2+3 support for input()
if sys.version_info[0] < 3:
input = raw_input
def add_help_to_parser(parser):
parser.add_help = True
parser.add_argument("-h", "--help",
action="help", default=SUPPRESS,
help="Show this help message and exit")
def init_settings(settings_filepath, template_filename,
db="sqlite", db_name="dbs/zing.db", db_user="",
db_password="", db_host="", db_port=""):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
:param db: Database engine to use
(default=sqlite, choices=[mysql, postgresql]).
:param db_name: Database name (default: zingdb) or path to database file
if using sqlite (default: dbs/zing.db)
:param db_user: Name of the database user. Not used with sqlite.
:param db_password: Password for the database user. Not used with sqlite.
:param db_host: Database host. Defaults to localhost. Not used with sqlite.
:param db_port: Database port. Defaults to backend default. Not used with
sqlite.
"""
from base64 import b64encode
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if db == "sqlite":
db_name = "working_path('%s')" % (db_name or "dbs/zing.db")
db_user = db_password = db_host = db_port = "''"
else:
db_name = "'%s'" % (db_name or "zingdb")
db_user = "'%s'" % (db_user or "zing")
db_password = "'%s'" % db_password
db_host = "'%s'" % db_host
db_port = "'%s'" % db_port
db_module = {
'sqlite': 'sqlite3',
'mysql': 'mysql',
'postgresql': 'postgresql',
}[db]
context = {
"default_key": ("'%s'"
% b64encode(os.urandom(KEY_LENGTH)).decode("utf-8")),
"db_engine": "'django.db.backends.%s'" % db_module,
"db_name": db_name,
"db_user": db_user,
"db_password": db_password,
"db_host": db_host,
"db_port": db_port,
}
with open(settings_filepath, 'w') as settings:
with open(template_filename) as template:
settings.write(
(template.read().decode("utf8") % context).encode("utf8"))
def init_command(parser, settings_template, args):
|
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode may conflict with jobs "
"that are dispatched to your workers.\n\n"
"It is safer to stop any workers before using "
"synchronous commands.\n\n")
if noinput:
print("Warning: %s" % redis_warning)
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
print("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
q['ASYNC'] = False
def configure_app(project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(
os.path.abspath(os.path.expanduser(config_path),))
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print(u"Configuration file does not exist at %r or "
u"%r environment variable has not been set.\n"
u"Use '%s init' to initialize the configuration file." %
(config_path, settings_envvar, runner_name))
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
runner_name = os.path.basename(sys.argv[0])
# This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_args(sys.argv[1:])
parser.add_argument(
"--config",
default=default_settings_path,
help=u"Use the specified configuration file.",
)
parser.add_argument(
"--noinput",
action="store_true",
default=False,
help=u"Never prompt for input",
)
parser.add_argument(
"--no-rq",
action="store_true",
default=False,
help=(u"Run all jobs in a single process, without "
"using rq workers"),
)
# Parse the init command by hand to prevent raising a SystemExit while
# parsing
args_provided = [c for c in sys.argv[1:] if not c.startswith("-")]
if args_provided and args_provided[0] == "init":
init_command(parser, settings_template, sys.argv[1:])
sys.exit(0)
args, remainder = parser.parse_known_args(sys.argv[1:])
# Configure settings from args.config path
configure_app(project=project, config_path=args.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
# If no CACHES backend set tell user and exit. This prevents raising
# ImproperlyConfigured error on trying to run any commands
# NB: it may be possible to remove this when #4006 is fixed
caches = settings.CACHES.keys()
if "stats" not in caches or "redis" not in caches:
sys.stdout.write("\nYou need to configure the CACHES setting, "
"or to use the defaults remove CACHES from %s\n\n"
"Once you have fixed the CACHES setting you should "
"run 'zing check' again\n\n"
% args.config)
sys.exit(2)
# Set synchronous mode
if args.no_rq:
set_sync_mode(args.noinput)
# Print the help message for "--help"
if len(remainder) == 1 and remainder[0] in ["-h", "--help"]:
add_help_to_parser(parser)
parser.parse_known_args(sys.argv[1:])
command = [runner_name] + remainder
# Respect the noinput flag
if args.noinput:
command += ["--noinput"]
management.execute_from_command_line(command)
sys.exit(0)
def get_version():
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version as django_version
return ('Zing %s (Django %s, Translate Toolkit %s)' %
(__version__, django_version(), tt_version.sver))
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='zing',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| """Parse and run the `init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param settings_template: Template file for initializing settings from.
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_to_parser(parser)
parser.add_argument("--db",
default="sqlite",
choices=['sqlite', 'mysql', 'postgresql'],
help=(u"Use the specified database backend (default: "
u"%(default)s)."))
parser.add_argument("--db-name", default="",
help=(u"Database name (default: 'zingdb') or path "
u"to database file if using sqlite (default: "
u"'%s/dbs/zing.db')" % src_dir))
parser.add_argument("--db-user", default="",
help=(u"Name of the database user. Not used with "
u"sqlite."))
parser.add_argument("--db-host", default="",
help=(u"Database host. Defaults to localhost. Not "
u"used with sqlite."))
parser.add_argument("--db-port", default="",
help=(u"Database port. Defaults to backend default. "
u"Not used with sqlite."))
args, remainder_ = parser.parse_known_args(args)
config_path = os.path.expanduser(args.config)
if os.path.exists(config_path):
resp = None
if args.noinput:
resp = 'n'
else:
resp = input("File already exists at %r, overwrite? [Ny] "
% config_path).lower()
if resp not in ("y", "yes"):
print("File already exists, not overwriting.")
exit(2)
try:
init_settings(config_path, settings_template,
db=args.db, db_name=args.db_name, db_user=args.db_user,
db_host=args.db_host, db_port=args.db_port)
except (IOError, OSError) as e:
raise e.__class__('Unable to write default settings file to %r'
% config_path)
if args.db in ['mysql', 'postgresql']:
print("Configuration file created at %r. Your database password is "
"not currently set . You may want to update the database "
"settings now" % config_path)
else:
print("Configuration file created at %r" % config_path) | identifier_body |
runner.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
# Copyright (C) Zing contributors.
#
# This file is a part of the Zing project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import os
import sys
from argparse import SUPPRESS, ArgumentParser
from django.conf import settings
from django.core import management
import syspath_override # noqa
#: Length for the generated :setting:`SECRET_KEY`
KEY_LENGTH = 50
#: Default path for the settings file
DEFAULT_SETTINGS_PATH = '~/.zing/zing.conf'
#: Template that will be used to initialize settings from
SETTINGS_TEMPLATE_FILENAME = 'settings/90-local.conf.template'
# Python 2+3 support for input()
if sys.version_info[0] < 3:
input = raw_input
def add_help_to_parser(parser):
parser.add_help = True
parser.add_argument("-h", "--help",
action="help", default=SUPPRESS,
help="Show this help message and exit")
def init_settings(settings_filepath, template_filename,
db="sqlite", db_name="dbs/zing.db", db_user="",
db_password="", db_host="", db_port=""):
"""Initializes a sample settings file for new installations.
:param settings_filepath: The target file path where the initial settings
will be written to.
:param template_filename: Template file used to initialize settings from.
:param db: Database engine to use
(default=sqlite, choices=[mysql, postgresql]).
:param db_name: Database name (default: zingdb) or path to database file
if using sqlite (default: dbs/zing.db)
:param db_user: Name of the database user. Not used with sqlite.
:param db_password: Password for the database user. Not used with sqlite.
:param db_host: Database host. Defaults to localhost. Not used with sqlite.
:param db_port: Database port. Defaults to backend default. Not used with
sqlite.
"""
from base64 import b64encode
dirname = os.path.dirname(settings_filepath)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname)
if db == "sqlite":
db_name = "working_path('%s')" % (db_name or "dbs/zing.db")
db_user = db_password = db_host = db_port = "''"
else:
db_name = "'%s'" % (db_name or "zingdb")
db_user = "'%s'" % (db_user or "zing")
db_password = "'%s'" % db_password
db_host = "'%s'" % db_host
db_port = "'%s'" % db_port
db_module = {
'sqlite': 'sqlite3',
'mysql': 'mysql',
'postgresql': 'postgresql',
}[db]
context = {
"default_key": ("'%s'"
% b64encode(os.urandom(KEY_LENGTH)).decode("utf-8")),
"db_engine": "'django.db.backends.%s'" % db_module,
"db_name": db_name,
"db_user": db_user,
"db_password": db_password,
"db_host": db_host,
"db_port": db_port,
}
with open(settings_filepath, 'w') as settings:
with open(template_filename) as template:
settings.write(
(template.read().decode("utf8") % context).encode("utf8"))
def init_command(parser, settings_template, args):
"""Parse and run the `init` command
:param parser: `argparse.ArgumentParser` instance to use for parsing
:param settings_template: Template file for initializing settings from.
:param args: Arguments to call init command with.
"""
src_dir = os.path.abspath(os.path.dirname(__file__))
add_help_to_parser(parser)
parser.add_argument("--db",
default="sqlite",
choices=['sqlite', 'mysql', 'postgresql'],
help=(u"Use the specified database backend (default: "
u"%(default)s)."))
parser.add_argument("--db-name", default="",
help=(u"Database name (default: 'zingdb') or path "
u"to database file if using sqlite (default: "
u"'%s/dbs/zing.db')" % src_dir))
parser.add_argument("--db-user", default="",
help=(u"Name of the database user. Not used with "
u"sqlite."))
parser.add_argument("--db-host", default="",
help=(u"Database host. Defaults to localhost. Not "
u"used with sqlite."))
parser.add_argument("--db-port", default="",
help=(u"Database port. Defaults to backend default. "
u"Not used with sqlite."))
args, remainder_ = parser.parse_known_args(args)
config_path = os.path.expanduser(args.config)
if os.path.exists(config_path):
resp = None
if args.noinput:
resp = 'n'
else:
resp = input("File already exists at %r, overwrite? [Ny] "
% config_path).lower()
if resp not in ("y", "yes"):
print("File already exists, not overwriting.")
exit(2)
try:
init_settings(config_path, settings_template,
db=args.db, db_name=args.db_name, db_user=args.db_user,
db_host=args.db_host, db_port=args.db_port)
except (IOError, OSError) as e:
raise e.__class__('Unable to write default settings file to %r'
% config_path)
if args.db in ['mysql', 'postgresql']:
print("Configuration file created at %r. Your database password is "
"not currently set . You may want to update the database "
"settings now" % config_path)
else:
print("Configuration file created at %r" % config_path)
def set_sync_mode(noinput=False):
"""Sets ASYNC = False on all redis worker queues
"""
from .core.utils.redis_rq import rq_workers_are_running
if rq_workers_are_running():
redis_warning = ("\nYou currently have RQ workers running.\n\n"
"Running in synchronous mode may conflict with jobs "
"that are dispatched to your workers.\n\n"
"It is safer to stop any workers before using "
"synchronous commands.\n\n")
if noinput:
print("Warning: %s" % redis_warning)
else:
resp = input("%sDo you wish to proceed? [Ny] " % redis_warning)
if resp not in ("y", "yes"):
print("RQ workers running, not proceeding.")
exit(2)
# Update settings to set queues to ASYNC = False.
for q in settings.RQ_QUEUES.itervalues():
q['ASYNC'] = False
def | (project, config_path, django_settings_module, runner_name):
"""Determines which settings file to use and sets environment variables
accordingly.
:param project: Project's name. Will be used to generate the settings
environment variable.
:param config_path: The path to the user's configuration file.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
:param runner_name: The name of the running script.
"""
settings_envvar = project.upper() + '_SETTINGS'
# Normalize path and expand ~ constructions
config_path = os.path.normpath(
os.path.abspath(os.path.expanduser(config_path),))
if not (os.path.exists(config_path) or
os.environ.get(settings_envvar, None)):
print(u"Configuration file does not exist at %r or "
u"%r environment variable has not been set.\n"
u"Use '%s init' to initialize the configuration file." %
(config_path, settings_envvar, runner_name))
sys.exit(2)
os.environ.setdefault(settings_envvar, config_path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', django_settings_module)
def run_app(project, default_settings_path, settings_template,
django_settings_module):
"""Wrapper around django-admin.py.
:param project: Project's name.
:param default_settings_path: Default filepath to search for custom
settings. This will also be used as a default location for writing
initial settings.
:param settings_template: Template file for initializing settings from.
:param django_settings_module: The module that ``DJANGO_SETTINGS_MODULE``
will be set to.
"""
runner_name = os.path.basename(sys.argv[0])
# This parser should ignore the --help flag, unless there is no subcommand
parser = ArgumentParser(add_help=False)
parser.add_argument("--version", action="version",
version=get_version())
# Print version and exit if --version present
args, remainder = parser.parse_known_args(sys.argv[1:])
parser.add_argument(
"--config",
default=default_settings_path,
help=u"Use the specified configuration file.",
)
parser.add_argument(
"--noinput",
action="store_true",
default=False,
help=u"Never prompt for input",
)
parser.add_argument(
"--no-rq",
action="store_true",
default=False,
help=(u"Run all jobs in a single process, without "
"using rq workers"),
)
# Parse the init command by hand to prevent raising a SystemExit while
# parsing
args_provided = [c for c in sys.argv[1:] if not c.startswith("-")]
if args_provided and args_provided[0] == "init":
init_command(parser, settings_template, sys.argv[1:])
sys.exit(0)
args, remainder = parser.parse_known_args(sys.argv[1:])
# Configure settings from args.config path
configure_app(project=project, config_path=args.config,
django_settings_module=django_settings_module,
runner_name=runner_name)
# If no CACHES backend set tell user and exit. This prevents raising
# ImproperlyConfigured error on trying to run any commands
# NB: it may be possible to remove this when #4006 is fixed
caches = settings.CACHES.keys()
if "stats" not in caches or "redis" not in caches:
sys.stdout.write("\nYou need to configure the CACHES setting, "
"or to use the defaults remove CACHES from %s\n\n"
"Once you have fixed the CACHES setting you should "
"run 'zing check' again\n\n"
% args.config)
sys.exit(2)
# Set synchronous mode
if args.no_rq:
set_sync_mode(args.noinput)
# Print the help message for "--help"
if len(remainder) == 1 and remainder[0] in ["-h", "--help"]:
add_help_to_parser(parser)
parser.parse_known_args(sys.argv[1:])
command = [runner_name] + remainder
# Respect the noinput flag
if args.noinput:
command += ["--noinput"]
management.execute_from_command_line(command)
sys.exit(0)
def get_version():
from pootle import __version__
from translate import __version__ as tt_version
from django import get_version as django_version
return ('Zing %s (Django %s, Translate Toolkit %s)' %
(__version__, django_version(), tt_version.sver))
def main():
src_dir = os.path.abspath(os.path.dirname(__file__))
settings_template = os.path.join(src_dir, SETTINGS_TEMPLATE_FILENAME)
run_app(project='zing',
default_settings_path=DEFAULT_SETTINGS_PATH,
settings_template=settings_template,
django_settings_module='pootle.settings')
if __name__ == '__main__':
main()
| configure_app | identifier_name |
angular-locale_haw-us.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"L\u0101pule",
"Po\u02bbakahi",
"Po\u02bbalua",
"Po\u02bbakolu",
"Po\u02bbah\u0101",
"Po\u02bbalima",
"Po\u02bbaono"
],
"ERANAMES": [
"BCE",
"CE"
],
"ERAS": [
"BCE",
"CE"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"Ianuali",
"Pepeluali",
"Malaki",
"\u02bbApelila",
"Mei",
"Iune",
"Iulai",
"\u02bbAukake",
"Kepakemapa",
"\u02bbOkakopa",
"Nowemapa",
"Kekemapa"
],
"SHORTDAY": [
"LP",
"P1",
"P2",
"P3",
"P4",
"P5",
"P6"
],
"SHORTMONTH": [
"Ian.",
"Pep.",
"Mal.",
"\u02bbAp.",
"Mei",
"Iun.",
"Iul.",
"\u02bbAu.",
"Kep.",
"\u02bbOk.",
"Now.",
"Kek."
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "haw-us",
"pluralCat": function(n, opt_precision) { if (n == 1) | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
angular-locale_haw-us.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"L\u0101pule",
"Po\u02bbakahi",
"Po\u02bbalua",
"Po\u02bbakolu",
"Po\u02bbah\u0101",
"Po\u02bbalima",
"Po\u02bbaono"
],
"ERANAMES": [
"BCE",
"CE"
],
"ERAS": [
"BCE",
"CE"
],
"FIRSTDAYOFWEEK": 6,
"MONTH": [
"Ianuali",
"Pepeluali",
"Malaki",
"\u02bbApelila",
"Mei",
"Iune",
"Iulai",
"\u02bbAukake",
"Kepakemapa",
"\u02bbOkakopa",
"Nowemapa",
"Kekemapa"
],
"SHORTDAY": [
"LP",
"P1",
"P2",
"P3",
"P4",
"P5",
"P6"
],
"SHORTMONTH": [
"Ian.",
"Pep.",
"Mal.",
"\u02bbAp.",
"Mei",
"Iun.",
"Iul.",
"\u02bbAu.",
| "Now.",
"Kek."
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "d/M/yy h:mm a",
"shortDate": "d/M/yy",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "$",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "haw-us",
"pluralCat": function(n, opt_precision) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]); | "Kep.",
"\u02bbOk.",
| random_line_split |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function | (id,n,type,mod,size){
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var startx = center+xmod;
var starty = height+xmod;
var spin = -90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
case 2:
var startx = 0;
var starty = height/2+xmod;
var spin = -90;
var angle = 90;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 3:
var startx = center+xmod;
var starty = height+xmod;
var spin = 90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 4:
var startx = center+xmod;
var starty = -(height/2);
var spin = 90;
var angle = 180;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
default:
var startx = center+xmod;
var starty = height+xmod;
break;
}
var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle];
var arcs = paper.path(path_string);
arcs.attr("stroke", "#4babe0");
arcs.toBack();
};
};
// ElementID , number of arcs, arctype, offset, size
// TODO: ADD RESIZE EVENT
var a = arcs('#overview',5,1,15,1500);
var a = arcs('#overview',5,2,30,2500);
var a = arcs('#overview',5,3,15,2000);
var a = arcs('#overview',5,4,15,1000);
}); | arcs | identifier_name |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function arcs(id,n,type,mod,size){
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var startx = center+xmod;
var starty = height+xmod;
var spin = -90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
case 2:
var startx = 0;
var starty = height/2+xmod;
var spin = -90;
var angle = 90;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 3:
var startx = center+xmod;
var starty = height+xmod;
var spin = 90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 4:
var startx = center+xmod;
var starty = -(height/2);
var spin = 90;
var angle = 180;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 1; | break;
default:
var startx = center+xmod;
var starty = height+xmod;
break;
}
var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle];
var arcs = paper.path(path_string);
arcs.attr("stroke", "#4babe0");
arcs.toBack();
};
};
// ElementID , number of arcs, arctype, offset, size
// TODO: ADD RESIZE EVENT
var a = arcs('#overview',5,1,15,1500);
var a = arcs('#overview',5,2,30,2500);
var a = arcs('#overview',5,3,15,2000);
var a = arcs('#overview',5,4,15,1000);
}); | var quad = 1; | random_line_split |
all.js | //= require jquery/jquery
//= require raphael
//= require_tree .
$(document).ready(function(){
function arcs(id,n,type,mod,size) | ;
// ElementID , number of arcs, arctype, offset, size
// TODO: ADD RESIZE EVENT
var a = arcs('#overview',5,1,15,1500);
var a = arcs('#overview',5,2,30,2500);
var a = arcs('#overview',5,3,15,2000);
var a = arcs('#overview',5,4,15,1000);
}); | {
var top = $(id).position().top;
var height = $(id).height();
var width = $(id).width();
var center = width/2;
var R = 100;
var paper = Raphael(0, top, width, height);
xmod = 0;
for (i = 0; i < n; i++) {
var xmod = xmod + mod;
switch(type) {
case 1:
var startx = center+xmod;
var starty = height+xmod;
var spin = -90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
case 2:
var startx = 0;
var starty = height/2+xmod;
var spin = -90;
var angle = 90;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 3:
var startx = center+xmod;
var starty = height+xmod;
var spin = 90;
var angle = 90;
var elx = size-(xmod*4);
var ely = size+(size*0.25)-(xmod*4);
var dir = 0;
var quad = 1;
break;
case 4:
var startx = center+xmod;
var starty = -(height/2);
var spin = 90;
var angle = 180;
var elx = size-xmod*4;
var ely = size+(size*0.25)-(xmod*4);
var dir = 1;
var quad = 1;
break;
default:
var startx = center+xmod;
var starty = height+xmod;
break;
}
var path_string = ['m', startx, starty, 'a', elx, ely, 3, quad, dir, spin, angle];
var arcs = paper.path(path_string);
arcs.attr("stroke", "#4babe0");
arcs.toBack();
};
} | identifier_body |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOpenset):
""" The base class for PascalVOC dataset.
The archive contains 17125 images. Total size 1.9GB.
You can unpack the archive to the directory its been downloaded by specifing `unpack` flag.
Tracks of the PascalVOC challenge:
1. Classification
2. Detection
3. Segmentation
4. Action Classification Task
5. Boxless Action Classification
6. Person Layout
Notes
-----
Each track contains only the subset of the total images with labels provided.
"""
SOURCE_URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar'
SETS_PATH = 'VOCdevkit/VOC2012/ImageSets'
task = None
def __init__(self, *args, unpack=False, preloaded=None, train_test=True, **kwargs):
self.localname = None
super().__init__(*args, preloaded=preloaded, train_test=train_test, **kwargs)
if unpack:
with tarfile.open((self.localname), "r") as archive:
archive.extractall(dirname(self.localname))
def download_archive(self, path=None):
""" Download archive"""
if path is None:
path = tempfile.gettempdir()
filename = os.path.basename(self.SOURCE_URL)
localname = os.path.join(path, filename)
self.localname = localname
if not os.path.isfile(localname):
r = requests.get(self.SOURCE_URL, stream=True)
file_size = int(r.headers['Content-Length'])
chunk = 1
chunk_size = 1024
num_bars = int(file_size / chunk_size)
with open(localname, 'wb') as f:
for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size), total=num_bars, unit='KB',
desc=filename, leave=True):
f.write(chunk)
def _name(self, path):
""" Return file name without format """
return basename(path).split('.')[0]
def _image_path(self, name):
""" Return the path to the .jpg image in the archive by its name """
return os.path.join(dirname(self.SETS_PATH), 'JPEGImages', name + '.jpg')
def _extract_image(self, archive, file):
data = archive.extractfile(file).read()
return PIL.Image.open(BytesIO(data))
def _extract_ids(self, archive, part):
""" Train and test images ids are located in specific for each task folder"""
part_path = os.path.join(self.SETS_PATH, self.task, part) + '.txt'
raw_ids = archive.extractfile(part_path)
list_ids = raw_ids.read().decode().split('\n')
return list_ids[:-1]
class PascalSegmentation(BasePascal):
""" Contains 2913 images and masks.
Notes
-----
Class 0 corresponds to background and class 255 corresponds to 'void' or unlabelled.
"""
task = 'Segmentation'
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa',
'train', 'TV/monitor']
def _mask_path(self, name):
""" Return the path in the archive to the mask which is .png image by its name"""
return os.path.join(dirname(self.SETS_PATH), 'SegmentationClass', name + '.png')
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
masks = np.array([self._extract_image(archive, self._mask_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
preloaded = images, masks
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
class PascalClassification(BasePascal):
""" Contains 11540 images and corresponding classes
Notes
-----
- Labels are represented by the vector of size 20. '1' stands for the presence of at least one object from
coresponding class on the image. '-1' stands for the absence. '0' indicates that the object is presented,
but can hardly be detected.
- You can control zeros among targets via `process_zero` keyword argument:
Setting `process_zero=0` leaves the targets as it is.
Setting `process_zero=1` or any other positive number replaces `0` with `1`
Setting `process_zero=-1` or any other negative number replaces `0` with `-1`
"""
task = 'Main'
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa', 'train',
'tvmonitor']
def __init__(self, *args, replace_zero=-1, unpack=False, preloaded=None, train_test=True, **kwargs):
self.replace_zero = replace_zero
super().__init__(*args, unpack=unpack, preloaded=preloaded, train_test=train_test, **kwargs)
def _process_targets(self, targets):
np.place(targets, targets == 0, np.sign(self.replace_zero))
labels = (targets > 0).astype(int)
return labels
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
d = defaultdict(list)
class_files = [os.path.join(self.SETS_PATH, self.task, name.replace(' ', '')) + '_trainval.txt'
for name in self.classes]
for class_file in class_files:
|
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name))
for name in [*train_ids, *test_ids]], dtype=object)
targets = np.array([d[self._name(name)] for name in [*train_ids, *test_ids]])
labels = self._process_targets(targets)
preloaded = images, labels
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
| data = archive.extractfile(class_file).read()
for row in data.decode().split('\n')[:-1]:
key = row.split()[0]
value = int(row.split()[1])
d[key].append(value) | conditional_block |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOpenset):
""" The base class for PascalVOC dataset.
The archive contains 17125 images. Total size 1.9GB.
You can unpack the archive to the directory its been downloaded by specifing `unpack` flag.
Tracks of the PascalVOC challenge:
1. Classification
2. Detection
3. Segmentation
4. Action Classification Task
5. Boxless Action Classification
6. Person Layout
Notes
-----
Each track contains only the subset of the total images with labels provided.
"""
SOURCE_URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar'
SETS_PATH = 'VOCdevkit/VOC2012/ImageSets'
task = None
def __init__(self, *args, unpack=False, preloaded=None, train_test=True, **kwargs):
self.localname = None
super().__init__(*args, preloaded=preloaded, train_test=train_test, **kwargs)
if unpack:
with tarfile.open((self.localname), "r") as archive:
archive.extractall(dirname(self.localname))
def download_archive(self, path=None):
""" Download archive"""
if path is None:
path = tempfile.gettempdir()
filename = os.path.basename(self.SOURCE_URL)
localname = os.path.join(path, filename)
self.localname = localname
if not os.path.isfile(localname):
r = requests.get(self.SOURCE_URL, stream=True)
file_size = int(r.headers['Content-Length'])
chunk = 1
chunk_size = 1024
num_bars = int(file_size / chunk_size)
with open(localname, 'wb') as f:
for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size), total=num_bars, unit='KB',
desc=filename, leave=True):
f.write(chunk)
| """ Return the path to the .jpg image in the archive by its name """
return os.path.join(dirname(self.SETS_PATH), 'JPEGImages', name + '.jpg')
def _extract_image(self, archive, file):
data = archive.extractfile(file).read()
return PIL.Image.open(BytesIO(data))
def _extract_ids(self, archive, part):
""" Train and test images ids are located in specific for each task folder"""
part_path = os.path.join(self.SETS_PATH, self.task, part) + '.txt'
raw_ids = archive.extractfile(part_path)
list_ids = raw_ids.read().decode().split('\n')
return list_ids[:-1]
class PascalSegmentation(BasePascal):
""" Contains 2913 images and masks.
Notes
-----
Class 0 corresponds to background and class 255 corresponds to 'void' or unlabelled.
"""
task = 'Segmentation'
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa',
'train', 'TV/monitor']
def _mask_path(self, name):
""" Return the path in the archive to the mask which is .png image by its name"""
return os.path.join(dirname(self.SETS_PATH), 'SegmentationClass', name + '.png')
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
masks = np.array([self._extract_image(archive, self._mask_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
preloaded = images, masks
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
class PascalClassification(BasePascal):
""" Contains 11540 images and corresponding classes
Notes
-----
- Labels are represented by the vector of size 20. '1' stands for the presence of at least one object from
coresponding class on the image. '-1' stands for the absence. '0' indicates that the object is presented,
but can hardly be detected.
- You can control zeros among targets via `process_zero` keyword argument:
Setting `process_zero=0` leaves the targets as it is.
Setting `process_zero=1` or any other positive number replaces `0` with `1`
Setting `process_zero=-1` or any other negative number replaces `0` with `-1`
"""
task = 'Main'
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa', 'train',
'tvmonitor']
def __init__(self, *args, replace_zero=-1, unpack=False, preloaded=None, train_test=True, **kwargs):
self.replace_zero = replace_zero
super().__init__(*args, unpack=unpack, preloaded=preloaded, train_test=train_test, **kwargs)
def _process_targets(self, targets):
np.place(targets, targets == 0, np.sign(self.replace_zero))
labels = (targets > 0).astype(int)
return labels
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
d = defaultdict(list)
class_files = [os.path.join(self.SETS_PATH, self.task, name.replace(' ', '')) + '_trainval.txt'
for name in self.classes]
for class_file in class_files:
data = archive.extractfile(class_file).read()
for row in data.decode().split('\n')[:-1]:
key = row.split()[0]
value = int(row.split()[1])
d[key].append(value)
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name))
for name in [*train_ids, *test_ids]], dtype=object)
targets = np.array([d[self._name(name)] for name in [*train_ids, *test_ids]])
labels = self._process_targets(targets)
preloaded = images, labels
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index | def _name(self, path):
""" Return file name without format """
return basename(path).split('.')[0]
def _image_path(self, name): | random_line_split |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class | (ImagesOpenset):
""" The base class for PascalVOC dataset.
The archive contains 17125 images. Total size 1.9GB.
You can unpack the archive to the directory its been downloaded by specifing `unpack` flag.
Tracks of the PascalVOC challenge:
1. Classification
2. Detection
3. Segmentation
4. Action Classification Task
5. Boxless Action Classification
6. Person Layout
Notes
-----
Each track contains only the subset of the total images with labels provided.
"""
SOURCE_URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar'
SETS_PATH = 'VOCdevkit/VOC2012/ImageSets'
task = None
def __init__(self, *args, unpack=False, preloaded=None, train_test=True, **kwargs):
self.localname = None
super().__init__(*args, preloaded=preloaded, train_test=train_test, **kwargs)
if unpack:
with tarfile.open((self.localname), "r") as archive:
archive.extractall(dirname(self.localname))
def download_archive(self, path=None):
""" Download archive"""
if path is None:
path = tempfile.gettempdir()
filename = os.path.basename(self.SOURCE_URL)
localname = os.path.join(path, filename)
self.localname = localname
if not os.path.isfile(localname):
r = requests.get(self.SOURCE_URL, stream=True)
file_size = int(r.headers['Content-Length'])
chunk = 1
chunk_size = 1024
num_bars = int(file_size / chunk_size)
with open(localname, 'wb') as f:
for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size), total=num_bars, unit='KB',
desc=filename, leave=True):
f.write(chunk)
def _name(self, path):
""" Return file name without format """
return basename(path).split('.')[0]
def _image_path(self, name):
""" Return the path to the .jpg image in the archive by its name """
return os.path.join(dirname(self.SETS_PATH), 'JPEGImages', name + '.jpg')
def _extract_image(self, archive, file):
data = archive.extractfile(file).read()
return PIL.Image.open(BytesIO(data))
def _extract_ids(self, archive, part):
""" Train and test images ids are located in specific for each task folder"""
part_path = os.path.join(self.SETS_PATH, self.task, part) + '.txt'
raw_ids = archive.extractfile(part_path)
list_ids = raw_ids.read().decode().split('\n')
return list_ids[:-1]
class PascalSegmentation(BasePascal):
""" Contains 2913 images and masks.
Notes
-----
Class 0 corresponds to background and class 255 corresponds to 'void' or unlabelled.
"""
task = 'Segmentation'
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa',
'train', 'TV/monitor']
def _mask_path(self, name):
""" Return the path in the archive to the mask which is .png image by its name"""
return os.path.join(dirname(self.SETS_PATH), 'SegmentationClass', name + '.png')
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
masks = np.array([self._extract_image(archive, self._mask_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
preloaded = images, masks
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
class PascalClassification(BasePascal):
""" Contains 11540 images and corresponding classes
Notes
-----
- Labels are represented by the vector of size 20. '1' stands for the presence of at least one object from
coresponding class on the image. '-1' stands for the absence. '0' indicates that the object is presented,
but can hardly be detected.
- You can control zeros among targets via `process_zero` keyword argument:
Setting `process_zero=0` leaves the targets as it is.
Setting `process_zero=1` or any other positive number replaces `0` with `1`
Setting `process_zero=-1` or any other negative number replaces `0` with `-1`
"""
task = 'Main'
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa', 'train',
'tvmonitor']
def __init__(self, *args, replace_zero=-1, unpack=False, preloaded=None, train_test=True, **kwargs):
self.replace_zero = replace_zero
super().__init__(*args, unpack=unpack, preloaded=preloaded, train_test=train_test, **kwargs)
def _process_targets(self, targets):
np.place(targets, targets == 0, np.sign(self.replace_zero))
labels = (targets > 0).astype(int)
return labels
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
d = defaultdict(list)
class_files = [os.path.join(self.SETS_PATH, self.task, name.replace(' ', '')) + '_trainval.txt'
for name in self.classes]
for class_file in class_files:
data = archive.extractfile(class_file).read()
for row in data.decode().split('\n')[:-1]:
key = row.split()[0]
value = int(row.split()[1])
d[key].append(value)
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name))
for name in [*train_ids, *test_ids]], dtype=object)
targets = np.array([d[self._name(name)] for name in [*train_ids, *test_ids]])
labels = self._process_targets(targets)
preloaded = images, labels
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
| BasePascal | identifier_name |
pascal.py | """ Contains PascalVOC dataset and labels for different tasks """
import os
from os.path import dirname, basename
from io import BytesIO
import tarfile
import tempfile
from collections import defaultdict
import PIL
import tqdm
import numpy as np
import requests
from . import ImagesOpenset
class BasePascal(ImagesOpenset):
""" The base class for PascalVOC dataset.
The archive contains 17125 images. Total size 1.9GB.
You can unpack the archive to the directory its been downloaded by specifing `unpack` flag.
Tracks of the PascalVOC challenge:
1. Classification
2. Detection
3. Segmentation
4. Action Classification Task
5. Boxless Action Classification
6. Person Layout
Notes
-----
Each track contains only the subset of the total images with labels provided.
"""
SOURCE_URL = 'http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar'
SETS_PATH = 'VOCdevkit/VOC2012/ImageSets'
task = None
def __init__(self, *args, unpack=False, preloaded=None, train_test=True, **kwargs):
self.localname = None
super().__init__(*args, preloaded=preloaded, train_test=train_test, **kwargs)
if unpack:
with tarfile.open((self.localname), "r") as archive:
archive.extractall(dirname(self.localname))
def download_archive(self, path=None):
""" Download archive"""
if path is None:
path = tempfile.gettempdir()
filename = os.path.basename(self.SOURCE_URL)
localname = os.path.join(path, filename)
self.localname = localname
if not os.path.isfile(localname):
r = requests.get(self.SOURCE_URL, stream=True)
file_size = int(r.headers['Content-Length'])
chunk = 1
chunk_size = 1024
num_bars = int(file_size / chunk_size)
with open(localname, 'wb') as f:
for chunk in tqdm.tqdm(r.iter_content(chunk_size=chunk_size), total=num_bars, unit='KB',
desc=filename, leave=True):
f.write(chunk)
def _name(self, path):
""" Return file name without format """
return basename(path).split('.')[0]
def _image_path(self, name):
""" Return the path to the .jpg image in the archive by its name """
return os.path.join(dirname(self.SETS_PATH), 'JPEGImages', name + '.jpg')
def _extract_image(self, archive, file):
data = archive.extractfile(file).read()
return PIL.Image.open(BytesIO(data))
def _extract_ids(self, archive, part):
""" Train and test images ids are located in specific for each task folder"""
part_path = os.path.join(self.SETS_PATH, self.task, part) + '.txt'
raw_ids = archive.extractfile(part_path)
list_ids = raw_ids.read().decode().split('\n')
return list_ids[:-1]
class PascalSegmentation(BasePascal):
""" Contains 2913 images and masks.
Notes
-----
Class 0 corresponds to background and class 255 corresponds to 'void' or unlabelled.
"""
task = 'Segmentation'
classes = ['background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair',
'cow', 'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa',
'train', 'TV/monitor']
def _mask_path(self, name):
""" Return the path in the archive to the mask which is .png image by its name"""
return os.path.join(dirname(self.SETS_PATH), 'SegmentationClass', name + '.png')
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
masks = np.array([self._extract_image(archive, self._mask_path(name)) \
for name in [*train_ids, *test_ids]], dtype=object)
preloaded = images, masks
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index
class PascalClassification(BasePascal):
| """ Contains 11540 images and corresponding classes
Notes
-----
- Labels are represented by the vector of size 20. '1' stands for the presence of at least one object from
coresponding class on the image. '-1' stands for the absence. '0' indicates that the object is presented,
but can hardly be detected.
- You can control zeros among targets via `process_zero` keyword argument:
Setting `process_zero=0` leaves the targets as it is.
Setting `process_zero=1` or any other positive number replaces `0` with `1`
Setting `process_zero=-1` or any other negative number replaces `0` with `-1`
"""
task = 'Main'
classes = ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow',
'dining table', 'dog', 'horse', 'motorbike', 'person', 'potted plant', 'sheep', 'sofa', 'train',
'tvmonitor']
def __init__(self, *args, replace_zero=-1, unpack=False, preloaded=None, train_test=True, **kwargs):
self.replace_zero = replace_zero
super().__init__(*args, unpack=unpack, preloaded=preloaded, train_test=train_test, **kwargs)
def _process_targets(self, targets):
np.place(targets, targets == 0, np.sign(self.replace_zero))
labels = (targets > 0).astype(int)
return labels
def download(self, path):
""" Download a dataset from the source web-site """
self.download_archive(path)
with tarfile.open(self.localname, "r") as archive:
d = defaultdict(list)
class_files = [os.path.join(self.SETS_PATH, self.task, name.replace(' ', '')) + '_trainval.txt'
for name in self.classes]
for class_file in class_files:
data = archive.extractfile(class_file).read()
for row in data.decode().split('\n')[:-1]:
key = row.split()[0]
value = int(row.split()[1])
d[key].append(value)
train_ids = self._extract_ids(archive, 'train')
test_ids = self._extract_ids(archive, 'val')
images = np.array([self._extract_image(archive, self._image_path(name))
for name in [*train_ids, *test_ids]], dtype=object)
targets = np.array([d[self._name(name)] for name in [*train_ids, *test_ids]])
labels = self._process_targets(targets)
preloaded = images, labels
train_len, test_len = len(train_ids), len(test_ids)
index, train_index, test_index = self._infer_train_test_index(train_len, test_len)
return preloaded, index, train_index, test_index | identifier_body | |
GoogleSheetsDataImportService.js | /**
* @license
* Copyright 2020 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
| methods: [
{
name: 'getColumns',
javaType: 'String[]',
args: [
{
name: 'x',
type: 'Context',
},
{
name: 'importConfig',
type: 'foam.nanos.google.api.sheets.GoogleSheetsImportConfig'
}
]
},
{
name: 'importData',
type: 'foam.nanos.google.api.sheets.ImportDataMessage',
args: [
{
name: 'x',
type: 'Context',
},
{
name: 'importConfig',
type: 'foam.nanos.google.api.sheets.GoogleSheetsImportConfig'
}
]
}
]
}); | foam.INTERFACE({
package: 'foam.nanos.google.api.sheets',
name: 'GoogleSheetsDataImportService', | random_line_split |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: number
bodyLength: number
totalLength: number
}
export function parseMessageHeader(message: Buffer): ParsedHeaderInfo | undefined {
if (message.readUInt8(0) !== SOH || message.readUInt8(2) !== SENDER_ID) {
return undefined
}
const bodyLength = bufferReadHex(message, 5, 1)
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
return undefined
}
return {
deviceId: message.readUInt8(2),
type,
bodyLength,
totalLength: bodyLength + 9,
}
}
export interface ParsedResponse {
page: number
opcode: number
value: string | number
}
export function parseMessage(commandId: number[], message: Buffer): string | number {
const checksumByte = message.readUInt8(message.length - 2)
const calculatedChecksum = calculateCheckCode(message.slice(1, message.length - 2))
if (checksumByte !== calculatedChecksum) {
throw new Error(`Message checksum failed. Got: ${calculatedChecksum} Expected ${checksumByte}`)
}
const headerProps = parseHeader(message)
// console.log('header', headerProps)
const body = message.slice(7, message.length - 2)
if (body.length !== headerProps.length) {
throw new Error(`Message body length incorrect. Got: ${body.length} Expected ${headerProps.length}`)
}
switch (headerProps.type) {
case MessageType.GetReply:
case MessageType.SetReply: {
const res = parseGetSetReply(body)
if (commandId[0] !== res.page || commandId[1] !== res.opcode) {
throw new Error('wrong command response')
}
return res.value
}
case MessageType.CommandReply:
return parseCommandReply(commandId, body)
default:
throw new Error(`Message received of unsupported type: ${MessageType[headerProps.type]}`)
}
}
function parseHeader(message: Buffer) {
// in hex: 01 30 _ID_ 30 _TYPE_ _LEN_ _LEN2_
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
throw new Error(`Message received with unknown type: ${type}`)
}
return {
type,
length: bufferReadHex(message, 5, 1),
}
}
function parseGetSetReply(body: Buffer) {
const result = bufferReadHex(body, 1, 1)
const page = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
// const type = bufferReadHex(body, 7, 1)
// const maxValue = bufferReadHex(body, 9, 2)
const currentValue = bufferReadHex(body, 13, 2)
// check result was good
if (result !== 0x00) {
throw new Error('Unsupported operation')
}
// var commandType = Commands.fromCodes(page, code)
// if (commandType === null) unknownCommand()
// result.command = commandType.key
// result.operationType = linq.from(OperationType).firstOrDefault(function(t) {
// return t.value == type
// })
// if (result.operationType === null) return (result.err = 'UNKNOWN_OPERATION_TYPE')
// result.operationType = result.operationType.key
// result.maxValue = maxValue
// result.value = currentValue
// if (commandType.value.type == 'range') result.value = parseInt(result.value, 16)
// TODO - if range, decode hex?
return {
page,
opcode,
value: currentValue,
}
}
/**
* Parsing command responses is a lot more complex, as there doesnt appear to be much uniformity in them. | case 0xd6: {
// Power get response
const page = bufferReadHex(body, 5, 1)
if (page !== commandId[0]) {
throw new Error('wrong command response')
}
const result = bufferReadHex(body, 3, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
return bufferReadHex(body, 13, 2)
}
case 0xc2: {
// Power set response
const result = bufferReadHex(body, 1, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
const actualPage = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
if (actualPage !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
return bufferReadHex(body, 9, 2)
}
case 0xc3: {
const page = bufferReadHex(body, 1, 1)
const opcode = bufferReadHex(body, 3, 1)
// console.log(page, opcode, commandId)
if (page !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
const strLength = body.length / 2 - 5 - 1
const decodedStr = bufferReadString(body, 5, strLength).replace(/\0/g, '')
return decodedStr
}
default:
throw new Error('Unknown command')
}
} | */
function parseCommandReply(commandId: number[], body: Buffer): string | number {
// console.log('command response', body, commandId)
switch (commandId[0]) { | random_line_split |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: number
bodyLength: number
totalLength: number
}
export function | (message: Buffer): ParsedHeaderInfo | undefined {
if (message.readUInt8(0) !== SOH || message.readUInt8(2) !== SENDER_ID) {
return undefined
}
const bodyLength = bufferReadHex(message, 5, 1)
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
return undefined
}
return {
deviceId: message.readUInt8(2),
type,
bodyLength,
totalLength: bodyLength + 9,
}
}
export interface ParsedResponse {
page: number
opcode: number
value: string | number
}
export function parseMessage(commandId: number[], message: Buffer): string | number {
const checksumByte = message.readUInt8(message.length - 2)
const calculatedChecksum = calculateCheckCode(message.slice(1, message.length - 2))
if (checksumByte !== calculatedChecksum) {
throw new Error(`Message checksum failed. Got: ${calculatedChecksum} Expected ${checksumByte}`)
}
const headerProps = parseHeader(message)
// console.log('header', headerProps)
const body = message.slice(7, message.length - 2)
if (body.length !== headerProps.length) {
throw new Error(`Message body length incorrect. Got: ${body.length} Expected ${headerProps.length}`)
}
switch (headerProps.type) {
case MessageType.GetReply:
case MessageType.SetReply: {
const res = parseGetSetReply(body)
if (commandId[0] !== res.page || commandId[1] !== res.opcode) {
throw new Error('wrong command response')
}
return res.value
}
case MessageType.CommandReply:
return parseCommandReply(commandId, body)
default:
throw new Error(`Message received of unsupported type: ${MessageType[headerProps.type]}`)
}
}
function parseHeader(message: Buffer) {
// in hex: 01 30 _ID_ 30 _TYPE_ _LEN_ _LEN2_
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
throw new Error(`Message received with unknown type: ${type}`)
}
return {
type,
length: bufferReadHex(message, 5, 1),
}
}
function parseGetSetReply(body: Buffer) {
const result = bufferReadHex(body, 1, 1)
const page = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
// const type = bufferReadHex(body, 7, 1)
// const maxValue = bufferReadHex(body, 9, 2)
const currentValue = bufferReadHex(body, 13, 2)
// check result was good
if (result !== 0x00) {
throw new Error('Unsupported operation')
}
// var commandType = Commands.fromCodes(page, code)
// if (commandType === null) unknownCommand()
// result.command = commandType.key
// result.operationType = linq.from(OperationType).firstOrDefault(function(t) {
// return t.value == type
// })
// if (result.operationType === null) return (result.err = 'UNKNOWN_OPERATION_TYPE')
// result.operationType = result.operationType.key
// result.maxValue = maxValue
// result.value = currentValue
// if (commandType.value.type == 'range') result.value = parseInt(result.value, 16)
// TODO - if range, decode hex?
return {
page,
opcode,
value: currentValue,
}
}
/**
* Parsing command responses is a lot more complex, as there doesnt appear to be much uniformity in them.
*/
function parseCommandReply(commandId: number[], body: Buffer): string | number {
// console.log('command response', body, commandId)
switch (commandId[0]) {
case 0xd6: {
// Power get response
const page = bufferReadHex(body, 5, 1)
if (page !== commandId[0]) {
throw new Error('wrong command response')
}
const result = bufferReadHex(body, 3, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
return bufferReadHex(body, 13, 2)
}
case 0xc2: {
// Power set response
const result = bufferReadHex(body, 1, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
const actualPage = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
if (actualPage !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
return bufferReadHex(body, 9, 2)
}
case 0xc3: {
const page = bufferReadHex(body, 1, 1)
const opcode = bufferReadHex(body, 3, 1)
// console.log(page, opcode, commandId)
if (page !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
const strLength = body.length / 2 - 5 - 1
const decodedStr = bufferReadString(body, 5, strLength).replace(/\0/g, '')
return decodedStr
}
default:
throw new Error('Unknown command')
}
}
| parseMessageHeader | identifier_name |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: number
bodyLength: number
totalLength: number
}
export function parseMessageHeader(message: Buffer): ParsedHeaderInfo | undefined {
if (message.readUInt8(0) !== SOH || message.readUInt8(2) !== SENDER_ID) {
return undefined
}
const bodyLength = bufferReadHex(message, 5, 1)
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
return undefined
}
return {
deviceId: message.readUInt8(2),
type,
bodyLength,
totalLength: bodyLength + 9,
}
}
export interface ParsedResponse {
page: number
opcode: number
value: string | number
}
export function parseMessage(commandId: number[], message: Buffer): string | number {
const checksumByte = message.readUInt8(message.length - 2)
const calculatedChecksum = calculateCheckCode(message.slice(1, message.length - 2))
if (checksumByte !== calculatedChecksum) {
throw new Error(`Message checksum failed. Got: ${calculatedChecksum} Expected ${checksumByte}`)
}
const headerProps = parseHeader(message)
// console.log('header', headerProps)
const body = message.slice(7, message.length - 2)
if (body.length !== headerProps.length) {
throw new Error(`Message body length incorrect. Got: ${body.length} Expected ${headerProps.length}`)
}
switch (headerProps.type) {
case MessageType.GetReply:
case MessageType.SetReply: {
const res = parseGetSetReply(body)
if (commandId[0] !== res.page || commandId[1] !== res.opcode) {
throw new Error('wrong command response')
}
return res.value
}
case MessageType.CommandReply:
return parseCommandReply(commandId, body)
default:
throw new Error(`Message received of unsupported type: ${MessageType[headerProps.type]}`)
}
}
function parseHeader(message: Buffer) |
function parseGetSetReply(body: Buffer) {
const result = bufferReadHex(body, 1, 1)
const page = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
// const type = bufferReadHex(body, 7, 1)
// const maxValue = bufferReadHex(body, 9, 2)
const currentValue = bufferReadHex(body, 13, 2)
// check result was good
if (result !== 0x00) {
throw new Error('Unsupported operation')
}
// var commandType = Commands.fromCodes(page, code)
// if (commandType === null) unknownCommand()
// result.command = commandType.key
// result.operationType = linq.from(OperationType).firstOrDefault(function(t) {
// return t.value == type
// })
// if (result.operationType === null) return (result.err = 'UNKNOWN_OPERATION_TYPE')
// result.operationType = result.operationType.key
// result.maxValue = maxValue
// result.value = currentValue
// if (commandType.value.type == 'range') result.value = parseInt(result.value, 16)
// TODO - if range, decode hex?
return {
page,
opcode,
value: currentValue,
}
}
/**
* Parsing command responses is a lot more complex, as there doesnt appear to be much uniformity in them.
*/
function parseCommandReply(commandId: number[], body: Buffer): string | number {
// console.log('command response', body, commandId)
switch (commandId[0]) {
case 0xd6: {
// Power get response
const page = bufferReadHex(body, 5, 1)
if (page !== commandId[0]) {
throw new Error('wrong command response')
}
const result = bufferReadHex(body, 3, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
return bufferReadHex(body, 13, 2)
}
case 0xc2: {
// Power set response
const result = bufferReadHex(body, 1, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
const actualPage = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
if (actualPage !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
return bufferReadHex(body, 9, 2)
}
case 0xc3: {
const page = bufferReadHex(body, 1, 1)
const opcode = bufferReadHex(body, 3, 1)
// console.log(page, opcode, commandId)
if (page !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
const strLength = body.length / 2 - 5 - 1
const decodedStr = bufferReadString(body, 5, strLength).replace(/\0/g, '')
return decodedStr
}
default:
throw new Error('Unknown command')
}
}
| {
// in hex: 01 30 _ID_ 30 _TYPE_ _LEN_ _LEN2_
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
throw new Error(`Message received with unknown type: ${type}`)
}
return {
type,
length: bufferReadHex(message, 5, 1),
}
} | identifier_body |
parser.ts | import { calculateCheckCode } from './builder'
import { SENDER_ID, SOH } from './constants'
import { MessageType } from './enums'
import { bufferReadHex, bufferReadString } from './util'
// var OperationType = {
// SET: '00',
// MOMENTARY: '01'
// }
export interface ParsedHeaderInfo {
deviceId: number
type: number
bodyLength: number
totalLength: number
}
export function parseMessageHeader(message: Buffer): ParsedHeaderInfo | undefined {
if (message.readUInt8(0) !== SOH || message.readUInt8(2) !== SENDER_ID) {
return undefined
}
const bodyLength = bufferReadHex(message, 5, 1)
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
return undefined
}
return {
deviceId: message.readUInt8(2),
type,
bodyLength,
totalLength: bodyLength + 9,
}
}
export interface ParsedResponse {
page: number
opcode: number
value: string | number
}
export function parseMessage(commandId: number[], message: Buffer): string | number {
const checksumByte = message.readUInt8(message.length - 2)
const calculatedChecksum = calculateCheckCode(message.slice(1, message.length - 2))
if (checksumByte !== calculatedChecksum) {
throw new Error(`Message checksum failed. Got: ${calculatedChecksum} Expected ${checksumByte}`)
}
const headerProps = parseHeader(message)
// console.log('header', headerProps)
const body = message.slice(7, message.length - 2)
if (body.length !== headerProps.length) |
switch (headerProps.type) {
case MessageType.GetReply:
case MessageType.SetReply: {
const res = parseGetSetReply(body)
if (commandId[0] !== res.page || commandId[1] !== res.opcode) {
throw new Error('wrong command response')
}
return res.value
}
case MessageType.CommandReply:
return parseCommandReply(commandId, body)
default:
throw new Error(`Message received of unsupported type: ${MessageType[headerProps.type]}`)
}
}
function parseHeader(message: Buffer) {
// in hex: 01 30 _ID_ 30 _TYPE_ _LEN_ _LEN2_
const type = message.readUInt8(4) as MessageType
if (!MessageType[type]) {
throw new Error(`Message received with unknown type: ${type}`)
}
return {
type,
length: bufferReadHex(message, 5, 1),
}
}
function parseGetSetReply(body: Buffer) {
const result = bufferReadHex(body, 1, 1)
const page = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
// const type = bufferReadHex(body, 7, 1)
// const maxValue = bufferReadHex(body, 9, 2)
const currentValue = bufferReadHex(body, 13, 2)
// check result was good
if (result !== 0x00) {
throw new Error('Unsupported operation')
}
// var commandType = Commands.fromCodes(page, code)
// if (commandType === null) unknownCommand()
// result.command = commandType.key
// result.operationType = linq.from(OperationType).firstOrDefault(function(t) {
// return t.value == type
// })
// if (result.operationType === null) return (result.err = 'UNKNOWN_OPERATION_TYPE')
// result.operationType = result.operationType.key
// result.maxValue = maxValue
// result.value = currentValue
// if (commandType.value.type == 'range') result.value = parseInt(result.value, 16)
// TODO - if range, decode hex?
return {
page,
opcode,
value: currentValue,
}
}
/**
* Parsing command responses is a lot more complex, as there doesnt appear to be much uniformity in them.
*/
function parseCommandReply(commandId: number[], body: Buffer): string | number {
// console.log('command response', body, commandId)
switch (commandId[0]) {
case 0xd6: {
// Power get response
const page = bufferReadHex(body, 5, 1)
if (page !== commandId[0]) {
throw new Error('wrong command response')
}
const result = bufferReadHex(body, 3, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
return bufferReadHex(body, 13, 2)
}
case 0xc2: {
// Power set response
const result = bufferReadHex(body, 1, 1)
if (result !== 0x00) {
// page is actually result
throw new Error('Unsupported operation')
}
const actualPage = bufferReadHex(body, 3, 1)
const opcode = bufferReadHex(body, 5, 1)
if (actualPage !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
return bufferReadHex(body, 9, 2)
}
case 0xc3: {
const page = bufferReadHex(body, 1, 1)
const opcode = bufferReadHex(body, 3, 1)
// console.log(page, opcode, commandId)
if (page !== commandId[0] || opcode !== commandId[1]) {
throw new Error('wrong command response')
}
const strLength = body.length / 2 - 5 - 1
const decodedStr = bufferReadString(body, 5, strLength).replace(/\0/g, '')
return decodedStr
}
default:
throw new Error('Unknown command')
}
}
| {
throw new Error(`Message body length incorrect. Got: ${body.length} Expected ${headerProps.length}`)
} | conditional_block |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup for tests."""
self.portal = self.layer['portal']
self.installer = api.portal.get_tool('portal_quickinstaller')
def test_product_installed(self):
"""Test if ade25.assetmanager is installed with portal_quickinstaller."""
self.assertTrue(self.installer.isProductInstalled('ade25.assetmanager'))
def test_uninstall(self):
"""Test if ade25.assetmanager is cleanly uninstalled."""
self.installer.uninstallProducts(['ade25.assetmanager'])
self.assertFalse(self.installer.isProductInstalled('ade25.assetmanager'))
# browserlayer.xml
def test_browserlayer(self):
| """Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces import IAde25AssetmanagerLayer
from plone.browserlayer import utils
self.failUnless(IAde25AssetmanagerLayer in utils.registered_layers()) | identifier_body | |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
| """Custom shared utility setup for tests."""
self.portal = self.layer['portal']
self.installer = api.portal.get_tool('portal_quickinstaller')
def test_product_installed(self):
"""Test if ade25.assetmanager is installed with portal_quickinstaller."""
self.assertTrue(self.installer.isProductInstalled('ade25.assetmanager'))
def test_uninstall(self):
"""Test if ade25.assetmanager is cleanly uninstalled."""
self.installer.uninstallProducts(['ade25.assetmanager'])
self.assertFalse(self.installer.isProductInstalled('ade25.assetmanager'))
# browserlayer.xml
def test_browserlayer(self):
"""Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces import IAde25AssetmanagerLayer
from plone.browserlayer import utils
self.failUnless(IAde25AssetmanagerLayer in utils.registered_layers()) | def setUp(self): | random_line_split |
test_setup.py | # -*- coding: utf-8 -*-
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup for tests."""
self.portal = self.layer['portal']
self.installer = api.portal.get_tool('portal_quickinstaller')
def test_product_installed(self):
"""Test if ade25.assetmanager is installed with portal_quickinstaller."""
self.assertTrue(self.installer.isProductInstalled('ade25.assetmanager'))
def test_uninstall(self):
"""Test if ade25.assetmanager is cleanly uninstalled."""
self.installer.uninstallProducts(['ade25.assetmanager'])
self.assertFalse(self.installer.isProductInstalled('ade25.assetmanager'))
# browserlayer.xml
def | (self):
"""Test that IAde25AssetmanagerLayer is registered."""
from ade25.assetmanager.interfaces import IAde25AssetmanagerLayer
from plone.browserlayer import utils
self.failUnless(IAde25AssetmanagerLayer in utils.registered_layers())
| test_browserlayer | identifier_name |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Utilities for working with DataCite metadata."""
from __future__ import absolute_import
import re
import urllib2
from invenio_utils.xmlDict import ElementTree, XmlDictConfig
__all__ = (
'DataciteMetadata',
)
class DataciteMetadata(object):
"""Helper class for working with DataCite metadata."""
def __init__(self, doi):
"""Initialize object."""
self.url = "http://data.datacite.org/application/x-datacite+xml/"
self.error = False
try:
data = urllib2.urlopen(self.url + doi).read()
except urllib2.HTTPError:
self.error = True
if not self.error:
# Clean the xml for parsing
data = re.sub('<\?xml.*\?>', '', data, count=1)
# Remove the resource tags
data = re.sub('<resource .*xsd">', '', data)
self.data = '<?xml version="1.0"?><datacite>' + \
data[0:len(data) - 11] + '</datacite>'
self.root = ElementTree.XML(self.data)
self.xml = XmlDictConfig(self.root)
def get_creators(self, attribute='creatorName'):
"""Get DataCite creators."""
if 'creators' in self.xml:
if isinstance(self.xml['creators']['creator'], list):
return [c[attribute] for c in self.xml['creators']['creator']]
else:
return self.xml['creators']['creator'][attribute]
return None
def get_titles(self):
"""Get DataCite titles."""
if 'titles' in self.xml:
return self.xml['titles']['title']
return None
def get_publisher(self):
"""Get DataCite publisher."""
if 'publisher' in self.xml:
return self.xml['publisher']
return None
def get_dates(self):
"""Get DataCite dates."""
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None
def get_publication_year(self):
"""Get DataCite publication year."""
if 'publicationYear' in self.xml:
|
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
"""Get DataCite related identifiers."""
pass
def get_description(self, description_type='Abstract'):
"""Get DataCite description."""
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if description_type in description:
return description[description_type]
elif isinstance(self.xml['descriptions']['description'], dict):
description = self.xml['descriptions']['description']
if description_type in description:
return description[description_type]
elif len(description) == 1:
# return the only description
return description.values()[0]
return None
def get_rights(self):
"""Get DataCite rights."""
if 'titles' in self.xml:
return self.xml['rights']
return None
| return self.xml['publicationYear'] | conditional_block |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Utilities for working with DataCite metadata."""
from __future__ import absolute_import
import re
import urllib2
from invenio_utils.xmlDict import ElementTree, XmlDictConfig
__all__ = (
'DataciteMetadata',
)
class DataciteMetadata(object):
"""Helper class for working with DataCite metadata."""
def __init__(self, doi):
"""Initialize object."""
self.url = "http://data.datacite.org/application/x-datacite+xml/"
self.error = False
try:
data = urllib2.urlopen(self.url + doi).read()
except urllib2.HTTPError:
self.error = True
if not self.error:
# Clean the xml for parsing
data = re.sub('<\?xml.*\?>', '', data, count=1)
# Remove the resource tags
data = re.sub('<resource .*xsd">', '', data)
self.data = '<?xml version="1.0"?><datacite>' + \
data[0:len(data) - 11] + '</datacite>'
self.root = ElementTree.XML(self.data)
self.xml = XmlDictConfig(self.root)
def get_creators(self, attribute='creatorName'):
"""Get DataCite creators."""
if 'creators' in self.xml:
if isinstance(self.xml['creators']['creator'], list):
return [c[attribute] for c in self.xml['creators']['creator']]
else:
return self.xml['creators']['creator'][attribute]
return None
def get_titles(self):
"""Get DataCite titles."""
if 'titles' in self.xml:
return self.xml['titles']['title']
return None
def get_publisher(self):
"""Get DataCite publisher."""
if 'publisher' in self.xml:
return self.xml['publisher']
return None
def get_dates(self):
"""Get DataCite dates."""
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None
def get_publication_year(self): | if 'publicationYear' in self.xml:
return self.xml['publicationYear']
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
"""Get DataCite related identifiers."""
pass
def get_description(self, description_type='Abstract'):
"""Get DataCite description."""
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if description_type in description:
return description[description_type]
elif isinstance(self.xml['descriptions']['description'], dict):
description = self.xml['descriptions']['description']
if description_type in description:
return description[description_type]
elif len(description) == 1:
# return the only description
return description.values()[0]
return None
def get_rights(self):
"""Get DataCite rights."""
if 'titles' in self.xml:
return self.xml['rights']
return None | """Get DataCite publication year.""" | random_line_split |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Utilities for working with DataCite metadata."""
from __future__ import absolute_import
import re
import urllib2
from invenio_utils.xmlDict import ElementTree, XmlDictConfig
__all__ = (
'DataciteMetadata',
)
class DataciteMetadata(object):
"""Helper class for working with DataCite metadata."""
def __init__(self, doi):
"""Initialize object."""
self.url = "http://data.datacite.org/application/x-datacite+xml/"
self.error = False
try:
data = urllib2.urlopen(self.url + doi).read()
except urllib2.HTTPError:
self.error = True
if not self.error:
# Clean the xml for parsing
data = re.sub('<\?xml.*\?>', '', data, count=1)
# Remove the resource tags
data = re.sub('<resource .*xsd">', '', data)
self.data = '<?xml version="1.0"?><datacite>' + \
data[0:len(data) - 11] + '</datacite>'
self.root = ElementTree.XML(self.data)
self.xml = XmlDictConfig(self.root)
def get_creators(self, attribute='creatorName'):
"""Get DataCite creators."""
if 'creators' in self.xml:
if isinstance(self.xml['creators']['creator'], list):
return [c[attribute] for c in self.xml['creators']['creator']]
else:
return self.xml['creators']['creator'][attribute]
return None
def get_titles(self):
"""Get DataCite titles."""
if 'titles' in self.xml:
return self.xml['titles']['title']
return None
def get_publisher(self):
"""Get DataCite publisher."""
if 'publisher' in self.xml:
return self.xml['publisher']
return None
def get_dates(self):
"""Get DataCite dates."""
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None
def get_publication_year(self):
"""Get DataCite publication year."""
if 'publicationYear' in self.xml:
return self.xml['publicationYear']
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
|
def get_description(self, description_type='Abstract'):
"""Get DataCite description."""
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if description_type in description:
return description[description_type]
elif isinstance(self.xml['descriptions']['description'], dict):
description = self.xml['descriptions']['description']
if description_type in description:
return description[description_type]
elif len(description) == 1:
# return the only description
return description.values()[0]
return None
def get_rights(self):
"""Get DataCite rights."""
if 'titles' in self.xml:
return self.xml['rights']
return None
| """Get DataCite related identifiers."""
pass | identifier_body |
datacite.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2015 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Utilities for working with DataCite metadata."""
from __future__ import absolute_import
import re
import urllib2
from invenio_utils.xmlDict import ElementTree, XmlDictConfig
__all__ = (
'DataciteMetadata',
)
class DataciteMetadata(object):
"""Helper class for working with DataCite metadata."""
def __init__(self, doi):
"""Initialize object."""
self.url = "http://data.datacite.org/application/x-datacite+xml/"
self.error = False
try:
data = urllib2.urlopen(self.url + doi).read()
except urllib2.HTTPError:
self.error = True
if not self.error:
# Clean the xml for parsing
data = re.sub('<\?xml.*\?>', '', data, count=1)
# Remove the resource tags
data = re.sub('<resource .*xsd">', '', data)
self.data = '<?xml version="1.0"?><datacite>' + \
data[0:len(data) - 11] + '</datacite>'
self.root = ElementTree.XML(self.data)
self.xml = XmlDictConfig(self.root)
def get_creators(self, attribute='creatorName'):
"""Get DataCite creators."""
if 'creators' in self.xml:
if isinstance(self.xml['creators']['creator'], list):
return [c[attribute] for c in self.xml['creators']['creator']]
else:
return self.xml['creators']['creator'][attribute]
return None
def | (self):
"""Get DataCite titles."""
if 'titles' in self.xml:
return self.xml['titles']['title']
return None
def get_publisher(self):
"""Get DataCite publisher."""
if 'publisher' in self.xml:
return self.xml['publisher']
return None
def get_dates(self):
"""Get DataCite dates."""
if 'dates' in self.xml:
if isinstance(self.xml['dates']['date'], dict):
return self.xml['dates']['date'].values()[0]
return self.xml['dates']['date']
return None
def get_publication_year(self):
"""Get DataCite publication year."""
if 'publicationYear' in self.xml:
return self.xml['publicationYear']
return None
def get_language(self):
"""Get DataCite language."""
if 'language' in self.xml:
return self.xml['language']
return None
def get_related_identifiers(self):
"""Get DataCite related identifiers."""
pass
def get_description(self, description_type='Abstract'):
"""Get DataCite description."""
if 'descriptions' in self.xml:
if isinstance(self.xml['descriptions']['description'], list):
for description in self.xml['descriptions']['description']:
if description_type in description:
return description[description_type]
elif isinstance(self.xml['descriptions']['description'], dict):
description = self.xml['descriptions']['description']
if description_type in description:
return description[description_type]
elif len(description) == 1:
# return the only description
return description.values()[0]
return None
def get_rights(self):
"""Get DataCite rights."""
if 'titles' in self.xml:
return self.xml['rights']
return None
| get_titles | identifier_name |
Sigmoid.ts | /**
* @license
* Copyright 2021 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/ | export const sigmoid = unaryKernelFunc({opType: UnaryOpType.SIGMOID});
export const sigmoidConfig: KernelConfig = {
kernelName: Sigmoid,
backendName: 'webgpu',
kernelFunc: sigmoid,
}; |
import {KernelConfig, Sigmoid} from '@tensorflow/tfjs-core';
import {unaryKernelFunc} from '../kernel_utils/kernel_funcs_utils';
import {UnaryOpType} from '../unary_op_util';
| random_line_split |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
-> Self
{
Frame {
global_index: global_index,
e: e,
cp: cp,
b: b,
bp: bp,
tr: tr,
h: h,
args: vec![Addr::HeapCell(0); n]
}
}
pub fn num_args(&self) -> usize {
self.args.len()
}
}
pub struct OrStack(Vec<Frame>);
impl OrStack {
pub fn new() -> Self {
OrStack(Vec::new())
}
pub fn push(&mut self,
global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
{
self.0.push(Frame::new(global_index, e, cp, b, bp, tr, h, n));
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn clear(&mut self) {
self.0.clear()
}
pub fn top(&self) -> Option<&Frame> {
self.0.last()
}
pub fn pop(&mut self) {
self.0.pop();
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl Index<usize> for OrStack {
type Output = Frame;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
}
}
impl IndexMut<usize> for OrStack {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn | (&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
}
| index | identifier_name |
or_stack.rs | use l3::ast::*;
use std::ops::{Index, IndexMut};
use std::vec::Vec;
pub struct Frame {
pub global_index: usize,
pub e: usize,
pub cp: CodePtr,
pub b: usize,
pub bp: CodePtr,
pub tr: usize,
pub h: usize,
args: Vec<Addr>
}
impl Frame {
fn new(global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
-> Self
{
Frame {
global_index: global_index,
e: e,
cp: cp,
b: b,
bp: bp,
tr: tr,
h: h,
args: vec![Addr::HeapCell(0); n]
}
}
pub fn num_args(&self) -> usize {
self.args.len()
}
}
pub struct OrStack(Vec<Frame>);
impl OrStack {
pub fn new() -> Self {
OrStack(Vec::new())
}
pub fn push(&mut self,
global_index: usize,
e: usize,
cp: CodePtr,
b: usize,
bp: CodePtr,
tr: usize,
h: usize,
n: usize)
{
self.0.push(Frame::new(global_index, e, cp, b, bp, tr, h, n));
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn clear(&mut self) {
self.0.clear()
}
pub fn top(&self) -> Option<&Frame> {
self.0.last()
}
pub fn pop(&mut self) {
self.0.pop();
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl Index<usize> for OrStack {
type Output = Frame;
fn index(&self, index: usize) -> &Self::Output {
self.0.index(index)
} | fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.0.index_mut(index)
}
}
impl Index<usize> for Frame {
type Output = Addr;
fn index(&self, index: usize) -> &Self::Output {
self.args.index(index - 1)
}
}
impl IndexMut<usize> for Frame {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
self.args.index_mut(index - 1)
}
} | }
impl IndexMut<usize> for OrStack { | random_line_split |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
count: number;
}
class ViewModel {
public onlineCount: KnockoutObservable<number>;
public latestTweets: KnockoutObservableArray<Tweet>;
public lastTweet: KnockoutComputed<Tweet>;
public latestPictures: KnockoutComputed<Tweet[]>;
public activeOverlay: KnockoutObservable<string>;
public topHashtags: KnockoutObservableArray<IHashtag>;
public panToTweet: any = (tweet: Tweet) => {
this._map.panTo(tweet);
return true;
};
private _map: TweetMap;
private _feed: Feed;
private _api: API;
constructor() {
this._api = new API('http://tweet.alexurquhart.com/');
this.latestTweets = ko.observableArray([]);
this.topHashtags = ko.observableArray([]);
this.latestPictures = ko.computed(() => { return this.getLatestPictures(); });
this.lastTweet = ko.computed(() => { return this.latestTweets()[0]; });
// Set the online count and update every 5 seconds or so
this.updateOnlineCount();
this.activeOverlay = ko.observable('liveFeed');
// Only update the last tweet once every 1500ms (for mobile)
this.lastTweet.extend({ rateLimit: { timeout: 1500, method: 'notifyAtFixedRate' }});
// Subscribe to changes to the last tweet
// TODO - add glow effect to alert box when new
// tweet appears
// this.lastTweet.subscribe(function(newTweet: Tweet): void {
// console.log('New tweet');
// });
// Start the map and the feed
this._map = new TweetMap;
this._feed = new Feed('ws://tweet.alexurquhart.com/ws/', (tweet: Tweet) => { this.addTweet(tweet); });
new Last24HoursChart('#chart', this._api);
this._api.getTweetData('hashtags/past24hours', (data: IHashtag[]) => {
this.topHashtags(data);
$('[data-toggle="tooltip"]').tooltip();
});
}
addTweet(tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (el.pictures) {
return true;
} else {
return false;
}
});
}
showTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).hide().slideDown(500);
}
}
hideTweet(tweet: any): void {
if (tweet.nodeType === 1) |
}
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
}
| {
$(tweet).slideUp(500);
} | conditional_block |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
count: number;
}
class ViewModel {
public onlineCount: KnockoutObservable<number>;
public latestTweets: KnockoutObservableArray<Tweet>;
public lastTweet: KnockoutComputed<Tweet>;
public latestPictures: KnockoutComputed<Tweet[]>;
public activeOverlay: KnockoutObservable<string>;
public topHashtags: KnockoutObservableArray<IHashtag>;
public panToTweet: any = (tweet: Tweet) => {
this._map.panTo(tweet);
return true;
};
private _map: TweetMap;
private _feed: Feed;
private _api: API;
constructor() {
this._api = new API('http://tweet.alexurquhart.com/');
this.latestTweets = ko.observableArray([]);
this.topHashtags = ko.observableArray([]);
this.latestPictures = ko.computed(() => { return this.getLatestPictures(); });
this.lastTweet = ko.computed(() => { return this.latestTweets()[0]; });
// Set the online count and update every 5 seconds or so
this.updateOnlineCount();
this.activeOverlay = ko.observable('liveFeed');
// Only update the last tweet once every 1500ms (for mobile)
this.lastTweet.extend({ rateLimit: { timeout: 1500, method: 'notifyAtFixedRate' }});
// Subscribe to changes to the last tweet
// TODO - add glow effect to alert box when new
// tweet appears
// this.lastTweet.subscribe(function(newTweet: Tweet): void {
// console.log('New tweet');
// });
// Start the map and the feed
this._map = new TweetMap;
this._feed = new Feed('ws://tweet.alexurquhart.com/ws/', (tweet: Tweet) => { this.addTweet(tweet); });
new Last24HoursChart('#chart', this._api);
this._api.getTweetData('hashtags/past24hours', (data: IHashtag[]) => {
this.topHashtags(data);
$('[data-toggle="tooltip"]').tooltip();
});
}
| (tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (el.pictures) {
return true;
} else {
return false;
}
});
}
showTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).hide().slideDown(500);
}
}
hideTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).slideUp(500);
}
}
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
}
| addTweet | identifier_name |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
count: number;
}
class ViewModel {
public onlineCount: KnockoutObservable<number>;
public latestTweets: KnockoutObservableArray<Tweet>;
public lastTweet: KnockoutComputed<Tweet>;
public latestPictures: KnockoutComputed<Tweet[]>;
public activeOverlay: KnockoutObservable<string>;
public topHashtags: KnockoutObservableArray<IHashtag>;
public panToTweet: any = (tweet: Tweet) => {
this._map.panTo(tweet);
return true;
};
private _map: TweetMap;
private _feed: Feed;
private _api: API;
constructor() |
addTweet(tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (el.pictures) {
return true;
} else {
return false;
}
});
}
showTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).hide().slideDown(500);
}
}
hideTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).slideUp(500);
}
}
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
}
| {
this._api = new API('http://tweet.alexurquhart.com/');
this.latestTweets = ko.observableArray([]);
this.topHashtags = ko.observableArray([]);
this.latestPictures = ko.computed(() => { return this.getLatestPictures(); });
this.lastTweet = ko.computed(() => { return this.latestTweets()[0]; });
// Set the online count and update every 5 seconds or so
this.updateOnlineCount();
this.activeOverlay = ko.observable('liveFeed');
// Only update the last tweet once every 1500ms (for mobile)
this.lastTweet.extend({ rateLimit: { timeout: 1500, method: 'notifyAtFixedRate' }});
// Subscribe to changes to the last tweet
// TODO - add glow effect to alert box when new
// tweet appears
// this.lastTweet.subscribe(function(newTweet: Tweet): void {
// console.log('New tweet');
// });
// Start the map and the feed
this._map = new TweetMap;
this._feed = new Feed('ws://tweet.alexurquhart.com/ws/', (tweet: Tweet) => { this.addTweet(tweet); });
new Last24HoursChart('#chart', this._api);
this._api.getTweetData('hashtags/past24hours', (data: IHashtag[]) => {
this.topHashtags(data);
$('[data-toggle="tooltip"]').tooltip();
});
} | identifier_body |
ViewModel.ts | /// <reference path="lib/knockout.d.ts"/>
/// <reference path="lib/jquery.d.ts"/>
/// <reference path="Tweet.ts"/>
/// <reference path="Map.ts"/>
/// <reference path="Feed.ts"/>
/// <reference path="API.ts"/>
/// <reference path="Overlay.ts"/>
/// <reference path="Chart.ts"/>
interface IHashtag {
hashtag: string;
count: number;
}
class ViewModel {
public onlineCount: KnockoutObservable<number>;
public latestTweets: KnockoutObservableArray<Tweet>;
public lastTweet: KnockoutComputed<Tweet>;
public latestPictures: KnockoutComputed<Tweet[]>;
public activeOverlay: KnockoutObservable<string>;
public topHashtags: KnockoutObservableArray<IHashtag>;
public panToTweet: any = (tweet: Tweet) => {
this._map.panTo(tweet);
return true;
};
private _map: TweetMap;
private _feed: Feed;
private _api: API;
constructor() {
this._api = new API('http://tweet.alexurquhart.com/');
this.latestTweets = ko.observableArray([]);
this.topHashtags = ko.observableArray([]);
this.latestPictures = ko.computed(() => { return this.getLatestPictures(); });
this.lastTweet = ko.computed(() => { return this.latestTweets()[0]; });
// Set the online count and update every 5 seconds or so
this.updateOnlineCount();
this.activeOverlay = ko.observable('liveFeed');
// Only update the last tweet once every 1500ms (for mobile)
this.lastTweet.extend({ rateLimit: { timeout: 1500, method: 'notifyAtFixedRate' }});
// Subscribe to changes to the last tweet
// TODO - add glow effect to alert box when new
// tweet appears
// this.lastTweet.subscribe(function(newTweet: Tweet): void {
// console.log('New tweet');
// });
// Start the map and the feed
this._map = new TweetMap;
this._feed = new Feed('ws://tweet.alexurquhart.com/ws/', (tweet: Tweet) => { this.addTweet(tweet); });
new Last24HoursChart('#chart', this._api);
this._api.getTweetData('hashtags/past24hours', (data: IHashtag[]) => {
this.topHashtags(data);
$('[data-toggle="tooltip"]').tooltip();
});
}
addTweet(tweet: Tweet): void {
this._map.addTweet(tweet);
this.latestTweets.unshift(tweet);
window.setTimeout(() => { this._map.removeTweet(this.latestTweets.pop()); }, 300000);
}
getLatestPictures(): Tweet[] {
return $.grep<Tweet>(this.latestTweets(), function(el: Tweet, index: number): boolean {
if (el.pictures) {
return true;
} else {
return false;
}
});
}
showTweet(tweet: any): void {
if (tweet.nodeType === 1) {
$(tweet).hide().slideDown(500);
}
}
hideTweet(tweet: any): void { |
changeOverlay(newOverlay: string): void {
this.activeOverlay(newOverlay);
}
updateOnlineCount(): void {
this.onlineCount = ko.observable(1);
setInterval(() => {
this._api.getOnlineCount((count: number) => { this.onlineCount(count); });
}, 5000);
}
} | if (tweet.nodeType === 1) {
$(tweet).slideUp(500);
}
} | random_line_split |
telequebec.py | from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/media/20984/le-couronnement-de-new-york/couronnement-de-new-york',
'md5': 'fe95a0957e5707b1b01f5013e725c90f',
'info_dict': {
'id': '20984',
'ext': 'mp4',
'title': 'Le couronnement de New York',
'description': 'md5:f5b3d27a689ec6c1486132b2d687d432',
'upload_date': '20160220',
'timestamp': 1455965438,
}
}
def _real_extract(self, url):
media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
return {
'_type': 'url_transparent',
'id': media_id,
'url': smuggle_url('limelight:media:' + media_data['streamInfo']['sourceId'], {'geo_countries': ['CA']}),
'title': media_data['title'],
'description': media_data.get('descriptions', [{'text': None}])[0].get('text'),
'duration': int_or_none(media_data.get('durationInMilliseconds'), 1000),
'ie_key': 'LimelightMedia',
} | # coding: utf-8
from __future__ import unicode_literals
| random_line_split | |
telequebec.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/media/20984/le-couronnement-de-new-york/couronnement-de-new-york',
'md5': 'fe95a0957e5707b1b01f5013e725c90f',
'info_dict': {
'id': '20984',
'ext': 'mp4',
'title': 'Le couronnement de New York',
'description': 'md5:f5b3d27a689ec6c1486132b2d687d432',
'upload_date': '20160220',
'timestamp': 1455965438,
}
}
def _real_extract(self, url):
| media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
return {
'_type': 'url_transparent',
'id': media_id,
'url': smuggle_url('limelight:media:' + media_data['streamInfo']['sourceId'], {'geo_countries': ['CA']}),
'title': media_data['title'],
'description': media_data.get('descriptions', [{'text': None}])[0].get('text'),
'duration': int_or_none(media_data.get('durationInMilliseconds'), 1000),
'ie_key': 'LimelightMedia',
} | identifier_body | |
telequebec.py | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
smuggle_url,
)
class TeleQuebecIE(InfoExtractor):
_VALID_URL = r'https?://zonevideo\.telequebec\.tv/media/(?P<id>\d+)'
_TEST = {
'url': 'http://zonevideo.telequebec.tv/media/20984/le-couronnement-de-new-york/couronnement-de-new-york',
'md5': 'fe95a0957e5707b1b01f5013e725c90f',
'info_dict': {
'id': '20984',
'ext': 'mp4',
'title': 'Le couronnement de New York',
'description': 'md5:f5b3d27a689ec6c1486132b2d687d432',
'upload_date': '20160220',
'timestamp': 1455965438,
}
}
def | (self, url):
media_id = self._match_id(url)
media_data = self._download_json(
'https://mnmedias.api.telequebec.tv/api/v2/media/' + media_id,
media_id)['media']
return {
'_type': 'url_transparent',
'id': media_id,
'url': smuggle_url('limelight:media:' + media_data['streamInfo']['sourceId'], {'geo_countries': ['CA']}),
'title': media_data['title'],
'description': media_data.get('descriptions', [{'text': None}])[0].get('text'),
'duration': int_or_none(media_data.get('durationInMilliseconds'), 1000),
'ie_key': 'LimelightMedia',
}
| _real_extract | identifier_name |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import json
class Target:
def __init__(self,id,name=None):
self.id = id
self.name = name
def reload(self):
"""Load target data from JSON interface."""
if self.id is None:
name = None
return
try:
data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None
def get(name):
|
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id']
| """Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d'] | identifier_body |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import json
class Target:
def __init__(self,id,name=None):
self.id = id
self.name = name
def | (self):
"""Load target data from JSON interface."""
if self.id is None:
name = None
return
try:
data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None
def get(name):
"""Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d']
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id']
| reload | identifier_name |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import json
class Target:
def __init__(self,id,name=None):
self.id = id
self.name = name
def reload(self):
"""Load target data from JSON interface."""
if self.id is None:
name = None
return
try: |
def get(name):
"""Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d']
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id'] | data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None | random_line_split |
target.py | # Library for RTS2 JSON calls.
# (C) 2012 Petr Kubanek, Institute of Physics
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
import json
class Target:
def __init__(self,id,name=None):
self.id = id
self.name = name
def reload(self):
"""Load target data from JSON interface."""
if self.id is None:
|
try:
data = json.getProxy().loadJson('/api/tbyid',{'id':self.id})['d'][0]
self.name = data[1]
except Exception,ex:
self.name = None
def get(name):
"""Return array with targets matching given name or target ID"""
try:
return json.getProxy().loadJson('/api/tbyid',{'id':int(name)})['d']
except ValueError:
return json.getProxy().loadJson('/api/tbyname',{'n':name})['d']
def create(name,ra,dec):
return json.getProxy().loadJson('/api/create_target', {'tn':name, 'ra':ra, 'dec':dec})['id']
| name = None
return | conditional_block |
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/. */
#![crate_name = "skia"]
#![crate_type = "rlib"]
#![feature(libc)]
extern crate libc;
| SkiaGrContextRef,
SkiaGrGLSharedSurfaceRef,
SkiaGrGLNativeContextRef,
SkiaSkNativeSharedGLContextCreate,
SkiaSkNativeSharedGLContextRetain,
SkiaSkNativeSharedGLContextRelease,
SkiaSkNativeSharedGLContextGetFBOID,
SkiaSkNativeSharedGLContextStealSurface,
SkiaSkNativeSharedGLContextGetGrContext,
SkiaSkNativeSharedGLContextMakeCurrent,
SkiaSkNativeSharedGLContextFlush,
};
pub mod skia; | pub use skia::{
SkiaSkNativeSharedGLContextRef, | random_line_split |
base_handler.py | #!/usr/bin/env python3
# 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/.
#
# Copyright 2017-2019 - Edoardo Morassutto <edoardo.morassutto@gmail.com>
# Copyright 2017 - Luca Versari <veluca93@gmail.com>
# Copyright 2018 - William Di Luigi <williamdiluigi@gmail.com>
import json
from datetime import datetime
from werkzeug.exceptions import HTTPException, BadRequest
from werkzeug.wrappers import Response
from ..handler_params import HandlerParams
from ..config import Config
from ..database import Database
from ..logger import Logger
class BaseHandler:
@staticmethod
def raise_exc(cls, code, message):
"""
Raise an HTTPException with a code and a message sent in a json like
{
"code": code
"message": message
}
:param cls: HTTPException of the error, for example NotFound, BadRequest, NotAuthorized
:param code: A brief message for the exception, like MISSING_PARAMETER
:param message: A longer description of the error
:return: Nothing, raise the provided exception with the correct response
"""
response = Response()
response.mimetype = "application/json"
response.status_code = cls.code
response.data = json.dumps({
"code": code,
"message": message
})
Logger.warning(cls.__name__.upper(), code + ": " + message)
raise cls(response=response)
def handle(self, endpoint, route_args, request):
"""
Handle a request in the derived handler. The request is routed to the correct method using *endpoint*
:param endpoint: A string with the name of the class method to call with (route_args, request) as parameters,
this method should return a Response or call self.raise_exc. *NOTE*: the method MUST be implemented in the
derived class
:param route_args: The route parameters, the parameters extracted from the matching route in the URL
:param request: The Request object, request.args contains the query parameters of the request
:return: Return a Response if the request is successful, an HTTPException if an error occurred
"""
try:
data = BaseHandler._call(self.__getattribute__(endpoint), route_args, request)
response = Response()
if data is not None:
response.code = 200
response.mimetype = "application/json"
response.data = json.dumps(data)
else:
response.code = 204
return response
except HTTPException as e:
return e
def parse_body(self, request):
"""
Parse the body part of the request in JSON
:param request: The request to be parsed
:return: A dict with the content of the body
"""
return request.form
@staticmethod
def get_end_time(user_extra_time):
"""
Compute the end time for a user
:param user_extra_time: Extra time specific for the user in seconds
:return: The timestamp at which the contest will be finished for this user
"""
start = Database.get_meta("start_time", type=int)
if start is None:
return None
contest_duration = Database.get_meta("contest_duration", type=int, default=0)
contest_extra_time = Database.get_meta("extra_time", type=int, default=0)
if user_extra_time is None:
user_extra_time = 0
return start + contest_duration + contest_extra_time + user_extra_time
@staticmethod
def get_window_end_time(user_extra_time, start_delay):
"""
Compute the end time for a window started after `start_delay` and with `extra_time` delay for the user.
Note that this time may exceed the contest end time, additional checks are required.
:param user_extra_time: Extra time specific for the user in seconds
:param start_delay: The time (in seconds) after the start of the contest of when the window started
:return: The timestamp at which the window ends. If the contest has no window None is returned.
"""
if start_delay is None:
return None
start = Database.get_meta("start_time", type=int)
if start is None:
return None
window_duration = Database.get_meta("window_duration", None, type=int)
if window_duration is None:
return None
if user_extra_time is None:
user_extra_time = 0
return start + user_extra_time + start_delay + window_duration
@staticmethod
def format_dates(dct, fields=["date"]):
"""
Given a dict, format all the *fields* fields from int to iso format. The original dict is modified
:param dct: dict to format
:param fields: list of the names of the fields to format
:return: The modified dict
"""
for k, v in dct.items():
if isinstance(v, dict):
dct[k] = BaseHandler.format_dates(v, fields)
elif isinstance(v, list):
for item in v:
BaseHandler.format_dates(item, fields)
elif k in fields and v is not None:
dct[k] = datetime.fromtimestamp(v).isoformat()
return dct
@staticmethod
def _call(method, route_args, request):
"""
This function is MAGIC!
It takes a method, reads it's parameters and automagically fetch from the request the values. Type-annotation
is also supported for a simple type validation.
The values are fetched, in order, from:
- route_args
- request.form
- general_attrs
- default values
If a parameter is required but not sent a BadRequest (MISSING_PARAMETERS) error is thrown, if a parameter cannot
be converted to the annotated type a BadRequest (FORMAT_ERROR) is thrown.
:param method: Method to be called
:param route_args: Arguments of the route
:param request: Request object
:return: The return value of method
"""
kwargs = {}
params = HandlerParams.get_handler_params(method)
general_attrs = {
'_request': request,
'_route_args': route_args,
'_file': {
"content": BaseHandler._get_file_content(request),
"name": BaseHandler._get_file_name(request)
},
'_ip': BaseHandler.get_ip(request)
}
missing_parameters = []
for name, data in params.items():
if name in route_args and name[0] != "_":
kwargs[name] = route_args[name]
elif name in request.form and name[0] != "_":
kwargs[name] = request.form[name]
elif name in general_attrs:
kwargs[name] = general_attrs[name]
elif name == "file" and general_attrs["_file"]["name"] is not None:
kwargs[name] = general_attrs["_file"]
elif data["required"]:
missing_parameters.append(name)
if len(missing_parameters) > 0:
BaseHandler.raise_exc(BadRequest, "MISSING_PARAMETERS",
"The missing parameters are: " + ", ".join(missing_parameters))
for key, value in kwargs.items():
type = params[key]["type"]
if type is None: continue
try:
kwargs[key] = type(value)
except ValueError:
BaseHandler.raise_exc(BadRequest, "FORMAT_ERROR",
"The parameter %s cannot be converted to %s" % (key, type.__name__))
Logger.debug(
"HTTP",
"Received request from %s for endpoint %s%s" %
(
general_attrs['_ip'],
method.__name__,
", with parameters " + ", ".join(
"=".join((kv[0], str(kv[1]))) for kv in kwargs.items()
if not kv[0].startswith("_") and not kv[0] == "file"
) if len(kwargs) > 0 else ""
)
)
return method(**kwargs)
@staticmethod
def _get_file_name(request):
"""
Extract the name of the file from the multipart body
:param request: The Request object
:return: The filename in the request
"""
if "file" not in request.files:
return None
return request.files["file"].filename
@staticmethod
def _get_file_content(request):
"""
Extract the content of the file from the multipart of the body
:param request: The Request object
:return: A *bytes* with the content of the file
"""
if "file" not in request.files:
|
return request.files["file"].stream.read()
@staticmethod
def get_ip(request):
"""
Return the real IP of the client
:param request: The Request object
:return: A string with the IP of the client
"""
num_proxies = Config.num_proxies
if num_proxies == 0 or len(request.access_route) < num_proxies:
return request.remote_addr
return request.access_route[-num_proxies]
| return None | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.