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
append.ts
'use strict'; var append: { (parentNode: HTMLElement, node: any, position?: string): HTMLElement; create: (node: string) => HTMLElement; remove: (node: HTMLElement) => void; toIndex: (parentNode: HTMLElement, node: HTMLElement, index: number) => HTMLElement; }; append = (() => { var append: any = function(parentNode: HTMLElement, node: any, position: string) { if (typeof(node) === 'string')
parentNode.insertAdjacentElement(position || 'beforeEnd', node); return node; }; if (!window.document.body || !window.document.body.insertAdjacentElement) { append = function(parentNode: HTMLElement, node: any, position: string) { if (typeof(node) === 'string') { node = parentNode.ownerDocument.createElement(node); } if (!position) { parentNode.appendChild(node); } else { if (position === 'beforeBegin') { parentNode.parentNode.insertBefore(node, parentNode); } } return node; }; } append.create = function (node: string) { return window.document.createElement(node); }; append.remove = function (node: HTMLElement) { if (node.parentNode) { node.parentNode.removeChild(node); } }; append.toIndex = function (parentNode: HTMLElement, node: HTMLElement, index: number) { var cur = 0, currentChild: Node; if (typeof(index) === 'undefined') { return append(parentNode, node); } else { currentChild = parentNode.firstChild; while (currentChild && (cur < index)) { currentChild = currentChild.nextSibling; cur += 1; } if (!currentChild) { return append(parentNode, node); } else { parentNode.insertBefore(node, currentChild); } } }; return append; })(); export var toIndex = append.toIndex; export var remove = append.remove; export var create = append.create; export default append;
{ node = parentNode.ownerDocument.createElement(node); }
conditional_block
append.ts
'use strict'; var append: { (parentNode: HTMLElement, node: any, position?: string): HTMLElement; create: (node: string) => HTMLElement; remove: (node: HTMLElement) => void; toIndex: (parentNode: HTMLElement, node: HTMLElement, index: number) => HTMLElement; }; append = (() => { var append: any = function(parentNode: HTMLElement, node: any, position: string) { if (typeof(node) === 'string') { node = parentNode.ownerDocument.createElement(node); } parentNode.insertAdjacentElement(position || 'beforeEnd', node); return node; }; if (!window.document.body || !window.document.body.insertAdjacentElement) { append = function(parentNode: HTMLElement, node: any, position: string) { if (typeof(node) === 'string') { node = parentNode.ownerDocument.createElement(node); } if (!position) { parentNode.appendChild(node);
} return node; }; } append.create = function (node: string) { return window.document.createElement(node); }; append.remove = function (node: HTMLElement) { if (node.parentNode) { node.parentNode.removeChild(node); } }; append.toIndex = function (parentNode: HTMLElement, node: HTMLElement, index: number) { var cur = 0, currentChild: Node; if (typeof(index) === 'undefined') { return append(parentNode, node); } else { currentChild = parentNode.firstChild; while (currentChild && (cur < index)) { currentChild = currentChild.nextSibling; cur += 1; } if (!currentChild) { return append(parentNode, node); } else { parentNode.insertBefore(node, currentChild); } } }; return append; })(); export var toIndex = append.toIndex; export var remove = append.remove; export var create = append.create; export default append;
} else { if (position === 'beforeBegin') { parentNode.parentNode.insertBefore(node, parentNode); }
random_line_split
rollup-aot.config.js
/* eslint no-console: 0 */ 'use strict'; const fs = require('fs'); const mkdirp = require('mkdirp'); const rollup = require('rollup'); const nodeResolve = require('rollup-plugin-node-resolve'); const commonjs = require('rollup-plugin-commonjs'); const uglify = require('rollup-plugin-uglify'); const src = 'src'; const dest = 'dist/rollup-aot'; Promise.all([ // build main/app rollup.rollup({ entry: `${src}/main-aot.js`, context: 'this', plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify({ output: { comments: /@preserve|@license|@cc_on/i, }, mangle: { keep_fnames: true, }, compress: { warnings: false, }, }), ],
app.write({ format: 'iife', dest: `${dest}/app.js`, sourceMap: false, }) ), // build polyfills rollup.rollup({ entry: `${src}/polyfills-aot.js`, context: 'this', plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify(), ], }).then(app => app.write({ format: 'iife', dest: `${dest}/polyfills.js`, sourceMap: false, }) ), // create index.html new Promise((resolve, reject) => { fs.readFile(`${src}/index.html`, 'utf-8', (readErr, indexHtml) => { if (readErr) return reject(readErr); const newIndexHtml = indexHtml .replace('</head>', '<script src="polyfills.js"></script></head>') .replace('</body>', '<script src="app.js"></script></body>'); mkdirp(dest, mkdirpErr => { if (mkdirpErr) return reject(mkdirpErr); return true; }); return fs.writeFile( `${dest}/index.html`, newIndexHtml, 'utf-8', writeErr => { if (writeErr) return reject(writeErr); console.log('Created index.html'); return resolve(); } ); }); }), ]).then(() => { console.log('Rollup complete'); }).catch(err => { console.error('Rollup failed with ', err); });
}).then(app =>
random_line_split
history.component.ts
import { AlertController } from 'ionic-angular'; import { PlayService } from './../../service/playService'; import { Component } from '@angular/core'; @Component({ selector: 'history', templateUrl: './history.component.html', styleUrls: ['./history.component.scss'] }) export class HistoryComponent { constructor( private playSvr: PlayService, private alertCtrl: AlertController ) { } playTypes = []; histories = []; loading: boolean = true; ionViewWillEnter() { this.playTypes = this.playSvr.getPlayTypesList(); if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } else { this.playSvr.getPlayTypes().subscribe( data => { let result = data.json(); if (!result.error) { this.playTypes = result.data; if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } } }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取玩法分类失败") } ); } } selectTab(type) { this.loading = true; for (let py of this.playTypes) { if (py.id != type.id) {
type.selected = true; this.playSvr.getPlays(type.id).subscribe( data => { let result = data.json(); if (!result.error) { this.histories = result.data; } this.loading = false; }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取历史开奖记录失败"); } ); } }
delete py.selected; } }
conditional_block
history.component.ts
import { AlertController } from 'ionic-angular'; import { PlayService } from './../../service/playService'; import { Component } from '@angular/core'; @Component({ selector: 'history', templateUrl: './history.component.html', styleUrls: ['./history.component.scss'] }) export class HistoryComponent { constructor( private playSvr: PlayService, private alertCtrl: AlertController ) { } playTypes = []; histories = []; loading: boolean = true; ionViewWillEnter() { this.playTypes = this.playSvr.getPlayTypesList(); if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } else { this.playSvr.getPlayTypes().subscribe( data => { let result = data.json(); if (!result.error) { this.playTypes = result.data; if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } } }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取玩法分类失败") } ); } } selectTab(type) { this.l
oading = true; for (let py of this.playTypes) { if (py.id != type.id) { delete py.selected; } } type.selected = true; this.playSvr.getPlays(type.id).subscribe( data => { let result = data.json(); if (!result.error) { this.histories = result.data; } this.loading = false; }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取历史开奖记录失败"); } ); } }
identifier_body
history.component.ts
import { AlertController } from 'ionic-angular'; import { PlayService } from './../../service/playService'; import { Component } from '@angular/core'; @Component({ selector: 'history', templateUrl: './history.component.html', styleUrls: ['./history.component.scss'] }) export class
{ constructor( private playSvr: PlayService, private alertCtrl: AlertController ) { } playTypes = []; histories = []; loading: boolean = true; ionViewWillEnter() { this.playTypes = this.playSvr.getPlayTypesList(); if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } else { this.playSvr.getPlayTypes().subscribe( data => { let result = data.json(); if (!result.error) { this.playTypes = result.data; if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } } }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取玩法分类失败") } ); } } selectTab(type) { this.loading = true; for (let py of this.playTypes) { if (py.id != type.id) { delete py.selected; } } type.selected = true; this.playSvr.getPlays(type.id).subscribe( data => { let result = data.json(); if (!result.error) { this.histories = result.data; } this.loading = false; }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取历史开奖记录失败"); } ); } }
HistoryComponent
identifier_name
history.component.ts
import { AlertController } from 'ionic-angular'; import { PlayService } from './../../service/playService'; import { Component } from '@angular/core'; @Component({ selector: 'history', templateUrl: './history.component.html', styleUrls: ['./history.component.scss'] }) export class HistoryComponent { constructor( private playSvr: PlayService, private alertCtrl: AlertController ) { } playTypes = []; histories = []; loading: boolean = true; ionViewWillEnter() { this.playTypes = this.playSvr.getPlayTypesList(); if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } else { this.playSvr.getPlayTypes().subscribe( data => { let result = data.json(); if (!result.error) { this.playTypes = result.data; if (this.playTypes && this.playTypes.length) { this.playTypes[0].selected = true; this.selectTab(this.playTypes[0]); } } },
this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取玩法分类失败") } ); } } selectTab(type) { this.loading = true; for (let py of this.playTypes) { if (py.id != type.id) { delete py.selected; } } type.selected = true; this.playSvr.getPlays(type.id).subscribe( data => { let result = data.json(); if (!result.error) { this.histories = result.data; } this.loading = false; }, error => { this.playSvr.errorHandler(error, (msg) => { let alert = this.alertCtrl.create({ message: msg }); alert.present(); }, "获取历史开奖记录失败"); } ); } }
error => {
random_line_split
borland.py
# -*- coding: utf-8 -*- """ pygments.styles.borland ~~~~~~~~~~~~~~~~~~~~~~~ Style similar to the style used in the Borland IDEs. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class
(Style): """ Style similar to the style used in the borland IDEs. """ default_style = '' styles = { Whitespace: '#bbbbbb', Comment: 'italic #008800', Comment.Preproc: 'noitalic #008080', Comment.Special: 'noitalic bold', String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000', Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' }
BorlandStyle
identifier_name
borland.py
# -*- coding: utf-8 -*- """ pygments.styles.borland ~~~~~~~~~~~~~~~~~~~~~~~ Style similar to the style used in the Borland IDEs. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class BorlandStyle(Style):
""" Style similar to the style used in the borland IDEs. """ default_style = '' styles = { Whitespace: '#bbbbbb', Comment: 'italic #008800', Comment.Preproc: 'noitalic #008080', Comment.Special: 'noitalic bold', String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000', Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' }
identifier_body
borland.py
# -*- coding: utf-8 -*- """ pygments.styles.borland ~~~~~~~~~~~~~~~~~~~~~~~ Style similar to the style used in the Borland IDEs. :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, String, Error, \ Number, Operator, Generic, Whitespace class BorlandStyle(Style): """ Style similar to the style used in the borland IDEs. """ default_style = '' styles = { Whitespace: '#bbbbbb', Comment: 'italic #008800',
Comment.Special: 'noitalic bold', String: '#0000FF', String.Char: '#800080', Number: '#0000FF', Keyword: 'bold #000080', Operator.Word: 'bold', Name.Tag: 'bold #000080', Name.Attribute: '#FF0000', Generic.Heading: '#999999', Generic.Subheading: '#aaaaaa', Generic.Deleted: 'bg:#ffdddd #000000', Generic.Inserted: 'bg:#ddffdd #000000', Generic.Error: '#aa0000', Generic.Emph: 'italic', Generic.Strong: 'bold', Generic.Prompt: '#555555', Generic.Output: '#888888', Generic.Traceback: '#aa0000', Error: 'bg:#e3d2d2 #a61717' }
Comment.Preproc: 'noitalic #008080',
random_line_split
startup-assistant.js
function
(changelog) { this.justChangelog = changelog; // on first start, this message is displayed, along with the current version message from below this.firstMessage = $L('Here are some tips for first-timers:<ul><li>Lumberjack has no tips yet</li></ul>'); this.secondMessage = $L('We hope you enjoy chopping down trees, skipping and jumping, and wearing high heels, and watching your logs.<br>Please consider making a <a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R3Q2EUA52WJ7A\">donation</a> if you wish to show your appreciation.'); // on new version start this.newMessages = [ { version: '0.5.0', log: [ 'Added Scene Timing', 'Added ability to email the visible log in the app menu (Thanks Tibfib)' ] }, { version: '0.4.5', log: [ 'Added BetterListSelector widget to main scene \'What to look for\' selector', 'Added ability to quickly change the current log level from the app menu in the Follow Log scene' ] }, { version: '0.4.4', log: [ 'Added swipe-delete to the Retrieve Log scene' ] }, { version: '0.4.3', log: [ 'Fixed webOS version check funkyness', 'Added ability to swipe-delete lines from the Follow Log scene just for Lisa, but everyone else can use it too' ] }, { version: '0.4.2', log: [ 'Fixed listApps bug', 'Fixed get/follow log on the Pre2', 'Fixed Ls2 Monitor for webOS 2.0' ] }, { version: '0.4.1', log: [ 'Better graphs for resource monitor', 'Added Clear Log File to main scene and get log scene for clearing the /var/log/messages file', 'Fixed bug where resource monitor would fail to start a second time' ] }, { version: '0.4.0', log: [ 'Added Ls2 Monitor for webOS 2.0 (and hide Dbus Capture in 2.0 as it is no longer used)', 'Added Resource Monitor', 'Added font size preference', 'Added a way to get back to this changelog from the help scene' ] }, { version: '0.3.1', log: [ 'Exclude logging messages from dbus capture' ] }, { version: '0.3.0', log: [ 'Added DBus Capture for debugging services' , 'Type-to-Search in get-log scene' , 'More log level preferences' ] }, { version: '0.1.1', log: [ 'Service Stability Updates' ] }, { version: '0.1.0', log: [ 'Initial Release!' ] } ]; // setup menu this.menuModel = { visible: true, items: [ { label: $L("Help"), command: 'do-help' } ] }; // setup command menu this.cmdMenuModel = { visible: false, items: [ {}, { label: $L("Ok, I've read this. Let's continue ..."), command: 'do-continue' }, {} ] }; }; StartupAssistant.prototype.setup = function() { // set theme because this can be the first scene pushed this.controller.document.body.className = prefs.get().theme + ' ' + prefs.get().fontSize; // get elements this.titleContainer = this.controller.get('title'); this.dataContainer = this.controller.get('data'); // set title if (this.justChangelog) { this.titleContainer.innerHTML = $L('Changelog'); } else { if (vers.isFirst) { this.titleContainer.innerHTML = $L('Welcome To Lumberjack'); } else if (vers.isNew) { this.titleContainer.innerHTML = $L('Lumberjack Changelog'); } } // build data var html = ''; if (this.justChangelog) { for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } else { if (vers.isFirst) { html += '<div class="text">' + this.firstMessage + '</div>'; } if (vers.isNew) { if (!this.justChangelog) { html += '<div class="text">' + this.secondMessage + '</div>'; } for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } } // set data this.dataContainer.innerHTML = html; // setup menu this.controller.setupWidget(Mojo.Menu.appMenu, { omitDefaultItems: true }, this.menuModel); if (!this.justChangelog) { // set command menu this.controller.setupWidget(Mojo.Menu.commandMenu, { menuClass: 'no-fade' }, this.cmdMenuModel); } // set this scene's default transition this.controller.setDefaultTransition(Mojo.Transition.zoomFade); }; StartupAssistant.prototype.activate = function(event) { // start continue button timer this.timer = this.controller.window.setTimeout(this.showContinue.bind(this), 5 * 1000); }; StartupAssistant.prototype.showContinue = function() { // show the command menu this.controller.setMenuVisible(Mojo.Menu.commandMenu, true); }; StartupAssistant.prototype.handleCommand = function(event) { if (event.type == Mojo.Event.command) { switch (event.command) { case 'do-continue': this.controller.stageController.swapScene({name: 'main', transition: Mojo.Transition.crossFade}); break; case 'do-prefs': this.controller.stageController.pushScene('preferences'); break; case 'do-help': this.controller.stageController.pushScene('help'); break; } } }; // Local Variables: // tab-width: 4 // End:
StartupAssistant
identifier_name
startup-assistant.js
function StartupAssistant(changelog) { this.justChangelog = changelog; // on first start, this message is displayed, along with the current version message from below this.firstMessage = $L('Here are some tips for first-timers:<ul><li>Lumberjack has no tips yet</li></ul>'); this.secondMessage = $L('We hope you enjoy chopping down trees, skipping and jumping, and wearing high heels, and watching your logs.<br>Please consider making a <a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R3Q2EUA52WJ7A\">donation</a> if you wish to show your appreciation.'); // on new version start this.newMessages = [ { version: '0.5.0', log: [ 'Added Scene Timing', 'Added ability to email the visible log in the app menu (Thanks Tibfib)' ] }, { version: '0.4.5', log: [ 'Added BetterListSelector widget to main scene \'What to look for\' selector', 'Added ability to quickly change the current log level from the app menu in the Follow Log scene' ] }, { version: '0.4.4', log: [ 'Added swipe-delete to the Retrieve Log scene' ] }, { version: '0.4.3', log: [ 'Fixed webOS version check funkyness', 'Added ability to swipe-delete lines from the Follow Log scene just for Lisa, but everyone else can use it too' ] }, { version: '0.4.2', log: [ 'Fixed listApps bug', 'Fixed get/follow log on the Pre2', 'Fixed Ls2 Monitor for webOS 2.0' ] }, { version: '0.4.1', log: [ 'Better graphs for resource monitor', 'Added Clear Log File to main scene and get log scene for clearing the /var/log/messages file', 'Fixed bug where resource monitor would fail to start a second time' ] }, { version: '0.4.0', log: [ 'Added Ls2 Monitor for webOS 2.0 (and hide Dbus Capture in 2.0 as it is no longer used)', 'Added Resource Monitor', 'Added font size preference',
, 'More log level preferences' ] }, { version: '0.1.1', log: [ 'Service Stability Updates' ] }, { version: '0.1.0', log: [ 'Initial Release!' ] } ]; // setup menu this.menuModel = { visible: true, items: [ { label: $L("Help"), command: 'do-help' } ] }; // setup command menu this.cmdMenuModel = { visible: false, items: [ {}, { label: $L("Ok, I've read this. Let's continue ..."), command: 'do-continue' }, {} ] }; }; StartupAssistant.prototype.setup = function() { // set theme because this can be the first scene pushed this.controller.document.body.className = prefs.get().theme + ' ' + prefs.get().fontSize; // get elements this.titleContainer = this.controller.get('title'); this.dataContainer = this.controller.get('data'); // set title if (this.justChangelog) { this.titleContainer.innerHTML = $L('Changelog'); } else { if (vers.isFirst) { this.titleContainer.innerHTML = $L('Welcome To Lumberjack'); } else if (vers.isNew) { this.titleContainer.innerHTML = $L('Lumberjack Changelog'); } } // build data var html = ''; if (this.justChangelog) { for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } else { if (vers.isFirst) { html += '<div class="text">' + this.firstMessage + '</div>'; } if (vers.isNew) { if (!this.justChangelog) { html += '<div class="text">' + this.secondMessage + '</div>'; } for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } } // set data this.dataContainer.innerHTML = html; // setup menu this.controller.setupWidget(Mojo.Menu.appMenu, { omitDefaultItems: true }, this.menuModel); if (!this.justChangelog) { // set command menu this.controller.setupWidget(Mojo.Menu.commandMenu, { menuClass: 'no-fade' }, this.cmdMenuModel); } // set this scene's default transition this.controller.setDefaultTransition(Mojo.Transition.zoomFade); }; StartupAssistant.prototype.activate = function(event) { // start continue button timer this.timer = this.controller.window.setTimeout(this.showContinue.bind(this), 5 * 1000); }; StartupAssistant.prototype.showContinue = function() { // show the command menu this.controller.setMenuVisible(Mojo.Menu.commandMenu, true); }; StartupAssistant.prototype.handleCommand = function(event) { if (event.type == Mojo.Event.command) { switch (event.command) { case 'do-continue': this.controller.stageController.swapScene({name: 'main', transition: Mojo.Transition.crossFade}); break; case 'do-prefs': this.controller.stageController.pushScene('preferences'); break; case 'do-help': this.controller.stageController.pushScene('help'); break; } } }; // Local Variables: // tab-width: 4 // End:
'Added a way to get back to this changelog from the help scene' ] }, { version: '0.3.1', log: [ 'Exclude logging messages from dbus capture' ] }, { version: '0.3.0', log: [ 'Added DBus Capture for debugging services' , 'Type-to-Search in get-log scene'
random_line_split
startup-assistant.js
function StartupAssistant(changelog) { this.justChangelog = changelog; // on first start, this message is displayed, along with the current version message from below this.firstMessage = $L('Here are some tips for first-timers:<ul><li>Lumberjack has no tips yet</li></ul>'); this.secondMessage = $L('We hope you enjoy chopping down trees, skipping and jumping, and wearing high heels, and watching your logs.<br>Please consider making a <a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R3Q2EUA52WJ7A\">donation</a> if you wish to show your appreciation.'); // on new version start this.newMessages = [ { version: '0.5.0', log: [ 'Added Scene Timing', 'Added ability to email the visible log in the app menu (Thanks Tibfib)' ] }, { version: '0.4.5', log: [ 'Added BetterListSelector widget to main scene \'What to look for\' selector', 'Added ability to quickly change the current log level from the app menu in the Follow Log scene' ] }, { version: '0.4.4', log: [ 'Added swipe-delete to the Retrieve Log scene' ] }, { version: '0.4.3', log: [ 'Fixed webOS version check funkyness', 'Added ability to swipe-delete lines from the Follow Log scene just for Lisa, but everyone else can use it too' ] }, { version: '0.4.2', log: [ 'Fixed listApps bug', 'Fixed get/follow log on the Pre2', 'Fixed Ls2 Monitor for webOS 2.0' ] }, { version: '0.4.1', log: [ 'Better graphs for resource monitor', 'Added Clear Log File to main scene and get log scene for clearing the /var/log/messages file', 'Fixed bug where resource monitor would fail to start a second time' ] }, { version: '0.4.0', log: [ 'Added Ls2 Monitor for webOS 2.0 (and hide Dbus Capture in 2.0 as it is no longer used)', 'Added Resource Monitor', 'Added font size preference', 'Added a way to get back to this changelog from the help scene' ] }, { version: '0.3.1', log: [ 'Exclude logging messages from dbus capture' ] }, { version: '0.3.0', log: [ 'Added DBus Capture for debugging services' , 'Type-to-Search in get-log scene' , 'More log level preferences' ] }, { version: '0.1.1', log: [ 'Service Stability Updates' ] }, { version: '0.1.0', log: [ 'Initial Release!' ] } ]; // setup menu this.menuModel = { visible: true, items: [ { label: $L("Help"), command: 'do-help' } ] }; // setup command menu this.cmdMenuModel = { visible: false, items: [ {}, { label: $L("Ok, I've read this. Let's continue ..."), command: 'do-continue' }, {} ] }; }; StartupAssistant.prototype.setup = function() { // set theme because this can be the first scene pushed this.controller.document.body.className = prefs.get().theme + ' ' + prefs.get().fontSize; // get elements this.titleContainer = this.controller.get('title'); this.dataContainer = this.controller.get('data'); // set title if (this.justChangelog) { this.titleContainer.innerHTML = $L('Changelog'); } else { if (vers.isFirst) { this.titleContainer.innerHTML = $L('Welcome To Lumberjack'); } else if (vers.isNew) { this.titleContainer.innerHTML = $L('Lumberjack Changelog'); } } // build data var html = ''; if (this.justChangelog) { for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } else { if (vers.isFirst) { html += '<div class="text">' + this.firstMessage + '</div>'; } if (vers.isNew) { if (!this.justChangelog) { html += '<div class="text">' + this.secondMessage + '</div>'; } for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } } // set data this.dataContainer.innerHTML = html; // setup menu this.controller.setupWidget(Mojo.Menu.appMenu, { omitDefaultItems: true }, this.menuModel); if (!this.justChangelog) { // set command menu this.controller.setupWidget(Mojo.Menu.commandMenu, { menuClass: 'no-fade' }, this.cmdMenuModel); } // set this scene's default transition this.controller.setDefaultTransition(Mojo.Transition.zoomFade); }; StartupAssistant.prototype.activate = function(event) { // start continue button timer this.timer = this.controller.window.setTimeout(this.showContinue.bind(this), 5 * 1000); }; StartupAssistant.prototype.showContinue = function() { // show the command menu this.controller.setMenuVisible(Mojo.Menu.commandMenu, true); }; StartupAssistant.prototype.handleCommand = function(event) { if (event.type == Mojo.Event.command)
}; // Local Variables: // tab-width: 4 // End:
{ switch (event.command) { case 'do-continue': this.controller.stageController.swapScene({name: 'main', transition: Mojo.Transition.crossFade}); break; case 'do-prefs': this.controller.stageController.pushScene('preferences'); break; case 'do-help': this.controller.stageController.pushScene('help'); break; } }
conditional_block
startup-assistant.js
function StartupAssistant(changelog)
; StartupAssistant.prototype.setup = function() { // set theme because this can be the first scene pushed this.controller.document.body.className = prefs.get().theme + ' ' + prefs.get().fontSize; // get elements this.titleContainer = this.controller.get('title'); this.dataContainer = this.controller.get('data'); // set title if (this.justChangelog) { this.titleContainer.innerHTML = $L('Changelog'); } else { if (vers.isFirst) { this.titleContainer.innerHTML = $L('Welcome To Lumberjack'); } else if (vers.isNew) { this.titleContainer.innerHTML = $L('Lumberjack Changelog'); } } // build data var html = ''; if (this.justChangelog) { for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } else { if (vers.isFirst) { html += '<div class="text">' + this.firstMessage + '</div>'; } if (vers.isNew) { if (!this.justChangelog) { html += '<div class="text">' + this.secondMessage + '</div>'; } for (var m = 0; m < this.newMessages.length; m++) { html += Mojo.View.render({object: {title: 'v' + this.newMessages[m].version}, template: 'startup/changeLog'}); html += '<ul>'; for (var l = 0; l < this.newMessages[m].log.length; l++) { html += '<li>' + this.newMessages[m].log[l] + '</li>'; } html += '</ul>'; } } } // set data this.dataContainer.innerHTML = html; // setup menu this.controller.setupWidget(Mojo.Menu.appMenu, { omitDefaultItems: true }, this.menuModel); if (!this.justChangelog) { // set command menu this.controller.setupWidget(Mojo.Menu.commandMenu, { menuClass: 'no-fade' }, this.cmdMenuModel); } // set this scene's default transition this.controller.setDefaultTransition(Mojo.Transition.zoomFade); }; StartupAssistant.prototype.activate = function(event) { // start continue button timer this.timer = this.controller.window.setTimeout(this.showContinue.bind(this), 5 * 1000); }; StartupAssistant.prototype.showContinue = function() { // show the command menu this.controller.setMenuVisible(Mojo.Menu.commandMenu, true); }; StartupAssistant.prototype.handleCommand = function(event) { if (event.type == Mojo.Event.command) { switch (event.command) { case 'do-continue': this.controller.stageController.swapScene({name: 'main', transition: Mojo.Transition.crossFade}); break; case 'do-prefs': this.controller.stageController.pushScene('preferences'); break; case 'do-help': this.controller.stageController.pushScene('help'); break; } } }; // Local Variables: // tab-width: 4 // End:
{ this.justChangelog = changelog; // on first start, this message is displayed, along with the current version message from below this.firstMessage = $L('Here are some tips for first-timers:<ul><li>Lumberjack has no tips yet</li></ul>'); this.secondMessage = $L('We hope you enjoy chopping down trees, skipping and jumping, and wearing high heels, and watching your logs.<br>Please consider making a <a href=\"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=R3Q2EUA52WJ7A\">donation</a> if you wish to show your appreciation.'); // on new version start this.newMessages = [ { version: '0.5.0', log: [ 'Added Scene Timing', 'Added ability to email the visible log in the app menu (Thanks Tibfib)' ] }, { version: '0.4.5', log: [ 'Added BetterListSelector widget to main scene \'What to look for\' selector', 'Added ability to quickly change the current log level from the app menu in the Follow Log scene' ] }, { version: '0.4.4', log: [ 'Added swipe-delete to the Retrieve Log scene' ] }, { version: '0.4.3', log: [ 'Fixed webOS version check funkyness', 'Added ability to swipe-delete lines from the Follow Log scene just for Lisa, but everyone else can use it too' ] }, { version: '0.4.2', log: [ 'Fixed listApps bug', 'Fixed get/follow log on the Pre2', 'Fixed Ls2 Monitor for webOS 2.0' ] }, { version: '0.4.1', log: [ 'Better graphs for resource monitor', 'Added Clear Log File to main scene and get log scene for clearing the /var/log/messages file', 'Fixed bug where resource monitor would fail to start a second time' ] }, { version: '0.4.0', log: [ 'Added Ls2 Monitor for webOS 2.0 (and hide Dbus Capture in 2.0 as it is no longer used)', 'Added Resource Monitor', 'Added font size preference', 'Added a way to get back to this changelog from the help scene' ] }, { version: '0.3.1', log: [ 'Exclude logging messages from dbus capture' ] }, { version: '0.3.0', log: [ 'Added DBus Capture for debugging services' , 'Type-to-Search in get-log scene' , 'More log level preferences' ] }, { version: '0.1.1', log: [ 'Service Stability Updates' ] }, { version: '0.1.0', log: [ 'Initial Release!' ] } ]; // setup menu this.menuModel = { visible: true, items: [ { label: $L("Help"), command: 'do-help' } ] }; // setup command menu this.cmdMenuModel = { visible: false, items: [ {}, { label: $L("Ok, I've read this. Let's continue ..."), command: 'do-continue' }, {} ] }; }
identifier_body
extra.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shuup.xtheme._theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("View %r not callable" % view) return view def get_view_by_name(theme, view_name):
def extra_view_dispatch(request, view): """ Dispatch to an Xtheme extra view. :param request: A request :type request: django.http.HttpRequest :param view: View name :type view: str :return: A response of some ilk :rtype: django.http.HttpResponse """ theme = get_current_theme(request) view_func = get_view_by_name(theme, view) if not view_func: msg = "%s/%s: Not found" % (getattr(theme, "identifier", None), view) return HttpResponseNotFound(msg) return view_func(request)
if not theme: return None cache_key = (theme.identifier, view_name) if cache_key not in _VIEW_CACHE: view = _get_view_by_name(theme, view_name) _VIEW_CACHE[cache_key] = view else: view = _VIEW_CACHE[cache_key] return view
identifier_body
extra.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shuup.xtheme._theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("View %r not callable" % view) return view def get_view_by_name(theme, view_name): if not theme:
cache_key = (theme.identifier, view_name) if cache_key not in _VIEW_CACHE: view = _get_view_by_name(theme, view_name) _VIEW_CACHE[cache_key] = view else: view = _VIEW_CACHE[cache_key] return view def extra_view_dispatch(request, view): """ Dispatch to an Xtheme extra view. :param request: A request :type request: django.http.HttpRequest :param view: View name :type view: str :return: A response of some ilk :rtype: django.http.HttpResponse """ theme = get_current_theme(request) view_func = get_view_by_name(theme, view) if not view_func: msg = "%s/%s: Not found" % (getattr(theme, "identifier", None), view) return HttpResponseNotFound(msg) return view_func(request)
return None
conditional_block
extra.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shuup.xtheme._theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("View %r not callable" % view) return view def get_view_by_name(theme, view_name): if not theme: return None cache_key = (theme.identifier, view_name) if cache_key not in _VIEW_CACHE: view = _get_view_by_name(theme, view_name) _VIEW_CACHE[cache_key] = view else: view = _VIEW_CACHE[cache_key] return view def
(request, view): """ Dispatch to an Xtheme extra view. :param request: A request :type request: django.http.HttpRequest :param view: View name :type view: str :return: A response of some ilk :rtype: django.http.HttpResponse """ theme = get_current_theme(request) view_func = get_view_by_name(theme, view) if not view_func: msg = "%s/%s: Not found" % (getattr(theme, "identifier", None), view) return HttpResponseNotFound(msg) return view_func(request)
extra_view_dispatch
identifier_name
extra.py
# -*- coding: utf-8 -*- # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.http.response import HttpResponseNotFound from shuup.xtheme._theme import get_current_theme _VIEW_CACHE = {} def clear_view_cache(**kwargs): _VIEW_CACHE.clear() setting_changed.connect(clear_view_cache, dispatch_uid="shuup.xtheme.views.extra.clear_view_cache") def _get_view_by_name(theme, view_name): view = theme.get_view(view_name) if hasattr(view, "as_view"): # Handle CBVs view = view.as_view() if view and not callable(view): raise ImproperlyConfigured("View %r not callable" % view) return view def get_view_by_name(theme, view_name): if not theme: return None cache_key = (theme.identifier, view_name) if cache_key not in _VIEW_CACHE: view = _get_view_by_name(theme, view_name) _VIEW_CACHE[cache_key] = view else: view = _VIEW_CACHE[cache_key] return view def extra_view_dispatch(request, view): """ Dispatch to an Xtheme extra view. :param request: A request :type request: django.http.HttpRequest
:rtype: django.http.HttpResponse """ theme = get_current_theme(request) view_func = get_view_by_name(theme, view) if not view_func: msg = "%s/%s: Not found" % (getattr(theme, "identifier", None), view) return HttpResponseNotFound(msg) return view_func(request)
:param view: View name :type view: str :return: A response of some ilk
random_line_split
collectionsearch.py
# Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ensure_default_collection(collection_list=None): default_collection = AnsibleCollectionLoader().default_collection # Will be None when used as the default if collection_list is None:
# FIXME: exclude role tasks? if default_collection and default_collection not in collection_list: collection_list.insert(0, default_collection) # if there's something in the list, ensure that builtin or legacy is always there too if collection_list and 'ansible.builtin' not in collection_list and 'ansible.legacy' not in collection_list: collection_list.append('ansible.legacy') return collection_list class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validate=True, static=True) def _load_collections(self, attr, ds): # We are always a mixin with Base, so we can validate this untemplated # field early on to guarantee we are dealing with a list. ds = self.get_validated_value('collections', self._collections, ds, None) # this will only be called if someone specified a value; call the shared value _ensure_default_collection(collection_list=ds) if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it may # error before it ever gets to the post_validate() warning (e.g. trying # to import a role from the collection). env = Environment() for collection_name in ds: if is_template(collection_name, env): display.warning('"collections" is not templatable, but we found: %s, ' 'it will not be templated and will be used "as is".' % (collection_name)) return ds
collection_list = []
conditional_block
collectionsearch.py
# Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ensure_default_collection(collection_list=None):
class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validate=True, static=True) def _load_collections(self, attr, ds): # We are always a mixin with Base, so we can validate this untemplated # field early on to guarantee we are dealing with a list. ds = self.get_validated_value('collections', self._collections, ds, None) # this will only be called if someone specified a value; call the shared value _ensure_default_collection(collection_list=ds) if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it may # error before it ever gets to the post_validate() warning (e.g. trying # to import a role from the collection). env = Environment() for collection_name in ds: if is_template(collection_name, env): display.warning('"collections" is not templatable, but we found: %s, ' 'it will not be templated and will be used "as is".' % (collection_name)) return ds
default_collection = AnsibleCollectionLoader().default_collection # Will be None when used as the default if collection_list is None: collection_list = [] # FIXME: exclude role tasks? if default_collection and default_collection not in collection_list: collection_list.insert(0, default_collection) # if there's something in the list, ensure that builtin or legacy is always there too if collection_list and 'ansible.builtin' not in collection_list and 'ansible.legacy' not in collection_list: collection_list.append('ansible.legacy') return collection_list
identifier_body
collectionsearch.py
# Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ensure_default_collection(collection_list=None): default_collection = AnsibleCollectionLoader().default_collection # Will be None when used as the default if collection_list is None: collection_list = [] # FIXME: exclude role tasks? if default_collection and default_collection not in collection_list: collection_list.insert(0, default_collection) # if there's something in the list, ensure that builtin or legacy is always there too if collection_list and 'ansible.builtin' not in collection_list and 'ansible.legacy' not in collection_list: collection_list.append('ansible.legacy') return collection_list class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validate=True, static=True) def _load_collections(self, attr, ds):
# field early on to guarantee we are dealing with a list. ds = self.get_validated_value('collections', self._collections, ds, None) # this will only be called if someone specified a value; call the shared value _ensure_default_collection(collection_list=ds) if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it may # error before it ever gets to the post_validate() warning (e.g. trying # to import a role from the collection). env = Environment() for collection_name in ds: if is_template(collection_name, env): display.warning('"collections" is not templatable, but we found: %s, ' 'it will not be templated and will be used "as is".' % (collection_name)) return ds
# We are always a mixin with Base, so we can validate this untemplated
random_line_split
collectionsearch.py
# Copyright: (c) 2019, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.six import string_types from ansible.playbook.attribute import FieldAttribute from ansible.utils.collection_loader import AnsibleCollectionLoader from ansible.template import is_template, Environment from ansible.utils.display import Display display = Display() def _ensure_default_collection(collection_list=None): default_collection = AnsibleCollectionLoader().default_collection # Will be None when used as the default if collection_list is None: collection_list = [] # FIXME: exclude role tasks? if default_collection and default_collection not in collection_list: collection_list.insert(0, default_collection) # if there's something in the list, ensure that builtin or legacy is always there too if collection_list and 'ansible.builtin' not in collection_list and 'ansible.legacy' not in collection_list: collection_list.append('ansible.legacy') return collection_list class CollectionSearch: # this needs to be populated before we can resolve tasks/roles/etc _collections = FieldAttribute(isa='list', listof=string_types, priority=100, default=_ensure_default_collection, always_post_validate=True, static=True) def
(self, attr, ds): # We are always a mixin with Base, so we can validate this untemplated # field early on to guarantee we are dealing with a list. ds = self.get_validated_value('collections', self._collections, ds, None) # this will only be called if someone specified a value; call the shared value _ensure_default_collection(collection_list=ds) if not ds: # don't return an empty collection list, just return None return None # This duplicates static attr checking logic from post_validate() # because if the user attempts to template a collection name, it may # error before it ever gets to the post_validate() warning (e.g. trying # to import a role from the collection). env = Environment() for collection_name in ds: if is_template(collection_name, env): display.warning('"collections" is not templatable, but we found: %s, ' 'it will not be templated and will be used "as is".' % (collection_name)) return ds
_load_collections
identifier_name
lib.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. #![feature(rustc_private, plugin_registrar, quote)] extern crate platformtree; extern crate rustc; extern crate serialize; extern crate syntax; extern crate rustc_plugin; use std::clone::Clone; use std::ops::Deref; use rustc_plugin::Registry; use syntax::ast; use syntax::tokenstream; use syntax::codemap::DUMMY_SP; use syntax::codemap::Span; use syntax::ext::base::{ExtCtxt, MacResult, MultiModifier, Annotatable}; use syntax::ext::build::AstBuilder; use syntax::print::pprust; use syntax::util::small_vector::SmallVector; use syntax::ptr::P; use platformtree::parser::Parser; use platformtree::builder::Builder; use platformtree::builder::meta_args::ToTyHash; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("platformtree", macro_platformtree); reg.register_macro("platformtree_verbose", macro_platformtree_verbose); reg.register_syntax_extension(syntax::parse::token::intern("zinc_task"), MultiModifier(Box::new(macro_zinc_task))); } pub fn macro_platformtree(cx: &mut ExtCtxt, _: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let pt = Parser::new(cx, tts).parse_platformtree(); let items = Builder::build(cx, pt.unwrap()) .expect(format!("Unexpected failure on {}", line!()).as_str()) .emit_items(cx); MacItems::new(items) } pub fn macro_platformtree_verbose(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let result = macro_platformtree(cx, sp, tts); println!("Platform Tree dump:"); for i in result.make_items().unwrap().as_slice().iter() { println!("{}", pprust::item_to_string(i.deref())); } macro_platformtree(cx, sp, tts) } fn macro_zinc_task(cx: &mut ExtCtxt, _: Span, _: &ast::MetaItem, ann: Annotatable) -> Annotatable { match ann { Annotatable::Item(it) => {Annotatable::Item(macro_zinc_task_item(cx, it))} other => {other} } } fn
(cx: &mut ExtCtxt, it: P<ast::Item>) -> P<ast::Item> { match it.node { ast::ItemKind::Fn(ref decl, style, constness, abi, _, ref block) => { let istr = it.ident.name.as_str(); let fn_name = &*istr; let ty_params = platformtree::builder::meta_args::get_ty_params_for_task(cx, fn_name); let params = ty_params.iter().map(|ty| { cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!(cx.typarambound( cx.path(DUMMY_SP, ty.as_str().split("::").map(|t| cx.ident_of(t)).collect())))), None) }).collect(); let new_arg = cx.arg(DUMMY_SP, cx.ident_of("args"), cx.ty_rptr( DUMMY_SP, cx.ty_path( cx.path_all( DUMMY_SP, false, ["pt".to_string(), fn_name.to_string() + "_args"].iter().map(|t| cx.ident_of(t.as_str())).collect(), vec!(), ty_params.iter().map(|ty| { cx.ty_path(cx.path_ident(DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()))) }).collect(), vec!())), None, ast::Mutability::Immutable)); let new_decl = P(ast::FnDecl { inputs: vec!(new_arg), ..decl.deref().clone() }); let new_generics = ast::Generics { lifetimes: vec!(), ty_params: P::from_vec(params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), }, span : DUMMY_SP, }; let new_node = ast::ItemKind::Fn(new_decl, style, constness, abi, new_generics, block.clone()); P(ast::Item {node: new_node, ..it.deref().clone() }) }, _ => panic!(), } } pub struct MacItems { items: Vec<P<ast::Item>> } impl MacItems { pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> { Box::new(MacItems { items: items }) } } impl MacResult for MacItems { fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> { Some(SmallVector::many(self.items.clone())) } }
macro_zinc_task_item
identifier_name
lib.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. #![feature(rustc_private, plugin_registrar, quote)] extern crate platformtree; extern crate rustc; extern crate serialize; extern crate syntax; extern crate rustc_plugin; use std::clone::Clone; use std::ops::Deref; use rustc_plugin::Registry; use syntax::ast; use syntax::tokenstream; use syntax::codemap::DUMMY_SP; use syntax::codemap::Span; use syntax::ext::base::{ExtCtxt, MacResult, MultiModifier, Annotatable}; use syntax::ext::build::AstBuilder; use syntax::print::pprust; use syntax::util::small_vector::SmallVector; use syntax::ptr::P; use platformtree::parser::Parser; use platformtree::builder::Builder; use platformtree::builder::meta_args::ToTyHash; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("platformtree", macro_platformtree); reg.register_macro("platformtree_verbose", macro_platformtree_verbose); reg.register_syntax_extension(syntax::parse::token::intern("zinc_task"), MultiModifier(Box::new(macro_zinc_task))); } pub fn macro_platformtree(cx: &mut ExtCtxt, _: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let pt = Parser::new(cx, tts).parse_platformtree(); let items = Builder::build(cx, pt.unwrap()) .expect(format!("Unexpected failure on {}", line!()).as_str()) .emit_items(cx); MacItems::new(items) } pub fn macro_platformtree_verbose(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let result = macro_platformtree(cx, sp, tts); println!("Platform Tree dump:"); for i in result.make_items().unwrap().as_slice().iter() { println!("{}", pprust::item_to_string(i.deref()));
fn macro_zinc_task(cx: &mut ExtCtxt, _: Span, _: &ast::MetaItem, ann: Annotatable) -> Annotatable { match ann { Annotatable::Item(it) => {Annotatable::Item(macro_zinc_task_item(cx, it))} other => {other} } } fn macro_zinc_task_item(cx: &mut ExtCtxt, it: P<ast::Item>) -> P<ast::Item> { match it.node { ast::ItemKind::Fn(ref decl, style, constness, abi, _, ref block) => { let istr = it.ident.name.as_str(); let fn_name = &*istr; let ty_params = platformtree::builder::meta_args::get_ty_params_for_task(cx, fn_name); let params = ty_params.iter().map(|ty| { cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!(cx.typarambound( cx.path(DUMMY_SP, ty.as_str().split("::").map(|t| cx.ident_of(t)).collect())))), None) }).collect(); let new_arg = cx.arg(DUMMY_SP, cx.ident_of("args"), cx.ty_rptr( DUMMY_SP, cx.ty_path( cx.path_all( DUMMY_SP, false, ["pt".to_string(), fn_name.to_string() + "_args"].iter().map(|t| cx.ident_of(t.as_str())).collect(), vec!(), ty_params.iter().map(|ty| { cx.ty_path(cx.path_ident(DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()))) }).collect(), vec!())), None, ast::Mutability::Immutable)); let new_decl = P(ast::FnDecl { inputs: vec!(new_arg), ..decl.deref().clone() }); let new_generics = ast::Generics { lifetimes: vec!(), ty_params: P::from_vec(params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), }, span : DUMMY_SP, }; let new_node = ast::ItemKind::Fn(new_decl, style, constness, abi, new_generics, block.clone()); P(ast::Item {node: new_node, ..it.deref().clone() }) }, _ => panic!(), } } pub struct MacItems { items: Vec<P<ast::Item>> } impl MacItems { pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> { Box::new(MacItems { items: items }) } } impl MacResult for MacItems { fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> { Some(SmallVector::many(self.items.clone())) } }
} macro_platformtree(cx, sp, tts) }
random_line_split
lib.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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. #![feature(rustc_private, plugin_registrar, quote)] extern crate platformtree; extern crate rustc; extern crate serialize; extern crate syntax; extern crate rustc_plugin; use std::clone::Clone; use std::ops::Deref; use rustc_plugin::Registry; use syntax::ast; use syntax::tokenstream; use syntax::codemap::DUMMY_SP; use syntax::codemap::Span; use syntax::ext::base::{ExtCtxt, MacResult, MultiModifier, Annotatable}; use syntax::ext::build::AstBuilder; use syntax::print::pprust; use syntax::util::small_vector::SmallVector; use syntax::ptr::P; use platformtree::parser::Parser; use platformtree::builder::Builder; use platformtree::builder::meta_args::ToTyHash; #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("platformtree", macro_platformtree); reg.register_macro("platformtree_verbose", macro_platformtree_verbose); reg.register_syntax_extension(syntax::parse::token::intern("zinc_task"), MultiModifier(Box::new(macro_zinc_task))); } pub fn macro_platformtree(cx: &mut ExtCtxt, _: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let pt = Parser::new(cx, tts).parse_platformtree(); let items = Builder::build(cx, pt.unwrap()) .expect(format!("Unexpected failure on {}", line!()).as_str()) .emit_items(cx); MacItems::new(items) } pub fn macro_platformtree_verbose(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree]) -> Box<MacResult+'static> { let result = macro_platformtree(cx, sp, tts); println!("Platform Tree dump:"); for i in result.make_items().unwrap().as_slice().iter() { println!("{}", pprust::item_to_string(i.deref())); } macro_platformtree(cx, sp, tts) } fn macro_zinc_task(cx: &mut ExtCtxt, _: Span, _: &ast::MetaItem, ann: Annotatable) -> Annotatable { match ann { Annotatable::Item(it) => {Annotatable::Item(macro_zinc_task_item(cx, it))} other => {other} } } fn macro_zinc_task_item(cx: &mut ExtCtxt, it: P<ast::Item>) -> P<ast::Item> { match it.node { ast::ItemKind::Fn(ref decl, style, constness, abi, _, ref block) =>
, _ => panic!(), } } pub struct MacItems { items: Vec<P<ast::Item>> } impl MacItems { pub fn new(items: Vec<P<ast::Item>>) -> Box<MacResult+'static> { Box::new(MacItems { items: items }) } } impl MacResult for MacItems { fn make_items(self: Box<MacItems>) -> Option<SmallVector<P<ast::Item>>> { Some(SmallVector::many(self.items.clone())) } }
{ let istr = it.ident.name.as_str(); let fn_name = &*istr; let ty_params = platformtree::builder::meta_args::get_ty_params_for_task(cx, fn_name); let params = ty_params.iter().map(|ty| { cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!(cx.typarambound( cx.path(DUMMY_SP, ty.as_str().split("::").map(|t| cx.ident_of(t)).collect())))), None) }).collect(); let new_arg = cx.arg(DUMMY_SP, cx.ident_of("args"), cx.ty_rptr( DUMMY_SP, cx.ty_path( cx.path_all( DUMMY_SP, false, ["pt".to_string(), fn_name.to_string() + "_args"].iter().map(|t| cx.ident_of(t.as_str())).collect(), vec!(), ty_params.iter().map(|ty| { cx.ty_path(cx.path_ident(DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()))) }).collect(), vec!())), None, ast::Mutability::Immutable)); let new_decl = P(ast::FnDecl { inputs: vec!(new_arg), ..decl.deref().clone() }); let new_generics = ast::Generics { lifetimes: vec!(), ty_params: P::from_vec(params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), }, span : DUMMY_SP, }; let new_node = ast::ItemKind::Fn(new_decl, style, constness, abi, new_generics, block.clone()); P(ast::Item {node: new_node, ..it.deref().clone() }) }
conditional_block
card.component.ts
/* * Copyright [2019] [Metamagic] * * 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. * * Created by ketangote on 12/18/17. */ import { DOCUMENT } from '@angular/common'; import { AfterContentChecked, AfterContentInit, AfterViewInit, Component, ElementRef, EventEmitter, HostListener, Inject, Input, OnDestroy, OnInit, Output, Renderer2, ViewChild, } from '@angular/core'; import { ContentChildren, QueryList } from '@angular/core'; import { LifeCycleBaseComponent } from '../../base/lifecycle.base.component'; import { AmexioHeaderComponent } from '../../panes/header/pane.action.header'; import { AmexioFooterComponent } from './../../panes/action/pane.action.footer'; import { AmexioBodyComponent } from './../../panes/body/pane.action.body'; @Component({ selector: 'amexio-card', templateUrl: './card.component.html', }) export class AmexioCardComponent extends LifeCycleBaseComponent implements OnInit, OnDestroy, AfterContentChecked, AfterViewInit, AfterContentInit { /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card header example : right,center,left. */ @Input('header-align') headeralign: string; /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : User can enable header of card by setting this flag to true.. */ @Input() header: boolean; /* Properties name : footer datatype : boolean version : 4.0 onwards default : false description : User can enable footer of card by setting this flag to true. */ @Input() footer: boolean; /* Properties name : footer-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card footer example : right,center,left.. */ @Input('footer-align') footeralign: string; /* Properties name : show datatype : boolean version : 4.0 onwards default : true description : User can bind variable to this and hide/unhide card based on requirement.. */ @Input() show = true; /* Properties name : height datatype : any version : 4.0 onwards default : description : User can set the height to body.. */ @Input() height: any; /* Properties name : min-height datatype : any version : 4.0 onwards default : description : Provides minimum card height. */ @Input('min-height') minHeight: any; /* Properties name : body-height datatype : any version : 4.0 onwards default : description : Provides card height. Not in use */ @Input('body-height') bodyheight: any; /* Properties name : context-menu datatype : string version : 5.0.1 onwards default : description : Context Menu provides the list of menus on right click. */ @Input('context-menu') contextmenu: any[]; @Input('polaroid-type') styletype: any; @Input() parentRef: any; @Output() nodeRightClick: any = new EventEmitter<any>(); @Output() rightClick: any = new EventEmitter<any>(); /* view child begins */ @ViewChild('cardHeader', { read: ElementRef }) public cardHeader: ElementRef; @ViewChild('cardFooter', { read: ElementRef }) public cardFooter: ElementRef; headerPadding: string; bodyPadding: string; footerPadding: string; flag: boolean; posixUp: boolean; rightClickNodeData: any; contextStyle: any; timeOut: any; mouseLocation: { left: number; top: number } = { left: 0, top: 0 }; amexioComponentId = 'amexio-card'; themeCss: any; polarideStyleMap: Map<any, string>; tempPolaride: any; maximizeflagchanged = false; headerinst: any; @ContentChildren(AmexioHeaderComponent) amexioHeader: QueryList<AmexioHeaderComponent>; headerComponentList: AmexioHeaderComponent[]; @ContentChildren(AmexioBodyComponent) amexioBody: QueryList<AmexioBodyComponent>; bodyComponentList: AmexioBodyComponent[]; @ContentChildren(AmexioFooterComponent) amexioFooter: QueryList<AmexioFooterComponent>; footerComponentList: AmexioFooterComponent[]; globalClickListenFunc: () => void; constructor(private renderer: Renderer2, @Inject(DOCUMENT) public document: any) { super(document); this.headeralign = 'left'; this.footeralign = 'right'; } ngOnInit() { super.ngOnInit();
this.polarideStyleMap.set('tilted-minus-2-degree', 'card-container-pol-styl'); this.polarideStyleMap.set('tilted-2-degree', 'card-container-pol-styl2'); this.polarideStyleMap.set('tilted-4-degree', 'card-container-pol-styl3'); this.polarideStyleMap.set('tilted-minus-4-degree', 'card-container-pol-styl4'); this.polarideStyleMap.forEach((ele: any, key: any) => { if (key === this.styletype) { this.tempPolaride = ele; } }); return 'this.tempPolaide'; } ngAfterViewInit() { super.ngAfterViewInit(); } ngAfterContentChecked() { } ngAfterContentInit() { // FOR HEADER PADING this.headerComponentList = this.amexioHeader.toArray(); this.headerComponentList.forEach((item: AmexioHeaderComponent, currentIndex) => { item.fullScreenFlag = this.yesFullScreen; item.fullscreenMaxCard = true; item.aComponent = 'card'; if (item.padding) { this.headerPadding = item.padding; } }); // FOR BODY PADDING this.bodyComponentList = this.amexioBody.toArray(); this.bodyComponentList.forEach((item: AmexioBodyComponent, currentIndex) => { if (item.padding) { this.bodyPadding = item.padding; } }); // FOR FOOTER PADDING this.footerComponentList = this.amexioFooter.toArray(); this.footerComponentList.forEach((item: AmexioFooterComponent, currentIndex) => { if (item.padding) { this.footerPadding = item.padding; } item.footer = this.footer; item.setFooterAlignment(this.footeralign); }); this.onResize(); if (this.yesFullScreen) { this.amexioHeader.toArray()[0].maximizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.maxScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); this.amexioHeader.toArray()[0].minimizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.minScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); } } adjustHeight(event: any) { this.onResize(); } // Calculate body size based on browser height onResize() { if (this.bodyheight) { let h = (window.innerHeight / 100) * this.bodyheight; if (this.cardHeader && this.cardHeader.nativeElement && this.cardHeader.nativeElement.offsetHeight) { h = h - this.cardHeader.nativeElement.offsetHeight; } if (this.cardFooter && this.cardFooter.nativeElement && this.cardFooter.nativeElement.offsetHeight) { h = h - this.cardFooter.nativeElement.offsetHeight; } if (this.bodyheight === 100) { h = h - 40; } this.minHeight = h; this.height = h; } } getContextMenu() { if (this.contextmenu && this.contextmenu.length > 0) { this.flag = true; this.addListner(); } } getListPosition(elementRef: any): boolean { const height = 240; if ((window.screen.height - elementRef.getBoundingClientRect().bottom) < height) { return true; } else { return false; } } loadContextMenu(rightClickData: any) { if (this.contextmenu && this.contextmenu.length > 0) { this.mouseLocation.left = rightClickData.event.clientX; this.mouseLocation.top = rightClickData.event.clientY; this.getContextMenu(); this.posixUp = this.getListPosition(rightClickData.ref); rightClickData.event.preventDefault(); rightClickData.event.stopPropagation(); this.rightClickNodeData = rightClickData.data; this.nodeRightClick.emit(rightClickData); } } rightClickDataEmit(Data: any) { this.rightClick.emit(Data); } addListner() { this.globalClickListenFunc = this.renderer.listen('document', 'click', (e: any) => { this.flag = false; if (!this.flag) { this.removeListner(); } }); } removeListner() { if (this.globalClickListenFunc) { this.globalClickListenFunc(); } } ngOnDestroy(): void { super.ngOnDestroy(); this.removeListner(); } // Theme Apply setColorPalette(themeClass: any) { this.themeCss = themeClass; } }
this.instance = this; this.polarideStyleMap = new Map();
random_line_split
card.component.ts
/* * Copyright [2019] [Metamagic] * * 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. * * Created by ketangote on 12/18/17. */ import { DOCUMENT } from '@angular/common'; import { AfterContentChecked, AfterContentInit, AfterViewInit, Component, ElementRef, EventEmitter, HostListener, Inject, Input, OnDestroy, OnInit, Output, Renderer2, ViewChild, } from '@angular/core'; import { ContentChildren, QueryList } from '@angular/core'; import { LifeCycleBaseComponent } from '../../base/lifecycle.base.component'; import { AmexioHeaderComponent } from '../../panes/header/pane.action.header'; import { AmexioFooterComponent } from './../../panes/action/pane.action.footer'; import { AmexioBodyComponent } from './../../panes/body/pane.action.body'; @Component({ selector: 'amexio-card', templateUrl: './card.component.html', }) export class AmexioCardComponent extends LifeCycleBaseComponent implements OnInit, OnDestroy, AfterContentChecked, AfterViewInit, AfterContentInit { /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card header example : right,center,left. */ @Input('header-align') headeralign: string; /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : User can enable header of card by setting this flag to true.. */ @Input() header: boolean; /* Properties name : footer datatype : boolean version : 4.0 onwards default : false description : User can enable footer of card by setting this flag to true. */ @Input() footer: boolean; /* Properties name : footer-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card footer example : right,center,left.. */ @Input('footer-align') footeralign: string; /* Properties name : show datatype : boolean version : 4.0 onwards default : true description : User can bind variable to this and hide/unhide card based on requirement.. */ @Input() show = true; /* Properties name : height datatype : any version : 4.0 onwards default : description : User can set the height to body.. */ @Input() height: any; /* Properties name : min-height datatype : any version : 4.0 onwards default : description : Provides minimum card height. */ @Input('min-height') minHeight: any; /* Properties name : body-height datatype : any version : 4.0 onwards default : description : Provides card height. Not in use */ @Input('body-height') bodyheight: any; /* Properties name : context-menu datatype : string version : 5.0.1 onwards default : description : Context Menu provides the list of menus on right click. */ @Input('context-menu') contextmenu: any[]; @Input('polaroid-type') styletype: any; @Input() parentRef: any; @Output() nodeRightClick: any = new EventEmitter<any>(); @Output() rightClick: any = new EventEmitter<any>(); /* view child begins */ @ViewChild('cardHeader', { read: ElementRef }) public cardHeader: ElementRef; @ViewChild('cardFooter', { read: ElementRef }) public cardFooter: ElementRef; headerPadding: string; bodyPadding: string; footerPadding: string; flag: boolean; posixUp: boolean; rightClickNodeData: any; contextStyle: any; timeOut: any; mouseLocation: { left: number; top: number } = { left: 0, top: 0 }; amexioComponentId = 'amexio-card'; themeCss: any; polarideStyleMap: Map<any, string>; tempPolaride: any; maximizeflagchanged = false; headerinst: any; @ContentChildren(AmexioHeaderComponent) amexioHeader: QueryList<AmexioHeaderComponent>; headerComponentList: AmexioHeaderComponent[]; @ContentChildren(AmexioBodyComponent) amexioBody: QueryList<AmexioBodyComponent>; bodyComponentList: AmexioBodyComponent[]; @ContentChildren(AmexioFooterComponent) amexioFooter: QueryList<AmexioFooterComponent>; footerComponentList: AmexioFooterComponent[]; globalClickListenFunc: () => void; constructor(private renderer: Renderer2, @Inject(DOCUMENT) public document: any) { super(document); this.headeralign = 'left'; this.footeralign = 'right'; } ngOnInit() { super.ngOnInit(); this.instance = this; this.polarideStyleMap = new Map(); this.polarideStyleMap.set('tilted-minus-2-degree', 'card-container-pol-styl'); this.polarideStyleMap.set('tilted-2-degree', 'card-container-pol-styl2'); this.polarideStyleMap.set('tilted-4-degree', 'card-container-pol-styl3'); this.polarideStyleMap.set('tilted-minus-4-degree', 'card-container-pol-styl4'); this.polarideStyleMap.forEach((ele: any, key: any) => { if (key === this.styletype) { this.tempPolaride = ele; } }); return 'this.tempPolaide'; } ngAfterViewInit() { super.ngAfterViewInit(); } ngAfterContentChecked() { }
() { // FOR HEADER PADING this.headerComponentList = this.amexioHeader.toArray(); this.headerComponentList.forEach((item: AmexioHeaderComponent, currentIndex) => { item.fullScreenFlag = this.yesFullScreen; item.fullscreenMaxCard = true; item.aComponent = 'card'; if (item.padding) { this.headerPadding = item.padding; } }); // FOR BODY PADDING this.bodyComponentList = this.amexioBody.toArray(); this.bodyComponentList.forEach((item: AmexioBodyComponent, currentIndex) => { if (item.padding) { this.bodyPadding = item.padding; } }); // FOR FOOTER PADDING this.footerComponentList = this.amexioFooter.toArray(); this.footerComponentList.forEach((item: AmexioFooterComponent, currentIndex) => { if (item.padding) { this.footerPadding = item.padding; } item.footer = this.footer; item.setFooterAlignment(this.footeralign); }); this.onResize(); if (this.yesFullScreen) { this.amexioHeader.toArray()[0].maximizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.maxScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); this.amexioHeader.toArray()[0].minimizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.minScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); } } adjustHeight(event: any) { this.onResize(); } // Calculate body size based on browser height onResize() { if (this.bodyheight) { let h = (window.innerHeight / 100) * this.bodyheight; if (this.cardHeader && this.cardHeader.nativeElement && this.cardHeader.nativeElement.offsetHeight) { h = h - this.cardHeader.nativeElement.offsetHeight; } if (this.cardFooter && this.cardFooter.nativeElement && this.cardFooter.nativeElement.offsetHeight) { h = h - this.cardFooter.nativeElement.offsetHeight; } if (this.bodyheight === 100) { h = h - 40; } this.minHeight = h; this.height = h; } } getContextMenu() { if (this.contextmenu && this.contextmenu.length > 0) { this.flag = true; this.addListner(); } } getListPosition(elementRef: any): boolean { const height = 240; if ((window.screen.height - elementRef.getBoundingClientRect().bottom) < height) { return true; } else { return false; } } loadContextMenu(rightClickData: any) { if (this.contextmenu && this.contextmenu.length > 0) { this.mouseLocation.left = rightClickData.event.clientX; this.mouseLocation.top = rightClickData.event.clientY; this.getContextMenu(); this.posixUp = this.getListPosition(rightClickData.ref); rightClickData.event.preventDefault(); rightClickData.event.stopPropagation(); this.rightClickNodeData = rightClickData.data; this.nodeRightClick.emit(rightClickData); } } rightClickDataEmit(Data: any) { this.rightClick.emit(Data); } addListner() { this.globalClickListenFunc = this.renderer.listen('document', 'click', (e: any) => { this.flag = false; if (!this.flag) { this.removeListner(); } }); } removeListner() { if (this.globalClickListenFunc) { this.globalClickListenFunc(); } } ngOnDestroy(): void { super.ngOnDestroy(); this.removeListner(); } // Theme Apply setColorPalette(themeClass: any) { this.themeCss = themeClass; } }
ngAfterContentInit
identifier_name
card.component.ts
/* * Copyright [2019] [Metamagic] * * 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. * * Created by ketangote on 12/18/17. */ import { DOCUMENT } from '@angular/common'; import { AfterContentChecked, AfterContentInit, AfterViewInit, Component, ElementRef, EventEmitter, HostListener, Inject, Input, OnDestroy, OnInit, Output, Renderer2, ViewChild, } from '@angular/core'; import { ContentChildren, QueryList } from '@angular/core'; import { LifeCycleBaseComponent } from '../../base/lifecycle.base.component'; import { AmexioHeaderComponent } from '../../panes/header/pane.action.header'; import { AmexioFooterComponent } from './../../panes/action/pane.action.footer'; import { AmexioBodyComponent } from './../../panes/body/pane.action.body'; @Component({ selector: 'amexio-card', templateUrl: './card.component.html', }) export class AmexioCardComponent extends LifeCycleBaseComponent implements OnInit, OnDestroy, AfterContentChecked, AfterViewInit, AfterContentInit { /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card header example : right,center,left. */ @Input('header-align') headeralign: string; /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : User can enable header of card by setting this flag to true.. */ @Input() header: boolean; /* Properties name : footer datatype : boolean version : 4.0 onwards default : false description : User can enable footer of card by setting this flag to true. */ @Input() footer: boolean; /* Properties name : footer-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card footer example : right,center,left.. */ @Input('footer-align') footeralign: string; /* Properties name : show datatype : boolean version : 4.0 onwards default : true description : User can bind variable to this and hide/unhide card based on requirement.. */ @Input() show = true; /* Properties name : height datatype : any version : 4.0 onwards default : description : User can set the height to body.. */ @Input() height: any; /* Properties name : min-height datatype : any version : 4.0 onwards default : description : Provides minimum card height. */ @Input('min-height') minHeight: any; /* Properties name : body-height datatype : any version : 4.0 onwards default : description : Provides card height. Not in use */ @Input('body-height') bodyheight: any; /* Properties name : context-menu datatype : string version : 5.0.1 onwards default : description : Context Menu provides the list of menus on right click. */ @Input('context-menu') contextmenu: any[]; @Input('polaroid-type') styletype: any; @Input() parentRef: any; @Output() nodeRightClick: any = new EventEmitter<any>(); @Output() rightClick: any = new EventEmitter<any>(); /* view child begins */ @ViewChild('cardHeader', { read: ElementRef }) public cardHeader: ElementRef; @ViewChild('cardFooter', { read: ElementRef }) public cardFooter: ElementRef; headerPadding: string; bodyPadding: string; footerPadding: string; flag: boolean; posixUp: boolean; rightClickNodeData: any; contextStyle: any; timeOut: any; mouseLocation: { left: number; top: number } = { left: 0, top: 0 }; amexioComponentId = 'amexio-card'; themeCss: any; polarideStyleMap: Map<any, string>; tempPolaride: any; maximizeflagchanged = false; headerinst: any; @ContentChildren(AmexioHeaderComponent) amexioHeader: QueryList<AmexioHeaderComponent>; headerComponentList: AmexioHeaderComponent[]; @ContentChildren(AmexioBodyComponent) amexioBody: QueryList<AmexioBodyComponent>; bodyComponentList: AmexioBodyComponent[]; @ContentChildren(AmexioFooterComponent) amexioFooter: QueryList<AmexioFooterComponent>; footerComponentList: AmexioFooterComponent[]; globalClickListenFunc: () => void; constructor(private renderer: Renderer2, @Inject(DOCUMENT) public document: any) { super(document); this.headeralign = 'left'; this.footeralign = 'right'; } ngOnInit() { super.ngOnInit(); this.instance = this; this.polarideStyleMap = new Map(); this.polarideStyleMap.set('tilted-minus-2-degree', 'card-container-pol-styl'); this.polarideStyleMap.set('tilted-2-degree', 'card-container-pol-styl2'); this.polarideStyleMap.set('tilted-4-degree', 'card-container-pol-styl3'); this.polarideStyleMap.set('tilted-minus-4-degree', 'card-container-pol-styl4'); this.polarideStyleMap.forEach((ele: any, key: any) => { if (key === this.styletype) { this.tempPolaride = ele; } }); return 'this.tempPolaide'; } ngAfterViewInit()
ngAfterContentChecked() { } ngAfterContentInit() { // FOR HEADER PADING this.headerComponentList = this.amexioHeader.toArray(); this.headerComponentList.forEach((item: AmexioHeaderComponent, currentIndex) => { item.fullScreenFlag = this.yesFullScreen; item.fullscreenMaxCard = true; item.aComponent = 'card'; if (item.padding) { this.headerPadding = item.padding; } }); // FOR BODY PADDING this.bodyComponentList = this.amexioBody.toArray(); this.bodyComponentList.forEach((item: AmexioBodyComponent, currentIndex) => { if (item.padding) { this.bodyPadding = item.padding; } }); // FOR FOOTER PADDING this.footerComponentList = this.amexioFooter.toArray(); this.footerComponentList.forEach((item: AmexioFooterComponent, currentIndex) => { if (item.padding) { this.footerPadding = item.padding; } item.footer = this.footer; item.setFooterAlignment(this.footeralign); }); this.onResize(); if (this.yesFullScreen) { this.amexioHeader.toArray()[0].maximizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.maxScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); this.amexioHeader.toArray()[0].minimizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.minScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); } } adjustHeight(event: any) { this.onResize(); } // Calculate body size based on browser height onResize() { if (this.bodyheight) { let h = (window.innerHeight / 100) * this.bodyheight; if (this.cardHeader && this.cardHeader.nativeElement && this.cardHeader.nativeElement.offsetHeight) { h = h - this.cardHeader.nativeElement.offsetHeight; } if (this.cardFooter && this.cardFooter.nativeElement && this.cardFooter.nativeElement.offsetHeight) { h = h - this.cardFooter.nativeElement.offsetHeight; } if (this.bodyheight === 100) { h = h - 40; } this.minHeight = h; this.height = h; } } getContextMenu() { if (this.contextmenu && this.contextmenu.length > 0) { this.flag = true; this.addListner(); } } getListPosition(elementRef: any): boolean { const height = 240; if ((window.screen.height - elementRef.getBoundingClientRect().bottom) < height) { return true; } else { return false; } } loadContextMenu(rightClickData: any) { if (this.contextmenu && this.contextmenu.length > 0) { this.mouseLocation.left = rightClickData.event.clientX; this.mouseLocation.top = rightClickData.event.clientY; this.getContextMenu(); this.posixUp = this.getListPosition(rightClickData.ref); rightClickData.event.preventDefault(); rightClickData.event.stopPropagation(); this.rightClickNodeData = rightClickData.data; this.nodeRightClick.emit(rightClickData); } } rightClickDataEmit(Data: any) { this.rightClick.emit(Data); } addListner() { this.globalClickListenFunc = this.renderer.listen('document', 'click', (e: any) => { this.flag = false; if (!this.flag) { this.removeListner(); } }); } removeListner() { if (this.globalClickListenFunc) { this.globalClickListenFunc(); } } ngOnDestroy(): void { super.ngOnDestroy(); this.removeListner(); } // Theme Apply setColorPalette(themeClass: any) { this.themeCss = themeClass; } }
{ super.ngAfterViewInit(); }
identifier_body
card.component.ts
/* * Copyright [2019] [Metamagic] * * 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. * * Created by ketangote on 12/18/17. */ import { DOCUMENT } from '@angular/common'; import { AfterContentChecked, AfterContentInit, AfterViewInit, Component, ElementRef, EventEmitter, HostListener, Inject, Input, OnDestroy, OnInit, Output, Renderer2, ViewChild, } from '@angular/core'; import { ContentChildren, QueryList } from '@angular/core'; import { LifeCycleBaseComponent } from '../../base/lifecycle.base.component'; import { AmexioHeaderComponent } from '../../panes/header/pane.action.header'; import { AmexioFooterComponent } from './../../panes/action/pane.action.footer'; import { AmexioBodyComponent } from './../../panes/body/pane.action.body'; @Component({ selector: 'amexio-card', templateUrl: './card.component.html', }) export class AmexioCardComponent extends LifeCycleBaseComponent implements OnInit, OnDestroy, AfterContentChecked, AfterViewInit, AfterContentInit { /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card header example : right,center,left. */ @Input('header-align') headeralign: string; /* Properties name : header-align datatype : string version : 4.0 onwards default : left description : User can enable header of card by setting this flag to true.. */ @Input() header: boolean; /* Properties name : footer datatype : boolean version : 4.0 onwards default : false description : User can enable footer of card by setting this flag to true. */ @Input() footer: boolean; /* Properties name : footer-align datatype : string version : 4.0 onwards default : left description : Align of item elements inside card footer example : right,center,left.. */ @Input('footer-align') footeralign: string; /* Properties name : show datatype : boolean version : 4.0 onwards default : true description : User can bind variable to this and hide/unhide card based on requirement.. */ @Input() show = true; /* Properties name : height datatype : any version : 4.0 onwards default : description : User can set the height to body.. */ @Input() height: any; /* Properties name : min-height datatype : any version : 4.0 onwards default : description : Provides minimum card height. */ @Input('min-height') minHeight: any; /* Properties name : body-height datatype : any version : 4.0 onwards default : description : Provides card height. Not in use */ @Input('body-height') bodyheight: any; /* Properties name : context-menu datatype : string version : 5.0.1 onwards default : description : Context Menu provides the list of menus on right click. */ @Input('context-menu') contextmenu: any[]; @Input('polaroid-type') styletype: any; @Input() parentRef: any; @Output() nodeRightClick: any = new EventEmitter<any>(); @Output() rightClick: any = new EventEmitter<any>(); /* view child begins */ @ViewChild('cardHeader', { read: ElementRef }) public cardHeader: ElementRef; @ViewChild('cardFooter', { read: ElementRef }) public cardFooter: ElementRef; headerPadding: string; bodyPadding: string; footerPadding: string; flag: boolean; posixUp: boolean; rightClickNodeData: any; contextStyle: any; timeOut: any; mouseLocation: { left: number; top: number } = { left: 0, top: 0 }; amexioComponentId = 'amexio-card'; themeCss: any; polarideStyleMap: Map<any, string>; tempPolaride: any; maximizeflagchanged = false; headerinst: any; @ContentChildren(AmexioHeaderComponent) amexioHeader: QueryList<AmexioHeaderComponent>; headerComponentList: AmexioHeaderComponent[]; @ContentChildren(AmexioBodyComponent) amexioBody: QueryList<AmexioBodyComponent>; bodyComponentList: AmexioBodyComponent[]; @ContentChildren(AmexioFooterComponent) amexioFooter: QueryList<AmexioFooterComponent>; footerComponentList: AmexioFooterComponent[]; globalClickListenFunc: () => void; constructor(private renderer: Renderer2, @Inject(DOCUMENT) public document: any) { super(document); this.headeralign = 'left'; this.footeralign = 'right'; } ngOnInit() { super.ngOnInit(); this.instance = this; this.polarideStyleMap = new Map(); this.polarideStyleMap.set('tilted-minus-2-degree', 'card-container-pol-styl'); this.polarideStyleMap.set('tilted-2-degree', 'card-container-pol-styl2'); this.polarideStyleMap.set('tilted-4-degree', 'card-container-pol-styl3'); this.polarideStyleMap.set('tilted-minus-4-degree', 'card-container-pol-styl4'); this.polarideStyleMap.forEach((ele: any, key: any) => { if (key === this.styletype) { this.tempPolaride = ele; } }); return 'this.tempPolaide'; } ngAfterViewInit() { super.ngAfterViewInit(); } ngAfterContentChecked() { } ngAfterContentInit() { // FOR HEADER PADING this.headerComponentList = this.amexioHeader.toArray(); this.headerComponentList.forEach((item: AmexioHeaderComponent, currentIndex) => { item.fullScreenFlag = this.yesFullScreen; item.fullscreenMaxCard = true; item.aComponent = 'card'; if (item.padding) { this.headerPadding = item.padding; } }); // FOR BODY PADDING this.bodyComponentList = this.amexioBody.toArray(); this.bodyComponentList.forEach((item: AmexioBodyComponent, currentIndex) => { if (item.padding) { this.bodyPadding = item.padding; } }); // FOR FOOTER PADDING this.footerComponentList = this.amexioFooter.toArray(); this.footerComponentList.forEach((item: AmexioFooterComponent, currentIndex) => { if (item.padding) { this.footerPadding = item.padding; } item.footer = this.footer; item.setFooterAlignment(this.footeralign); }); this.onResize(); if (this.yesFullScreen) { this.amexioHeader.toArray()[0].maximizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.maxScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); this.amexioHeader.toArray()[0].minimizeWindow1.subscribe((obj: any) => { this.headerinst = obj.tempThis; this.maximizeflagchanged = this.minScreenChange(obj.tempEvent); obj.tempThis.fullscreenMaxCard = !this.maximizeflagchanged; }); } } adjustHeight(event: any) { this.onResize(); } // Calculate body size based on browser height onResize() { if (this.bodyheight) { let h = (window.innerHeight / 100) * this.bodyheight; if (this.cardHeader && this.cardHeader.nativeElement && this.cardHeader.nativeElement.offsetHeight) { h = h - this.cardHeader.nativeElement.offsetHeight; } if (this.cardFooter && this.cardFooter.nativeElement && this.cardFooter.nativeElement.offsetHeight) { h = h - this.cardFooter.nativeElement.offsetHeight; } if (this.bodyheight === 100) { h = h - 40; } this.minHeight = h; this.height = h; } } getContextMenu() { if (this.contextmenu && this.contextmenu.length > 0) { this.flag = true; this.addListner(); } } getListPosition(elementRef: any): boolean { const height = 240; if ((window.screen.height - elementRef.getBoundingClientRect().bottom) < height) { return true; } else { return false; } } loadContextMenu(rightClickData: any) { if (this.contextmenu && this.contextmenu.length > 0) { this.mouseLocation.left = rightClickData.event.clientX; this.mouseLocation.top = rightClickData.event.clientY; this.getContextMenu(); this.posixUp = this.getListPosition(rightClickData.ref); rightClickData.event.preventDefault(); rightClickData.event.stopPropagation(); this.rightClickNodeData = rightClickData.data; this.nodeRightClick.emit(rightClickData); } } rightClickDataEmit(Data: any) { this.rightClick.emit(Data); } addListner() { this.globalClickListenFunc = this.renderer.listen('document', 'click', (e: any) => { this.flag = false; if (!this.flag) { this.removeListner(); } }); } removeListner() { if (this.globalClickListenFunc)
} ngOnDestroy(): void { super.ngOnDestroy(); this.removeListner(); } // Theme Apply setColorPalette(themeClass: any) { this.themeCss = themeClass; } }
{ this.globalClickListenFunc(); }
conditional_block
move_imagery.py
from tempfile import TemporaryDirectory import psycopg2 conn = psycopg2.connect( database='innoter', user='postgres', password='postgres', host='192.168.0.107', port='5432') cursor = conn.cursor() dst_dir = r"\\nas1\storage\DG_archive\sat" path_list = [] cursor.execute( """SELECT path, order_id FROM geoarchive.dg_orders WHERE aero is not TRUE""") results = cursor.fetchall() for i, result in enumerate(results): zip_path, order_id = result[0], result[1] print(i + 1, zip_path) dst_filepath = os.path.join(dst_dir, os.path.basename(zip_path)) shutil.move(zip_path, dst_filepath) cursor.execute("""UPDATE geoarchive.dg_orders SET path = %s WHERE order_id = %s""", [dst_filepath, order_id, ], ) conn.commit() print('Готово...\n') # with zipfile.ZipFile(zip_path) as zf: # order_shape = [fnm for fnm in zf.namelist() if re.match(r'.+ORDER_SHAPE.+', fnm, re.I)] # if not order_shape: # # for fnm in zf.namelist(): # # if re.match(r'.+ORDER_SHAPE.+', fnm, re.I) is None: # cursor.execute("""UPDATE geoarchive.dg_orders # SET aero = TRUE # WHERE order_id = %s""", [order_id, ],) # conn.commit() # print(80*'=', order_id, 80*'=') # aero_list.append(order_id) # # print('\nDone:\n', len(aero_list)) # for i in aero_list: # print(i)
import os import shutil import re import zipfile import xml.etree.ElementTree as ET
random_line_split
move_imagery.py
import os import shutil import re import zipfile import xml.etree.ElementTree as ET from tempfile import TemporaryDirectory import psycopg2 conn = psycopg2.connect( database='innoter', user='postgres', password='postgres', host='192.168.0.107', port='5432') cursor = conn.cursor() dst_dir = r"\\nas1\storage\DG_archive\sat" path_list = [] cursor.execute( """SELECT path, order_id FROM geoarchive.dg_orders WHERE aero is not TRUE""") results = cursor.fetchall() for i, result in enumerate(results):
with zipfile.ZipFile(zip_path) as zf: # order_shape = [fnm for fnm in zf.namelist() if re.match(r'.+ORDER_SHAPE.+', fnm, re.I)] # if not order_shape: # # for fnm in zf.namelist(): # # if re.match(r'.+ORDER_SHAPE.+', fnm, re.I) is None: # cursor.execute("""UPDATE geoarchive.dg_orders # SET aero = TRUE # WHERE order_id = %s""", [order_id, ],) # conn.commit() # print(80*'=', order_id, 80*'=') # aero_list.append(order_id) # # print('\nDone:\n', len(aero_list)) # for i in aero_list: # print(i)
zip_path, order_id = result[0], result[1] print(i + 1, zip_path) dst_filepath = os.path.join(dst_dir, os.path.basename(zip_path)) shutil.move(zip_path, dst_filepath) cursor.execute("""UPDATE geoarchive.dg_orders SET path = %s WHERE order_id = %s""", [dst_filepath, order_id, ], ) conn.commit() print('Готово...\n') #
conditional_block
PlatformExpress.spec.ts
import {PlatformBuilder} from "@tsed/common"; import Sinon from "sinon"; import {expect} from "chai"; import {PlatformExpress} from "@tsed/platform-express"; const sandbox = Sinon.createSandbox(); class
{} describe("PlatformExpress", () => { describe("create()", () => { beforeEach(() => { sandbox.stub(PlatformBuilder, "create"); }); afterEach(() => sandbox.restore()); it("should create platform", () => { PlatformExpress.create(Server, {}); expect(PlatformBuilder.create).to.have.been.calledWithExactly(Server, { adapter: PlatformExpress }); }); }); describe("bootstrap()", () => { beforeEach(() => { sandbox.stub(PlatformBuilder, "bootstrap"); }); afterEach(() => sandbox.restore()); it("should create platform", async () => { await PlatformExpress.bootstrap(Server, {}); expect(PlatformBuilder.bootstrap).to.have.been.calledWithExactly(Server, { adapter: PlatformExpress }); }); }); });
Server
identifier_name
PlatformExpress.spec.ts
import {PlatformBuilder} from "@tsed/common"; import Sinon from "sinon"; import {expect} from "chai"; import {PlatformExpress} from "@tsed/platform-express";
describe("PlatformExpress", () => { describe("create()", () => { beforeEach(() => { sandbox.stub(PlatformBuilder, "create"); }); afterEach(() => sandbox.restore()); it("should create platform", () => { PlatformExpress.create(Server, {}); expect(PlatformBuilder.create).to.have.been.calledWithExactly(Server, { adapter: PlatformExpress }); }); }); describe("bootstrap()", () => { beforeEach(() => { sandbox.stub(PlatformBuilder, "bootstrap"); }); afterEach(() => sandbox.restore()); it("should create platform", async () => { await PlatformExpress.bootstrap(Server, {}); expect(PlatformBuilder.bootstrap).to.have.been.calledWithExactly(Server, { adapter: PlatformExpress }); }); }); });
const sandbox = Sinon.createSandbox(); class Server {}
random_line_split
form-list.component.spec.ts
import { TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectorRef } from '@angular/core'; import { Pipe, PipeTransform } from '@angular/core'; import { of } from 'rxjs'; import { Ng2FilterPipe } from '../../../shared/pipes/ng2-filter.pipe'; import { FormListService } from './form-list.service'; import { FormListComponent } from './form-list.component'; import { FormsResourceService } from '../../../openmrs-api/forms-resource.service'; import { FormOrderMetaDataService } from './form-order-metadata.service'; import { LocalStorageService } from '../../../utils/local-storage.service'; import { AppSettingsService } from '../../../app-settings/app-settings.service'; import { forms } from './forms'; import { HttpClientTestingModule } from '@angular/common/http/testing'; @Pipe({ name: 'translate' }) export class FakeTranslatePipe implements PipeTransform { transform(value: any, decimalPlaces: number): any { return value; } } describe('FormList Component', () => { const fakeChangeDetectorRef = { markForCheck: () => {} }; let fixture, nativeElement, comp; beforeEach(async(() => { TestBed.configureTestingModule({ schemas: [NO_ERRORS_SCHEMA], declarations: [FormListComponent, FakeTranslatePipe, Ng2FilterPipe], providers: [ LocalStorageService, AppSettingsService, { provide: ChangeDetectorRef, useValue: fakeChangeDetectorRef }, FormsResourceService, FormOrderMetaDataService, FormListService ], imports: [HttpClientTestingModule] }) .compileComponents() .then(() => { fixture = TestBed.createComponent(FormListComponent); comp = fixture.componentInstance; nativeElement = fixture.nativeElement; fixture.detectChanges(); }); })); afterEach(() => { TestBed.resetTestingModule(); }); it('should defined', inject([FormListService], (service: FormListService) => { expect(comp).toBeDefined(); })); it('should render form list properly given the forms are available', inject( [FormListService, FormOrderMetaDataService, FormsResourceService], ( service: FormListService, formOrderMetaDataService: FormOrderMetaDataService, formsResourceService: FormsResourceService ) => { const favourite = [ { name: 'form 5' }, { name: 'form 3' } ]; const defualtOrdering = [ { name: 'form 2' }, { name: 'form 3'
{ name: 'form 2', display: 'form 2', published: true, uuid: 'uuid2', version: '1.0', favourite: false }, { name: 'form 1', display: 'form 1', published: true, uuid: 'uuid', version: '1.0', favourite: false }, { name: 'form 4', display: 'form 4', published: true, uuid: 'uuid4', version: '1.0', favourite: false } ]; const favouriteFormsSpy = spyOn( formOrderMetaDataService, 'getFavouriteForm' ).and.returnValue(of(favourite)); const defaultOrderSpy = spyOn( formOrderMetaDataService, 'getDefaultFormOrder' ).and.returnValue(of(defualtOrdering)); const formListSpy = spyOn( formsResourceService, 'getForms' ).and.returnValue(of(forms)); const formServiceSpy = spyOn(service, 'getFormList').and.returnValue( of(forms) ); const toggleFavouriteSpy = spyOn(comp, 'toggleFavourite'); const formSelectedSypy = spyOn(comp, 'formSelected'); comp.ngOnInit(); fixture.detectChanges(); const formList = nativeElement.querySelectorAll('.list-group-item'); expect(comp.forms).toBeTruthy(); expect(comp.forms.length).toEqual(6); expect(formList).toBeTruthy(); expect(formList.length).toEqual(6); expect(formList[0].innerHTML).toContain('form 1'); } )); });
} ]; const expectedFormsList = [
random_line_split
form-list.component.spec.ts
import { TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ChangeDetectorRef } from '@angular/core'; import { Pipe, PipeTransform } from '@angular/core'; import { of } from 'rxjs'; import { Ng2FilterPipe } from '../../../shared/pipes/ng2-filter.pipe'; import { FormListService } from './form-list.service'; import { FormListComponent } from './form-list.component'; import { FormsResourceService } from '../../../openmrs-api/forms-resource.service'; import { FormOrderMetaDataService } from './form-order-metadata.service'; import { LocalStorageService } from '../../../utils/local-storage.service'; import { AppSettingsService } from '../../../app-settings/app-settings.service'; import { forms } from './forms'; import { HttpClientTestingModule } from '@angular/common/http/testing'; @Pipe({ name: 'translate' }) export class
implements PipeTransform { transform(value: any, decimalPlaces: number): any { return value; } } describe('FormList Component', () => { const fakeChangeDetectorRef = { markForCheck: () => {} }; let fixture, nativeElement, comp; beforeEach(async(() => { TestBed.configureTestingModule({ schemas: [NO_ERRORS_SCHEMA], declarations: [FormListComponent, FakeTranslatePipe, Ng2FilterPipe], providers: [ LocalStorageService, AppSettingsService, { provide: ChangeDetectorRef, useValue: fakeChangeDetectorRef }, FormsResourceService, FormOrderMetaDataService, FormListService ], imports: [HttpClientTestingModule] }) .compileComponents() .then(() => { fixture = TestBed.createComponent(FormListComponent); comp = fixture.componentInstance; nativeElement = fixture.nativeElement; fixture.detectChanges(); }); })); afterEach(() => { TestBed.resetTestingModule(); }); it('should defined', inject([FormListService], (service: FormListService) => { expect(comp).toBeDefined(); })); it('should render form list properly given the forms are available', inject( [FormListService, FormOrderMetaDataService, FormsResourceService], ( service: FormListService, formOrderMetaDataService: FormOrderMetaDataService, formsResourceService: FormsResourceService ) => { const favourite = [ { name: 'form 5' }, { name: 'form 3' } ]; const defualtOrdering = [ { name: 'form 2' }, { name: 'form 3' } ]; const expectedFormsList = [ { name: 'form 2', display: 'form 2', published: true, uuid: 'uuid2', version: '1.0', favourite: false }, { name: 'form 1', display: 'form 1', published: true, uuid: 'uuid', version: '1.0', favourite: false }, { name: 'form 4', display: 'form 4', published: true, uuid: 'uuid4', version: '1.0', favourite: false } ]; const favouriteFormsSpy = spyOn( formOrderMetaDataService, 'getFavouriteForm' ).and.returnValue(of(favourite)); const defaultOrderSpy = spyOn( formOrderMetaDataService, 'getDefaultFormOrder' ).and.returnValue(of(defualtOrdering)); const formListSpy = spyOn( formsResourceService, 'getForms' ).and.returnValue(of(forms)); const formServiceSpy = spyOn(service, 'getFormList').and.returnValue( of(forms) ); const toggleFavouriteSpy = spyOn(comp, 'toggleFavourite'); const formSelectedSypy = spyOn(comp, 'formSelected'); comp.ngOnInit(); fixture.detectChanges(); const formList = nativeElement.querySelectorAll('.list-group-item'); expect(comp.forms).toBeTruthy(); expect(comp.forms.length).toEqual(6); expect(formList).toBeTruthy(); expect(formList.length).toEqual(6); expect(formList[0].innerHTML).toContain('form 1'); } )); });
FakeTranslatePipe
identifier_name
main.rs
//! Module with the entry point of the binary. extern crate case; extern crate clap; extern crate conv; #[macro_use] extern crate log; extern crate rush; mod args; mod logging; mod rcfile; use std::error::Error; // for .cause() method use std::io::{self, Write}; use std::iter::repeat; use std::process::exit; use conv::TryFrom; use rush::Context; use args::InputMode; fn main() { logging::init().unwrap(); let opts = args::parse(); let before = opts.before.as_ref().map(|b| b as &str); let exprs: Vec<&str> = opts.expressions.iter().map(|e| e as &str).collect(); let after = opts.after.as_ref().map(|a| a as &str); match opts.input_mode { Some(mode) => { if let Err(error) = process_input(mode, before, &exprs, after) { handle_error(error); exit(1); } }, None => { if let Some(before) = before { println!("--before expression:"); print_ast(before); println!(""); } for expr in exprs { print_ast(expr); } if let Some(after) = after { println!(""); println!("--after expression:"); print_ast(after); } }, } } /// Process standard input through given expressions, writing results to stdout. fn process_input(mode: InputMode, before: Option<&str>, exprs: &[&str], after: Option<&str>) -> io::Result<()> { // Prepare a Context for the processing. // This includes evaluating any "before" expression within it. let mut context = Context::new(); try!(rcfile::load_into(&mut context) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, format!("Error processing startup file: {}", err)))); if let Some(before) = before { try!(rush::exec(before, &mut context)); } // Do the processing. // // If there is an "after" expression provided, it is that expression that should produce // the only output of the program. So we'll just consume whatever results would normally // be printed otherwise. if after.is_some() { // HACK: Because the intermediate results have to be printed out -- even if only to /dev/null // -- we have to ensure there is always a non-empty value to use as the intermediate result. // This is necessary especially since with --after (and --before), intermediate expressions // are likely to be just assignments (and the result of an assignment is empty). // // We can make sure there is always a value to print simply by adding one more expression // at the end of the chain. It so happens that zero (or any number) is compatible with // all the input modes, so let's use that. let mut exprs = exprs.to_vec(); exprs.push("0"); try!(apply_multi_ctx(mode, &mut context, &exprs, &mut io::sink())); } else { try!(apply_multi_ctx(mode, &mut context, exprs, &mut io::stdout())); } // Evaluate the "after" expression, if provided, and return it as the result. if let Some(after) = after
Ok(()) } /// Apply the expressions to the standard input with given mode. /// This forms the bulk of the input processing. #[inline] fn apply_multi_ctx(mode: InputMode, context: &mut Context, exprs: &[&str], mut output: &mut Write) -> io::Result<()> { let func: fn(_, _, _, _) -> _ = match mode { InputMode::String => rush::apply_string_multi_ctx, InputMode::Lines => rush::map_lines_multi_ctx, InputMode::Words => rush::map_words_multi_ctx, InputMode::Chars => rush::map_chars_multi_ctx, InputMode::Bytes => rush::map_bytes_multi_ctx, InputMode::Files => rush::map_files_multi_ctx, }; func(context, exprs, io::stdin(), &mut output) } /// Handle an error that occurred while processing the input. fn handle_error(error: io::Error) { writeln!(&mut io::stderr(), "error: {}", error).unwrap(); // Print the error causes as an indented "tree". let mut cause = error.cause(); let mut indent = 0; while let Some(error) = cause { writeln!(&mut io::stderr(), "{}{}{}", repeat(" ").take(CAUSE_PREFIX.len() * indent).collect::<String>(), CAUSE_PREFIX, error).unwrap(); indent += 1; cause = error.cause(); } } const CAUSE_PREFIX: &'static str = "└ "; // U+2514 /// Print the AST for given expression to stdout. fn print_ast(expr: &str) { debug!("Printing the AST of: {}", expr); match rush::parse(expr) { Ok(ast) => println!("{:?}", ast), Err(error) => { error!("{:?}", error); exit(1); }, } }
{ let result = try!(rush::eval(after, &mut context)); let result_string = try!(String::try_from(result) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))); // Make it so that the output always ends with a newline, // regardless whether it consists of a single value or multiple lines. return if result_string.ends_with("\n") { write!(&mut io::stdout(), "{}", result_string) } else { write!(&mut io::stdout(), "{}\n", result_string) }; }
conditional_block
main.rs
//! Module with the entry point of the binary. extern crate case; extern crate clap; extern crate conv; #[macro_use] extern crate log; extern crate rush; mod args; mod logging; mod rcfile; use std::error::Error; // for .cause() method use std::io::{self, Write}; use std::iter::repeat; use std::process::exit; use conv::TryFrom; use rush::Context; use args::InputMode; fn main() { logging::init().unwrap(); let opts = args::parse(); let before = opts.before.as_ref().map(|b| b as &str); let exprs: Vec<&str> = opts.expressions.iter().map(|e| e as &str).collect(); let after = opts.after.as_ref().map(|a| a as &str); match opts.input_mode { Some(mode) => { if let Err(error) = process_input(mode, before, &exprs, after) { handle_error(error); exit(1); } }, None => { if let Some(before) = before { println!("--before expression:"); print_ast(before); println!(""); } for expr in exprs { print_ast(expr); } if let Some(after) = after { println!(""); println!("--after expression:"); print_ast(after); } }, } } /// Process standard input through given expressions, writing results to stdout. fn process_input(mode: InputMode, before: Option<&str>, exprs: &[&str], after: Option<&str>) -> io::Result<()> { // Prepare a Context for the processing. // This includes evaluating any "before" expression within it. let mut context = Context::new(); try!(rcfile::load_into(&mut context) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, format!("Error processing startup file: {}", err))));
// Do the processing. // // If there is an "after" expression provided, it is that expression that should produce // the only output of the program. So we'll just consume whatever results would normally // be printed otherwise. if after.is_some() { // HACK: Because the intermediate results have to be printed out -- even if only to /dev/null // -- we have to ensure there is always a non-empty value to use as the intermediate result. // This is necessary especially since with --after (and --before), intermediate expressions // are likely to be just assignments (and the result of an assignment is empty). // // We can make sure there is always a value to print simply by adding one more expression // at the end of the chain. It so happens that zero (or any number) is compatible with // all the input modes, so let's use that. let mut exprs = exprs.to_vec(); exprs.push("0"); try!(apply_multi_ctx(mode, &mut context, &exprs, &mut io::sink())); } else { try!(apply_multi_ctx(mode, &mut context, exprs, &mut io::stdout())); } // Evaluate the "after" expression, if provided, and return it as the result. if let Some(after) = after { let result = try!(rush::eval(after, &mut context)); let result_string = try!(String::try_from(result) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))); // Make it so that the output always ends with a newline, // regardless whether it consists of a single value or multiple lines. return if result_string.ends_with("\n") { write!(&mut io::stdout(), "{}", result_string) } else { write!(&mut io::stdout(), "{}\n", result_string) }; } Ok(()) } /// Apply the expressions to the standard input with given mode. /// This forms the bulk of the input processing. #[inline] fn apply_multi_ctx(mode: InputMode, context: &mut Context, exprs: &[&str], mut output: &mut Write) -> io::Result<()> { let func: fn(_, _, _, _) -> _ = match mode { InputMode::String => rush::apply_string_multi_ctx, InputMode::Lines => rush::map_lines_multi_ctx, InputMode::Words => rush::map_words_multi_ctx, InputMode::Chars => rush::map_chars_multi_ctx, InputMode::Bytes => rush::map_bytes_multi_ctx, InputMode::Files => rush::map_files_multi_ctx, }; func(context, exprs, io::stdin(), &mut output) } /// Handle an error that occurred while processing the input. fn handle_error(error: io::Error) { writeln!(&mut io::stderr(), "error: {}", error).unwrap(); // Print the error causes as an indented "tree". let mut cause = error.cause(); let mut indent = 0; while let Some(error) = cause { writeln!(&mut io::stderr(), "{}{}{}", repeat(" ").take(CAUSE_PREFIX.len() * indent).collect::<String>(), CAUSE_PREFIX, error).unwrap(); indent += 1; cause = error.cause(); } } const CAUSE_PREFIX: &'static str = "└ "; // U+2514 /// Print the AST for given expression to stdout. fn print_ast(expr: &str) { debug!("Printing the AST of: {}", expr); match rush::parse(expr) { Ok(ast) => println!("{:?}", ast), Err(error) => { error!("{:?}", error); exit(1); }, } }
if let Some(before) = before { try!(rush::exec(before, &mut context)); }
random_line_split
main.rs
//! Module with the entry point of the binary. extern crate case; extern crate clap; extern crate conv; #[macro_use] extern crate log; extern crate rush; mod args; mod logging; mod rcfile; use std::error::Error; // for .cause() method use std::io::{self, Write}; use std::iter::repeat; use std::process::exit; use conv::TryFrom; use rush::Context; use args::InputMode; fn main() { logging::init().unwrap(); let opts = args::parse(); let before = opts.before.as_ref().map(|b| b as &str); let exprs: Vec<&str> = opts.expressions.iter().map(|e| e as &str).collect(); let after = opts.after.as_ref().map(|a| a as &str); match opts.input_mode { Some(mode) => { if let Err(error) = process_input(mode, before, &exprs, after) { handle_error(error); exit(1); } }, None => { if let Some(before) = before { println!("--before expression:"); print_ast(before); println!(""); } for expr in exprs { print_ast(expr); } if let Some(after) = after { println!(""); println!("--after expression:"); print_ast(after); } }, } } /// Process standard input through given expressions, writing results to stdout. fn
(mode: InputMode, before: Option<&str>, exprs: &[&str], after: Option<&str>) -> io::Result<()> { // Prepare a Context for the processing. // This includes evaluating any "before" expression within it. let mut context = Context::new(); try!(rcfile::load_into(&mut context) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, format!("Error processing startup file: {}", err)))); if let Some(before) = before { try!(rush::exec(before, &mut context)); } // Do the processing. // // If there is an "after" expression provided, it is that expression that should produce // the only output of the program. So we'll just consume whatever results would normally // be printed otherwise. if after.is_some() { // HACK: Because the intermediate results have to be printed out -- even if only to /dev/null // -- we have to ensure there is always a non-empty value to use as the intermediate result. // This is necessary especially since with --after (and --before), intermediate expressions // are likely to be just assignments (and the result of an assignment is empty). // // We can make sure there is always a value to print simply by adding one more expression // at the end of the chain. It so happens that zero (or any number) is compatible with // all the input modes, so let's use that. let mut exprs = exprs.to_vec(); exprs.push("0"); try!(apply_multi_ctx(mode, &mut context, &exprs, &mut io::sink())); } else { try!(apply_multi_ctx(mode, &mut context, exprs, &mut io::stdout())); } // Evaluate the "after" expression, if provided, and return it as the result. if let Some(after) = after { let result = try!(rush::eval(after, &mut context)); let result_string = try!(String::try_from(result) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))); // Make it so that the output always ends with a newline, // regardless whether it consists of a single value or multiple lines. return if result_string.ends_with("\n") { write!(&mut io::stdout(), "{}", result_string) } else { write!(&mut io::stdout(), "{}\n", result_string) }; } Ok(()) } /// Apply the expressions to the standard input with given mode. /// This forms the bulk of the input processing. #[inline] fn apply_multi_ctx(mode: InputMode, context: &mut Context, exprs: &[&str], mut output: &mut Write) -> io::Result<()> { let func: fn(_, _, _, _) -> _ = match mode { InputMode::String => rush::apply_string_multi_ctx, InputMode::Lines => rush::map_lines_multi_ctx, InputMode::Words => rush::map_words_multi_ctx, InputMode::Chars => rush::map_chars_multi_ctx, InputMode::Bytes => rush::map_bytes_multi_ctx, InputMode::Files => rush::map_files_multi_ctx, }; func(context, exprs, io::stdin(), &mut output) } /// Handle an error that occurred while processing the input. fn handle_error(error: io::Error) { writeln!(&mut io::stderr(), "error: {}", error).unwrap(); // Print the error causes as an indented "tree". let mut cause = error.cause(); let mut indent = 0; while let Some(error) = cause { writeln!(&mut io::stderr(), "{}{}{}", repeat(" ").take(CAUSE_PREFIX.len() * indent).collect::<String>(), CAUSE_PREFIX, error).unwrap(); indent += 1; cause = error.cause(); } } const CAUSE_PREFIX: &'static str = "└ "; // U+2514 /// Print the AST for given expression to stdout. fn print_ast(expr: &str) { debug!("Printing the AST of: {}", expr); match rush::parse(expr) { Ok(ast) => println!("{:?}", ast), Err(error) => { error!("{:?}", error); exit(1); }, } }
process_input
identifier_name
main.rs
//! Module with the entry point of the binary. extern crate case; extern crate clap; extern crate conv; #[macro_use] extern crate log; extern crate rush; mod args; mod logging; mod rcfile; use std::error::Error; // for .cause() method use std::io::{self, Write}; use std::iter::repeat; use std::process::exit; use conv::TryFrom; use rush::Context; use args::InputMode; fn main() { logging::init().unwrap(); let opts = args::parse(); let before = opts.before.as_ref().map(|b| b as &str); let exprs: Vec<&str> = opts.expressions.iter().map(|e| e as &str).collect(); let after = opts.after.as_ref().map(|a| a as &str); match opts.input_mode { Some(mode) => { if let Err(error) = process_input(mode, before, &exprs, after) { handle_error(error); exit(1); } }, None => { if let Some(before) = before { println!("--before expression:"); print_ast(before); println!(""); } for expr in exprs { print_ast(expr); } if let Some(after) = after { println!(""); println!("--after expression:"); print_ast(after); } }, } } /// Process standard input through given expressions, writing results to stdout. fn process_input(mode: InputMode, before: Option<&str>, exprs: &[&str], after: Option<&str>) -> io::Result<()> { // Prepare a Context for the processing. // This includes evaluating any "before" expression within it. let mut context = Context::new(); try!(rcfile::load_into(&mut context) .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, format!("Error processing startup file: {}", err)))); if let Some(before) = before { try!(rush::exec(before, &mut context)); } // Do the processing. // // If there is an "after" expression provided, it is that expression that should produce // the only output of the program. So we'll just consume whatever results would normally // be printed otherwise. if after.is_some() { // HACK: Because the intermediate results have to be printed out -- even if only to /dev/null // -- we have to ensure there is always a non-empty value to use as the intermediate result. // This is necessary especially since with --after (and --before), intermediate expressions // are likely to be just assignments (and the result of an assignment is empty). // // We can make sure there is always a value to print simply by adding one more expression // at the end of the chain. It so happens that zero (or any number) is compatible with // all the input modes, so let's use that. let mut exprs = exprs.to_vec(); exprs.push("0"); try!(apply_multi_ctx(mode, &mut context, &exprs, &mut io::sink())); } else { try!(apply_multi_ctx(mode, &mut context, exprs, &mut io::stdout())); } // Evaluate the "after" expression, if provided, and return it as the result. if let Some(after) = after { let result = try!(rush::eval(after, &mut context)); let result_string = try!(String::try_from(result) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))); // Make it so that the output always ends with a newline, // regardless whether it consists of a single value or multiple lines. return if result_string.ends_with("\n") { write!(&mut io::stdout(), "{}", result_string) } else { write!(&mut io::stdout(), "{}\n", result_string) }; } Ok(()) } /// Apply the expressions to the standard input with given mode. /// This forms the bulk of the input processing. #[inline] fn apply_multi_ctx(mode: InputMode, context: &mut Context, exprs: &[&str], mut output: &mut Write) -> io::Result<()>
/// Handle an error that occurred while processing the input. fn handle_error(error: io::Error) { writeln!(&mut io::stderr(), "error: {}", error).unwrap(); // Print the error causes as an indented "tree". let mut cause = error.cause(); let mut indent = 0; while let Some(error) = cause { writeln!(&mut io::stderr(), "{}{}{}", repeat(" ").take(CAUSE_PREFIX.len() * indent).collect::<String>(), CAUSE_PREFIX, error).unwrap(); indent += 1; cause = error.cause(); } } const CAUSE_PREFIX: &'static str = "└ "; // U+2514 /// Print the AST for given expression to stdout. fn print_ast(expr: &str) { debug!("Printing the AST of: {}", expr); match rush::parse(expr) { Ok(ast) => println!("{:?}", ast), Err(error) => { error!("{:?}", error); exit(1); }, } }
{ let func: fn(_, _, _, _) -> _ = match mode { InputMode::String => rush::apply_string_multi_ctx, InputMode::Lines => rush::map_lines_multi_ctx, InputMode::Words => rush::map_words_multi_ctx, InputMode::Chars => rush::map_chars_multi_ctx, InputMode::Bytes => rush::map_bytes_multi_ctx, InputMode::Files => rush::map_files_multi_ctx, }; func(context, exprs, io::stdin(), &mut output) }
identifier_body
aws_logs.py
# Copyright 2018 PerfKitBenchmarker Authors. 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. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token:
stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
get_cmd.extend(['--next-token', token])
conditional_block
aws_logs.py
# Copyright 2018 PerfKitBenchmarker Authors. 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. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None):
def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
"""Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout)
identifier_body
aws_logs.py
# Copyright 2018 PerfKitBenchmarker Authors. 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. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups',
'--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def _PostCreate(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
'--log-group-name-prefix', self.name,
random_line_split
aws_logs.py
# Copyright 2018 PerfKitBenchmarker Authors. 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. """Module containing classes related to AWS CloudWatch Logs.""" import json from perfkitbenchmarker import resource from perfkitbenchmarker import vm_util from perfkitbenchmarker.providers.aws import util class LogGroup(resource.BaseResource): """Class representing a CloudWatch log group.""" def __init__(self, region, name, retention_in_days=7): super(LogGroup, self).__init__() self.region = region self.name = name self.retention_in_days = retention_in_days def _Create(self): """Create the log group.""" create_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'create-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(create_cmd) def _Delete(self): """Delete the log group.""" delete_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'delete-log-group', '--log-group-name', self.name ] vm_util.IssueCommand(delete_cmd, raise_on_failure=False) def Exists(self): """Returns True if the log group exists.""" describe_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'describe-log-groups', '--log-group-name-prefix', self.name, '--no-paginate' ] stdout, _, _ = vm_util.IssueCommand(describe_cmd) log_groups = json.loads(stdout)['logGroups'] group = next((group for group in log_groups if group['logGroupName'] == self.name), None) return bool(group) def
(self): """Set the retention policy.""" put_cmd = util.AWS_PREFIX + [ '--region', self.region, 'logs', 'put-retention-policy', '--log-group-name', self.name, '--retention-in-days', str(self.retention_in_days) ] vm_util.IssueCommand(put_cmd) def GetLogs(region, stream_name, group_name, token=None): """Fetches the JSON formatted log stream starting at the token.""" get_cmd = util.AWS_PREFIX + [ '--region', region, 'logs', 'get-log-events', '--start-from-head', '--log-group-name', group_name, '--log-stream-name', stream_name, ] if token: get_cmd.extend(['--next-token', token]) stdout, _, _ = vm_util.IssueCommand(get_cmd) return json.loads(stdout) def GetLogStreamAsString(region, stream_name, log_group): """Returns the messages of the log stream as a string.""" log_lines = [] token = None events = [] while token is None or events: response = GetLogs(region, stream_name, log_group, token) events = response['events'] token = response['nextForwardToken'] for event in events: log_lines.append(event['message']) return '\n'.join(log_lines)
_PostCreate
identifier_name
test_directory.py
"""Tests for the directory module""" import os from translate.storage import directory class TestDirectory: """a test class to run tests on a test Pootle Server""" def setup_method(self, method): """sets up a test directory""" print("setup_method called on", self.__class__.__name__) self.testdir = "%s_testdir" % (self.__class__.__name__) self.cleardir(self.testdir) os.mkdir(self.testdir) def teardown_method(self, method): """removes the attributes set up by setup_method""" self.cleardir(self.testdir) def cleardir(self, dirname): """removes the given directory""" if os.path.exists(dirname): for dirpath, subdirs, filenames in os.walk(dirname, topdown=False): for name in filenames: os.remove(os.path.join(dirpath, name)) for name in subdirs: os.rmdir(os.path.join(dirpath, name)) if os.path.exists(dirname): os.rmdir(dirname) assert not os.path.exists(dirname) def touchfiles(self, dir, filenames, content=None): for filename in filenames: with open(os.path.join(dir, filename), "w") as fh: if content: fh.write(content) def mkdir(self, dir): """Makes a directory inside self.testdir.""" os.mkdir(os.path.join(self.testdir, dir)) def test_created(self): """test that the directory actually exists""" print(self.testdir) assert os.path.isdir(self.testdir) def test_basic(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] files.sort() self.touchfiles(self.testdir, files) d = directory.Directory(self.testdir) filenames = [name for dir, name in d.getfiles()] filenames.sort() assert filenames == files def test_structure(self): """Tests a small directory structure.""" files = ["a.po", "b.po", "c.po"] self.touchfiles(self.testdir, files) self.mkdir("bla") self.touchfiles(os.path.join(self.testdir, "bla"), files) d = directory.Directory(self.testdir) filenames = [name for dirname, name in d.getfiles()] filenames.sort() files = files * 2 files.sort() assert filenames == files def test_getunits(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] posource = '''msgid "bla"\nmsgstr "blabla"\n''' self.touchfiles(self.testdir, files, posource) d = directory.Directory(self.testdir) for unit in d.getunits():
assert len(d.getunits()) == 3
assert unit.target == "blabla"
conditional_block
test_directory.py
"""Tests for the directory module""" import os from translate.storage import directory class TestDirectory: """a test class to run tests on a test Pootle Server""" def setup_method(self, method): """sets up a test directory""" print("setup_method called on", self.__class__.__name__) self.testdir = "%s_testdir" % (self.__class__.__name__) self.cleardir(self.testdir) os.mkdir(self.testdir) def teardown_method(self, method): """removes the attributes set up by setup_method""" self.cleardir(self.testdir) def cleardir(self, dirname): """removes the given directory""" if os.path.exists(dirname): for dirpath, subdirs, filenames in os.walk(dirname, topdown=False): for name in filenames: os.remove(os.path.join(dirpath, name)) for name in subdirs: os.rmdir(os.path.join(dirpath, name)) if os.path.exists(dirname): os.rmdir(dirname) assert not os.path.exists(dirname) def touchfiles(self, dir, filenames, content=None): for filename in filenames: with open(os.path.join(dir, filename), "w") as fh: if content: fh.write(content) def mkdir(self, dir): """Makes a directory inside self.testdir.""" os.mkdir(os.path.join(self.testdir, dir)) def test_created(self): """test that the directory actually exists""" print(self.testdir) assert os.path.isdir(self.testdir) def test_basic(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] files.sort() self.touchfiles(self.testdir, files) d = directory.Directory(self.testdir) filenames = [name for dir, name in d.getfiles()] filenames.sort() assert filenames == files def
(self): """Tests a small directory structure.""" files = ["a.po", "b.po", "c.po"] self.touchfiles(self.testdir, files) self.mkdir("bla") self.touchfiles(os.path.join(self.testdir, "bla"), files) d = directory.Directory(self.testdir) filenames = [name for dirname, name in d.getfiles()] filenames.sort() files = files * 2 files.sort() assert filenames == files def test_getunits(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] posource = '''msgid "bla"\nmsgstr "blabla"\n''' self.touchfiles(self.testdir, files, posource) d = directory.Directory(self.testdir) for unit in d.getunits(): assert unit.target == "blabla" assert len(d.getunits()) == 3
test_structure
identifier_name
test_directory.py
"""Tests for the directory module""" import os from translate.storage import directory class TestDirectory: """a test class to run tests on a test Pootle Server""" def setup_method(self, method): """sets up a test directory""" print("setup_method called on", self.__class__.__name__) self.testdir = "%s_testdir" % (self.__class__.__name__) self.cleardir(self.testdir) os.mkdir(self.testdir) def teardown_method(self, method): """removes the attributes set up by setup_method""" self.cleardir(self.testdir) def cleardir(self, dirname): """removes the given directory""" if os.path.exists(dirname): for dirpath, subdirs, filenames in os.walk(dirname, topdown=False): for name in filenames: os.remove(os.path.join(dirpath, name)) for name in subdirs: os.rmdir(os.path.join(dirpath, name)) if os.path.exists(dirname): os.rmdir(dirname) assert not os.path.exists(dirname) def touchfiles(self, dir, filenames, content=None): for filename in filenames: with open(os.path.join(dir, filename), "w") as fh: if content: fh.write(content) def mkdir(self, dir): """Makes a directory inside self.testdir.""" os.mkdir(os.path.join(self.testdir, dir)) def test_created(self): """test that the directory actually exists""" print(self.testdir) assert os.path.isdir(self.testdir) def test_basic(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] files.sort() self.touchfiles(self.testdir, files) d = directory.Directory(self.testdir) filenames = [name for dir, name in d.getfiles()] filenames.sort() assert filenames == files def test_structure(self): """Tests a small directory structure.""" files = ["a.po", "b.po", "c.po"] self.touchfiles(self.testdir, files) self.mkdir("bla")
files = files * 2 files.sort() assert filenames == files def test_getunits(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] posource = '''msgid "bla"\nmsgstr "blabla"\n''' self.touchfiles(self.testdir, files, posource) d = directory.Directory(self.testdir) for unit in d.getunits(): assert unit.target == "blabla" assert len(d.getunits()) == 3
self.touchfiles(os.path.join(self.testdir, "bla"), files) d = directory.Directory(self.testdir) filenames = [name for dirname, name in d.getfiles()] filenames.sort()
random_line_split
test_directory.py
"""Tests for the directory module""" import os from translate.storage import directory class TestDirectory: """a test class to run tests on a test Pootle Server""" def setup_method(self, method): """sets up a test directory""" print("setup_method called on", self.__class__.__name__) self.testdir = "%s_testdir" % (self.__class__.__name__) self.cleardir(self.testdir) os.mkdir(self.testdir) def teardown_method(self, method): """removes the attributes set up by setup_method""" self.cleardir(self.testdir) def cleardir(self, dirname): """removes the given directory""" if os.path.exists(dirname): for dirpath, subdirs, filenames in os.walk(dirname, topdown=False): for name in filenames: os.remove(os.path.join(dirpath, name)) for name in subdirs: os.rmdir(os.path.join(dirpath, name)) if os.path.exists(dirname): os.rmdir(dirname) assert not os.path.exists(dirname) def touchfiles(self, dir, filenames, content=None): for filename in filenames: with open(os.path.join(dir, filename), "w") as fh: if content: fh.write(content) def mkdir(self, dir):
def test_created(self): """test that the directory actually exists""" print(self.testdir) assert os.path.isdir(self.testdir) def test_basic(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] files.sort() self.touchfiles(self.testdir, files) d = directory.Directory(self.testdir) filenames = [name for dir, name in d.getfiles()] filenames.sort() assert filenames == files def test_structure(self): """Tests a small directory structure.""" files = ["a.po", "b.po", "c.po"] self.touchfiles(self.testdir, files) self.mkdir("bla") self.touchfiles(os.path.join(self.testdir, "bla"), files) d = directory.Directory(self.testdir) filenames = [name for dirname, name in d.getfiles()] filenames.sort() files = files * 2 files.sort() assert filenames == files def test_getunits(self): """Tests basic functionality.""" files = ["a.po", "b.po", "c.po"] posource = '''msgid "bla"\nmsgstr "blabla"\n''' self.touchfiles(self.testdir, files, posource) d = directory.Directory(self.testdir) for unit in d.getunits(): assert unit.target == "blabla" assert len(d.getunits()) == 3
"""Makes a directory inside self.testdir.""" os.mkdir(os.path.join(self.testdir, dir))
identifier_body
config.rs
// In heavy WIP use std::fs::{ self, File }; use std::io::Read; use std::path::Path; use toml; use error::PackageError; use repository::RepositoryUrls; /// Represents the config file. #[derive(Debug, Deserialize)] pub struct Config { pub buffer_size: Option<u64>, // pub config_path: Option<String>, pub download_path: Option<String>, pub unpack_path: Option<String>, pub repository: Option<RepositoryUrls>, } impl Default for Config { fn default() -> Self { Self { buffer_size: Some(65536), // config_path: Some(String::from("~/.wiz/config/")), download_path: Some(String::from("~/.wiz/downloads/")), unpack_path: Some(String::from("~/.wiz/downloads/unpacked/")), repository: Some(RepositoryUrls(Vec::new())), } } } impl Config { /// Read the config file from the config path specified in `path`. /// If the config file is read & parsed properly, it should return /// a `Config`. pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> { let mut content = String::new(); // Check whether there are tons of configs in the path if path.as_ref().is_dir() { // Read every config files and put them into a string, if it is for entry in fs::read_dir(path)? { let entry = entry?; let mut config = File::open(entry.path())?; config.read_to_string(&mut content)?; } } else { // Read the config file into a string, if it isn't let mut config = File::open(path)?; config.read_to_string(&mut content)?; } // Try to parse the string, and convert it into a `Config`. let config = content.parse::<toml::Value>()?; let config = config.try_into::<Self>()?; Ok(config) } /// This function sets the None(s) in the config, to the default values. pub fn fill_with_default(mut self) -> Self
}
{ // Destructuring the default configs into individual variables. let Self { buffer_size: buf_size, download_path: dl_path, unpack_path: unpk_path, repository: repo, } = Self::default(); /// Internal macro, to ease the implementation of `fill_with_default`. macro_rules! set_on_none { ($dest:ident, $key:ident, $value:expr) => ( match $dest { Self { $key: ref mut x, .. } => { match x { &mut Some(_) => {}, &mut None => *x = $value, } } } // Wait for RFC-2086 to be implemented first. /* [allow(irrefutable_let_pattern)] if let Config { $key: mut x, .. } = $dest { if let None = x { x = $value } } */ ); }; // If there are None(s), set them to the default value. set_on_none!(self, buffer_size, buf_size); set_on_none!(self, download_path, dl_path); set_on_none!(self, unpack_path, unpk_path); set_on_none!(self, repository, repo); self }
identifier_body
config.rs
// In heavy WIP use std::fs::{ self, File }; use std::io::Read; use std::path::Path; use toml; use error::PackageError; use repository::RepositoryUrls; /// Represents the config file. #[derive(Debug, Deserialize)] pub struct Config { pub buffer_size: Option<u64>, // pub config_path: Option<String>, pub download_path: Option<String>, pub unpack_path: Option<String>, pub repository: Option<RepositoryUrls>, } impl Default for Config { fn default() -> Self { Self { buffer_size: Some(65536), // config_path: Some(String::from("~/.wiz/config/")), download_path: Some(String::from("~/.wiz/downloads/")), unpack_path: Some(String::from("~/.wiz/downloads/unpacked/")), repository: Some(RepositoryUrls(Vec::new())), } } } impl Config { /// Read the config file from the config path specified in `path`. /// If the config file is read & parsed properly, it should return /// a `Config`. pub fn
<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> { let mut content = String::new(); // Check whether there are tons of configs in the path if path.as_ref().is_dir() { // Read every config files and put them into a string, if it is for entry in fs::read_dir(path)? { let entry = entry?; let mut config = File::open(entry.path())?; config.read_to_string(&mut content)?; } } else { // Read the config file into a string, if it isn't let mut config = File::open(path)?; config.read_to_string(&mut content)?; } // Try to parse the string, and convert it into a `Config`. let config = content.parse::<toml::Value>()?; let config = config.try_into::<Self>()?; Ok(config) } /// This function sets the None(s) in the config, to the default values. pub fn fill_with_default(mut self) -> Self { // Destructuring the default configs into individual variables. let Self { buffer_size: buf_size, download_path: dl_path, unpack_path: unpk_path, repository: repo, } = Self::default(); /// Internal macro, to ease the implementation of `fill_with_default`. macro_rules! set_on_none { ($dest:ident, $key:ident, $value:expr) => ( match $dest { Self { $key: ref mut x, .. } => { match x { &mut Some(_) => {}, &mut None => *x = $value, } } } // Wait for RFC-2086 to be implemented first. /* [allow(irrefutable_let_pattern)] if let Config { $key: mut x, .. } = $dest { if let None = x { x = $value } } */ ); }; // If there are None(s), set them to the default value. set_on_none!(self, buffer_size, buf_size); set_on_none!(self, download_path, dl_path); set_on_none!(self, unpack_path, unpk_path); set_on_none!(self, repository, repo); self } }
read_from
identifier_name
config.rs
// In heavy WIP use std::fs::{ self, File }; use std::io::Read; use std::path::Path; use toml; use error::PackageError; use repository::RepositoryUrls; /// Represents the config file. #[derive(Debug, Deserialize)] pub struct Config { pub buffer_size: Option<u64>, // pub config_path: Option<String>, pub download_path: Option<String>, pub unpack_path: Option<String>, pub repository: Option<RepositoryUrls>, } impl Default for Config { fn default() -> Self { Self { buffer_size: Some(65536), // config_path: Some(String::from("~/.wiz/config/")), download_path: Some(String::from("~/.wiz/downloads/")), unpack_path: Some(String::from("~/.wiz/downloads/unpacked/")), repository: Some(RepositoryUrls(Vec::new())), } } } impl Config { /// Read the config file from the config path specified in `path`. /// If the config file is read & parsed properly, it should return /// a `Config`. pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> { let mut content = String::new(); // Check whether there are tons of configs in the path if path.as_ref().is_dir()
else { // Read the config file into a string, if it isn't let mut config = File::open(path)?; config.read_to_string(&mut content)?; } // Try to parse the string, and convert it into a `Config`. let config = content.parse::<toml::Value>()?; let config = config.try_into::<Self>()?; Ok(config) } /// This function sets the None(s) in the config, to the default values. pub fn fill_with_default(mut self) -> Self { // Destructuring the default configs into individual variables. let Self { buffer_size: buf_size, download_path: dl_path, unpack_path: unpk_path, repository: repo, } = Self::default(); /// Internal macro, to ease the implementation of `fill_with_default`. macro_rules! set_on_none { ($dest:ident, $key:ident, $value:expr) => ( match $dest { Self { $key: ref mut x, .. } => { match x { &mut Some(_) => {}, &mut None => *x = $value, } } } // Wait for RFC-2086 to be implemented first. /* [allow(irrefutable_let_pattern)] if let Config { $key: mut x, .. } = $dest { if let None = x { x = $value } } */ ); }; // If there are None(s), set them to the default value. set_on_none!(self, buffer_size, buf_size); set_on_none!(self, download_path, dl_path); set_on_none!(self, unpack_path, unpk_path); set_on_none!(self, repository, repo); self } }
{ // Read every config files and put them into a string, if it is for entry in fs::read_dir(path)? { let entry = entry?; let mut config = File::open(entry.path())?; config.read_to_string(&mut content)?; } }
conditional_block
config.rs
// In heavy WIP use std::fs::{ self, File }; use std::io::Read; use std::path::Path; use toml; use error::PackageError; use repository::RepositoryUrls; /// Represents the config file. #[derive(Debug, Deserialize)] pub struct Config { pub buffer_size: Option<u64>, // pub config_path: Option<String>, pub download_path: Option<String>, pub unpack_path: Option<String>, pub repository: Option<RepositoryUrls>, } impl Default for Config { fn default() -> Self { Self { buffer_size: Some(65536), // config_path: Some(String::from("~/.wiz/config/")), download_path: Some(String::from("~/.wiz/downloads/")), unpack_path: Some(String::from("~/.wiz/downloads/unpacked/")), repository: Some(RepositoryUrls(Vec::new())), } } } impl Config { /// Read the config file from the config path specified in `path`. /// If the config file is read & parsed properly, it should return /// a `Config`. pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Self, PackageError> { let mut content = String::new(); // Check whether there are tons of configs in the path if path.as_ref().is_dir() { // Read every config files and put them into a string, if it is for entry in fs::read_dir(path)? { let entry = entry?; let mut config = File::open(entry.path())?; config.read_to_string(&mut content)?; } } else { // Read the config file into a string, if it isn't let mut config = File::open(path)?; config.read_to_string(&mut content)?; } // Try to parse the string, and convert it into a `Config`. let config = content.parse::<toml::Value>()?; let config = config.try_into::<Self>()?; Ok(config) } /// This function sets the None(s) in the config, to the default values. pub fn fill_with_default(mut self) -> Self { // Destructuring the default configs into individual variables. let Self { buffer_size: buf_size, download_path: dl_path, unpack_path: unpk_path, repository: repo, } = Self::default(); /// Internal macro, to ease the implementation of `fill_with_default`.
match $dest { Self { $key: ref mut x, .. } => { match x { &mut Some(_) => {}, &mut None => *x = $value, } } } // Wait for RFC-2086 to be implemented first. /* [allow(irrefutable_let_pattern)] if let Config { $key: mut x, .. } = $dest { if let None = x { x = $value } } */ ); }; // If there are None(s), set them to the default value. set_on_none!(self, buffer_size, buf_size); set_on_none!(self, download_path, dl_path); set_on_none!(self, unpack_path, unpk_path); set_on_none!(self, repository, repo); self } }
macro_rules! set_on_none { ($dest:ident, $key:ident, $value:expr) => (
random_line_split
entities.js
// since it is a class both letter are capitilized // player class. Shows the image that the player is, the height and width //also the shape of it game.PlayerEntity = me.Entity.extend({ init: function(x, y, settings) { //leads to set super fuction below //use these fucntions to orgainize code this.setSuper(x, y); //leads to set player timer function this.setPlayerTimers(); //leads to the function attribute this.setAttributes(); //sets type so that creep can collide with it this.type = "PlayerEntity"; //leads to set flags function this.setFlags(); //where ever the player goes the screen follows me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //leads to add animation fucntion below //used to organize code this.addAnimation(); //sets currect animation this.renderable.setCurrentAnimation("idle"); }, //function sets up the super class setSuper: function (x, y){ this._super(me.Entity, 'init', [x, y, { image: "player", width: 64, height: 64, spritewidth: "64", spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 100, 70)).toPolygon(); } }]); }, //takes all the code from other parts and puts it in a function to make it more organized //timers set setPlayerTimers: function(){ //keeps track of what time it is for the game this.now = new Date().getTime(); //lets the character hit the other characters over and over again this.lastHit = this.now; //controls when the next spear spons this.lastSpear = this.now; //controls when the time of the last attack was this.lastAttack = new Date().getTime(); }, //set attributes function //leads up to line 11 setAttributes: function(){ //sets players health //uses the global variable that helps the player loose health //variable located in game.js this.heatlth = game.data.playerHealth; //sets the speed of the character this.body.setVelocity(game.data.playerMoveSpeed, 20); //a gold is added when the creep dies from attack this.attack = game.data.playerAttack; }, //used to organize our code //leads to line of code above setFlags: function(){ //keeps track of what direction your character is going this.facing = "right"; //players death function //what happens if the player dies this.dead = false; //linked to update class or attacking fuctnion //used to orgainze code this.attacking = false; }, //leads to add animation line of code above //used to orgainze code addAnimation: function(){ //this anmiantion is used for when we are just standing this.renderable.addAnimation("idle", [78]); //adds animation to orcs/ characters walk // 80 at the end is the speed of the walk // the numbers in the brackets are the different pics we are using for the animation this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80); //adds animation to the action attack this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80); }, update: function(delta){ //updates this.now this.now = new Date().getTime(); //checks to see if our player has or had not died //leads to function below //used to organize code this.dead = this.checkIfDead(); //leads to fucntion below //organizes code this.checkKeyPressesAndMove (); //checks the characters ability keys this.checkAbilityKeys(); //organizes our code this.setAnimation(); //checks for collisions me.collision.check(this, true, this.collideHandler.bind(this), true); // tells the code above to work this.body.update(delta); //another call to the parent class this._super(me.Entity, "update", [delta]); return true; }, //fucntion leads up to line of code //organizes our code checkIfDead: function(){ //makes the player die if (this.health <= 0){ return true; } return false; }, //organizes my code //leads up to code under update fucntion checkKeyPressesAndMove: function(){ //checks and sees if the right key is pressed if(me.input.isKeyPressed("right")){ //function below //organizes code this.moveRight(); //if we press the wrong button then the else statement will go into effect // if statement binds the left key so that we can move left }else if(me.input.isKeyPressed("left")){ //linked to fucntion below //organizes code this.moveLeft(); }else{ this.body.vel.x = 0; } //not in else statement because jumping involves the y axis not the x // binds the space bar so that we can jump if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){ //linked to code below //organizes code this.jump(); } //attack function //orgainzes update function this.attacking = me.input.isKeyPressed("attack"); }, //organizes code //linked to pressandmove fucntion moveRight: function(){ // adds the position of my x by adding the velocity defined above in // setVelocity() and multiplying it by me.timer.tick // me.timer.tick makes the movement look smooth this.body.vel.x += this.body.accel.x * me.timer.tick; //checks what way your character is going this.facing = "right"; //flips the character so he doesnt go backwards this.flipX(true); }, //organizes code //linked to pressandmove fucntion moveLeft: function(){ this.facing = "left"; this.body.vel.x -=this.body.accel.x * me.timer.tick; this.flipX(false); }, //organizes code //linked to pressandmove fucntion jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; me.audio.play("stomp"); }, //checks the players ability. Like if they are elligable for an update or more gold checkAbilityKeys: function(){ //checks if the skill key is pressed if(me.input.isKeyPressed("skill1")){ //this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ //this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, //enables the player to throw the spear throwSpear: function(){ //sets the spear timer to tell when the next spear can spon if((this.now-this.lastSpear) >= game.data.spearTimer*1000 && game.data.ability3 > 0){ //controls when the spear spons this.lastSpear = this.now; //bulids a spear and puts it into the world var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, //linked to attack fucntion in update class setAnimation: function(){ //if attack key is pressed character will attack //linked to checkKeyPressesandMove fucntion to organize code if(this.attacking){ //checks if it has gone through its animation stage if(!this.renderable.isCurrentAnimation("attack")){ //sets the current animation to attackand once that is over // goes back to the idle animation this.renderable.setCurrentAnimation("attack", "idle"); //makes it so that the next time we start this sequence we begin // from the the first animation, not wherever we left off when we // switched to another animation //this.renderable.setCurrentAnimationFrame(); me.audio.play("jump"); } } //checks if character is moving //checks that we dont have an attack animation going on else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //if statement checks to see whats going on with the character if(!this.renderable.isCurrentAnimation("walk")){ this.renderable.setCurrentAnimation("walk"); } }//else statement fixes the error of the character walking backwards else if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("idle"); } }, loseHealth: function(damage){ //player loses health this.health = this.health - damage; //prints out what our health is console.log(this.health); }, // tells us if we collide with the enemy base collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //organizes the code this.collideWithEnemyBase(response); //makes the creep loose health }else if(response.b.type==='EnemyCreep'){ //orgainzes the code this.collideWithEnemyCreep(response); } }, collideWithEnemyBase:function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; //checks to see when character collides with enemy base console.log("xdif " + xdif + "ydif " + ydif); //jumping through the top of the enemy base if(ydif<-40 && xdif< 70 && xdif>-35){ this.body.falling = false; this.body.vel.y = -1; } //the the player goes more than the number placed then it will stop moving //facing code allows us to move away from the base // xdif makes sure that both if statements wont trigger else if(xdif>-35 && this.facing==='right' && (xdif<0)){ //stops player from moving if they hit the base this.body.vel.x = 0; // moves player back a bit ////this.pos.x = this.pos.x - 1; //else if statement is used if the character is facing left }else if(xdif<70 && this.facing==='left' && xdif>0){ this.body.vel.x = 0; ////this.pos.x = this.pos.x +1; } //checks if the current animation is attack //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //cosole.log("tower Hit"); this.lastHit = this.now; //character dies/looses health when the player attacks the creep more than a certain number of attacks response.b.loseHealth(game.data.playerAttack); } }, collideWithEnemyCreep:function(response){ //lets you loose health if you are facing the x axis var xdif = this.pos.x - response.b.pos.x; //lets you loose health if you are facing the y axis var ydif = this.pos.y - response.b.pos.y; //orgainizes code this.stopMovement(xdif); //linked to check attack fucntion if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ //loose health if character comes in form the right or left //makes it so that we cant walk right into the base if (xdif>0){ ////this.pos.x = this.pos.x + 1; //keeps track of what way we are facing if(this.facing==="left"){ this.body.vel.x = 0; } }else{ this.pos.x = this.pos.x - 1; //keeps track of what way we are facing if(this.facing==="right")
} }, checkAttack: function(xdif, ydif){ //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer //checks the absolute value of the y and x difference && (Math.abs(ydif) <=40) && (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")) ){ //updates the timers this.lastHit = this.now; return true; } //if the attack check is false it will return false return false; }, hitCreep: function (response) { //linked to the line of code above //if the creepe health is less than our attack, execute code in if statement if(response.b.health <= game.data.playerAttack){ //adds one gold for a creep kill game.data.gold += 1; console.log("Current gold: " + game.data.gold); } //the player dies or looses health if it is attacking for too long //timer response.b.loseHealth(game.data.playerAttack); } });
{ this.body.vel.x = 0; }
conditional_block
entities.js
// since it is a class both letter are capitilized // player class. Shows the image that the player is, the height and width //also the shape of it game.PlayerEntity = me.Entity.extend({ init: function(x, y, settings) { //leads to set super fuction below //use these fucntions to orgainize code this.setSuper(x, y); //leads to set player timer function this.setPlayerTimers(); //leads to the function attribute this.setAttributes(); //sets type so that creep can collide with it this.type = "PlayerEntity"; //leads to set flags function this.setFlags(); //where ever the player goes the screen follows me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH); //leads to add animation fucntion below //used to organize code this.addAnimation(); //sets currect animation this.renderable.setCurrentAnimation("idle"); }, //function sets up the super class setSuper: function (x, y){ this._super(me.Entity, 'init', [x, y, { image: "player", width: 64, height: 64, spritewidth: "64", spriteheight: "64", getShape: function(){ return(new me.Rect(0, 0, 100, 70)).toPolygon(); } }]); }, //takes all the code from other parts and puts it in a function to make it more organized //timers set setPlayerTimers: function(){ //keeps track of what time it is for the game this.now = new Date().getTime(); //lets the character hit the other characters over and over again this.lastHit = this.now; //controls when the next spear spons this.lastSpear = this.now; //controls when the time of the last attack was this.lastAttack = new Date().getTime(); }, //set attributes function //leads up to line 11 setAttributes: function(){ //sets players health //uses the global variable that helps the player loose health //variable located in game.js this.heatlth = game.data.playerHealth; //sets the speed of the character
this.body.setVelocity(game.data.playerMoveSpeed, 20); //a gold is added when the creep dies from attack this.attack = game.data.playerAttack; }, //used to organize our code //leads to line of code above setFlags: function(){ //keeps track of what direction your character is going this.facing = "right"; //players death function //what happens if the player dies this.dead = false; //linked to update class or attacking fuctnion //used to orgainze code this.attacking = false; }, //leads to add animation line of code above //used to orgainze code addAnimation: function(){ //this anmiantion is used for when we are just standing this.renderable.addAnimation("idle", [78]); //adds animation to orcs/ characters walk // 80 at the end is the speed of the walk // the numbers in the brackets are the different pics we are using for the animation this.renderable.addAnimation("walk", [117, 118, 119, 120, 121, 122, 123, 124, 125], 80); //adds animation to the action attack this.renderable.addAnimation("attack", [65, 66, 67, 68, 69, 70, 71, 72], 80); }, update: function(delta){ //updates this.now this.now = new Date().getTime(); //checks to see if our player has or had not died //leads to function below //used to organize code this.dead = this.checkIfDead(); //leads to fucntion below //organizes code this.checkKeyPressesAndMove (); //checks the characters ability keys this.checkAbilityKeys(); //organizes our code this.setAnimation(); //checks for collisions me.collision.check(this, true, this.collideHandler.bind(this), true); // tells the code above to work this.body.update(delta); //another call to the parent class this._super(me.Entity, "update", [delta]); return true; }, //fucntion leads up to line of code //organizes our code checkIfDead: function(){ //makes the player die if (this.health <= 0){ return true; } return false; }, //organizes my code //leads up to code under update fucntion checkKeyPressesAndMove: function(){ //checks and sees if the right key is pressed if(me.input.isKeyPressed("right")){ //function below //organizes code this.moveRight(); //if we press the wrong button then the else statement will go into effect // if statement binds the left key so that we can move left }else if(me.input.isKeyPressed("left")){ //linked to fucntion below //organizes code this.moveLeft(); }else{ this.body.vel.x = 0; } //not in else statement because jumping involves the y axis not the x // binds the space bar so that we can jump if(me.input.isKeyPressed("jump") && !this.body.jumping && !this.body.falling){ //linked to code below //organizes code this.jump(); } //attack function //orgainzes update function this.attacking = me.input.isKeyPressed("attack"); }, //organizes code //linked to pressandmove fucntion moveRight: function(){ // adds the position of my x by adding the velocity defined above in // setVelocity() and multiplying it by me.timer.tick // me.timer.tick makes the movement look smooth this.body.vel.x += this.body.accel.x * me.timer.tick; //checks what way your character is going this.facing = "right"; //flips the character so he doesnt go backwards this.flipX(true); }, //organizes code //linked to pressandmove fucntion moveLeft: function(){ this.facing = "left"; this.body.vel.x -=this.body.accel.x * me.timer.tick; this.flipX(false); }, //organizes code //linked to pressandmove fucntion jump: function(){ this.body.jumping = true; this.body.vel.y -= this.body.accel.y * me.timer.tick; me.audio.play("stomp"); }, //checks the players ability. Like if they are elligable for an update or more gold checkAbilityKeys: function(){ //checks if the skill key is pressed if(me.input.isKeyPressed("skill1")){ //this.speedBurst(); }else if(me.input.isKeyPressed("skill2")){ //this.eatCreep(); }else if(me.input.isKeyPressed("skill3")){ this.throwSpear(); } }, //enables the player to throw the spear throwSpear: function(){ //sets the spear timer to tell when the next spear can spon if((this.now-this.lastSpear) >= game.data.spearTimer*1000 && game.data.ability3 > 0){ //controls when the spear spons this.lastSpear = this.now; //bulids a spear and puts it into the world var spear = me.pool.pull("spear", this.pos.x, this.pos.y, {}, this.facing); me.game.world.addChild(spear, 10); } }, //linked to attack fucntion in update class setAnimation: function(){ //if attack key is pressed character will attack //linked to checkKeyPressesandMove fucntion to organize code if(this.attacking){ //checks if it has gone through its animation stage if(!this.renderable.isCurrentAnimation("attack")){ //sets the current animation to attackand once that is over // goes back to the idle animation this.renderable.setCurrentAnimation("attack", "idle"); //makes it so that the next time we start this sequence we begin // from the the first animation, not wherever we left off when we // switched to another animation //this.renderable.setCurrentAnimationFrame(); me.audio.play("jump"); } } //checks if character is moving //checks that we dont have an attack animation going on else if(this.body.vel.x !== 0 && !this.renderable.isCurrentAnimation("attack")){ //if statement checks to see whats going on with the character if(!this.renderable.isCurrentAnimation("walk")){ this.renderable.setCurrentAnimation("walk"); } }//else statement fixes the error of the character walking backwards else if(!this.renderable.isCurrentAnimation("attack")){ this.renderable.setCurrentAnimation("idle"); } }, loseHealth: function(damage){ //player loses health this.health = this.health - damage; //prints out what our health is console.log(this.health); }, // tells us if we collide with the enemy base collideHandler: function(response){ if(response.b.type==='EnemyBaseEntity'){ //organizes the code this.collideWithEnemyBase(response); //makes the creep loose health }else if(response.b.type==='EnemyCreep'){ //orgainzes the code this.collideWithEnemyCreep(response); } }, collideWithEnemyBase:function(response){ var ydif = this.pos.y - response.b.pos.y; var xdif = this.pos.x - response.b.pos.x; //checks to see when character collides with enemy base console.log("xdif " + xdif + "ydif " + ydif); //jumping through the top of the enemy base if(ydif<-40 && xdif< 70 && xdif>-35){ this.body.falling = false; this.body.vel.y = -1; } //the the player goes more than the number placed then it will stop moving //facing code allows us to move away from the base // xdif makes sure that both if statements wont trigger else if(xdif>-35 && this.facing==='right' && (xdif<0)){ //stops player from moving if they hit the base this.body.vel.x = 0; // moves player back a bit ////this.pos.x = this.pos.x - 1; //else if statement is used if the character is facing left }else if(xdif<70 && this.facing==='left' && xdif>0){ this.body.vel.x = 0; ////this.pos.x = this.pos.x +1; } //checks if the current animation is attack //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer){ //cosole.log("tower Hit"); this.lastHit = this.now; //character dies/looses health when the player attacks the creep more than a certain number of attacks response.b.loseHealth(game.data.playerAttack); } }, collideWithEnemyCreep:function(response){ //lets you loose health if you are facing the x axis var xdif = this.pos.x - response.b.pos.x; //lets you loose health if you are facing the y axis var ydif = this.pos.y - response.b.pos.y; //orgainizes code this.stopMovement(xdif); //linked to check attack fucntion if(this.checkAttack(xdif, ydif)){ this.hitCreep(response); }; }, stopMovement: function(xdif){ //loose health if character comes in form the right or left //makes it so that we cant walk right into the base if (xdif>0){ ////this.pos.x = this.pos.x + 1; //keeps track of what way we are facing if(this.facing==="left"){ this.body.vel.x = 0; } }else{ this.pos.x = this.pos.x - 1; //keeps track of what way we are facing if(this.facing==="right"){ this.body.vel.x = 0; } } }, checkAttack: function(xdif, ydif){ //uses the global variable that helps the player loose health //variable located in game.js if(this.renderable.isCurrentAnimation("attack") && this.now-this.lastHit >= game.data.playerAttackTimer //checks the absolute value of the y and x difference && (Math.abs(ydif) <=40) && (((xdif>0) && this.facing==="left") || ((xdif<0) && this.facing==="right")) ){ //updates the timers this.lastHit = this.now; return true; } //if the attack check is false it will return false return false; }, hitCreep: function (response) { //linked to the line of code above //if the creepe health is less than our attack, execute code in if statement if(response.b.health <= game.data.playerAttack){ //adds one gold for a creep kill game.data.gold += 1; console.log("Current gold: " + game.data.gold); } //the player dies or looses health if it is attacking for too long //timer response.b.loseHealth(game.data.playerAttack); } });
random_line_split
augment_test.py
# Copyright 2017 Google Inc. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from isl import augment from isl import test_util from isl import util flags = tf.flags test = tf.test lt = tf.contrib.labeled_tensor FLAGS = flags.FLAGS class CorruptTest(test_util.Base): def setUp(self): super(CorruptTest, self).setUp() self.signal_lt = lt.select(self.input_lt, {'mask': util.slice_1(False)}) rc = lt.ReshapeCoder(['z', 'channel', 'mask'], ['channel']) self.corrupt_coded_lt = augment.corrupt(0.1, 0.05, 0.1, rc.encode(self.signal_lt)) self.corrupt_lt = rc.decode(self.corrupt_coded_lt) def test_name(self): self.assertIn('corrupt', self.corrupt_coded_lt.name) def test(self): self.assertEqual(self.corrupt_lt.axes, self.signal_lt.axes) self.save_images('corrupt', [self.get_images('', self.corrupt_lt)]) self.assert_images_near('corrupt', True) class AugmentTest(test_util.Base): def setUp(self): super(AugmentTest, self).setUp() ap = augment.AugmentParameters(0.1, 0.05, 0.1) self.input_augment_lt, self.target_augment_lt = augment.augment( ap, self.input_lt, self.target_lt) def test_name(self): self.assertIn('augment/input', self.input_augment_lt.name) self.assertIn('augment/target', self.target_augment_lt.name) def
(self): self.assertEqual(self.input_augment_lt.axes, self.input_lt.axes) self.assertEqual(self.target_augment_lt.axes, self.target_lt.axes) self.save_images('augment', [ self.get_images('input_', self.input_augment_lt), self.get_images('target_', self.target_augment_lt) ]) self.assert_images_near('augment', True) if __name__ == '__main__': test.main()
test
identifier_name
augment_test.py
# Copyright 2017 Google Inc. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from isl import augment from isl import test_util from isl import util flags = tf.flags test = tf.test lt = tf.contrib.labeled_tensor FLAGS = flags.FLAGS class CorruptTest(test_util.Base): def setUp(self): super(CorruptTest, self).setUp() self.signal_lt = lt.select(self.input_lt, {'mask': util.slice_1(False)}) rc = lt.ReshapeCoder(['z', 'channel', 'mask'], ['channel']) self.corrupt_coded_lt = augment.corrupt(0.1, 0.05, 0.1, rc.encode(self.signal_lt)) self.corrupt_lt = rc.decode(self.corrupt_coded_lt) def test_name(self): self.assertIn('corrupt', self.corrupt_coded_lt.name) def test(self): self.assertEqual(self.corrupt_lt.axes, self.signal_lt.axes) self.save_images('corrupt', [self.get_images('', self.corrupt_lt)]) self.assert_images_near('corrupt', True) class AugmentTest(test_util.Base): def setUp(self): super(AugmentTest, self).setUp() ap = augment.AugmentParameters(0.1, 0.05, 0.1) self.input_augment_lt, self.target_augment_lt = augment.augment( ap, self.input_lt, self.target_lt) def test_name(self): self.assertIn('augment/input', self.input_augment_lt.name) self.assertIn('augment/target', self.target_augment_lt.name) def test(self): self.assertEqual(self.input_augment_lt.axes, self.input_lt.axes) self.assertEqual(self.target_augment_lt.axes, self.target_lt.axes) self.save_images('augment', [ self.get_images('input_', self.input_augment_lt), self.get_images('target_', self.target_augment_lt) ]) self.assert_images_near('augment', True) if __name__ == '__main__':
test.main()
conditional_block
augment_test.py
# Copyright 2017 Google Inc. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from isl import augment from isl import test_util from isl import util flags = tf.flags test = tf.test lt = tf.contrib.labeled_tensor FLAGS = flags.FLAGS class CorruptTest(test_util.Base):
def setUp(self): super(CorruptTest, self).setUp() self.signal_lt = lt.select(self.input_lt, {'mask': util.slice_1(False)}) rc = lt.ReshapeCoder(['z', 'channel', 'mask'], ['channel']) self.corrupt_coded_lt = augment.corrupt(0.1, 0.05, 0.1, rc.encode(self.signal_lt)) self.corrupt_lt = rc.decode(self.corrupt_coded_lt) def test_name(self): self.assertIn('corrupt', self.corrupt_coded_lt.name) def test(self): self.assertEqual(self.corrupt_lt.axes, self.signal_lt.axes) self.save_images('corrupt', [self.get_images('', self.corrupt_lt)]) self.assert_images_near('corrupt', True) class AugmentTest(test_util.Base): def setUp(self): super(AugmentTest, self).setUp() ap = augment.AugmentParameters(0.1, 0.05, 0.1) self.input_augment_lt, self.target_augment_lt = augment.augment( ap, self.input_lt, self.target_lt) def test_name(self): self.assertIn('augment/input', self.input_augment_lt.name) self.assertIn('augment/target', self.target_augment_lt.name) def test(self): self.assertEqual(self.input_augment_lt.axes, self.input_lt.axes) self.assertEqual(self.target_augment_lt.axes, self.target_lt.axes) self.save_images('augment', [ self.get_images('input_', self.input_augment_lt), self.get_images('target_', self.target_augment_lt) ]) self.assert_images_near('augment', True) if __name__ == '__main__': test.main()
random_line_split
augment_test.py
# Copyright 2017 Google Inc. # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # pylint: disable=g-bad-import-order from isl import augment from isl import test_util from isl import util flags = tf.flags test = tf.test lt = tf.contrib.labeled_tensor FLAGS = flags.FLAGS class CorruptTest(test_util.Base): def setUp(self): super(CorruptTest, self).setUp() self.signal_lt = lt.select(self.input_lt, {'mask': util.slice_1(False)}) rc = lt.ReshapeCoder(['z', 'channel', 'mask'], ['channel']) self.corrupt_coded_lt = augment.corrupt(0.1, 0.05, 0.1, rc.encode(self.signal_lt)) self.corrupt_lt = rc.decode(self.corrupt_coded_lt) def test_name(self): self.assertIn('corrupt', self.corrupt_coded_lt.name) def test(self): self.assertEqual(self.corrupt_lt.axes, self.signal_lt.axes) self.save_images('corrupt', [self.get_images('', self.corrupt_lt)]) self.assert_images_near('corrupt', True) class AugmentTest(test_util.Base): def setUp(self):
def test_name(self): self.assertIn('augment/input', self.input_augment_lt.name) self.assertIn('augment/target', self.target_augment_lt.name) def test(self): self.assertEqual(self.input_augment_lt.axes, self.input_lt.axes) self.assertEqual(self.target_augment_lt.axes, self.target_lt.axes) self.save_images('augment', [ self.get_images('input_', self.input_augment_lt), self.get_images('target_', self.target_augment_lt) ]) self.assert_images_near('augment', True) if __name__ == '__main__': test.main()
super(AugmentTest, self).setUp() ap = augment.AugmentParameters(0.1, 0.05, 0.1) self.input_augment_lt, self.target_augment_lt = augment.augment( ap, self.input_lt, self.target_lt)
identifier_body
config.py
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from buildbot.config import BuilderConfig from twisted.python import log from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.triggerable import Triggerable from inplace_build import InplaceBuildFactory from project import Project from setup_build import SetupBuildFactory from worker import Worker from pprint import pformat class NamedList(list): def named_set(self, elem): self.named_del(elem.name) self.append(elem) def named_del(self, name): for elem in self: if elem.name == name: self.remove(elem) def named_get(self, name): for elem in self: if elem.name == name: return elem def clear(self): del self[:] @property def names(self): return map(lambda elem: elem.name, self) class Wrapper(dict): """ Wrapper for the configuration dictionary """ def __init__(self, **kwargs): super(Wrapper, self).__init__(**kwargs) self._inplace_workers = NamedList() self._projects = NamedList() @property def builders(self): return self.named_list('builders') @property def schedulers(self): return self.named_list('schedulers') @property def change_source(self): return self.named_list('change_source') @property def workers(self): return self.named_list('workers') @property def inplace_workers(self): return self._inplace_workers @property def projects(self): return self._projects def named_list(self, key): if key not in self: self[key] = NamedList() return self[key] def load_workers(self, path): Worker.load(path, self.inplace_workers, self.workers) def load_projects(self, path): Project.load(path, self.projects) DUMMY_NAME = "Dummy" DUMMY_TRIGGER = "Trigger_Dummy" def setup_inplace(self):
def project_profile_worker_names(self, profile): return [worker.name for worker in self.inplace_workers if set(profile.setups).issubset(set(worker.setups)) and profile.platform in worker.platforms] def setup_project_inplace(self, project): self.setup_inplace() for worker in self.inplace_workers: log.msg("Got worker '%s' for platform %s and setups %s" % (worker.name, pformat(worker.platforms), pformat(worker.setups)), system='Inplace Config') for profile in project.inplace.profiles: worker_names = self.project_profile_worker_names(profile) if not worker_names: log.msg("Failed to find worker for platform '%s' and setups '%s' (project '%s')" % (profile.platform, pformat(profile.setups), project.name), system='Inplace Config') continue # profile not executable builder_name = "_".join([project.name, profile.platform, profile.name]) trigger_name = _project_profile_trigger_name(project.name, profile) build_factory = SetupBuildFactory(self, project, profile) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=build_factory)) self.schedulers.named_set(Triggerable(name=trigger_name, builderNames=[builder_name])) def project_trigger_names(self, project): return [ _project_profile_trigger_name(project.name, profile) for profile in project.inplace.profiles if self.project_profile_worker_names(profile)] def _project_profile_trigger_name(project_name, profile): return "_".join([project_name, profile.platform, profile.name, "Trigger"])
self.builders.clear() self.schedulers.clear() builder_name = self.DUMMY_NAME trigger_name = self.DUMMY_TRIGGER worker_names = self.inplace_workers.names self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=BuildFactory())) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) for project in self.projects: builder_name = "%s_Builder" % project.name trigger_name = "Force_%s_Build" % project.name builder_factory = InplaceBuildFactory(self, project) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=builder_factory)) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name]))
identifier_body
config.py
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from buildbot.config import BuilderConfig from twisted.python import log from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.triggerable import Triggerable from inplace_build import InplaceBuildFactory from project import Project from setup_build import SetupBuildFactory from worker import Worker from pprint import pformat class NamedList(list): def named_set(self, elem): self.named_del(elem.name) self.append(elem) def named_del(self, name): for elem in self: if elem.name == name: self.remove(elem) def
(self, name): for elem in self: if elem.name == name: return elem def clear(self): del self[:] @property def names(self): return map(lambda elem: elem.name, self) class Wrapper(dict): """ Wrapper for the configuration dictionary """ def __init__(self, **kwargs): super(Wrapper, self).__init__(**kwargs) self._inplace_workers = NamedList() self._projects = NamedList() @property def builders(self): return self.named_list('builders') @property def schedulers(self): return self.named_list('schedulers') @property def change_source(self): return self.named_list('change_source') @property def workers(self): return self.named_list('workers') @property def inplace_workers(self): return self._inplace_workers @property def projects(self): return self._projects def named_list(self, key): if key not in self: self[key] = NamedList() return self[key] def load_workers(self, path): Worker.load(path, self.inplace_workers, self.workers) def load_projects(self, path): Project.load(path, self.projects) DUMMY_NAME = "Dummy" DUMMY_TRIGGER = "Trigger_Dummy" def setup_inplace(self): self.builders.clear() self.schedulers.clear() builder_name = self.DUMMY_NAME trigger_name = self.DUMMY_TRIGGER worker_names = self.inplace_workers.names self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=BuildFactory())) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) for project in self.projects: builder_name = "%s_Builder" % project.name trigger_name = "Force_%s_Build" % project.name builder_factory = InplaceBuildFactory(self, project) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=builder_factory)) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) def project_profile_worker_names(self, profile): return [worker.name for worker in self.inplace_workers if set(profile.setups).issubset(set(worker.setups)) and profile.platform in worker.platforms] def setup_project_inplace(self, project): self.setup_inplace() for worker in self.inplace_workers: log.msg("Got worker '%s' for platform %s and setups %s" % (worker.name, pformat(worker.platforms), pformat(worker.setups)), system='Inplace Config') for profile in project.inplace.profiles: worker_names = self.project_profile_worker_names(profile) if not worker_names: log.msg("Failed to find worker for platform '%s' and setups '%s' (project '%s')" % (profile.platform, pformat(profile.setups), project.name), system='Inplace Config') continue # profile not executable builder_name = "_".join([project.name, profile.platform, profile.name]) trigger_name = _project_profile_trigger_name(project.name, profile) build_factory = SetupBuildFactory(self, project, profile) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=build_factory)) self.schedulers.named_set(Triggerable(name=trigger_name, builderNames=[builder_name])) def project_trigger_names(self, project): return [ _project_profile_trigger_name(project.name, profile) for profile in project.inplace.profiles if self.project_profile_worker_names(profile)] def _project_profile_trigger_name(project_name, profile): return "_".join([project_name, profile.platform, profile.name, "Trigger"])
named_get
identifier_name
config.py
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from buildbot.config import BuilderConfig from twisted.python import log from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.triggerable import Triggerable from inplace_build import InplaceBuildFactory from project import Project from setup_build import SetupBuildFactory from worker import Worker from pprint import pformat class NamedList(list): def named_set(self, elem): self.named_del(elem.name) self.append(elem) def named_del(self, name): for elem in self: if elem.name == name: self.remove(elem) def named_get(self, name): for elem in self: if elem.name == name: return elem def clear(self):
@property def names(self): return map(lambda elem: elem.name, self) class Wrapper(dict): """ Wrapper for the configuration dictionary """ def __init__(self, **kwargs): super(Wrapper, self).__init__(**kwargs) self._inplace_workers = NamedList() self._projects = NamedList() @property def builders(self): return self.named_list('builders') @property def schedulers(self): return self.named_list('schedulers') @property def change_source(self): return self.named_list('change_source') @property def workers(self): return self.named_list('workers') @property def inplace_workers(self): return self._inplace_workers @property def projects(self): return self._projects def named_list(self, key): if key not in self: self[key] = NamedList() return self[key] def load_workers(self, path): Worker.load(path, self.inplace_workers, self.workers) def load_projects(self, path): Project.load(path, self.projects) DUMMY_NAME = "Dummy" DUMMY_TRIGGER = "Trigger_Dummy" def setup_inplace(self): self.builders.clear() self.schedulers.clear() builder_name = self.DUMMY_NAME trigger_name = self.DUMMY_TRIGGER worker_names = self.inplace_workers.names self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=BuildFactory())) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) for project in self.projects: builder_name = "%s_Builder" % project.name trigger_name = "Force_%s_Build" % project.name builder_factory = InplaceBuildFactory(self, project) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=builder_factory)) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) def project_profile_worker_names(self, profile): return [worker.name for worker in self.inplace_workers if set(profile.setups).issubset(set(worker.setups)) and profile.platform in worker.platforms] def setup_project_inplace(self, project): self.setup_inplace() for worker in self.inplace_workers: log.msg("Got worker '%s' for platform %s and setups %s" % (worker.name, pformat(worker.platforms), pformat(worker.setups)), system='Inplace Config') for profile in project.inplace.profiles: worker_names = self.project_profile_worker_names(profile) if not worker_names: log.msg("Failed to find worker for platform '%s' and setups '%s' (project '%s')" % (profile.platform, pformat(profile.setups), project.name), system='Inplace Config') continue # profile not executable builder_name = "_".join([project.name, profile.platform, profile.name]) trigger_name = _project_profile_trigger_name(project.name, profile) build_factory = SetupBuildFactory(self, project, profile) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=build_factory)) self.schedulers.named_set(Triggerable(name=trigger_name, builderNames=[builder_name])) def project_trigger_names(self, project): return [ _project_profile_trigger_name(project.name, profile) for profile in project.inplace.profiles if self.project_profile_worker_names(profile)] def _project_profile_trigger_name(project_name, profile): return "_".join([project_name, profile.platform, profile.name, "Trigger"])
del self[:]
random_line_split
config.py
""" Buildbot inplace config (C) Copyright 2015 HicknHack Software GmbH The original code can be found at: https://github.com/hicknhack-software/buildbot-inplace-config Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from buildbot.config import BuilderConfig from twisted.python import log from buildbot.process.factory import BuildFactory from buildbot.schedulers.forcesched import ForceScheduler from buildbot.schedulers.triggerable import Triggerable from inplace_build import InplaceBuildFactory from project import Project from setup_build import SetupBuildFactory from worker import Worker from pprint import pformat class NamedList(list): def named_set(self, elem): self.named_del(elem.name) self.append(elem) def named_del(self, name): for elem in self: if elem.name == name: self.remove(elem) def named_get(self, name): for elem in self: if elem.name == name: return elem def clear(self): del self[:] @property def names(self): return map(lambda elem: elem.name, self) class Wrapper(dict): """ Wrapper for the configuration dictionary """ def __init__(self, **kwargs): super(Wrapper, self).__init__(**kwargs) self._inplace_workers = NamedList() self._projects = NamedList() @property def builders(self): return self.named_list('builders') @property def schedulers(self): return self.named_list('schedulers') @property def change_source(self): return self.named_list('change_source') @property def workers(self): return self.named_list('workers') @property def inplace_workers(self): return self._inplace_workers @property def projects(self): return self._projects def named_list(self, key): if key not in self:
return self[key] def load_workers(self, path): Worker.load(path, self.inplace_workers, self.workers) def load_projects(self, path): Project.load(path, self.projects) DUMMY_NAME = "Dummy" DUMMY_TRIGGER = "Trigger_Dummy" def setup_inplace(self): self.builders.clear() self.schedulers.clear() builder_name = self.DUMMY_NAME trigger_name = self.DUMMY_TRIGGER worker_names = self.inplace_workers.names self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=BuildFactory())) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) for project in self.projects: builder_name = "%s_Builder" % project.name trigger_name = "Force_%s_Build" % project.name builder_factory = InplaceBuildFactory(self, project) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=builder_factory)) self.schedulers.named_set(ForceScheduler(name=trigger_name, builderNames=[builder_name])) def project_profile_worker_names(self, profile): return [worker.name for worker in self.inplace_workers if set(profile.setups).issubset(set(worker.setups)) and profile.platform in worker.platforms] def setup_project_inplace(self, project): self.setup_inplace() for worker in self.inplace_workers: log.msg("Got worker '%s' for platform %s and setups %s" % (worker.name, pformat(worker.platforms), pformat(worker.setups)), system='Inplace Config') for profile in project.inplace.profiles: worker_names = self.project_profile_worker_names(profile) if not worker_names: log.msg("Failed to find worker for platform '%s' and setups '%s' (project '%s')" % (profile.platform, pformat(profile.setups), project.name), system='Inplace Config') continue # profile not executable builder_name = "_".join([project.name, profile.platform, profile.name]) trigger_name = _project_profile_trigger_name(project.name, profile) build_factory = SetupBuildFactory(self, project, profile) self.builders.named_set(BuilderConfig(name=builder_name, workernames=worker_names, factory=build_factory)) self.schedulers.named_set(Triggerable(name=trigger_name, builderNames=[builder_name])) def project_trigger_names(self, project): return [ _project_profile_trigger_name(project.name, profile) for profile in project.inplace.profiles if self.project_profile_worker_names(profile)] def _project_profile_trigger_name(project_name, profile): return "_".join([project_name, profile.platform, profile.name, "Trigger"])
self[key] = NamedList()
conditional_block
state.js
/* State * @class * @classdesc This class reprensent an automata state, a sub-type of a generic Node */ k.data.State = (function(_super) { 'use strict'; /* jshint latedef:false */ k.utils.obj.inherit(state, _super); /* * Constructor Automata State * * @constructor * @param {[ItemRule]} options.items Array of item rules that initialy compone this state * @param {[Object]} options.transitions Array of object that initialy compone this node * @param {[Node]} options.nodes Array of State instances that are children of this State */ function state (options) { _super.apply(this, arguments); k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator k.utils.obj.defineProperty(this, '_items'); k.utils.obj.defineProperty(this, '_registerItems'); k.utils.obj.defineProperty(this, '_condencedView'); k.utils.obj.defineProperty(this, '_unprocessedItems'); this.isAcceptanceState = false; this._items = options.items || []; this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : []; options.items = null; this._registerItems = {}; this._registerItemRules(); } /* @method REgister the list of item rules of the current stateso they are assesible by its id * @returns {Void} */ state.prototype._registerItemRules = function () { k.utils.obj.each(this._items, function (itemRule) { this._registerItems[itemRule.getIdentity()] = itemRule; }, this); }; state.constants = { AcceptanceStateName: 'AcceptanceState' }; /* @method Get the next unprocessed item rule * @returns {ItemRule} Next Item Rule */ state.prototype.getNextItem = function() { return this._unprocessedItems.splice(0,1)[0]; }; /* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added * @param {[ItemRule]} itemRules Array of item rules to add into the state * @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy * @returns {void} Nothing */ state.prototype.addItems = function(itemRules, options) { this._id = null; k.utils.obj.each(itemRules, function (itemRule) { // The same item rule can be added more than once if the grammar has loops. // For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS if (!this._registerItems[itemRule.getIdentity()]) { this._registerItems[itemRule.getIdentity()] = itemRule; this._items.push(itemRule); this._unprocessedItems.push(itemRule); } else if (!options || !options.notMergeLookAhead) { //As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads var original_itemRule = this._registerItems[itemRule.getIdentity()]; if (itemRule.lookAhead && itemRule.lookAhead.length) { original_itemRule.lookAhead = original_itemRule.lookAhead || []; itemRule.lookAhead = itemRule.lookAhead || []; var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead), original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length; this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;}); var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item) { return unprocessed_item.getIdentity() === itemRule.getIdentity(); }).length > 0; //If there were changes in the lookAhead and the rule is not already queued. if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued) { this._unprocessedItems.push(itemRule); } } } }, this); }; /* @method Convert the current state to its string representation * @returns {String} formatted string */ state.prototype.toString = function() { var strResult = 'ID: ' + this.getIdentity() + '\n' + this._items.join('\n') + '\nTRANSITIONS:\n'; k.utils.obj.each(this.transitions, function (transition) { strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n'; }); return strResult; }; /* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype.getCondencedString = function() { if(!this._condencedView) { this._condencedView = this._generateCondencedString(); } return this._condencedView; }; /* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype._generateCondencedString = function() { return k.utils.obj.map( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (item) { return item.rule.index; }).join('-'); }; /* @method Generates an ID that identify this state from any other state * @returns {String} Generated ID */
if (this.isAcceptanceState) { return state.constants.AcceptanceStateName; } else if (!this._items.length) { return _super.prototype._generateIdentity.apply(this, arguments); } return k.utils.obj.reduce( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (acc, item) { return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')'; }, ''); }; /* @method Returns a copy the items contained in the current state * @returns {[ItemRule]} Array of cloned item rules */ state.prototype.getItems = function() { return k.utils.obj.map(this._items, function(item) { return item.clone(); }); }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {[ItemRule]} Array of current item rules */ state.prototype.getOriginalItems = function() { return this._items; }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */ state.prototype.getOriginalItemById = function(id) { return this._registerItems[id]; }; /** @method Get the list of all supported symbol which are valid to generata transition from the current state. * @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */ state.prototype.getSupportedTransitionSymbols = function() { var itemsAux = {}, result = [], symbol; k.utils.obj.each(this._items, function (item) { symbol = item.getCurrentSymbol(); if (symbol) { if (itemsAux[symbol.name]) { itemsAux[symbol.name].push(item); } else { itemsAux[symbol.name] = [item]; result.push({ symbol: symbol, items: itemsAux[symbol.name] }); } } }); return result; }; /* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful * @param {Symbol} symbol Symbol use to make the transition, like the name of the transition * @param {State} state Destination state arrived when moving with the specified tranisiotn * @returns {Object} Transition object */ state.prototype._generateNewTransition = function (symbol, state) { return { symbol: symbol, state: state }; }; /* @method Returns the list of item rules contained in the current state that are reduce item rules. * @returns {[ItemRule]} Recude Item Rules */ state.prototype.getRecudeItems = function () { return k.utils.obj.filter(this._items, function (item) { return item.isReduce(); }); }; return state; })(k.data.Node);
state.prototype._generateIdentity = function() {
random_line_split
state.js
/* State * @class * @classdesc This class reprensent an automata state, a sub-type of a generic Node */ k.data.State = (function(_super) { 'use strict'; /* jshint latedef:false */ k.utils.obj.inherit(state, _super); /* * Constructor Automata State * * @constructor * @param {[ItemRule]} options.items Array of item rules that initialy compone this state * @param {[Object]} options.transitions Array of object that initialy compone this node * @param {[Node]} options.nodes Array of State instances that are children of this State */ function state (options)
/* @method REgister the list of item rules of the current stateso they are assesible by its id * @returns {Void} */ state.prototype._registerItemRules = function () { k.utils.obj.each(this._items, function (itemRule) { this._registerItems[itemRule.getIdentity()] = itemRule; }, this); }; state.constants = { AcceptanceStateName: 'AcceptanceState' }; /* @method Get the next unprocessed item rule * @returns {ItemRule} Next Item Rule */ state.prototype.getNextItem = function() { return this._unprocessedItems.splice(0,1)[0]; }; /* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added * @param {[ItemRule]} itemRules Array of item rules to add into the state * @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy * @returns {void} Nothing */ state.prototype.addItems = function(itemRules, options) { this._id = null; k.utils.obj.each(itemRules, function (itemRule) { // The same item rule can be added more than once if the grammar has loops. // For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS if (!this._registerItems[itemRule.getIdentity()]) { this._registerItems[itemRule.getIdentity()] = itemRule; this._items.push(itemRule); this._unprocessedItems.push(itemRule); } else if (!options || !options.notMergeLookAhead) { //As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads var original_itemRule = this._registerItems[itemRule.getIdentity()]; if (itemRule.lookAhead && itemRule.lookAhead.length) { original_itemRule.lookAhead = original_itemRule.lookAhead || []; itemRule.lookAhead = itemRule.lookAhead || []; var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead), original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length; this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;}); var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item) { return unprocessed_item.getIdentity() === itemRule.getIdentity(); }).length > 0; //If there were changes in the lookAhead and the rule is not already queued. if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued) { this._unprocessedItems.push(itemRule); } } } }, this); }; /* @method Convert the current state to its string representation * @returns {String} formatted string */ state.prototype.toString = function() { var strResult = 'ID: ' + this.getIdentity() + '\n' + this._items.join('\n') + '\nTRANSITIONS:\n'; k.utils.obj.each(this.transitions, function (transition) { strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n'; }); return strResult; }; /* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype.getCondencedString = function() { if(!this._condencedView) { this._condencedView = this._generateCondencedString(); } return this._condencedView; }; /* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype._generateCondencedString = function() { return k.utils.obj.map( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (item) { return item.rule.index; }).join('-'); }; /* @method Generates an ID that identify this state from any other state * @returns {String} Generated ID */ state.prototype._generateIdentity = function() { if (this.isAcceptanceState) { return state.constants.AcceptanceStateName; } else if (!this._items.length) { return _super.prototype._generateIdentity.apply(this, arguments); } return k.utils.obj.reduce( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (acc, item) { return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')'; }, ''); }; /* @method Returns a copy the items contained in the current state * @returns {[ItemRule]} Array of cloned item rules */ state.prototype.getItems = function() { return k.utils.obj.map(this._items, function(item) { return item.clone(); }); }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {[ItemRule]} Array of current item rules */ state.prototype.getOriginalItems = function() { return this._items; }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */ state.prototype.getOriginalItemById = function(id) { return this._registerItems[id]; }; /** @method Get the list of all supported symbol which are valid to generata transition from the current state. * @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */ state.prototype.getSupportedTransitionSymbols = function() { var itemsAux = {}, result = [], symbol; k.utils.obj.each(this._items, function (item) { symbol = item.getCurrentSymbol(); if (symbol) { if (itemsAux[symbol.name]) { itemsAux[symbol.name].push(item); } else { itemsAux[symbol.name] = [item]; result.push({ symbol: symbol, items: itemsAux[symbol.name] }); } } }); return result; }; /* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful * @param {Symbol} symbol Symbol use to make the transition, like the name of the transition * @param {State} state Destination state arrived when moving with the specified tranisiotn * @returns {Object} Transition object */ state.prototype._generateNewTransition = function (symbol, state) { return { symbol: symbol, state: state }; }; /* @method Returns the list of item rules contained in the current state that are reduce item rules. * @returns {[ItemRule]} Recude Item Rules */ state.prototype.getRecudeItems = function () { return k.utils.obj.filter(this._items, function (item) { return item.isReduce(); }); }; return state; })(k.data.Node);
{ _super.apply(this, arguments); k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator k.utils.obj.defineProperty(this, '_items'); k.utils.obj.defineProperty(this, '_registerItems'); k.utils.obj.defineProperty(this, '_condencedView'); k.utils.obj.defineProperty(this, '_unprocessedItems'); this.isAcceptanceState = false; this._items = options.items || []; this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : []; options.items = null; this._registerItems = {}; this._registerItemRules(); }
identifier_body
state.js
/* State * @class * @classdesc This class reprensent an automata state, a sub-type of a generic Node */ k.data.State = (function(_super) { 'use strict'; /* jshint latedef:false */ k.utils.obj.inherit(state, _super); /* * Constructor Automata State * * @constructor * @param {[ItemRule]} options.items Array of item rules that initialy compone this state * @param {[Object]} options.transitions Array of object that initialy compone this node * @param {[Node]} options.nodes Array of State instances that are children of this State */ function
(options) { _super.apply(this, arguments); k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator k.utils.obj.defineProperty(this, '_items'); k.utils.obj.defineProperty(this, '_registerItems'); k.utils.obj.defineProperty(this, '_condencedView'); k.utils.obj.defineProperty(this, '_unprocessedItems'); this.isAcceptanceState = false; this._items = options.items || []; this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : []; options.items = null; this._registerItems = {}; this._registerItemRules(); } /* @method REgister the list of item rules of the current stateso they are assesible by its id * @returns {Void} */ state.prototype._registerItemRules = function () { k.utils.obj.each(this._items, function (itemRule) { this._registerItems[itemRule.getIdentity()] = itemRule; }, this); }; state.constants = { AcceptanceStateName: 'AcceptanceState' }; /* @method Get the next unprocessed item rule * @returns {ItemRule} Next Item Rule */ state.prototype.getNextItem = function() { return this._unprocessedItems.splice(0,1)[0]; }; /* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added * @param {[ItemRule]} itemRules Array of item rules to add into the state * @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy * @returns {void} Nothing */ state.prototype.addItems = function(itemRules, options) { this._id = null; k.utils.obj.each(itemRules, function (itemRule) { // The same item rule can be added more than once if the grammar has loops. // For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS if (!this._registerItems[itemRule.getIdentity()]) { this._registerItems[itemRule.getIdentity()] = itemRule; this._items.push(itemRule); this._unprocessedItems.push(itemRule); } else if (!options || !options.notMergeLookAhead) { //As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads var original_itemRule = this._registerItems[itemRule.getIdentity()]; if (itemRule.lookAhead && itemRule.lookAhead.length) { original_itemRule.lookAhead = original_itemRule.lookAhead || []; itemRule.lookAhead = itemRule.lookAhead || []; var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead), original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length; this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;}); var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item) { return unprocessed_item.getIdentity() === itemRule.getIdentity(); }).length > 0; //If there were changes in the lookAhead and the rule is not already queued. if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued) { this._unprocessedItems.push(itemRule); } } } }, this); }; /* @method Convert the current state to its string representation * @returns {String} formatted string */ state.prototype.toString = function() { var strResult = 'ID: ' + this.getIdentity() + '\n' + this._items.join('\n') + '\nTRANSITIONS:\n'; k.utils.obj.each(this.transitions, function (transition) { strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n'; }); return strResult; }; /* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype.getCondencedString = function() { if(!this._condencedView) { this._condencedView = this._generateCondencedString(); } return this._condencedView; }; /* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype._generateCondencedString = function() { return k.utils.obj.map( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (item) { return item.rule.index; }).join('-'); }; /* @method Generates an ID that identify this state from any other state * @returns {String} Generated ID */ state.prototype._generateIdentity = function() { if (this.isAcceptanceState) { return state.constants.AcceptanceStateName; } else if (!this._items.length) { return _super.prototype._generateIdentity.apply(this, arguments); } return k.utils.obj.reduce( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (acc, item) { return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')'; }, ''); }; /* @method Returns a copy the items contained in the current state * @returns {[ItemRule]} Array of cloned item rules */ state.prototype.getItems = function() { return k.utils.obj.map(this._items, function(item) { return item.clone(); }); }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {[ItemRule]} Array of current item rules */ state.prototype.getOriginalItems = function() { return this._items; }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */ state.prototype.getOriginalItemById = function(id) { return this._registerItems[id]; }; /** @method Get the list of all supported symbol which are valid to generata transition from the current state. * @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */ state.prototype.getSupportedTransitionSymbols = function() { var itemsAux = {}, result = [], symbol; k.utils.obj.each(this._items, function (item) { symbol = item.getCurrentSymbol(); if (symbol) { if (itemsAux[symbol.name]) { itemsAux[symbol.name].push(item); } else { itemsAux[symbol.name] = [item]; result.push({ symbol: symbol, items: itemsAux[symbol.name] }); } } }); return result; }; /* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful * @param {Symbol} symbol Symbol use to make the transition, like the name of the transition * @param {State} state Destination state arrived when moving with the specified tranisiotn * @returns {Object} Transition object */ state.prototype._generateNewTransition = function (symbol, state) { return { symbol: symbol, state: state }; }; /* @method Returns the list of item rules contained in the current state that are reduce item rules. * @returns {[ItemRule]} Recude Item Rules */ state.prototype.getRecudeItems = function () { return k.utils.obj.filter(this._items, function (item) { return item.isReduce(); }); }; return state; })(k.data.Node);
state
identifier_name
state.js
/* State * @class * @classdesc This class reprensent an automata state, a sub-type of a generic Node */ k.data.State = (function(_super) { 'use strict'; /* jshint latedef:false */ k.utils.obj.inherit(state, _super); /* * Constructor Automata State * * @constructor * @param {[ItemRule]} options.items Array of item rules that initialy compone this state * @param {[Object]} options.transitions Array of object that initialy compone this node * @param {[Node]} options.nodes Array of State instances that are children of this State */ function state (options) { _super.apply(this, arguments); k.utils.obj.defineProperty(this, 'isAcceptanceState'); // This is set by the automata generator k.utils.obj.defineProperty(this, '_items'); k.utils.obj.defineProperty(this, '_registerItems'); k.utils.obj.defineProperty(this, '_condencedView'); k.utils.obj.defineProperty(this, '_unprocessedItems'); this.isAcceptanceState = false; this._items = options.items || []; this._unprocessedItems = this._items.length ? k.utils.obj.shallowClone(this._items) : []; options.items = null; this._registerItems = {}; this._registerItemRules(); } /* @method REgister the list of item rules of the current stateso they are assesible by its id * @returns {Void} */ state.prototype._registerItemRules = function () { k.utils.obj.each(this._items, function (itemRule) { this._registerItems[itemRule.getIdentity()] = itemRule; }, this); }; state.constants = { AcceptanceStateName: 'AcceptanceState' }; /* @method Get the next unprocessed item rule * @returns {ItemRule} Next Item Rule */ state.prototype.getNextItem = function() { return this._unprocessedItems.splice(0,1)[0]; }; /* @method Adds an array of item rule into the state. Only the rules that are not already present in the state will be added * @param {[ItemRule]} itemRules Array of item rules to add into the state * @param {Boolean} options.notMergeLookAhead If specified as true does not marge the lookAhead of the already existing items. Default: falsy * @returns {void} Nothing */ state.prototype.addItems = function(itemRules, options) { this._id = null; k.utils.obj.each(itemRules, function (itemRule) { // The same item rule can be added more than once if the grammar has loops. // For sample: (1)S -> A *EXPS B (2)EXPS -> *EXPS if (!this._registerItems[itemRule.getIdentity()]) { this._registerItems[itemRule.getIdentity()] = itemRule; this._items.push(itemRule); this._unprocessedItems.push(itemRule); } else if (!options || !options.notMergeLookAhead) { //As a way of generating a LALR(1) automata adds a item rule for each lookAhead we simply merge its lookAheads var original_itemRule = this._registerItems[itemRule.getIdentity()]; if (itemRule.lookAhead && itemRule.lookAhead.length) { original_itemRule.lookAhead = original_itemRule.lookAhead || []; itemRule.lookAhead = itemRule.lookAhead || []; var mergedLookAheads = original_itemRule.lookAhead.concat(itemRule.lookAhead), original_itemRule_lookAhead_length = this._registerItems[itemRule.getIdentity()].lookAhead.length; this._registerItems[itemRule.getIdentity()].lookAhead = k.utils.obj.uniq(mergedLookAheads, function (item) { return item.name;}); var is_item_already_queued = k.utils.obj.filter(this._unprocessedItems, function (unprocessed_item) { return unprocessed_item.getIdentity() === itemRule.getIdentity(); }).length > 0; //If there were changes in the lookAhead and the rule is not already queued. if (original_itemRule_lookAhead_length !== this._registerItems[itemRule.getIdentity()].lookAhead.length && !is_item_already_queued) { this._unprocessedItems.push(itemRule); } } } }, this); }; /* @method Convert the current state to its string representation * @returns {String} formatted string */ state.prototype.toString = function() { var strResult = 'ID: ' + this.getIdentity() + '\n' + this._items.join('\n') + '\nTRANSITIONS:\n'; k.utils.obj.each(this.transitions, function (transition) { strResult += '*--' + transition.symbol + '-->' + transition.state.getIdentity() + '\n'; }); return strResult; }; /* @method Returns the condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype.getCondencedString = function() { if(!this._condencedView) { this._condencedView = this._generateCondencedString(); } return this._condencedView; }; /* @method Internal method to generate a condenced (one line) string that reprenset the current 'state' of the current state * @returns {String} State Representation in one line */ state.prototype._generateCondencedString = function() { return k.utils.obj.map( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (item) { return item.rule.index; }).join('-'); }; /* @method Generates an ID that identify this state from any other state * @returns {String} Generated ID */ state.prototype._generateIdentity = function() { if (this.isAcceptanceState)
else if (!this._items.length) { return _super.prototype._generateIdentity.apply(this, arguments); } return k.utils.obj.reduce( k.utils.obj.sortBy(this._items, function(item) { return item.rule.index; }), function (acc, item) { return acc + item.getIdentity(); //.rule.index + '(' + item.dotLocation + ')'; }, ''); }; /* @method Returns a copy the items contained in the current state * @returns {[ItemRule]} Array of cloned item rules */ state.prototype.getItems = function() { return k.utils.obj.map(this._items, function(item) { return item.clone(); }); }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {[ItemRule]} Array of current item rules */ state.prototype.getOriginalItems = function() { return this._items; }; /* @method Returns an orignal item rule based on its id. This method is intended to be use as READ-ONLY, editing the returned items will affect the state and the rest of the automata at with this state belongs to. * @returns {ItemRule} Item rule corresponding to the id passed in if present or null otherwise */ state.prototype.getOriginalItemById = function(id) { return this._registerItems[id]; }; /** @method Get the list of all supported symbol which are valid to generata transition from the current state. * @returns {[Object]} Array of object of the form: {symbol, items} where items have an array of item rules */ state.prototype.getSupportedTransitionSymbols = function() { var itemsAux = {}, result = [], symbol; k.utils.obj.each(this._items, function (item) { symbol = item.getCurrentSymbol(); if (symbol) { if (itemsAux[symbol.name]) { itemsAux[symbol.name].push(item); } else { itemsAux[symbol.name] = [item]; result.push({ symbol: symbol, items: itemsAux[symbol.name] }); } } }); return result; }; /* @method Responsible of new transitions. We override this method to use the correct variable names and be more meanful * @param {Symbol} symbol Symbol use to make the transition, like the name of the transition * @param {State} state Destination state arrived when moving with the specified tranisiotn * @returns {Object} Transition object */ state.prototype._generateNewTransition = function (symbol, state) { return { symbol: symbol, state: state }; }; /* @method Returns the list of item rules contained in the current state that are reduce item rules. * @returns {[ItemRule]} Recude Item Rules */ state.prototype.getRecudeItems = function () { return k.utils.obj.filter(this._items, function (item) { return item.isReduce(); }); }; return state; })(k.data.Node);
{ return state.constants.AcceptanceStateName; }
conditional_block
benchmark.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * 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. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var fromCodePoint = require( '@stdlib/string/from-code-point' ); var pkg = require( './../package.json' ).name; var toJSON = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var err; var o; var i; err = new Error( 'beep' ); b.tic(); for ( i = 0; i < b.iterations; i++ )
b.toc(); if ( typeof o !== 'object' ) { b.fail( 'should return an object' ); } b.pass( 'benchmark finished' ); b.end(); });
{ err.message = 'be-'+fromCodePoint( (i%25)+97 )+' -ep'; o = toJSON( err ); if ( typeof o !== 'object' ) { b.fail( 'should return an object' ); } }
conditional_block
benchmark.js
/**
* 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. */ 'use strict'; // MODULES // var bench = require( '@stdlib/bench' ); var fromCodePoint = require( '@stdlib/string/from-code-point' ); var pkg = require( './../package.json' ).name; var toJSON = require( './../lib' ); // MAIN // bench( pkg, function benchmark( b ) { var err; var o; var i; err = new Error( 'beep' ); b.tic(); for ( i = 0; i < b.iterations; i++ ) { err.message = 'be-'+fromCodePoint( (i%25)+97 )+' -ep'; o = toJSON( err ); if ( typeof o !== 'object' ) { b.fail( 'should return an object' ); } } b.toc(); if ( typeof o !== 'object' ) { b.fail( 'should return an object' ); } b.pass( 'benchmark finished' ); b.end(); });
* @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. *
random_line_split
parameters.py
from property import * # Neuron common parameters iaf_neuronparams = {'E_L': -70., 'V_th': -50., 'V_reset': -67., 'C_m': 2., 't_ref': 2., 'V_m': -60., 'tau_syn_ex': 1., 'tau_syn_in': 1.33} # Synapse common parameters STDP_synapseparams = { 'model': 'stdp_synapse', 'tau_m': {'distribution': 'uniform', 'low': 15., 'high': 25.}, 'alpha': {'distribution': 'normal_clipped', 'low': 0.5, 'mu': 5.0, 'sigma': 1.0}, 'delay': {'distribution': 'uniform', 'low': 0.8, 'high': 2.5}, 'lambda': 0.5 }
STDP_synparams_Glu = dict({'delay': {'distribution': 'uniform', 'low': 1, 'high': 1.3}, 'weight': w_Glu, 'Wmax': 70.}, **STDP_synapseparams) # GABA synapse STDP_synparams_GABA = dict({'delay': {'distribution': 'uniform', 'low': 1., 'high': 1.3}, 'weight': w_GABA, 'Wmax': -60.}, **STDP_synapseparams) # Acetylcholine synapse STDP_synparams_ACh = dict({'delay': {'distribution': 'uniform', 'low': 1, 'high': 1.3}, 'weight': w_ACh, 'Wmax': 70.}, **STDP_synapseparams) # Dopamine synapse common parameter NORA_synparams = {'delay': 1.} # Dopamine exhibitory synapse NORA_synparams_ex = dict({'weight': w_NR_ex, 'Wmax': 100., 'Wmin': 85.}, **NORA_synparams) # Dopamine inhibitory synapse NORA_synparams_in = dict({'weight': w_NR_in, 'Wmax': -100., 'Wmin': -85.}, **NORA_synparams) # Create volume transmitters # Dictionary of synapses with keys and their parameters types = {GABA: (STDP_synparams_GABA, w_GABA, 'GABA'), ACh: (STDP_synparams_ACh, w_ACh, 'Ach'), Glu: (STDP_synparams_Glu, w_Glu, 'Glu'), DA_ex: (NORA_synparams_ex, w_NR_ex, 'DA_ex', nora_model_ex), DA_in: (NORA_synparams_in, w_NR_in, 'DA_in', nora_model_in)} # Parameters for generator links static_syn = { 'model': 'static_synapse', 'weight': w_Glu * 5, 'delay': pg_delay } # Connection parameters conn_dict = {'rule': 'all_to_all', 'multapses': True} # Device parameters multimeter_param = {'to_memory': True, 'to_file': False, 'withtime': True, 'interval': 0.1, 'record_from': ['V_m'], 'withgid': True} detector_param = {'label': 'spikes', 'withtime': True, 'withgid': True, 'to_file': False, 'to_memory': True, 'scientific': True}
# Glutamate synapse
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(macro_rules, plugin_registrar, quote, phase)] #![deny(unused_imports, unused_variable)] //! Exports macros for use in other Servo crates. extern crate syntax; #[phase(plugin, link)] extern crate rustc; #[cfg(test)] extern crate sync; use syntax::ast; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::middle::typeck::astconv::AstConv; use rustc::util::ppaux::Repr; declare_lint!(TRANSMUTE_TYPE_LINT, Allow, "Warn and report types being transmuted") declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects") struct TransmutePass; struct UnrootedPass; impl LintPass for TransmutePass { fn get_lints(&self) -> LintArray { lint_array!(TRANSMUTE_TYPE_LINT) } fn check_expr(&mut self, cx: &Context, ex: &ast::Expr) { match ex.node { ast::ExprCall(ref expr, ref args) => { match expr.node { ast::ExprPath(ref path) => { if path.segments.last() .map_or(false, |ref segment| segment.identifier.name.as_str() == "transmute") && args.len() == 1 { let tcx = cx.tcx(); cx.span_lint(TRANSMUTE_TYPE_LINT, ex.span, format!("Transmute from {} to {} detected", expr_ty(tcx, ex).repr(tcx), expr_ty(tcx, &**args.get(0)).repr(tcx) ).as_slice()); } } _ => {} } } _ => {} } } } fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str)
impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a| !a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty, "Type must be rooted, use #[must_root] on the struct definition to propagate"); } } } fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a| !a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } fn check_fn(&mut self, cx: &Context, kind: syntax::visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: syntax::codemap::Span, _id: ast::NodeId) { match kind { syntax::visit::FkItemFn(i, _, _, _) | syntax::visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; } _ => () } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted, use #[must_root] on the fn definition to propagate") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { // Catch the let binding let expr = match s.node { ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match ty::get(t).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_lint_pass(box TransmutePass as LintPassObject); reg.register_lint_pass(box UnrootedPass as LintPassObject); } #[macro_export] macro_rules! bitfield( ($bitfieldname:ident, $getter:ident, $setter:ident, $value:expr) => ( impl $bitfieldname { #[inline] pub fn $getter(self) -> bool { let $bitfieldname(this) = self; (this & $value) != 0 } #[inline] pub fn $setter(&mut self, value: bool) { let $bitfieldname(this) = *self; *self = $bitfieldname((this & !$value) | (if value { $value } else { 0 })) } } ) )
{ match ty.node { ast::TyBox(ref t) | ast::TyUniq(ref t) | ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(_, _, id) => { match cx.tcx.def_map.borrow().get_copy(&id) { def::DefTy(def_id) => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(macro_rules, plugin_registrar, quote, phase)] #![deny(unused_imports, unused_variable)] //! Exports macros for use in other Servo crates. extern crate syntax; #[phase(plugin, link)] extern crate rustc; #[cfg(test)] extern crate sync; use syntax::ast; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::middle::typeck::astconv::AstConv; use rustc::util::ppaux::Repr; declare_lint!(TRANSMUTE_TYPE_LINT, Allow, "Warn and report types being transmuted") declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects") struct TransmutePass; struct UnrootedPass; impl LintPass for TransmutePass { fn get_lints(&self) -> LintArray { lint_array!(TRANSMUTE_TYPE_LINT) } fn check_expr(&mut self, cx: &Context, ex: &ast::Expr) { match ex.node { ast::ExprCall(ref expr, ref args) => { match expr.node { ast::ExprPath(ref path) => { if path.segments.last() .map_or(false, |ref segment| segment.identifier.name.as_str() == "transmute") && args.len() == 1 { let tcx = cx.tcx(); cx.span_lint(TRANSMUTE_TYPE_LINT, ex.span, format!("Transmute from {} to {} detected", expr_ty(tcx, ex).repr(tcx), expr_ty(tcx, &**args.get(0)).repr(tcx) ).as_slice()); } } _ => {} } } _ => {} } } } fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) { match ty.node { ast::TyBox(ref t) | ast::TyUniq(ref t) | ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(_, _, id) => { match cx.tcx.def_map.borrow().get_copy(&id) { def::DefTy(def_id) => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a| !a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty,
fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a| !a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } fn check_fn(&mut self, cx: &Context, kind: syntax::visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: syntax::codemap::Span, _id: ast::NodeId) { match kind { syntax::visit::FkItemFn(i, _, _, _) | syntax::visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; } _ => () } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted, use #[must_root] on the fn definition to propagate") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { // Catch the let binding let expr = match s.node { ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match ty::get(t).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_lint_pass(box TransmutePass as LintPassObject); reg.register_lint_pass(box UnrootedPass as LintPassObject); } #[macro_export] macro_rules! bitfield( ($bitfieldname:ident, $getter:ident, $setter:ident, $value:expr) => ( impl $bitfieldname { #[inline] pub fn $getter(self) -> bool { let $bitfieldname(this) = self; (this & $value) != 0 } #[inline] pub fn $setter(&mut self, value: bool) { let $bitfieldname(this) = *self; *self = $bitfieldname((this & !$value) | (if value { $value } else { 0 })) } } ) )
"Type must be rooted, use #[must_root] on the struct definition to propagate"); } } }
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(macro_rules, plugin_registrar, quote, phase)] #![deny(unused_imports, unused_variable)] //! Exports macros for use in other Servo crates. extern crate syntax; #[phase(plugin, link)] extern crate rustc; #[cfg(test)] extern crate sync; use syntax::ast; use syntax::attr::AttrMetaMethods; use rustc::lint::{Context, LintPass, LintPassObject, LintArray}; use rustc::plugin::Registry; use rustc::middle::ty::expr_ty; use rustc::middle::{ty, def}; use rustc::middle::typeck::astconv::AstConv; use rustc::util::ppaux::Repr; declare_lint!(TRANSMUTE_TYPE_LINT, Allow, "Warn and report types being transmuted") declare_lint!(UNROOTED_MUST_ROOT, Deny, "Warn and report usage of unrooted jsmanaged objects") struct TransmutePass; struct UnrootedPass; impl LintPass for TransmutePass { fn get_lints(&self) -> LintArray { lint_array!(TRANSMUTE_TYPE_LINT) } fn check_expr(&mut self, cx: &Context, ex: &ast::Expr) { match ex.node { ast::ExprCall(ref expr, ref args) => { match expr.node { ast::ExprPath(ref path) => { if path.segments.last() .map_or(false, |ref segment| segment.identifier.name.as_str() == "transmute") && args.len() == 1 { let tcx = cx.tcx(); cx.span_lint(TRANSMUTE_TYPE_LINT, ex.span, format!("Transmute from {} to {} detected", expr_ty(tcx, ex).repr(tcx), expr_ty(tcx, &**args.get(0)).repr(tcx) ).as_slice()); } } _ => {} } } _ => {} } } } fn lint_unrooted_ty(cx: &Context, ty: &ast::Ty, warning: &str) { match ty.node { ast::TyBox(ref t) | ast::TyUniq(ref t) | ast::TyVec(ref t) | ast::TyFixedLengthVec(ref t, _) | ast::TyPtr(ast::MutTy { ty: ref t, ..}) | ast::TyRptr(_, ast::MutTy { ty: ref t, ..}) => lint_unrooted_ty(cx, &**t, warning), ast::TyPath(_, _, id) => { match cx.tcx.def_map.borrow().get_copy(&id) { def::DefTy(def_id) => { if ty::has_attr(cx.tcx, def_id, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, ty.span, warning); } } _ => (), } } _ => (), }; } impl LintPass for UnrootedPass { fn get_lints(&self) -> LintArray { lint_array!(UNROOTED_MUST_ROOT) } fn check_struct_def(&mut self, cx: &Context, def: &ast::StructDef, _i: ast::Ident, _gen: &ast::Generics, id: ast::NodeId) { if cx.tcx.map.expect_item(id).attrs.iter().all(|a| !a.check_name("must_root")) { for ref field in def.fields.iter() { lint_unrooted_ty(cx, &*field.node.ty, "Type must be rooted, use #[must_root] on the struct definition to propagate"); } } } fn check_variant(&mut self, cx: &Context, var: &ast::Variant, _gen: &ast::Generics) { let ref map = cx.tcx.map; if map.expect_item(map.get_parent(var.node.id)).attrs.iter().all(|a| !a.check_name("must_root")) { match var.node.kind { ast::TupleVariantKind(ref vec) => { for ty in vec.iter() { lint_unrooted_ty(cx, &*ty.ty, "Type must be rooted, use #[must_root] on the enum definition to propagate") } } _ => () // Struct variants already caught by check_struct_def } } } fn check_fn(&mut self, cx: &Context, kind: syntax::visit::FnKind, decl: &ast::FnDecl, block: &ast::Block, _span: syntax::codemap::Span, _id: ast::NodeId) { match kind { syntax::visit::FkItemFn(i, _, _, _) | syntax::visit::FkMethod(i, _, _) if i.as_str() == "new" || i.as_str() == "new_inherited" => { return; } _ => () } match block.rules { ast::DefaultBlock => { for arg in decl.inputs.iter() { lint_unrooted_ty(cx, &*arg.ty, "Type must be rooted, use #[must_root] on the fn definition to propagate") } } _ => () // fn is `unsafe` } } // Partially copied from rustc::middle::lint::builtin // Catches `let` statements which store a #[must_root] value // Expressions which return out of blocks eventually end up in a `let` // statement or a function return (which will be caught when it is used elsewhere) fn check_stmt(&mut self, cx: &Context, s: &ast::Stmt) { // Catch the let binding let expr = match s.node { ast::StmtDecl(ref decl, _) => match decl.node { ast::DeclLocal(ref loc) => match loc.init { Some(ref e) => &**e, _ => return }, _ => return }, _ => return }; let t = expr_ty(cx.tcx, &*expr); match ty::get(t).sty { ty::ty_struct(did, _) | ty::ty_enum(did, _) => { if ty::has_attr(cx.tcx, did, "must_root") { cx.span_lint(UNROOTED_MUST_ROOT, expr.span, format!("Expression of type {} must be rooted", t.repr(cx.tcx)).as_slice()); } } _ => {} } } } #[plugin_registrar] pub fn
(reg: &mut Registry) { reg.register_lint_pass(box TransmutePass as LintPassObject); reg.register_lint_pass(box UnrootedPass as LintPassObject); } #[macro_export] macro_rules! bitfield( ($bitfieldname:ident, $getter:ident, $setter:ident, $value:expr) => ( impl $bitfieldname { #[inline] pub fn $getter(self) -> bool { let $bitfieldname(this) = self; (this & $value) != 0 } #[inline] pub fn $setter(&mut self, value: bool) { let $bitfieldname(this) = *self; *self = $bitfieldname((this & !$value) | (if value { $value } else { 0 })) } } ) )
plugin_registrar
identifier_name
customcert.js
import fetch from 'isomorphic-fetch'; import { application } from '../../config'; import * as Action from './constants'; export function setCerts(data) { return ({ type: Action.SET_SET_OF_CERTS, data, }); } export function setObjectToEdit(data) { return ({ type: Action.SET_CUSTOMCERT_OBJECT_TO_EDIT, data, }); } export function loadCerts() { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/get_certs`, config) .then(response => response.json()) .then((data) => { if (!data.error) { dispatch(setCerts(data.data)); } }); }; } export function createNew(text) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/create_certificate`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; } export function editObject(objectToEdit) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ objectToEdit }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/edit_object`, config) .then(response => response.json()) .then((json) => { if (!json.error)
}); }; }
{ dispatch(loadCerts()); }
conditional_block
customcert.js
import fetch from 'isomorphic-fetch'; import { application } from '../../config'; import * as Action from './constants'; export function setCerts(data) { return ({ type: Action.SET_SET_OF_CERTS, data, }); } export function
(data) { return ({ type: Action.SET_CUSTOMCERT_OBJECT_TO_EDIT, data, }); } export function loadCerts() { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/get_certs`, config) .then(response => response.json()) .then((data) => { if (!data.error) { dispatch(setCerts(data.data)); } }); }; } export function createNew(text) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/create_certificate`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; } export function editObject(objectToEdit) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ objectToEdit }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/edit_object`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; }
setObjectToEdit
identifier_name
customcert.js
import fetch from 'isomorphic-fetch'; import { application } from '../../config'; import * as Action from './constants'; export function setCerts(data) { return ({ type: Action.SET_SET_OF_CERTS, data, }); } export function setObjectToEdit(data) { return ({ type: Action.SET_CUSTOMCERT_OBJECT_TO_EDIT, data, }); } export function loadCerts() { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/get_certs`, config) .then(response => response.json()) .then((data) => { if (!data.error) { dispatch(setCerts(data.data)); } }); }; } export function createNew(text) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/create_certificate`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; } export function editObject(objectToEdit)
{ return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ objectToEdit }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/edit_object`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; }
identifier_body
customcert.js
import fetch from 'isomorphic-fetch'; import { application } from '../../config'; import * as Action from './constants'; export function setCerts(data) { return ({ type: Action.SET_SET_OF_CERTS, data, }); } export function setObjectToEdit(data) { return ({ type: Action.SET_CUSTOMCERT_OBJECT_TO_EDIT, data, }); } export function loadCerts() { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include',
}, }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/get_certs`, config) .then(response => response.json()) .then((data) => { if (!data.error) { dispatch(setCerts(data.data)); } }); }; } export function createNew(text) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/create_certificate`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; } export function editObject(objectToEdit) { return (dispatch, getState) => { const eventId = getState().event.id; const config = { method: 'POST', mode: 'cors', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ objectToEdit }), }; fetch(`${application.url}/api/event/${eventId}/module/cert/cert/act/edit_object`, config) .then(response => response.json()) .then((json) => { if (!json.error) { dispatch(loadCerts()); } }); }; }
headers: { Accept: 'application/json', 'Content-Type': 'application/json',
random_line_split
FileHash58TestElement.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.defs.independent.TestType import TestType logger = logging.getLogger(__name__) class
(TestType): MODEL_MAP = { 'tag_name': 'filehash58_test', }
FileHash58TestElement
identifier_name
FileHash58TestElement.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or
# 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.defs.independent.TestType import TestType logger = logging.getLogger(__name__) class FileHash58TestElement(TestType): MODEL_MAP = { 'tag_name': 'filehash58_test', }
# (at your option) any later version. # # PySCAP is distributed in the hope that it will be useful,
random_line_split
FileHash58TestElement.py
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.oval_5.defs.independent.TestType import TestType logger = logging.getLogger(__name__) class FileHash58TestElement(TestType):
MODEL_MAP = { 'tag_name': 'filehash58_test', }
identifier_body
mod.rs
pub mod counts; mod hashing; pub mod mash; pub mod scaled; use needletail::parser::SequenceRecord; use serde::{Deserialize, Serialize}; use crate::bail; use crate::errors::FinchResult; use crate::filtering::FilterParams; use crate::serialization::Sketch; pub use hashing::ItemHash; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)] pub struct KmerCount { pub hash: ItemHash, pub kmer: Vec<u8>, pub count: u32, pub extra_count: u32, pub label: Option<Vec<u8>>, } pub trait SketchScheme { fn process(&mut self, seq: SequenceRecord); fn total_bases_and_kmers(&self) -> (u64, u64); fn to_vec(&self) -> Vec<KmerCount>; fn parameters(&self) -> SketchParams; fn to_sketch(&self) -> Sketch { // TODO: maybe this should be the primary teardown method for // sketching and sketch_stream should wrap it? // TODO: this doesn't really use filtering // TODO: also the pass-through for the post-filtering trimming is // weird for SketchParams::Mash let (seq_length, num_valid_kmers) = self.total_bases_and_kmers(); let hashes = self.to_vec(); Sketch { name: "".to_string(), seq_length, num_valid_kmers, comment: "".to_string(), hashes, filter_params: FilterParams::default(), sketch_params: self.parameters(), } } } #[derive(Clone, Debug, PartialEq)] pub enum SketchParams { Mash { kmers_to_sketch: usize, final_size: usize, no_strict: bool, kmer_length: u8, hash_seed: u64, }, Scaled { kmers_to_sketch: usize, kmer_length: u8, scale: f64, hash_seed: u64, }, AllCounts { kmer_length: u8, }, } impl Default for SketchParams { fn default() -> Self { SketchParams::Mash { kmers_to_sketch: 1000, final_size: 1000, no_strict: false, kmer_length: 21, hash_seed: 0, } } } impl SketchParams { pub fn create_sketcher(&self) -> Box<dyn SketchScheme> { match self { SketchParams::Mash { kmers_to_sketch, kmer_length, hash_seed, .. } => Box::new(mash::MashSketcher::new( *kmers_to_sketch, *kmer_length, *hash_seed, )), SketchParams::Scaled { kmers_to_sketch, kmer_length, scale, hash_seed, } => Box::new(scaled::ScaledSketcher::new( *kmers_to_sketch, *scale, *kmer_length, *hash_seed, )), SketchParams::AllCounts { kmer_length } => { Box::new(counts::AllCountsSketcher::new(*kmer_length)) } } } pub fn process_post_filter(&self, kmers: &mut Vec<KmerCount>, name: &str) -> FinchResult<()> { if let SketchParams::Mash { final_size, no_strict, .. } = self { kmers.truncate(*final_size); if !no_strict && kmers.len() < *final_size { bail!("{} had too few kmers ({}) to sketch", name, kmers.len(),); } } Ok(()) } pub fn k(&self) -> u8 { match self { SketchParams::Mash { kmer_length, .. } => *kmer_length, SketchParams::Scaled { kmer_length, .. } => *kmer_length, SketchParams::AllCounts { kmer_length, .. } => *kmer_length, } } pub fn hash_info(&self) -> (&str, u16, u64, Option<f64>) { match self { SketchParams::Mash { hash_seed, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, None), SketchParams::Scaled { hash_seed, scale, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, Some(*scale)), SketchParams::AllCounts { .. } => ("None", 0, 0, None), } } pub fn expected_size(&self) -> usize { match self { SketchParams::Mash { final_size, .. } => *final_size, SketchParams::Scaled { kmers_to_sketch, .. } => *kmers_to_sketch, SketchParams::AllCounts { kmer_length, .. } => 4usize.pow(u32::from(*kmer_length)), } } pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self> { let first_params = sketches[0].sketch_params.clone(); for (ix, sketch) in sketches.iter().enumerate().skip(1) { let params = &sketch.sketch_params; if let Some((mismatched_param, v1, v2)) = first_params.check_compatibility(&params) { bail!( "First sketch has {} {}, but sketch {} has {0} {}", mismatched_param, v1, ix + 1, v2, ); } // TODO: harmonize scaled/non-scaled sketches?
Ok(first_params) } /// Return any sketch parameter difference that would make comparisons /// between sketches generated by these parameter sets not work. /// /// Note this doesn't actually check the enum variants themselves, but it /// should still break if there are different variants because the hash /// types should be different. pub fn check_compatibility(&self, other: &SketchParams) -> Option<(&str, String, String)> { if self.k() != other.k() { return Some(("k", self.k().to_string(), other.k().to_string())); } if self.hash_info().0 != other.hash_info().0 { return Some(( "hash type", self.hash_info().0.to_string(), other.hash_info().0.to_string(), )); } if self.hash_info().1 != other.hash_info().1 { return Some(( "hash bits", self.hash_info().1.to_string(), other.hash_info().1.to_string(), )); } if self.hash_info().2 != other.hash_info().2 { return Some(( "hash seed", self.hash_info().2.to_string(), other.hash_info().2.to_string(), )); } None } }
// TODO: harminize sketch sizes? // TODO: do something with no_strict and final_size }
random_line_split
mod.rs
pub mod counts; mod hashing; pub mod mash; pub mod scaled; use needletail::parser::SequenceRecord; use serde::{Deserialize, Serialize}; use crate::bail; use crate::errors::FinchResult; use crate::filtering::FilterParams; use crate::serialization::Sketch; pub use hashing::ItemHash; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)] pub struct KmerCount { pub hash: ItemHash, pub kmer: Vec<u8>, pub count: u32, pub extra_count: u32, pub label: Option<Vec<u8>>, } pub trait SketchScheme { fn process(&mut self, seq: SequenceRecord); fn total_bases_and_kmers(&self) -> (u64, u64); fn to_vec(&self) -> Vec<KmerCount>; fn parameters(&self) -> SketchParams; fn to_sketch(&self) -> Sketch { // TODO: maybe this should be the primary teardown method for // sketching and sketch_stream should wrap it? // TODO: this doesn't really use filtering // TODO: also the pass-through for the post-filtering trimming is // weird for SketchParams::Mash let (seq_length, num_valid_kmers) = self.total_bases_and_kmers(); let hashes = self.to_vec(); Sketch { name: "".to_string(), seq_length, num_valid_kmers, comment: "".to_string(), hashes, filter_params: FilterParams::default(), sketch_params: self.parameters(), } } } #[derive(Clone, Debug, PartialEq)] pub enum SketchParams { Mash { kmers_to_sketch: usize, final_size: usize, no_strict: bool, kmer_length: u8, hash_seed: u64, }, Scaled { kmers_to_sketch: usize, kmer_length: u8, scale: f64, hash_seed: u64, }, AllCounts { kmer_length: u8, }, } impl Default for SketchParams { fn default() -> Self { SketchParams::Mash { kmers_to_sketch: 1000, final_size: 1000, no_strict: false, kmer_length: 21, hash_seed: 0, } } } impl SketchParams { pub fn create_sketcher(&self) -> Box<dyn SketchScheme> { match self { SketchParams::Mash { kmers_to_sketch, kmer_length, hash_seed, .. } => Box::new(mash::MashSketcher::new( *kmers_to_sketch, *kmer_length, *hash_seed, )), SketchParams::Scaled { kmers_to_sketch, kmer_length, scale, hash_seed, } => Box::new(scaled::ScaledSketcher::new( *kmers_to_sketch, *scale, *kmer_length, *hash_seed, )), SketchParams::AllCounts { kmer_length } => { Box::new(counts::AllCountsSketcher::new(*kmer_length)) } } } pub fn process_post_filter(&self, kmers: &mut Vec<KmerCount>, name: &str) -> FinchResult<()> { if let SketchParams::Mash { final_size, no_strict, .. } = self { kmers.truncate(*final_size); if !no_strict && kmers.len() < *final_size { bail!("{} had too few kmers ({}) to sketch", name, kmers.len(),); } } Ok(()) } pub fn k(&self) -> u8 { match self { SketchParams::Mash { kmer_length, .. } => *kmer_length, SketchParams::Scaled { kmer_length, .. } => *kmer_length, SketchParams::AllCounts { kmer_length, .. } => *kmer_length, } } pub fn
(&self) -> (&str, u16, u64, Option<f64>) { match self { SketchParams::Mash { hash_seed, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, None), SketchParams::Scaled { hash_seed, scale, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, Some(*scale)), SketchParams::AllCounts { .. } => ("None", 0, 0, None), } } pub fn expected_size(&self) -> usize { match self { SketchParams::Mash { final_size, .. } => *final_size, SketchParams::Scaled { kmers_to_sketch, .. } => *kmers_to_sketch, SketchParams::AllCounts { kmer_length, .. } => 4usize.pow(u32::from(*kmer_length)), } } pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self> { let first_params = sketches[0].sketch_params.clone(); for (ix, sketch) in sketches.iter().enumerate().skip(1) { let params = &sketch.sketch_params; if let Some((mismatched_param, v1, v2)) = first_params.check_compatibility(&params) { bail!( "First sketch has {} {}, but sketch {} has {0} {}", mismatched_param, v1, ix + 1, v2, ); } // TODO: harmonize scaled/non-scaled sketches? // TODO: harminize sketch sizes? // TODO: do something with no_strict and final_size } Ok(first_params) } /// Return any sketch parameter difference that would make comparisons /// between sketches generated by these parameter sets not work. /// /// Note this doesn't actually check the enum variants themselves, but it /// should still break if there are different variants because the hash /// types should be different. pub fn check_compatibility(&self, other: &SketchParams) -> Option<(&str, String, String)> { if self.k() != other.k() { return Some(("k", self.k().to_string(), other.k().to_string())); } if self.hash_info().0 != other.hash_info().0 { return Some(( "hash type", self.hash_info().0.to_string(), other.hash_info().0.to_string(), )); } if self.hash_info().1 != other.hash_info().1 { return Some(( "hash bits", self.hash_info().1.to_string(), other.hash_info().1.to_string(), )); } if self.hash_info().2 != other.hash_info().2 { return Some(( "hash seed", self.hash_info().2.to_string(), other.hash_info().2.to_string(), )); } None } }
hash_info
identifier_name
mod.rs
pub mod counts; mod hashing; pub mod mash; pub mod scaled; use needletail::parser::SequenceRecord; use serde::{Deserialize, Serialize}; use crate::bail; use crate::errors::FinchResult; use crate::filtering::FilterParams; use crate::serialization::Sketch; pub use hashing::ItemHash; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Hash, Serialize)] pub struct KmerCount { pub hash: ItemHash, pub kmer: Vec<u8>, pub count: u32, pub extra_count: u32, pub label: Option<Vec<u8>>, } pub trait SketchScheme { fn process(&mut self, seq: SequenceRecord); fn total_bases_and_kmers(&self) -> (u64, u64); fn to_vec(&self) -> Vec<KmerCount>; fn parameters(&self) -> SketchParams; fn to_sketch(&self) -> Sketch { // TODO: maybe this should be the primary teardown method for // sketching and sketch_stream should wrap it? // TODO: this doesn't really use filtering // TODO: also the pass-through for the post-filtering trimming is // weird for SketchParams::Mash let (seq_length, num_valid_kmers) = self.total_bases_and_kmers(); let hashes = self.to_vec(); Sketch { name: "".to_string(), seq_length, num_valid_kmers, comment: "".to_string(), hashes, filter_params: FilterParams::default(), sketch_params: self.parameters(), } } } #[derive(Clone, Debug, PartialEq)] pub enum SketchParams { Mash { kmers_to_sketch: usize, final_size: usize, no_strict: bool, kmer_length: u8, hash_seed: u64, }, Scaled { kmers_to_sketch: usize, kmer_length: u8, scale: f64, hash_seed: u64, }, AllCounts { kmer_length: u8, }, } impl Default for SketchParams { fn default() -> Self { SketchParams::Mash { kmers_to_sketch: 1000, final_size: 1000, no_strict: false, kmer_length: 21, hash_seed: 0, } } } impl SketchParams { pub fn create_sketcher(&self) -> Box<dyn SketchScheme>
pub fn process_post_filter(&self, kmers: &mut Vec<KmerCount>, name: &str) -> FinchResult<()> { if let SketchParams::Mash { final_size, no_strict, .. } = self { kmers.truncate(*final_size); if !no_strict && kmers.len() < *final_size { bail!("{} had too few kmers ({}) to sketch", name, kmers.len(),); } } Ok(()) } pub fn k(&self) -> u8 { match self { SketchParams::Mash { kmer_length, .. } => *kmer_length, SketchParams::Scaled { kmer_length, .. } => *kmer_length, SketchParams::AllCounts { kmer_length, .. } => *kmer_length, } } pub fn hash_info(&self) -> (&str, u16, u64, Option<f64>) { match self { SketchParams::Mash { hash_seed, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, None), SketchParams::Scaled { hash_seed, scale, .. } => ("MurmurHash3_x64_128", 64, *hash_seed, Some(*scale)), SketchParams::AllCounts { .. } => ("None", 0, 0, None), } } pub fn expected_size(&self) -> usize { match self { SketchParams::Mash { final_size, .. } => *final_size, SketchParams::Scaled { kmers_to_sketch, .. } => *kmers_to_sketch, SketchParams::AllCounts { kmer_length, .. } => 4usize.pow(u32::from(*kmer_length)), } } pub fn from_sketches(sketches: &[Sketch]) -> FinchResult<Self> { let first_params = sketches[0].sketch_params.clone(); for (ix, sketch) in sketches.iter().enumerate().skip(1) { let params = &sketch.sketch_params; if let Some((mismatched_param, v1, v2)) = first_params.check_compatibility(&params) { bail!( "First sketch has {} {}, but sketch {} has {0} {}", mismatched_param, v1, ix + 1, v2, ); } // TODO: harmonize scaled/non-scaled sketches? // TODO: harminize sketch sizes? // TODO: do something with no_strict and final_size } Ok(first_params) } /// Return any sketch parameter difference that would make comparisons /// between sketches generated by these parameter sets not work. /// /// Note this doesn't actually check the enum variants themselves, but it /// should still break if there are different variants because the hash /// types should be different. pub fn check_compatibility(&self, other: &SketchParams) -> Option<(&str, String, String)> { if self.k() != other.k() { return Some(("k", self.k().to_string(), other.k().to_string())); } if self.hash_info().0 != other.hash_info().0 { return Some(( "hash type", self.hash_info().0.to_string(), other.hash_info().0.to_string(), )); } if self.hash_info().1 != other.hash_info().1 { return Some(( "hash bits", self.hash_info().1.to_string(), other.hash_info().1.to_string(), )); } if self.hash_info().2 != other.hash_info().2 { return Some(( "hash seed", self.hash_info().2.to_string(), other.hash_info().2.to_string(), )); } None } }
{ match self { SketchParams::Mash { kmers_to_sketch, kmer_length, hash_seed, .. } => Box::new(mash::MashSketcher::new( *kmers_to_sketch, *kmer_length, *hash_seed, )), SketchParams::Scaled { kmers_to_sketch, kmer_length, scale, hash_seed, } => Box::new(scaled::ScaledSketcher::new( *kmers_to_sketch, *scale, *kmer_length, *hash_seed, )), SketchParams::AllCounts { kmer_length } => { Box::new(counts::AllCountsSketcher::new(*kmer_length)) } } }
identifier_body
cmd.js
#!/usr/bin/env node var CompactToStylishStream = require('../') var minimist = require('minimist') var argv = minimist(process.argv.slice(2), {
}) if (!process.stdin.isTTY || argv._[0] === '-' || argv.stdin) { var snazzy = new CompactToStylishStream() // Set the process exit code based on whether snazzy found errors process.on('exit', function (code) { if (code === 0 && snazzy.exitCode !== 0) { process.exitCode = snazzy.exitCode } }) process.stdin.pipe(snazzy).pipe(process.stdout) } else { console.error(` snazzy: 'standard' is no longer bundled with 'snazzy'. Install standard snazzy: ('npm install standard') then run 'standard | snazzy' instead. `) process.exitCode = 1 }
boolean: [ 'stdin' ]
random_line_split
cmd.js
#!/usr/bin/env node var CompactToStylishStream = require('../') var minimist = require('minimist') var argv = minimist(process.argv.slice(2), { boolean: [ 'stdin' ] }) if (!process.stdin.isTTY || argv._[0] === '-' || argv.stdin) { var snazzy = new CompactToStylishStream() // Set the process exit code based on whether snazzy found errors process.on('exit', function (code) { if (code === 0 && snazzy.exitCode !== 0) { process.exitCode = snazzy.exitCode } }) process.stdin.pipe(snazzy).pipe(process.stdout) } else
{ console.error(` snazzy: 'standard' is no longer bundled with 'snazzy'. Install standard snazzy: ('npm install standard') then run 'standard | snazzy' instead. `) process.exitCode = 1 }
conditional_block
htmltablecaptionelement.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/. */ use crate::dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTableCaptionElement { htmlelement: HTMLElement, }
document: &Document, ) -> HTMLTableCaptionElement { HTMLTableCaptionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn new( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTableCaptionElement> { Node::reflect_node( Box::new(HTMLTableCaptionElement::new_inherited( local_name, prefix, document, )), document, HTMLTableCaptionElementBinding::Wrap, ) } }
impl HTMLTableCaptionElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>,
random_line_split
htmltablecaptionelement.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/. */ use crate::dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding; use crate::dom::bindings::root::DomRoot; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTableCaptionElement { htmlelement: HTMLElement, } impl HTMLTableCaptionElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> HTMLTableCaptionElement { HTMLTableCaptionElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), } } #[allow(unrooted_must_root)] pub fn
( local_name: LocalName, prefix: Option<Prefix>, document: &Document, ) -> DomRoot<HTMLTableCaptionElement> { Node::reflect_node( Box::new(HTMLTableCaptionElement::new_inherited( local_name, prefix, document, )), document, HTMLTableCaptionElementBinding::Wrap, ) } }
new
identifier_name
route_registry_module.ts
/* Copyright 2020 The TensorFlow Authors. 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. ==============================================================================*/ import { Component, Inject, ModuleWithProviders, NgModule, Optional, Type, } from '@angular/core'; import {RouteConfigs} from './route_config'; import {isConcreteRouteDef, RouteDef} from './route_config_types'; import {ROUTE_CONFIGS_TOKEN} from './route_registry_types'; import {RouteKind} from './types'; @NgModule({}) export class RouteRegistryModule { private readonly routeConfigs: RouteConfigs; private readonly routeKindToNgComponent = new Map< RouteKind, Type<Component> >(); constructor( @Optional() @Inject(ROUTE_CONFIGS_TOKEN) configsList: RouteDef[][] ) { if (!configsList) { this.routeConfigs = new RouteConfigs([]); return; } const configs: RouteDef[] = []; for (const routeDefList of configsList) { for (const routeDef of routeDefList) { configs.push(routeDef); } } this.routeConfigs = new RouteConfigs(configs); configs.forEach((config) => { if (isConcreteRouteDef(config)) { this.routeKindToNgComponent.set(config.routeKind, config.ngComponent); } }); }
(): Iterable<RouteKind> { return this.routeKindToNgComponent.keys(); } /** * Returns RouteConfigs of current route configuration. Returnsn null if no * routes are registered. */ getRouteConfigs(): RouteConfigs { return this.routeConfigs; } getNgComponentByRouteKind(routeKind: RouteKind): Type<Component> | null { return this.routeKindToNgComponent.get(routeKind) || null; } /** * An NgModule that registers routes. * * Note: especially because Polymer based TensorBoard requires relative paths * for making requests, although not required, prefer to have path that ends * with "/". * * Example: * * function routeProvider() { * return [{ * path: '/experiments/', * ngComponent: ScalarsDashboard, * routeKind: RouteKind.EXPERIMENTS, * }]; * } * * @NgModule({ * imports: [ * RouteRegistryModule.registerRoutes(routesProvider), * ], * entryComponents: [ScalarsDashboard] * }) */ static registerRoutes( routeConfigProvider: () => RouteDef[] ): ModuleWithProviders<RouteRegistryModule> { return { ngModule: RouteRegistryModule, providers: [ { provide: ROUTE_CONFIGS_TOKEN, multi: true, useFactory: routeConfigProvider, }, ], }; } }
getRegisteredRouteKinds
identifier_name
route_registry_module.ts
/* Copyright 2020 The TensorFlow Authors. 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. ==============================================================================*/ import { Component, Inject, ModuleWithProviders, NgModule, Optional, Type, } from '@angular/core'; import {RouteConfigs} from './route_config'; import {isConcreteRouteDef, RouteDef} from './route_config_types'; import {ROUTE_CONFIGS_TOKEN} from './route_registry_types'; import {RouteKind} from './types'; @NgModule({}) export class RouteRegistryModule { private readonly routeConfigs: RouteConfigs; private readonly routeKindToNgComponent = new Map< RouteKind, Type<Component> >(); constructor( @Optional() @Inject(ROUTE_CONFIGS_TOKEN) configsList: RouteDef[][] ) { if (!configsList) { this.routeConfigs = new RouteConfigs([]); return; } const configs: RouteDef[] = []; for (const routeDefList of configsList) { for (const routeDef of routeDefList) { configs.push(routeDef); } } this.routeConfigs = new RouteConfigs(configs); configs.forEach((config) => { if (isConcreteRouteDef(config)) { this.routeKindToNgComponent.set(config.routeKind, config.ngComponent); } }); }
/** * Returns RouteConfigs of current route configuration. Returnsn null if no * routes are registered. */ getRouteConfigs(): RouteConfigs { return this.routeConfigs; } getNgComponentByRouteKind(routeKind: RouteKind): Type<Component> | null { return this.routeKindToNgComponent.get(routeKind) || null; } /** * An NgModule that registers routes. * * Note: especially because Polymer based TensorBoard requires relative paths * for making requests, although not required, prefer to have path that ends * with "/". * * Example: * * function routeProvider() { * return [{ * path: '/experiments/', * ngComponent: ScalarsDashboard, * routeKind: RouteKind.EXPERIMENTS, * }]; * } * * @NgModule({ * imports: [ * RouteRegistryModule.registerRoutes(routesProvider), * ], * entryComponents: [ScalarsDashboard] * }) */ static registerRoutes( routeConfigProvider: () => RouteDef[] ): ModuleWithProviders<RouteRegistryModule> { return { ngModule: RouteRegistryModule, providers: [ { provide: ROUTE_CONFIGS_TOKEN, multi: true, useFactory: routeConfigProvider, }, ], }; } }
getRegisteredRouteKinds(): Iterable<RouteKind> { return this.routeKindToNgComponent.keys(); }
random_line_split
route_registry_module.ts
/* Copyright 2020 The TensorFlow Authors. 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. ==============================================================================*/ import { Component, Inject, ModuleWithProviders, NgModule, Optional, Type, } from '@angular/core'; import {RouteConfigs} from './route_config'; import {isConcreteRouteDef, RouteDef} from './route_config_types'; import {ROUTE_CONFIGS_TOKEN} from './route_registry_types'; import {RouteKind} from './types'; @NgModule({}) export class RouteRegistryModule { private readonly routeConfigs: RouteConfigs; private readonly routeKindToNgComponent = new Map< RouteKind, Type<Component> >(); constructor( @Optional() @Inject(ROUTE_CONFIGS_TOKEN) configsList: RouteDef[][] ) { if (!configsList)
const configs: RouteDef[] = []; for (const routeDefList of configsList) { for (const routeDef of routeDefList) { configs.push(routeDef); } } this.routeConfigs = new RouteConfigs(configs); configs.forEach((config) => { if (isConcreteRouteDef(config)) { this.routeKindToNgComponent.set(config.routeKind, config.ngComponent); } }); } getRegisteredRouteKinds(): Iterable<RouteKind> { return this.routeKindToNgComponent.keys(); } /** * Returns RouteConfigs of current route configuration. Returnsn null if no * routes are registered. */ getRouteConfigs(): RouteConfigs { return this.routeConfigs; } getNgComponentByRouteKind(routeKind: RouteKind): Type<Component> | null { return this.routeKindToNgComponent.get(routeKind) || null; } /** * An NgModule that registers routes. * * Note: especially because Polymer based TensorBoard requires relative paths * for making requests, although not required, prefer to have path that ends * with "/". * * Example: * * function routeProvider() { * return [{ * path: '/experiments/', * ngComponent: ScalarsDashboard, * routeKind: RouteKind.EXPERIMENTS, * }]; * } * * @NgModule({ * imports: [ * RouteRegistryModule.registerRoutes(routesProvider), * ], * entryComponents: [ScalarsDashboard] * }) */ static registerRoutes( routeConfigProvider: () => RouteDef[] ): ModuleWithProviders<RouteRegistryModule> { return { ngModule: RouteRegistryModule, providers: [ { provide: ROUTE_CONFIGS_TOKEN, multi: true, useFactory: routeConfigProvider, }, ], }; } }
{ this.routeConfigs = new RouteConfigs([]); return; }
conditional_block
route_registry_module.ts
/* Copyright 2020 The TensorFlow Authors. 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. ==============================================================================*/ import { Component, Inject, ModuleWithProviders, NgModule, Optional, Type, } from '@angular/core'; import {RouteConfigs} from './route_config'; import {isConcreteRouteDef, RouteDef} from './route_config_types'; import {ROUTE_CONFIGS_TOKEN} from './route_registry_types'; import {RouteKind} from './types'; @NgModule({}) export class RouteRegistryModule { private readonly routeConfigs: RouteConfigs; private readonly routeKindToNgComponent = new Map< RouteKind, Type<Component> >(); constructor( @Optional() @Inject(ROUTE_CONFIGS_TOKEN) configsList: RouteDef[][] ) { if (!configsList) { this.routeConfigs = new RouteConfigs([]); return; } const configs: RouteDef[] = []; for (const routeDefList of configsList) { for (const routeDef of routeDefList) { configs.push(routeDef); } } this.routeConfigs = new RouteConfigs(configs); configs.forEach((config) => { if (isConcreteRouteDef(config)) { this.routeKindToNgComponent.set(config.routeKind, config.ngComponent); } }); } getRegisteredRouteKinds(): Iterable<RouteKind>
/** * Returns RouteConfigs of current route configuration. Returnsn null if no * routes are registered. */ getRouteConfigs(): RouteConfigs { return this.routeConfigs; } getNgComponentByRouteKind(routeKind: RouteKind): Type<Component> | null { return this.routeKindToNgComponent.get(routeKind) || null; } /** * An NgModule that registers routes. * * Note: especially because Polymer based TensorBoard requires relative paths * for making requests, although not required, prefer to have path that ends * with "/". * * Example: * * function routeProvider() { * return [{ * path: '/experiments/', * ngComponent: ScalarsDashboard, * routeKind: RouteKind.EXPERIMENTS, * }]; * } * * @NgModule({ * imports: [ * RouteRegistryModule.registerRoutes(routesProvider), * ], * entryComponents: [ScalarsDashboard] * }) */ static registerRoutes( routeConfigProvider: () => RouteDef[] ): ModuleWithProviders<RouteRegistryModule> { return { ngModule: RouteRegistryModule, providers: [ { provide: ROUTE_CONFIGS_TOKEN, multi: true, useFactory: routeConfigProvider, }, ], }; } }
{ return this.routeKindToNgComponent.keys(); }
identifier_body
yt.py
# # Copyright (C) 2013 Sean Poyser # # # This code is a derivative of the YouTube plugin for XBMC # released under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3 # Copyright (C) 2010-2012 Tobias Ussing And Henrik Mosgaard Jensen # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with XBMC; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # # 5: "240p h263 flv container", # 18: "360p h264 mp4 container | 270 for rtmpe?", # 22: "720p h264 mp4 container", # 26: "???", # 33: "???", # 34: "360p h264 flv container", # 35: "480p h264 flv container", # 37: "1080p h264 mp4 container", # 38: "720p vp8 webm container", # 43: "360p h264 flv container", # 44: "480p vp8 webm container", # 45: "720p vp8 webm container", # 46: "520p vp8 webm stereo", # 59: "480 for rtmpe", # 78: "seems to be around 400 for rtmpe", # 82: "360p h264 stereo", # 83: "240p h264 stereo", # 84: "720p h264 stereo", # 85: "520p h264 stereo", # 100: "360p vp8 webm stereo", # 101: "480p vp8 webm stereo", # 102: "720p vp8 webm stereo", # 120: "hd720", # 121: "hd1080" import re import urllib2 import urllib import cgi import HTMLParser try: import simplejson as json except ImportError: import json MAX_REC_DEPTH = 5 def Clean(text): text = text.replace('&#8211;', '-') text = text.replace('&#8217;', '\'') text = text.replace('&#8220;', '"') text = text.replace('&#8221;', '"') text = text.replace('&#39;', '\'') text = text.replace('<b>', '') text = text.replace('</b>', '') text = text.replace('&amp;', '&') text = text.replace('\ufeff', '') return text def PlayVideo(id, forcePlayer=False): import xbmcgui import sys import utils busy = utils.showBusy() video, links = GetVideoInformation(id) if busy: busy.close() if 'best' not in video: return False url = video['best'] title = video['title'] image = video['thumbnail'] liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": title} ) if forcePlayer or len(sys.argv) < 2 or int(sys.argv[1]) == -1: import xbmc pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) pl.clear() pl.add(url, liz) xbmc.Player().play(pl) else: import xbmcplugin liz.setPath(url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz) return True def GetVideoInformation(id): #id = 'H7iQ4sAf0OE' #test for HLSVP #id = 'ofHlUJuw8Ak' #test for stereo #id = 'ifZkeuSrNRc' #account closed #id = 'M7FIvfx5J10' #id = 'n-D1EB74Ckg' #vevo #id = 'lVMWEheQ2hU' #vevo video = {} links = [] try: video, links = GetVideoInfo(id) except : pass return video, links def GetVideoInfo(id): url = 'http://www.youtube.com/watch?v=%s&safeSearch=none' % id html = FetchPage(url) video, links = Scrape(html) video['videoid'] = id video['thumbnail'] = "http://i.ytimg.com/vi/%s/0.jpg" % video['videoid'] video['title'] = GetVideoTitle(html) if len(links) == 0: if 'hlsvp' in video: video['best'] = video['hlsvp'] else: video['best'] = links[0][1] return video, links def GetVideoTitle(html): try: return Clean(re.compile('<meta name="title" content="(.+?)">').search(html).groups(1)[0]) except: pass return 'YouTube Video' def Scrape(html): stereo = [82, 83, 84, 85, 100, 101, 102] video = {} links = [] flashvars = ExtractFlashVars(html) if not flashvars.has_key(u"url_encoded_fmt_stream_map"): return video, links if flashvars.has_key(u"ttsurl"): video[u"ttsurl"] = flashvars[u"ttsurl"] if flashvars.has_key(u"hlsvp"): video[u"hlsvp"] = flashvars[u"hlsvp"] for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","): url_desc_map = cgi.parse_qs(url_desc) if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")): continue key = int(url_desc_map[u"itag"][0]) url = u"" if url_desc_map.has_key(u"url"): url = urllib.unquote(url_desc_map[u"url"][0]) elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"): url = urllib.unquote(url_desc_map[u"conn"][0]) if url.rfind("/") < len(url) -1: url = url + "/" url = url + urllib.unquote(url_desc_map[u"stream"][0]) elif url_desc_map.has_key(u"stream") and not url_desc_map.has_key(u"conn"): url = urllib.unquote(url_desc_map[u"stream"][0]) if url_desc_map.has_key(u"sig"): url = url + u"&signature=" + url_desc_map[u"sig"][0] elif url_desc_map.has_key(u"s"): sig = url_desc_map[u"s"][0] #url = url + u"&signature=" + DecryptSignature(sig) flashvars = ExtractFlashVars(html, assets=True) js = flashvars[u"js"] url += u"&signature=" + DecryptSignatureNew(sig, js) if key not in stereo: links.append([key, url]) #links.sort(reverse=True) return video, links def DecryptSignature(s): ''' use decryption solution by Youtube-DL project ''' if len(s) == 88: return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12] elif len(s) == 87: return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1] elif len(s) == 86: return s[2:63] + s[82] + s[64:82] + s[63] elif len(s) == 85: return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1] elif len(s) == 84:
elif len(s) == 83: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[53] + s[34:53] + s[24] + s[54:] elif len(s) == 82: return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34] elif len(s) == 81: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[2] + s[34:53] + s[24] + s[54:81] elif len(s) == 92: return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]; #else: # print ('Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s))) def ExtractFlashVars(data, assets=False): flashvars = {} found = False for line in data.split("\n"): if line.strip().find(";ytplayer.config = ") > 0: found = True p1 = line.find(";ytplayer.config = ") + len(";ytplayer.config = ") - 1 p2 = line.rfind(";") if p1 <= 0 or p2 <= 0: continue data = line[p1 + 1:p2] break data = RemoveAdditionalEndingDelimiter(data) if found: data = json.loads(data) if assets: flashvars = data['assets'] else: flashvars = data['args'] return flashvars def FetchPage(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') req.add_header('Referer', 'http://www.youtube.com/') return urllib2.urlopen(req).read().decode("utf-8") def replaceHTMLCodes(txt): # Fix missing ; in &#<number>; txt = re.sub("(&#[0-9]+)([^;^0-9]+)", "\\1;\\2", txt) txt = HTMLParser.HTMLParser().unescape(txt) txt = txt.replace("&amp;", "&") return txt def RemoveAdditionalEndingDelimiter(data): pos = data.find("};") if pos != -1: data = data[:pos + 1] return data #################################################### global playerData global allLocalFunNamesTab global allLocalVarNamesTab def _extractVarLocalFuns(match): varName, objBody = match.groups() output = '' for func in objBody.split( '},' ): output += re.sub( r'^([^:]+):function\(([^)]*)\)', r'function %s__\1(\2,*args)' % varName, func ) + '\n' return output def _jsToPy(jsFunBody): pythonFunBody = re.sub(r'var ([^=]+)={(.*?)}};', _extractVarLocalFuns, jsFunBody) pythonFunBody = re.sub(r'function (\w*)\$(\w*)', r'function \1_S_\2', pythonFunBody) pythonFunBody = pythonFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\((\w+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) # a.splice(b,c) -> del a[b:c] match = re.search('(\w+?)\.splice\(([^,]+),([^)]+)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'del ' + match.group(1) + '[' + match.group(2) + ':' + match.group(3) + ']' ) pythonFunBody = "\n".join(lines) pythonFunBody = re.sub(r'(\w+)\.(\w+)\(', r'\1__\2(', pythonFunBody) pythonFunBody = re.sub(r'([^=])(\w+)\[::-1\]', r'\1\2.reverse()', pythonFunBody) return pythonFunBody def _jsToPy1(jsFunBody): pythonFunBody = jsFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\(([0-9]+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) return "\n".join(lines) def _getLocalFunBody(funName): # get function body funName = funName.replace('$', '\\$') match = re.search('(function %s\([^)]+?\){[^}]+?})' % funName, playerData) if match: return match.group(1) return '' def _getAllLocalSubFunNames(mainFunBody): match = re.compile('[ =(,](\w+?)\([^)]*?\)').findall( mainFunBody ) if len(match): # first item is name of main function, so omit it funNameTab = set( match[1:] ) return funNameTab return set() def _extractLocalVarNames(mainFunBody): valid_funcs = ( 'reverse', 'split', 'splice', 'slice', 'join' ) match = re.compile( r'[; =(,](\w+)\.(\w+)\(' ).findall( mainFunBody ) local_vars = [] for name in match: if name[1] not in valid_funcs: local_vars.append( name[0] ) return set(local_vars) def _getLocalVarObjBody(varName): match = re.search( r'var %s={.*?}};' % varName, playerData ) if match: return match.group(0) return '' def DecryptSignatureNew(s, playerUrl): if not playerUrl.startswith('http:'): playerUrl = 'http:' + playerUrl #print "Decrypt_signature sign_len[%d] playerUrl[%s]" % (len(s), playerUrl) global allLocalFunNamesTab global allLocalVarNamesTab global playerData allLocalFunNamesTab = [] allLocalVarNamesTab = [] playerData = '' request = urllib2.Request(playerUrl) #res = core._fetchPage({u"link": playerUrl}) #playerData = res["content"] try: playerData = urllib2.urlopen(request).read() playerData = playerData.decode('utf-8', 'ignore') except Exception, e: #print str(e) print 'Failed to decode playerData' return '' # get main function name match = re.search("signature=([$a-zA-Z]+)\([^)]\)", playerData) if match: mainFunName = match.group(1) else: print('Failed to get main signature function name') return '' _mainFunName = mainFunName.replace('$','_S_') fullAlgoCode = _getfullAlgoCode(mainFunName) # wrap all local algo function into one function extractedSignatureAlgo() algoLines = fullAlgoCode.split('\n') for i in range(len(algoLines)): algoLines[i] = '\t' + algoLines[i] fullAlgoCode = 'def extractedSignatureAlgo(param):' fullAlgoCode += '\n'.join(algoLines) fullAlgoCode += '\n\treturn %s(param)' % _mainFunName fullAlgoCode += '\noutSignature = extractedSignatureAlgo( inSignature )\n' # after this function we should have all needed code in fullAlgoCode #print '---------------------------------------' #print '| ALGO FOR SIGNATURE DECRYPTION |' #print '---------------------------------------' #print fullAlgoCode #print '---------------------------------------' try: algoCodeObj = compile(fullAlgoCode, '', 'exec') except: print 'Failed to obtain decryptSignature code' return '' # for security allow only flew python global function in algo code vGlobals = {"__builtins__": None, 'len': len, 'list': list} # local variable to pass encrypted sign and get decrypted sign vLocals = { 'inSignature': s, 'outSignature': '' } # execute prepared code try: exec(algoCodeObj, vGlobals, vLocals) except: print 'decryptSignature code failed to exceute correctly' return '' #print 'Decrypted signature = [%s]' % vLocals['outSignature'] return vLocals['outSignature'] # Note, this method is using a recursion def _getfullAlgoCode(mainFunName, recDepth=0): global playerData global allLocalFunNamesTab global allLocalVarNamesTab if MAX_REC_DEPTH <= recDepth: print '_getfullAlgoCode: Maximum recursion depth exceeded' return funBody = _getLocalFunBody(mainFunName) if funBody != '': funNames = _getAllLocalSubFunNames(funBody) if len(funNames): for funName in funNames: funName_ = funName.replace('$','_S_') if funName not in allLocalFunNamesTab: funBody=funBody.replace(funName,funName_) allLocalFunNamesTab.append(funName) #print 'Add local function %s to known functions' % mainFunName funbody = _getfullAlgoCode(funName, recDepth+1) + "\n" + funBody varNames = _extractLocalVarNames(funBody) if len(varNames): for varName in varNames: if varName not in allLocalVarNamesTab: allLocalVarNamesTab.append(varName) funBody = _getLocalVarObjBody(varName) + "\n" + funBody # convert code from javascript to python funBody = _jsToPy(funBody) return '\n' + funBody + '\n' return funBody
return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26]
conditional_block
yt.py
# # Copyright (C) 2013 Sean Poyser # # # This code is a derivative of the YouTube plugin for XBMC # released under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3 # Copyright (C) 2010-2012 Tobias Ussing And Henrik Mosgaard Jensen # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with XBMC; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # # 5: "240p h263 flv container", # 18: "360p h264 mp4 container | 270 for rtmpe?", # 22: "720p h264 mp4 container", # 26: "???", # 33: "???", # 34: "360p h264 flv container", # 35: "480p h264 flv container", # 37: "1080p h264 mp4 container", # 38: "720p vp8 webm container", # 43: "360p h264 flv container", # 44: "480p vp8 webm container", # 45: "720p vp8 webm container", # 46: "520p vp8 webm stereo", # 59: "480 for rtmpe", # 78: "seems to be around 400 for rtmpe", # 82: "360p h264 stereo", # 83: "240p h264 stereo", # 84: "720p h264 stereo", # 85: "520p h264 stereo", # 100: "360p vp8 webm stereo", # 101: "480p vp8 webm stereo", # 102: "720p vp8 webm stereo", # 120: "hd720", # 121: "hd1080" import re import urllib2 import urllib import cgi import HTMLParser try: import simplejson as json except ImportError: import json MAX_REC_DEPTH = 5 def Clean(text): text = text.replace('&#8211;', '-') text = text.replace('&#8217;', '\'') text = text.replace('&#8220;', '"') text = text.replace('&#8221;', '"') text = text.replace('&#39;', '\'') text = text.replace('<b>', '') text = text.replace('</b>', '') text = text.replace('&amp;', '&') text = text.replace('\ufeff', '') return text def PlayVideo(id, forcePlayer=False): import xbmcgui import sys import utils busy = utils.showBusy() video, links = GetVideoInformation(id) if busy: busy.close() if 'best' not in video: return False url = video['best'] title = video['title'] image = video['thumbnail'] liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": title} ) if forcePlayer or len(sys.argv) < 2 or int(sys.argv[1]) == -1: import xbmc pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) pl.clear() pl.add(url, liz) xbmc.Player().play(pl) else: import xbmcplugin liz.setPath(url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz) return True def GetVideoInformation(id): #id = 'H7iQ4sAf0OE' #test for HLSVP #id = 'ofHlUJuw8Ak' #test for stereo #id = 'ifZkeuSrNRc' #account closed #id = 'M7FIvfx5J10' #id = 'n-D1EB74Ckg' #vevo #id = 'lVMWEheQ2hU' #vevo video = {} links = [] try: video, links = GetVideoInfo(id) except : pass return video, links def GetVideoInfo(id): url = 'http://www.youtube.com/watch?v=%s&safeSearch=none' % id html = FetchPage(url) video, links = Scrape(html) video['videoid'] = id video['thumbnail'] = "http://i.ytimg.com/vi/%s/0.jpg" % video['videoid'] video['title'] = GetVideoTitle(html) if len(links) == 0: if 'hlsvp' in video: video['best'] = video['hlsvp'] else: video['best'] = links[0][1] return video, links def GetVideoTitle(html): try: return Clean(re.compile('<meta name="title" content="(.+?)">').search(html).groups(1)[0]) except: pass return 'YouTube Video' def Scrape(html): stereo = [82, 83, 84, 85, 100, 101, 102] video = {} links = [] flashvars = ExtractFlashVars(html) if not flashvars.has_key(u"url_encoded_fmt_stream_map"): return video, links if flashvars.has_key(u"ttsurl"): video[u"ttsurl"] = flashvars[u"ttsurl"] if flashvars.has_key(u"hlsvp"): video[u"hlsvp"] = flashvars[u"hlsvp"] for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","): url_desc_map = cgi.parse_qs(url_desc) if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")): continue key = int(url_desc_map[u"itag"][0]) url = u"" if url_desc_map.has_key(u"url"): url = urllib.unquote(url_desc_map[u"url"][0]) elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"): url = urllib.unquote(url_desc_map[u"conn"][0]) if url.rfind("/") < len(url) -1: url = url + "/" url = url + urllib.unquote(url_desc_map[u"stream"][0]) elif url_desc_map.has_key(u"stream") and not url_desc_map.has_key(u"conn"): url = urllib.unquote(url_desc_map[u"stream"][0]) if url_desc_map.has_key(u"sig"): url = url + u"&signature=" + url_desc_map[u"sig"][0] elif url_desc_map.has_key(u"s"): sig = url_desc_map[u"s"][0] #url = url + u"&signature=" + DecryptSignature(sig) flashvars = ExtractFlashVars(html, assets=True) js = flashvars[u"js"] url += u"&signature=" + DecryptSignatureNew(sig, js) if key not in stereo: links.append([key, url]) #links.sort(reverse=True) return video, links def DecryptSignature(s): ''' use decryption solution by Youtube-DL project ''' if len(s) == 88: return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12] elif len(s) == 87: return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1] elif len(s) == 86: return s[2:63] + s[82] + s[64:82] + s[63] elif len(s) == 85: return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1] elif len(s) == 84: return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26] elif len(s) == 83: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[53] + s[34:53] + s[24] + s[54:] elif len(s) == 82: return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34] elif len(s) == 81: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[2] + s[34:53] + s[24] + s[54:81] elif len(s) == 92: return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]; #else: # print ('Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s))) def ExtractFlashVars(data, assets=False): flashvars = {} found = False for line in data.split("\n"): if line.strip().find(";ytplayer.config = ") > 0: found = True p1 = line.find(";ytplayer.config = ") + len(";ytplayer.config = ") - 1 p2 = line.rfind(";") if p1 <= 0 or p2 <= 0: continue data = line[p1 + 1:p2] break data = RemoveAdditionalEndingDelimiter(data) if found: data = json.loads(data) if assets: flashvars = data['assets'] else: flashvars = data['args'] return flashvars def FetchPage(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') req.add_header('Referer', 'http://www.youtube.com/') return urllib2.urlopen(req).read().decode("utf-8") def replaceHTMLCodes(txt): # Fix missing ; in &#<number>; txt = re.sub("(&#[0-9]+)([^;^0-9]+)", "\\1;\\2", txt) txt = HTMLParser.HTMLParser().unescape(txt) txt = txt.replace("&amp;", "&") return txt def RemoveAdditionalEndingDelimiter(data):
#################################################### global playerData global allLocalFunNamesTab global allLocalVarNamesTab def _extractVarLocalFuns(match): varName, objBody = match.groups() output = '' for func in objBody.split( '},' ): output += re.sub( r'^([^:]+):function\(([^)]*)\)', r'function %s__\1(\2,*args)' % varName, func ) + '\n' return output def _jsToPy(jsFunBody): pythonFunBody = re.sub(r'var ([^=]+)={(.*?)}};', _extractVarLocalFuns, jsFunBody) pythonFunBody = re.sub(r'function (\w*)\$(\w*)', r'function \1_S_\2', pythonFunBody) pythonFunBody = pythonFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\((\w+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) # a.splice(b,c) -> del a[b:c] match = re.search('(\w+?)\.splice\(([^,]+),([^)]+)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'del ' + match.group(1) + '[' + match.group(2) + ':' + match.group(3) + ']' ) pythonFunBody = "\n".join(lines) pythonFunBody = re.sub(r'(\w+)\.(\w+)\(', r'\1__\2(', pythonFunBody) pythonFunBody = re.sub(r'([^=])(\w+)\[::-1\]', r'\1\2.reverse()', pythonFunBody) return pythonFunBody def _jsToPy1(jsFunBody): pythonFunBody = jsFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\(([0-9]+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) return "\n".join(lines) def _getLocalFunBody(funName): # get function body funName = funName.replace('$', '\\$') match = re.search('(function %s\([^)]+?\){[^}]+?})' % funName, playerData) if match: return match.group(1) return '' def _getAllLocalSubFunNames(mainFunBody): match = re.compile('[ =(,](\w+?)\([^)]*?\)').findall( mainFunBody ) if len(match): # first item is name of main function, so omit it funNameTab = set( match[1:] ) return funNameTab return set() def _extractLocalVarNames(mainFunBody): valid_funcs = ( 'reverse', 'split', 'splice', 'slice', 'join' ) match = re.compile( r'[; =(,](\w+)\.(\w+)\(' ).findall( mainFunBody ) local_vars = [] for name in match: if name[1] not in valid_funcs: local_vars.append( name[0] ) return set(local_vars) def _getLocalVarObjBody(varName): match = re.search( r'var %s={.*?}};' % varName, playerData ) if match: return match.group(0) return '' def DecryptSignatureNew(s, playerUrl): if not playerUrl.startswith('http:'): playerUrl = 'http:' + playerUrl #print "Decrypt_signature sign_len[%d] playerUrl[%s]" % (len(s), playerUrl) global allLocalFunNamesTab global allLocalVarNamesTab global playerData allLocalFunNamesTab = [] allLocalVarNamesTab = [] playerData = '' request = urllib2.Request(playerUrl) #res = core._fetchPage({u"link": playerUrl}) #playerData = res["content"] try: playerData = urllib2.urlopen(request).read() playerData = playerData.decode('utf-8', 'ignore') except Exception, e: #print str(e) print 'Failed to decode playerData' return '' # get main function name match = re.search("signature=([$a-zA-Z]+)\([^)]\)", playerData) if match: mainFunName = match.group(1) else: print('Failed to get main signature function name') return '' _mainFunName = mainFunName.replace('$','_S_') fullAlgoCode = _getfullAlgoCode(mainFunName) # wrap all local algo function into one function extractedSignatureAlgo() algoLines = fullAlgoCode.split('\n') for i in range(len(algoLines)): algoLines[i] = '\t' + algoLines[i] fullAlgoCode = 'def extractedSignatureAlgo(param):' fullAlgoCode += '\n'.join(algoLines) fullAlgoCode += '\n\treturn %s(param)' % _mainFunName fullAlgoCode += '\noutSignature = extractedSignatureAlgo( inSignature )\n' # after this function we should have all needed code in fullAlgoCode #print '---------------------------------------' #print '| ALGO FOR SIGNATURE DECRYPTION |' #print '---------------------------------------' #print fullAlgoCode #print '---------------------------------------' try: algoCodeObj = compile(fullAlgoCode, '', 'exec') except: print 'Failed to obtain decryptSignature code' return '' # for security allow only flew python global function in algo code vGlobals = {"__builtins__": None, 'len': len, 'list': list} # local variable to pass encrypted sign and get decrypted sign vLocals = { 'inSignature': s, 'outSignature': '' } # execute prepared code try: exec(algoCodeObj, vGlobals, vLocals) except: print 'decryptSignature code failed to exceute correctly' return '' #print 'Decrypted signature = [%s]' % vLocals['outSignature'] return vLocals['outSignature'] # Note, this method is using a recursion def _getfullAlgoCode(mainFunName, recDepth=0): global playerData global allLocalFunNamesTab global allLocalVarNamesTab if MAX_REC_DEPTH <= recDepth: print '_getfullAlgoCode: Maximum recursion depth exceeded' return funBody = _getLocalFunBody(mainFunName) if funBody != '': funNames = _getAllLocalSubFunNames(funBody) if len(funNames): for funName in funNames: funName_ = funName.replace('$','_S_') if funName not in allLocalFunNamesTab: funBody=funBody.replace(funName,funName_) allLocalFunNamesTab.append(funName) #print 'Add local function %s to known functions' % mainFunName funbody = _getfullAlgoCode(funName, recDepth+1) + "\n" + funBody varNames = _extractLocalVarNames(funBody) if len(varNames): for varName in varNames: if varName not in allLocalVarNamesTab: allLocalVarNamesTab.append(varName) funBody = _getLocalVarObjBody(varName) + "\n" + funBody # convert code from javascript to python funBody = _jsToPy(funBody) return '\n' + funBody + '\n' return funBody
pos = data.find("};") if pos != -1: data = data[:pos + 1] return data
identifier_body
yt.py
# # Copyright (C) 2013 Sean Poyser # # # This code is a derivative of the YouTube plugin for XBMC # released under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3 # Copyright (C) 2010-2012 Tobias Ussing And Henrik Mosgaard Jensen # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with XBMC; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # # 5: "240p h263 flv container", # 18: "360p h264 mp4 container | 270 for rtmpe?", # 22: "720p h264 mp4 container", # 26: "???", # 33: "???", # 34: "360p h264 flv container", # 35: "480p h264 flv container", # 37: "1080p h264 mp4 container", # 38: "720p vp8 webm container", # 43: "360p h264 flv container", # 44: "480p vp8 webm container", # 45: "720p vp8 webm container", # 46: "520p vp8 webm stereo", # 59: "480 for rtmpe", # 78: "seems to be around 400 for rtmpe", # 82: "360p h264 stereo", # 83: "240p h264 stereo", # 84: "720p h264 stereo", # 85: "520p h264 stereo", # 100: "360p vp8 webm stereo", # 101: "480p vp8 webm stereo", # 102: "720p vp8 webm stereo", # 120: "hd720", # 121: "hd1080" import re import urllib2 import urllib import cgi import HTMLParser try: import simplejson as json except ImportError: import json MAX_REC_DEPTH = 5 def Clean(text): text = text.replace('&#8211;', '-') text = text.replace('&#8217;', '\'') text = text.replace('&#8220;', '"') text = text.replace('&#8221;', '"') text = text.replace('&#39;', '\'') text = text.replace('<b>', '') text = text.replace('</b>', '') text = text.replace('&amp;', '&') text = text.replace('\ufeff', '') return text def PlayVideo(id, forcePlayer=False): import xbmcgui import sys import utils busy = utils.showBusy() video, links = GetVideoInformation(id) if busy: busy.close() if 'best' not in video: return False url = video['best'] title = video['title'] image = video['thumbnail'] liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": title} ) if forcePlayer or len(sys.argv) < 2 or int(sys.argv[1]) == -1: import xbmc pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) pl.clear() pl.add(url, liz) xbmc.Player().play(pl) else: import xbmcplugin liz.setPath(url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz) return True def GetVideoInformation(id): #id = 'H7iQ4sAf0OE' #test for HLSVP #id = 'ofHlUJuw8Ak' #test for stereo #id = 'ifZkeuSrNRc' #account closed #id = 'M7FIvfx5J10' #id = 'n-D1EB74Ckg' #vevo #id = 'lVMWEheQ2hU' #vevo video = {} links = [] try: video, links = GetVideoInfo(id) except : pass return video, links def GetVideoInfo(id): url = 'http://www.youtube.com/watch?v=%s&safeSearch=none' % id html = FetchPage(url) video, links = Scrape(html) video['videoid'] = id video['thumbnail'] = "http://i.ytimg.com/vi/%s/0.jpg" % video['videoid'] video['title'] = GetVideoTitle(html) if len(links) == 0: if 'hlsvp' in video: video['best'] = video['hlsvp'] else: video['best'] = links[0][1] return video, links def GetVideoTitle(html): try: return Clean(re.compile('<meta name="title" content="(.+?)">').search(html).groups(1)[0]) except: pass return 'YouTube Video' def Scrape(html): stereo = [82, 83, 84, 85, 100, 101, 102] video = {} links = [] flashvars = ExtractFlashVars(html) if not flashvars.has_key(u"url_encoded_fmt_stream_map"): return video, links if flashvars.has_key(u"ttsurl"): video[u"ttsurl"] = flashvars[u"ttsurl"] if flashvars.has_key(u"hlsvp"): video[u"hlsvp"] = flashvars[u"hlsvp"] for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","): url_desc_map = cgi.parse_qs(url_desc) if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")): continue key = int(url_desc_map[u"itag"][0]) url = u"" if url_desc_map.has_key(u"url"): url = urllib.unquote(url_desc_map[u"url"][0]) elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"): url = urllib.unquote(url_desc_map[u"conn"][0]) if url.rfind("/") < len(url) -1: url = url + "/" url = url + urllib.unquote(url_desc_map[u"stream"][0]) elif url_desc_map.has_key(u"stream") and not url_desc_map.has_key(u"conn"): url = urllib.unquote(url_desc_map[u"stream"][0]) if url_desc_map.has_key(u"sig"): url = url + u"&signature=" + url_desc_map[u"sig"][0] elif url_desc_map.has_key(u"s"): sig = url_desc_map[u"s"][0] #url = url + u"&signature=" + DecryptSignature(sig) flashvars = ExtractFlashVars(html, assets=True) js = flashvars[u"js"] url += u"&signature=" + DecryptSignatureNew(sig, js) if key not in stereo: links.append([key, url]) #links.sort(reverse=True) return video, links def DecryptSignature(s): ''' use decryption solution by Youtube-DL project ''' if len(s) == 88: return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12] elif len(s) == 87: return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1] elif len(s) == 86: return s[2:63] + s[82] + s[64:82] + s[63] elif len(s) == 85: return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1] elif len(s) == 84: return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26] elif len(s) == 83: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[53] + s[34:53] + s[24] + s[54:] elif len(s) == 82: return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34] elif len(s) == 81: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[2] + s[34:53] + s[24] + s[54:81] elif len(s) == 92: return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]; #else: # print ('Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s))) def ExtractFlashVars(data, assets=False): flashvars = {} found = False for line in data.split("\n"): if line.strip().find(";ytplayer.config = ") > 0: found = True p1 = line.find(";ytplayer.config = ") + len(";ytplayer.config = ") - 1 p2 = line.rfind(";") if p1 <= 0 or p2 <= 0: continue data = line[p1 + 1:p2] break data = RemoveAdditionalEndingDelimiter(data) if found: data = json.loads(data) if assets: flashvars = data['assets'] else: flashvars = data['args']
req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') req.add_header('Referer', 'http://www.youtube.com/') return urllib2.urlopen(req).read().decode("utf-8") def replaceHTMLCodes(txt): # Fix missing ; in &#<number>; txt = re.sub("(&#[0-9]+)([^;^0-9]+)", "\\1;\\2", txt) txt = HTMLParser.HTMLParser().unescape(txt) txt = txt.replace("&amp;", "&") return txt def RemoveAdditionalEndingDelimiter(data): pos = data.find("};") if pos != -1: data = data[:pos + 1] return data #################################################### global playerData global allLocalFunNamesTab global allLocalVarNamesTab def _extractVarLocalFuns(match): varName, objBody = match.groups() output = '' for func in objBody.split( '},' ): output += re.sub( r'^([^:]+):function\(([^)]*)\)', r'function %s__\1(\2,*args)' % varName, func ) + '\n' return output def _jsToPy(jsFunBody): pythonFunBody = re.sub(r'var ([^=]+)={(.*?)}};', _extractVarLocalFuns, jsFunBody) pythonFunBody = re.sub(r'function (\w*)\$(\w*)', r'function \1_S_\2', pythonFunBody) pythonFunBody = pythonFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\((\w+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) # a.splice(b,c) -> del a[b:c] match = re.search('(\w+?)\.splice\(([^,]+),([^)]+)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'del ' + match.group(1) + '[' + match.group(2) + ':' + match.group(3) + ']' ) pythonFunBody = "\n".join(lines) pythonFunBody = re.sub(r'(\w+)\.(\w+)\(', r'\1__\2(', pythonFunBody) pythonFunBody = re.sub(r'([^=])(\w+)\[::-1\]', r'\1\2.reverse()', pythonFunBody) return pythonFunBody def _jsToPy1(jsFunBody): pythonFunBody = jsFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\(([0-9]+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) return "\n".join(lines) def _getLocalFunBody(funName): # get function body funName = funName.replace('$', '\\$') match = re.search('(function %s\([^)]+?\){[^}]+?})' % funName, playerData) if match: return match.group(1) return '' def _getAllLocalSubFunNames(mainFunBody): match = re.compile('[ =(,](\w+?)\([^)]*?\)').findall( mainFunBody ) if len(match): # first item is name of main function, so omit it funNameTab = set( match[1:] ) return funNameTab return set() def _extractLocalVarNames(mainFunBody): valid_funcs = ( 'reverse', 'split', 'splice', 'slice', 'join' ) match = re.compile( r'[; =(,](\w+)\.(\w+)\(' ).findall( mainFunBody ) local_vars = [] for name in match: if name[1] not in valid_funcs: local_vars.append( name[0] ) return set(local_vars) def _getLocalVarObjBody(varName): match = re.search( r'var %s={.*?}};' % varName, playerData ) if match: return match.group(0) return '' def DecryptSignatureNew(s, playerUrl): if not playerUrl.startswith('http:'): playerUrl = 'http:' + playerUrl #print "Decrypt_signature sign_len[%d] playerUrl[%s]" % (len(s), playerUrl) global allLocalFunNamesTab global allLocalVarNamesTab global playerData allLocalFunNamesTab = [] allLocalVarNamesTab = [] playerData = '' request = urllib2.Request(playerUrl) #res = core._fetchPage({u"link": playerUrl}) #playerData = res["content"] try: playerData = urllib2.urlopen(request).read() playerData = playerData.decode('utf-8', 'ignore') except Exception, e: #print str(e) print 'Failed to decode playerData' return '' # get main function name match = re.search("signature=([$a-zA-Z]+)\([^)]\)", playerData) if match: mainFunName = match.group(1) else: print('Failed to get main signature function name') return '' _mainFunName = mainFunName.replace('$','_S_') fullAlgoCode = _getfullAlgoCode(mainFunName) # wrap all local algo function into one function extractedSignatureAlgo() algoLines = fullAlgoCode.split('\n') for i in range(len(algoLines)): algoLines[i] = '\t' + algoLines[i] fullAlgoCode = 'def extractedSignatureAlgo(param):' fullAlgoCode += '\n'.join(algoLines) fullAlgoCode += '\n\treturn %s(param)' % _mainFunName fullAlgoCode += '\noutSignature = extractedSignatureAlgo( inSignature )\n' # after this function we should have all needed code in fullAlgoCode #print '---------------------------------------' #print '| ALGO FOR SIGNATURE DECRYPTION |' #print '---------------------------------------' #print fullAlgoCode #print '---------------------------------------' try: algoCodeObj = compile(fullAlgoCode, '', 'exec') except: print 'Failed to obtain decryptSignature code' return '' # for security allow only flew python global function in algo code vGlobals = {"__builtins__": None, 'len': len, 'list': list} # local variable to pass encrypted sign and get decrypted sign vLocals = { 'inSignature': s, 'outSignature': '' } # execute prepared code try: exec(algoCodeObj, vGlobals, vLocals) except: print 'decryptSignature code failed to exceute correctly' return '' #print 'Decrypted signature = [%s]' % vLocals['outSignature'] return vLocals['outSignature'] # Note, this method is using a recursion def _getfullAlgoCode(mainFunName, recDepth=0): global playerData global allLocalFunNamesTab global allLocalVarNamesTab if MAX_REC_DEPTH <= recDepth: print '_getfullAlgoCode: Maximum recursion depth exceeded' return funBody = _getLocalFunBody(mainFunName) if funBody != '': funNames = _getAllLocalSubFunNames(funBody) if len(funNames): for funName in funNames: funName_ = funName.replace('$','_S_') if funName not in allLocalFunNamesTab: funBody=funBody.replace(funName,funName_) allLocalFunNamesTab.append(funName) #print 'Add local function %s to known functions' % mainFunName funbody = _getfullAlgoCode(funName, recDepth+1) + "\n" + funBody varNames = _extractLocalVarNames(funBody) if len(varNames): for varName in varNames: if varName not in allLocalVarNamesTab: allLocalVarNamesTab.append(varName) funBody = _getLocalVarObjBody(varName) + "\n" + funBody # convert code from javascript to python funBody = _jsToPy(funBody) return '\n' + funBody + '\n' return funBody
return flashvars def FetchPage(url): req = urllib2.Request(url)
random_line_split
yt.py
# # Copyright (C) 2013 Sean Poyser # # # This code is a derivative of the YouTube plugin for XBMC # released under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3 # Copyright (C) 2010-2012 Tobias Ussing And Henrik Mosgaard Jensen # # This Program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This Program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with XBMC; see the file COPYING. If not, write to # the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. # http://www.gnu.org/copyleft/gpl.html # # 5: "240p h263 flv container", # 18: "360p h264 mp4 container | 270 for rtmpe?", # 22: "720p h264 mp4 container", # 26: "???", # 33: "???", # 34: "360p h264 flv container", # 35: "480p h264 flv container", # 37: "1080p h264 mp4 container", # 38: "720p vp8 webm container", # 43: "360p h264 flv container", # 44: "480p vp8 webm container", # 45: "720p vp8 webm container", # 46: "520p vp8 webm stereo", # 59: "480 for rtmpe", # 78: "seems to be around 400 for rtmpe", # 82: "360p h264 stereo", # 83: "240p h264 stereo", # 84: "720p h264 stereo", # 85: "520p h264 stereo", # 100: "360p vp8 webm stereo", # 101: "480p vp8 webm stereo", # 102: "720p vp8 webm stereo", # 120: "hd720", # 121: "hd1080" import re import urllib2 import urllib import cgi import HTMLParser try: import simplejson as json except ImportError: import json MAX_REC_DEPTH = 5 def Clean(text): text = text.replace('&#8211;', '-') text = text.replace('&#8217;', '\'') text = text.replace('&#8220;', '"') text = text.replace('&#8221;', '"') text = text.replace('&#39;', '\'') text = text.replace('<b>', '') text = text.replace('</b>', '') text = text.replace('&amp;', '&') text = text.replace('\ufeff', '') return text def PlayVideo(id, forcePlayer=False): import xbmcgui import sys import utils busy = utils.showBusy() video, links = GetVideoInformation(id) if busy: busy.close() if 'best' not in video: return False url = video['best'] title = video['title'] image = video['thumbnail'] liz = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image) liz.setInfo( type="Video", infoLabels={ "Title": title} ) if forcePlayer or len(sys.argv) < 2 or int(sys.argv[1]) == -1: import xbmc pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) pl.clear() pl.add(url, liz) xbmc.Player().play(pl) else: import xbmcplugin liz.setPath(url) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, liz) return True def GetVideoInformation(id): #id = 'H7iQ4sAf0OE' #test for HLSVP #id = 'ofHlUJuw8Ak' #test for stereo #id = 'ifZkeuSrNRc' #account closed #id = 'M7FIvfx5J10' #id = 'n-D1EB74Ckg' #vevo #id = 'lVMWEheQ2hU' #vevo video = {} links = [] try: video, links = GetVideoInfo(id) except : pass return video, links def GetVideoInfo(id): url = 'http://www.youtube.com/watch?v=%s&safeSearch=none' % id html = FetchPage(url) video, links = Scrape(html) video['videoid'] = id video['thumbnail'] = "http://i.ytimg.com/vi/%s/0.jpg" % video['videoid'] video['title'] = GetVideoTitle(html) if len(links) == 0: if 'hlsvp' in video: video['best'] = video['hlsvp'] else: video['best'] = links[0][1] return video, links def GetVideoTitle(html): try: return Clean(re.compile('<meta name="title" content="(.+?)">').search(html).groups(1)[0]) except: pass return 'YouTube Video' def Scrape(html): stereo = [82, 83, 84, 85, 100, 101, 102] video = {} links = [] flashvars = ExtractFlashVars(html) if not flashvars.has_key(u"url_encoded_fmt_stream_map"): return video, links if flashvars.has_key(u"ttsurl"): video[u"ttsurl"] = flashvars[u"ttsurl"] if flashvars.has_key(u"hlsvp"): video[u"hlsvp"] = flashvars[u"hlsvp"] for url_desc in flashvars[u"url_encoded_fmt_stream_map"].split(u","): url_desc_map = cgi.parse_qs(url_desc) if not (url_desc_map.has_key(u"url") or url_desc_map.has_key(u"stream")): continue key = int(url_desc_map[u"itag"][0]) url = u"" if url_desc_map.has_key(u"url"): url = urllib.unquote(url_desc_map[u"url"][0]) elif url_desc_map.has_key(u"conn") and url_desc_map.has_key(u"stream"): url = urllib.unquote(url_desc_map[u"conn"][0]) if url.rfind("/") < len(url) -1: url = url + "/" url = url + urllib.unquote(url_desc_map[u"stream"][0]) elif url_desc_map.has_key(u"stream") and not url_desc_map.has_key(u"conn"): url = urllib.unquote(url_desc_map[u"stream"][0]) if url_desc_map.has_key(u"sig"): url = url + u"&signature=" + url_desc_map[u"sig"][0] elif url_desc_map.has_key(u"s"): sig = url_desc_map[u"s"][0] #url = url + u"&signature=" + DecryptSignature(sig) flashvars = ExtractFlashVars(html, assets=True) js = flashvars[u"js"] url += u"&signature=" + DecryptSignatureNew(sig, js) if key not in stereo: links.append([key, url]) #links.sort(reverse=True) return video, links def DecryptSignature(s): ''' use decryption solution by Youtube-DL project ''' if len(s) == 88: return s[48] + s[81:67:-1] + s[82] + s[66:62:-1] + s[85] + s[61:48:-1] + s[67] + s[47:12:-1] + s[3] + s[11:3:-1] + s[2] + s[12] elif len(s) == 87: return s[62] + s[82:62:-1] + s[83] + s[61:52:-1] + s[0] + s[51:2:-1] elif len(s) == 86: return s[2:63] + s[82] + s[64:82] + s[63] elif len(s) == 85: return s[76] + s[82:76:-1] + s[83] + s[75:60:-1] + s[0] + s[59:50:-1] + s[1] + s[49:2:-1] elif len(s) == 84: return s[83:36:-1] + s[2] + s[35:26:-1] + s[3] + s[25:3:-1] + s[26] elif len(s) == 83: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[53] + s[34:53] + s[24] + s[54:] elif len(s) == 82: return s[36] + s[79:67:-1] + s[81] + s[66:40:-1] + s[33] + s[39:36:-1] + s[40] + s[35] + s[0] + s[67] + s[32:0:-1] + s[34] elif len(s) == 81: return s[6] + s[3:6] + s[33] + s[7:24] + s[0] + s[25:33] + s[2] + s[34:53] + s[24] + s[54:81] elif len(s) == 92: return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]; #else: # print ('Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s))) def ExtractFlashVars(data, assets=False): flashvars = {} found = False for line in data.split("\n"): if line.strip().find(";ytplayer.config = ") > 0: found = True p1 = line.find(";ytplayer.config = ") + len(";ytplayer.config = ") - 1 p2 = line.rfind(";") if p1 <= 0 or p2 <= 0: continue data = line[p1 + 1:p2] break data = RemoveAdditionalEndingDelimiter(data) if found: data = json.loads(data) if assets: flashvars = data['assets'] else: flashvars = data['args'] return flashvars def FetchPage(url): req = urllib2.Request(url) req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3') req.add_header('Referer', 'http://www.youtube.com/') return urllib2.urlopen(req).read().decode("utf-8") def replaceHTMLCodes(txt): # Fix missing ; in &#<number>; txt = re.sub("(&#[0-9]+)([^;^0-9]+)", "\\1;\\2", txt) txt = HTMLParser.HTMLParser().unescape(txt) txt = txt.replace("&amp;", "&") return txt def RemoveAdditionalEndingDelimiter(data): pos = data.find("};") if pos != -1: data = data[:pos + 1] return data #################################################### global playerData global allLocalFunNamesTab global allLocalVarNamesTab def _extractVarLocalFuns(match): varName, objBody = match.groups() output = '' for func in objBody.split( '},' ): output += re.sub( r'^([^:]+):function\(([^)]*)\)', r'function %s__\1(\2,*args)' % varName, func ) + '\n' return output def _jsToPy(jsFunBody): pythonFunBody = re.sub(r'var ([^=]+)={(.*?)}};', _extractVarLocalFuns, jsFunBody) pythonFunBody = re.sub(r'function (\w*)\$(\w*)', r'function \1_S_\2', pythonFunBody) pythonFunBody = pythonFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\((\w+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) # a.splice(b,c) -> del a[b:c] match = re.search('(\w+?)\.splice\(([^,]+),([^)]+)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'del ' + match.group(1) + '[' + match.group(2) + ':' + match.group(3) + ']' ) pythonFunBody = "\n".join(lines) pythonFunBody = re.sub(r'(\w+)\.(\w+)\(', r'\1__\2(', pythonFunBody) pythonFunBody = re.sub(r'([^=])(\w+)\[::-1\]', r'\1\2.reverse()', pythonFunBody) return pythonFunBody def _jsToPy1(jsFunBody): pythonFunBody = jsFunBody.replace('function', 'def').replace('{', ':\n\t').replace('}', '').replace(';', '\n\t').replace('var ', '') pythonFunBody = pythonFunBody.replace('.reverse()', '[::-1]') lines = pythonFunBody.split('\n') for i in range(len(lines)): # a.split("") -> list(a) match = re.search('(\w+?)\.split\(""\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'list(' + match.group(1) + ')') # a.length -> len(a) match = re.search('(\w+?)\.length', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), 'len(' + match.group(1) + ')') # a.slice(3) -> a[3:] match = re.search('(\w+?)\.slice\(([0-9]+?)\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(1) + ('[%s:]' % match.group(2)) ) # a.join("") -> "".join(a) match = re.search('(\w+?)\.join\(("[^"]*?")\)', lines[i]) if match: lines[i] = lines[i].replace( match.group(0), match.group(2) + '.join(' + match.group(1) + ')' ) return "\n".join(lines) def
(funName): # get function body funName = funName.replace('$', '\\$') match = re.search('(function %s\([^)]+?\){[^}]+?})' % funName, playerData) if match: return match.group(1) return '' def _getAllLocalSubFunNames(mainFunBody): match = re.compile('[ =(,](\w+?)\([^)]*?\)').findall( mainFunBody ) if len(match): # first item is name of main function, so omit it funNameTab = set( match[1:] ) return funNameTab return set() def _extractLocalVarNames(mainFunBody): valid_funcs = ( 'reverse', 'split', 'splice', 'slice', 'join' ) match = re.compile( r'[; =(,](\w+)\.(\w+)\(' ).findall( mainFunBody ) local_vars = [] for name in match: if name[1] not in valid_funcs: local_vars.append( name[0] ) return set(local_vars) def _getLocalVarObjBody(varName): match = re.search( r'var %s={.*?}};' % varName, playerData ) if match: return match.group(0) return '' def DecryptSignatureNew(s, playerUrl): if not playerUrl.startswith('http:'): playerUrl = 'http:' + playerUrl #print "Decrypt_signature sign_len[%d] playerUrl[%s]" % (len(s), playerUrl) global allLocalFunNamesTab global allLocalVarNamesTab global playerData allLocalFunNamesTab = [] allLocalVarNamesTab = [] playerData = '' request = urllib2.Request(playerUrl) #res = core._fetchPage({u"link": playerUrl}) #playerData = res["content"] try: playerData = urllib2.urlopen(request).read() playerData = playerData.decode('utf-8', 'ignore') except Exception, e: #print str(e) print 'Failed to decode playerData' return '' # get main function name match = re.search("signature=([$a-zA-Z]+)\([^)]\)", playerData) if match: mainFunName = match.group(1) else: print('Failed to get main signature function name') return '' _mainFunName = mainFunName.replace('$','_S_') fullAlgoCode = _getfullAlgoCode(mainFunName) # wrap all local algo function into one function extractedSignatureAlgo() algoLines = fullAlgoCode.split('\n') for i in range(len(algoLines)): algoLines[i] = '\t' + algoLines[i] fullAlgoCode = 'def extractedSignatureAlgo(param):' fullAlgoCode += '\n'.join(algoLines) fullAlgoCode += '\n\treturn %s(param)' % _mainFunName fullAlgoCode += '\noutSignature = extractedSignatureAlgo( inSignature )\n' # after this function we should have all needed code in fullAlgoCode #print '---------------------------------------' #print '| ALGO FOR SIGNATURE DECRYPTION |' #print '---------------------------------------' #print fullAlgoCode #print '---------------------------------------' try: algoCodeObj = compile(fullAlgoCode, '', 'exec') except: print 'Failed to obtain decryptSignature code' return '' # for security allow only flew python global function in algo code vGlobals = {"__builtins__": None, 'len': len, 'list': list} # local variable to pass encrypted sign and get decrypted sign vLocals = { 'inSignature': s, 'outSignature': '' } # execute prepared code try: exec(algoCodeObj, vGlobals, vLocals) except: print 'decryptSignature code failed to exceute correctly' return '' #print 'Decrypted signature = [%s]' % vLocals['outSignature'] return vLocals['outSignature'] # Note, this method is using a recursion def _getfullAlgoCode(mainFunName, recDepth=0): global playerData global allLocalFunNamesTab global allLocalVarNamesTab if MAX_REC_DEPTH <= recDepth: print '_getfullAlgoCode: Maximum recursion depth exceeded' return funBody = _getLocalFunBody(mainFunName) if funBody != '': funNames = _getAllLocalSubFunNames(funBody) if len(funNames): for funName in funNames: funName_ = funName.replace('$','_S_') if funName not in allLocalFunNamesTab: funBody=funBody.replace(funName,funName_) allLocalFunNamesTab.append(funName) #print 'Add local function %s to known functions' % mainFunName funbody = _getfullAlgoCode(funName, recDepth+1) + "\n" + funBody varNames = _extractLocalVarNames(funBody) if len(varNames): for varName in varNames: if varName not in allLocalVarNamesTab: allLocalVarNamesTab.append(varName) funBody = _getLocalVarObjBody(varName) + "\n" + funBody # convert code from javascript to python funBody = _jsToPy(funBody) return '\n' + funBody + '\n' return funBody
_getLocalFunBody
identifier_name
SideNavigatorItem.tsx
import React from 'react' import cc from 'classcat' import styled from '../../lib/styled' import { sideBarTextColor, sideBarSecondaryTextColor, activeBackgroundColor, iconColor } from '../../lib/styled/styleFunctions' import { IconArrowSingleRight, IconArrowSingleDown } from '../icons' const Container = styled.div` position: relative; user-select: none; height: 34px; display: flex; justify-content: space-between; .sideNavWrapper { min-width: 0; flex: 1 1 auto; button > span { width: 30px; ${iconColor} } } transition: 200ms background-color; &:hover, &:focus, &:active, &.active { ${activeBackgroundColor} button > span { ${sideBarTextColor} } } &:hover { cursor: pointer; } .control { opacity: 0; } &:hover .control { opacity: 1; } &.allnotes-sidenav { padding-left: 4px !important; button { padding-left: 6px !important; } } &.bookmark-sidenav { padding-left: 4px !important; margin-bottom: 25px; button { padding-left: 6px !important; } } ` const FoldButton = styled.button` position: absolute; width: 26px; height: 26px; padding-left: 15px; border: none; background-color: transparent; margin-right: 3px; border-radius: 2px; flex: 0 0 26px; top: 5px; ${sideBarSecondaryTextColor} &:focus { box-shadow: none; } ` const ClickableContainer = styled.button` background-color: transparent; border: none; height: 35px; display: flex; align-items: center; min-width: 0; width: 100%; flex: 1 1 auto; ${sideBarTextColor} .icon { flex: 0 0 auto; margin-right: 4px; ${sideBarSecondaryTextColor} } ` const Label = styled.div` min-width: 0 overflow: hidden; white-space: nowrap; flex: 1 1 auto; text-align: left; ` const ControlContainer = styled.div` position: absolute; right: 0; top: 4px; padding-left: 10px; display: flex; flex: 2 0 auto; justify-content: flex-end; button { ${iconColor} } ` const SideNavigatorItemIconContainer = styled.span` padding-right: 6px; ` interface SideNaviagtorItemProps { label: string icon?: React.ReactNode depth: number controlComponents?: any[] className?: string folded?: boolean active?: boolean onFoldButtonClick?: (event: React.MouseEvent) => void onClick?: (event: React.MouseEvent) => void onContextMenu?: (event: React.MouseEvent) => void onDrop?: (event: React.DragEvent) => void onDragOver?: (event: React.DragEvent) => void onDragEnd?: (event: React.DragEvent) => void onDoubleClick?: (event: React.MouseEvent) => void } const SideNaviagtorItem = ({ label, icon, depth, controlComponents, className, folded, active, onFoldButtonClick, onClick, onDoubleClick, onContextMenu, onDrop, onDragOver, onDragEnd }: SideNaviagtorItemProps) => { return ( <Container className={cc([className, active && 'active'])} onContextMenu={onContextMenu} onDrop={onDrop} onDragOver={onDragOver} onDragEnd={onDragEnd} > <div className='sideNavWrapper'> {folded != null && ( <FoldButton className={folded ? 'folded' : ''} onClick={onFoldButtonClick} style={{ left: `${10 * depth}px` }}
<IconArrowSingleDown color='currentColor' /> )} </FoldButton> )} <ClickableContainer style={{ paddingLeft: `${10 * depth + 30}px`, cursor: onClick ? 'pointer' : 'initial', fontSize: '15px' }} onClick={onClick} onDoubleClick={onDoubleClick} > {icon != null && ( <SideNavigatorItemIconContainer> {icon} </SideNavigatorItemIconContainer> )} <Label>{label}</Label> </ClickableContainer> </div> {controlComponents && ( <ControlContainer className='control'> {controlComponents} </ControlContainer> )} </Container> ) } export default SideNaviagtorItem
> {folded ? ( <IconArrowSingleRight color='currentColor' /> ) : (
random_line_split
client.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-server. # # lai-server is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-server 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 lai-server. If not, see <http://www.gnu.org/licenses/>. import os.path import urllib import urllib2 import base64 import json from laiserver.lib import crypto SERVER_URL = 'http://127.0.0.1:8888/sync' PUB_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa.pub") PUB_KEY = open(PUB_KEY_FILE).read() PRV_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa") PRV_KEY = open(PRV_KEY_FILE).read()
def fetch(data=None): url = SERVER_URL if data is not None: data = urllib.urlencode({'data': data}) req = urllib2.Request(url, data) else: req = url res = urllib2.urlopen(req) return res.read() if __name__ == '__main__': doc = {'user' : 'lvidarte@gmail.com', 'key_name' : 'howl', 'session_id': None, 'process' : 'update', 'last_tid' : 0, 'docs' : []} msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id'] import time time.sleep(9) # Commit doc['process'] = 'commit' msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id']
random_line_split
client.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-server. # # lai-server is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-server 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 lai-server. If not, see <http://www.gnu.org/licenses/>. import os.path import urllib import urllib2 import base64 import json from laiserver.lib import crypto SERVER_URL = 'http://127.0.0.1:8888/sync' PUB_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa.pub") PUB_KEY = open(PUB_KEY_FILE).read() PRV_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa") PRV_KEY = open(PRV_KEY_FILE).read() def
(data=None): url = SERVER_URL if data is not None: data = urllib.urlencode({'data': data}) req = urllib2.Request(url, data) else: req = url res = urllib2.urlopen(req) return res.read() if __name__ == '__main__': doc = {'user' : 'lvidarte@gmail.com', 'key_name' : 'howl', 'session_id': None, 'process' : 'update', 'last_tid' : 0, 'docs' : []} msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id'] import time time.sleep(9) # Commit doc['process'] = 'commit' msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id']
fetch
identifier_name
client.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-server. # # lai-server is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-server 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 lai-server. If not, see <http://www.gnu.org/licenses/>. import os.path import urllib import urllib2 import base64 import json from laiserver.lib import crypto SERVER_URL = 'http://127.0.0.1:8888/sync' PUB_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa.pub") PUB_KEY = open(PUB_KEY_FILE).read() PRV_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa") PRV_KEY = open(PRV_KEY_FILE).read() def fetch(data=None): url = SERVER_URL if data is not None: data = urllib.urlencode({'data': data}) req = urllib2.Request(url, data) else: req = url res = urllib2.urlopen(req) return res.read() if __name__ == '__main__': doc = {'user' : 'lvidarte@gmail.com', 'key_name' : 'howl', 'session_id': None, 'process' : 'update', 'last_tid' : 0, 'docs' : []} msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else:
import time time.sleep(9) # Commit doc['process'] = 'commit' msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id']
enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id']
conditional_block
client.py
# -*- coding: utf-8 -*- # Author: Leo Vidarte <http://nerdlabs.com.ar> # # This file is part of lai-server. # # lai-server is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 # as published by the Free Software Foundation. # # lai-server 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 lai-server. If not, see <http://www.gnu.org/licenses/>. import os.path import urllib import urllib2 import base64 import json from laiserver.lib import crypto SERVER_URL = 'http://127.0.0.1:8888/sync' PUB_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa.pub") PUB_KEY = open(PUB_KEY_FILE).read() PRV_KEY_FILE = os.path.join(os.path.expanduser('~'), ".ssh/id_rsa") PRV_KEY = open(PRV_KEY_FILE).read() def fetch(data=None):
if __name__ == '__main__': doc = {'user' : 'lvidarte@gmail.com', 'key_name' : 'howl', 'session_id': None, 'process' : 'update', 'last_tid' : 0, 'docs' : []} msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id'] import time time.sleep(9) # Commit doc['process'] = 'commit' msg = json.dumps(doc) enc = crypto.encrypt(msg, PUB_KEY) data = base64.b64encode(enc) try: data = fetch(data) except: print "Fetch error" else: enc = base64.b64decode(data) msg = crypto.decrypt(enc, PRV_KEY) doc = json.loads(msg) print doc['session_id']
url = SERVER_URL if data is not None: data = urllib.urlencode({'data': data}) req = urllib2.Request(url, data) else: req = url res = urllib2.urlopen(req) return res.read()
identifier_body
main.rs
#![feature(async_await)] use futures_util::stream::StreamExt; use std::env; use std::io::*; use std::process::Stdio; use tokio::codec::{FramedRead, LinesCodec}; use tokio::prelude::*; use tokio::process::{Child, Command}; const USAGE: &str = "args: config_file"; struct Qemu { pub process: Child, } impl Qemu { fn new(disk_file: &str) -> Self { let cmd: &str = &vec![ "qemu-system-x86_64.exe", "-m", "4G", "-no-reboot", "-no-shutdown", "-drive", &format!("file={},format=raw,if=ide", disk_file), "-monitor", "stdio", "-s", "-S", ] .join(" "); let process = Command::new("sh") .args(&["-c", cmd]) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .expect("Unable to start qemu"); Self { process } } fn
(mut self) { { self.process .stdin() .as_mut() .unwrap() .write_all(b"q\n") .unwrap(); } let ecode = self.process.wait().expect("failed to wait on child"); assert!(ecode.success()); } } struct Gdb { pub process: Child, stdout: FramedRead<Vec<u8>, LinesCodec>, } impl Gdb { fn new() -> Self { let process = Command::new("gdb") .stdin(Stdio::piped()) .stdout(Stdio::null()) // .stderr(Stdio::null()) .spawn() .expect("Unable to start gdb"); let stdout = process.stdout().take().unwrap(); Self { process, stdout: FramedRead::new(stdout, LinesCodec::new()), } } fn read(&mut self) -> Vec<u8> { let mut result = Vec::new(); self.process .stdout .as_mut() .unwrap() .read_to_end(&mut result) .unwrap(); result } fn write(&mut self, bytes: &[u8]) { self.process .stdin .as_mut() .unwrap() .write_all(bytes) .unwrap(); } fn start(&mut self) {} fn terminate(mut self) { self.write(b"q\n"); let ecode = self.process.wait().expect("failed to wait on child"); assert!(ecode.success()); } } #[tokio::main] async fn main() { let _args: Vec<_> = env::args().skip(1).collect(); let mut qemu = Qemu::new("build/test_disk.img"); let mut gdb = Gdb::new(); gdb.start(); std::thread::sleep_ms(1000); gdb.terminate(); qemu.terminate(); println!("DONE") }
terminate
identifier_name
main.rs
#![feature(async_await)] use futures_util::stream::StreamExt; use std::env; use std::io::*; use std::process::Stdio; use tokio::codec::{FramedRead, LinesCodec}; use tokio::prelude::*; use tokio::process::{Child, Command}; const USAGE: &str = "args: config_file"; struct Qemu { pub process: Child, } impl Qemu { fn new(disk_file: &str) -> Self { let cmd: &str = &vec![ "qemu-system-x86_64.exe", "-m", "4G", "-no-reboot", "-no-shutdown", "-drive", &format!("file={},format=raw,if=ide", disk_file), "-monitor", "stdio", "-s", "-S", ] .join(" "); let process = Command::new("sh") .args(&["-c", cmd]) .stdin(Stdio::piped()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .expect("Unable to start qemu"); Self { process } } fn terminate(mut self) { { self.process .stdin() .as_mut() .unwrap() .write_all(b"q\n") .unwrap(); } let ecode = self.process.wait().expect("failed to wait on child"); assert!(ecode.success()); } } struct Gdb { pub process: Child, stdout: FramedRead<Vec<u8>, LinesCodec>, } impl Gdb { fn new() -> Self
fn read(&mut self) -> Vec<u8> { let mut result = Vec::new(); self.process .stdout .as_mut() .unwrap() .read_to_end(&mut result) .unwrap(); result } fn write(&mut self, bytes: &[u8]) { self.process .stdin .as_mut() .unwrap() .write_all(bytes) .unwrap(); } fn start(&mut self) {} fn terminate(mut self) { self.write(b"q\n"); let ecode = self.process.wait().expect("failed to wait on child"); assert!(ecode.success()); } } #[tokio::main] async fn main() { let _args: Vec<_> = env::args().skip(1).collect(); let mut qemu = Qemu::new("build/test_disk.img"); let mut gdb = Gdb::new(); gdb.start(); std::thread::sleep_ms(1000); gdb.terminate(); qemu.terminate(); println!("DONE") }
{ let process = Command::new("gdb") .stdin(Stdio::piped()) .stdout(Stdio::null()) // .stderr(Stdio::null()) .spawn() .expect("Unable to start gdb"); let stdout = process.stdout().take().unwrap(); Self { process, stdout: FramedRead::new(stdout, LinesCodec::new()), } }
identifier_body