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
inkweb.js
/* ** InkWeb - Inkscape's Javscript features for the open vector web ** ** Copyright (C) 2009 Aurelio A. Heckert, aurium (a) gmail dot com ** ** ********* Bugs and New Fetures ************************************* ** If you found any bug on this script or if you want to propose a ** new feature, please report it in the inkscape bug traker ** https://bugs.launchpad.net/inkscape/+filebug ** and assign that to Aurium. ** ******************************************************************** ** ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as published ** by the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. */ var InkWeb = { version: 0.04, NS: { svg: "http://www.w3.org/2000/svg", sodipodi: "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd", inkscape: "http://www.inkscape.org/namespaces/inkscape", cc: "http://creativecommons.org/ns#", dc: "http://purl.org/dc/elements/1.1/", rdf: "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
xml: "http://www.w3.org/XML/1998/namespace" } }; InkWeb.el = function (tag, attributes) { // A helper to create SVG elements var element = document.createElementNS( this.NS.svg, tag ); for ( var att in attributes ) { switch ( att ) { case "parent": attributes.parent.appendChild( element ); break; case "text": element.appendChild( document.createTextNode( attributes.text ) ); break; default: element.setAttribute( att, attributes[att] ); } } return element; } InkWeb.reGetStyleAttVal = function (att) { return new RegExp( "(^|.*;)[ ]*"+ att +":([^;]*)(;.*|$)" ) } InkWeb.getStyle = function (el, att) { // This method is needed because el.style is only working // to HTML style in the Firefox 3.0 if ( typeof(el) == "string" ) el = document.getElementById(el); var style = el.getAttribute("style"); var match = this.reGetStyleAttVal(att).exec(style); if ( match ) { return match[2]; } else { return false; } } InkWeb.setStyle = function (el, att, val) { if ( typeof(el) == "string" ) el = document.getElementById(el); var style = el.getAttribute("style"); re = this.reGetStyleAttVal(att); if ( re.test(style) ) { style = style.replace( re, "$1"+ att +":"+ val +"$3" ); } else { style += ";"+ att +":"+ val; } el.setAttribute( "style", style ); return val } InkWeb.transmitAtt = function (conf) { conf.att = conf.att.split( /\s+/ ); if ( typeof(conf.from) == "string" ) conf.from = document.getElementById( conf.from ); if ( ! conf.to.join ) conf.to = [ conf.to ]; for ( var toEl,elN=0; toEl=conf.to[elN]; elN++ ) { if ( typeof(toEl) == "string" ) toEl = document.getElementById( toEl ); for ( var i=0; i<conf.att.length; i++ ) { var val = this.getStyle( conf.from, conf.att[i] ); if ( val ) { this.setStyle( toEl, conf.att[i], val ); } else { val = conf.from.getAttribute(conf.att[i]); toEl.setAttribute( conf.att[i], val ); } } } } InkWeb.setAtt = function (conf) { if ( ! conf.el.join ) conf.to = [ conf.el ]; conf.att = conf.att.split( /\s+/ ); conf.val = conf.val.split( /\s+/ ); for ( var el,elN=0; el=conf.el[elN]; elN++ ) { if ( typeof(el) == "string" ) el = document.getElementById( el ); for ( var att,i=0; att=conf.att[i]; i++ ) { if ( att == "width" || att == "height" || att == "x" || att == "y" || att == "cx" || att == "cy" || att == "r" || att == "rx" || att == "ry" || att == "transform" ) { el.setAttribute( att, conf.val[i] ); } else { this.setStyle( el, att, conf.val[i] ); } } } } InkWeb.moveElTo = function (startConf) { if ( typeof(startConf) == "string" ) { // startConf may be only a element Id, to timeout recursive calls. var el = document.getElementById( startConf ); } else { if ( typeof(startConf.el) == "string" ) startConf.el = document.getElementById( startConf.el ); var el = startConf.el; } if ( ! el.inkWebMoving ) { el.inkWebMoving = { step: 0 }; } var conf = el.inkWebMoving; if ( conf.step == 0 ) { conf.x = startConf.x; conf.y = startConf.y; // dur : duration of the animation in seconds if ( startConf.dur ) { conf.dur = startConf.dur } else { conf.dur = 1 } // steps : animation steps in a second if ( startConf.stepsBySec ) { conf.stepsBySec = startConf.stepsBySec } else { conf.stepsBySec = 16 } conf.sleep = Math.round( 1000 / conf.stepsBySec ); conf.steps = conf.dur * conf.stepsBySec; var startPos = el.getBBox(); conf.xInc = ( conf.x - startPos.x ) / conf.steps; conf.yInc = ( conf.y - startPos.y ) / conf.steps; conf.transform = el.transform.baseVal.consolidate(); if ( ! conf.transform ) { conf.transform = el.ownerSVGElement.createSVGTransform(); } el.transform.baseVal.clear(); el.transform.baseVal.appendItem(conf.transform); } if ( conf.step < conf.steps ) { conf.step++; conf.transform.matrix.e += conf.xInc; conf.transform.matrix.f += conf.yInc; try{ el.ownerSVGElement.forceRedraw() } catch(e){ this.log(e, "this "+el.ownerSVGElement+" has no forceRedraw().") } conf.timeout = setTimeout( 'InkWeb.moveElTo("'+el.id+'")', conf.sleep ); } else { delete el.inkWebMoving; } } InkWeb.log = function () { /* if you need that, use the inkweb-debug.js too */ }
xlink: "http://www.w3.org/1999/xlink",
random_line_split
create-feedback-thread-modal.component.spec.ts
// Copyright 2021 The Oppia 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. /** * @fileoverview Unit tests for CreateFeedbackThreadModalComponent. */ import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { AlertsService } from 'services/alerts.service'; import { ComponentFixture, waitForAsync, TestBed } from '@angular/core/testing'; import { CreateFeedbackThreadModalComponent } from './create-feedback-thread-modal.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; class MockActiveModal { close(): void { return; } dismiss(): void
} describe('Create Feedback Thread Modal Controller', function() { let component: CreateFeedbackThreadModalComponent; let fixture: ComponentFixture<CreateFeedbackThreadModalComponent>; let alertsService: AlertsService; let ngbActiveModal: NgbActiveModal; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ CreateFeedbackThreadModalComponent ], providers: [ { provide: NgbActiveModal, useClass: MockActiveModal } ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CreateFeedbackThreadModalComponent); component = fixture.componentInstance; ngbActiveModal = TestBed.inject(NgbActiveModal); alertsService = TestBed.inject(AlertsService); fixture.detectChanges(); }); it('should initialize properties after component is initialized', function() { expect(component.newThreadSubject).toEqual(''); expect(component.newThreadText).toEqual(''); }); it('should not close modal when new thread subject is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = ''; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a thread subject.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should not close modal when new thread text is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = ''; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a message.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should close modal when both new thread subject and new thread text are' + ' valid', function() { spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(ngbActiveModal.close).toHaveBeenCalledWith({ newThreadSubject: 'subject', newThreadText: 'text' }); }); });
{ return; }
identifier_body
create-feedback-thread-modal.component.spec.ts
// Copyright 2021 The Oppia Authors. All Rights Reserved. //
// // 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. /** * @fileoverview Unit tests for CreateFeedbackThreadModalComponent. */ import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { AlertsService } from 'services/alerts.service'; import { ComponentFixture, waitForAsync, TestBed } from '@angular/core/testing'; import { CreateFeedbackThreadModalComponent } from './create-feedback-thread-modal.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; class MockActiveModal { close(): void { return; } dismiss(): void { return; } } describe('Create Feedback Thread Modal Controller', function() { let component: CreateFeedbackThreadModalComponent; let fixture: ComponentFixture<CreateFeedbackThreadModalComponent>; let alertsService: AlertsService; let ngbActiveModal: NgbActiveModal; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ CreateFeedbackThreadModalComponent ], providers: [ { provide: NgbActiveModal, useClass: MockActiveModal } ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CreateFeedbackThreadModalComponent); component = fixture.componentInstance; ngbActiveModal = TestBed.inject(NgbActiveModal); alertsService = TestBed.inject(AlertsService); fixture.detectChanges(); }); it('should initialize properties after component is initialized', function() { expect(component.newThreadSubject).toEqual(''); expect(component.newThreadText).toEqual(''); }); it('should not close modal when new thread subject is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = ''; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a thread subject.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should not close modal when new thread text is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = ''; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a message.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should close modal when both new thread subject and new thread text are' + ' valid', function() { spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(ngbActiveModal.close).toHaveBeenCalledWith({ newThreadSubject: 'subject', newThreadText: 'text' }); }); });
// 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
random_line_split
create-feedback-thread-modal.component.spec.ts
// Copyright 2021 The Oppia 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. /** * @fileoverview Unit tests for CreateFeedbackThreadModalComponent. */ import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { AlertsService } from 'services/alerts.service'; import { ComponentFixture, waitForAsync, TestBed } from '@angular/core/testing'; import { CreateFeedbackThreadModalComponent } from './create-feedback-thread-modal.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; class MockActiveModal { close(): void { return; }
(): void { return; } } describe('Create Feedback Thread Modal Controller', function() { let component: CreateFeedbackThreadModalComponent; let fixture: ComponentFixture<CreateFeedbackThreadModalComponent>; let alertsService: AlertsService; let ngbActiveModal: NgbActiveModal; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ CreateFeedbackThreadModalComponent ], providers: [ { provide: NgbActiveModal, useClass: MockActiveModal } ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CreateFeedbackThreadModalComponent); component = fixture.componentInstance; ngbActiveModal = TestBed.inject(NgbActiveModal); alertsService = TestBed.inject(AlertsService); fixture.detectChanges(); }); it('should initialize properties after component is initialized', function() { expect(component.newThreadSubject).toEqual(''); expect(component.newThreadText).toEqual(''); }); it('should not close modal when new thread subject is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = ''; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a thread subject.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should not close modal when new thread text is empty', function() { spyOn(alertsService, 'addWarning').and.callThrough(); spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = ''; component.create(newThreadSubject, newThreadText); expect(alertsService.addWarning).toHaveBeenCalledWith( 'Please specify a message.'); expect(ngbActiveModal.close).not.toHaveBeenCalled(); }); it('should close modal when both new thread subject and new thread text are' + ' valid', function() { spyOn(ngbActiveModal, 'close').and.callThrough(); let newThreadSubject = 'subject'; let newThreadText = 'text'; component.create(newThreadSubject, newThreadText); expect(ngbActiveModal.close).toHaveBeenCalledWith({ newThreadSubject: 'subject', newThreadText: 'text' }); }); });
dismiss
identifier_name
crew.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Gang } from '../models/gang'; import { Session } from '../models/session'; import { CREW_2_ROUTE } from '../../app/app.routes.model'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CrewService { private crewOne: Observable<Gang>; private crewTwo: Observable<Gang>; constructor(private http: HttpClient) { } public getCrewDataForPath(path: string): Observable<Gang> { if (path === CREW_2_ROUTE) { return this.getCrewTwoData(); } else { return this.getCrewOneData(); } } public getCrewOneData(): Observable<Gang> { if (!this.crewOne) { this.crewOne = this.getCrew('assassins'); } return this.crewOne; } public getCrewTwoData(): Observable<Gang> { if (!this.crewTwo) { this.crewTwo = this.getCrew('assassins2'); } return this.crewTwo; } private getCrew(filename: string): Observable<Gang>
private sortSessions(sessions: Session[]): Session[] { return sessions.map((session: Session) => { session.date = Date.parse(<any> session.date); return session; }).sort((a, b) => a.date - b.date); } }
{ return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => { gang.sessions = this.sortSessions(gang.sessions); return gang; }); }
identifier_body
crew.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Gang } from '../models/gang'; import { Session } from '../models/session'; import { CREW_2_ROUTE } from '../../app/app.routes.model'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CrewService { private crewOne: Observable<Gang>; private crewTwo: Observable<Gang>; constructor(private http: HttpClient) { } public getCrewDataForPath(path: string): Observable<Gang> { if (path === CREW_2_ROUTE) { return this.getCrewTwoData(); } else { return this.getCrewOneData(); } } public getCrewOneData(): Observable<Gang> { if (!this.crewOne) { this.crewOne = this.getCrew('assassins'); } return this.crewOne; } public getCrewTwoData(): Observable<Gang> { if (!this.crewTwo) { this.crewTwo = this.getCrew('assassins2'); } return this.crewTwo; } private getCrew(filename: string): Observable<Gang> { return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => { gang.sessions = this.sortSessions(gang.sessions); return gang; }); } private sortSessions(sessions: Session[]): Session[] { return sessions.map((session: Session) => {
} }
session.date = Date.parse(<any> session.date); return session; }).sort((a, b) => a.date - b.date);
random_line_split
crew.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Gang } from '../models/gang'; import { Session } from '../models/session'; import { CREW_2_ROUTE } from '../../app/app.routes.model'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CrewService { private crewOne: Observable<Gang>; private crewTwo: Observable<Gang>; constructor(private http: HttpClient) { } public getCrewDataForPath(path: string): Observable<Gang> { if (path === CREW_2_ROUTE)
else { return this.getCrewOneData(); } } public getCrewOneData(): Observable<Gang> { if (!this.crewOne) { this.crewOne = this.getCrew('assassins'); } return this.crewOne; } public getCrewTwoData(): Observable<Gang> { if (!this.crewTwo) { this.crewTwo = this.getCrew('assassins2'); } return this.crewTwo; } private getCrew(filename: string): Observable<Gang> { return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => { gang.sessions = this.sortSessions(gang.sessions); return gang; }); } private sortSessions(sessions: Session[]): Session[] { return sessions.map((session: Session) => { session.date = Date.parse(<any> session.date); return session; }).sort((a, b) => a.date - b.date); } }
{ return this.getCrewTwoData(); }
conditional_block
crew.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Gang } from '../models/gang'; import { Session } from '../models/session'; import { CREW_2_ROUTE } from '../../app/app.routes.model'; import { HttpClient } from '@angular/common/http'; @Injectable() export class CrewService { private crewOne: Observable<Gang>; private crewTwo: Observable<Gang>; constructor(private http: HttpClient) { } public getCrewDataForPath(path: string): Observable<Gang> { if (path === CREW_2_ROUTE) { return this.getCrewTwoData(); } else { return this.getCrewOneData(); } } public getCrewOneData(): Observable<Gang> { if (!this.crewOne) { this.crewOne = this.getCrew('assassins'); } return this.crewOne; } public
(): Observable<Gang> { if (!this.crewTwo) { this.crewTwo = this.getCrew('assassins2'); } return this.crewTwo; } private getCrew(filename: string): Observable<Gang> { return this.http.get('/assets/data/' + filename + '.json').map((gang: Gang) => { gang.sessions = this.sortSessions(gang.sessions); return gang; }); } private sortSessions(sessions: Session[]): Session[] { return sessions.map((session: Session) => { session.date = Date.parse(<any> session.date); return session; }).sort((a, b) => a.date - b.date); } }
getCrewTwoData
identifier_name
AndroidfilehostCom.py
# -*- coding: utf-8 -* # # Test links: # https://www.androidfilehost.com/?fid=95916177934518197 import re from module.plugins.internal.SimpleHoster import SimpleHoster class
(SimpleHoster): __name__ = "AndroidfilehostCom" __type__ = "hoster" __version__ = "0.05" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?androidfilehost\.com/\?fid=\d+' __config__ = [("activated" , "bool", "Activated" , True), ("use_premium" , "bool", "Use premium account if available" , True), ("fallback" , "bool", "Fallback to free download if premium fails" , True), ("chk_filesize", "bool", "Check file size" , True), ("max_wait" , "int" , "Reconnect if waiting time is greater than minutes", 10 )] __description__ = """Androidfilehost.com hoster plugin""" __license__ = "GPLv3" __authors__ = [("zapp-brannigan", "fuerst.reinje@web.de")] NAME_PATTERN = r'<br />(?P<N>.*?)</h1>' SIZE_PATTERN = r'<h4>size</h4>\s*<p>(?P<S>[\d.,]+)(?P<U>[\w^_]+)</p>' HASHSUM_PATTERN = r'<h4>(?P<H>.*?)</h4>\s*<p><code>(?P<D>.*?)</code></p>' OFFLINE_PATTERN = r'404 not found' WAIT_PATTERN = r'users must wait <strong>(\d+) secs' def setup(self): self.multiDL = True self.resume_download = True self.chunk_limit = 1 def handle_free(self, pyfile): wait = re.search(self.WAIT_PATTERN, self.data) self.log_debug("Waiting time: %s seconds" % wait.group(1)) fid = re.search(r'id="fid" value="(\d+)" />', self.data).group(1) self.log_debug("FID: %s" % fid) html = self.load("https://www.androidfilehost.com/libs/otf/mirrors.otf.php", post={'submit': 'submit', 'action': 'getdownloadmirrors', 'fid' : fid}) self.link = re.findall('"url":"(.*?)"', html)[0].replace("\\", "") mirror_host = self.link.split("/")[2] self.log_debug("Mirror Host: %s" % mirror_host) html = self.load("https://www.androidfilehost.com/libs/otf/stats.otf.php", get={'fid' : fid, 'w' : 'download', 'mirror': mirror_host})
AndroidfilehostCom
identifier_name
AndroidfilehostCom.py
# -*- coding: utf-8 -* # # Test links: # https://www.androidfilehost.com/?fid=95916177934518197 import re from module.plugins.internal.SimpleHoster import SimpleHoster class AndroidfilehostCom(SimpleHoster):
__name__ = "AndroidfilehostCom" __type__ = "hoster" __version__ = "0.05" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?androidfilehost\.com/\?fid=\d+' __config__ = [("activated" , "bool", "Activated" , True), ("use_premium" , "bool", "Use premium account if available" , True), ("fallback" , "bool", "Fallback to free download if premium fails" , True), ("chk_filesize", "bool", "Check file size" , True), ("max_wait" , "int" , "Reconnect if waiting time is greater than minutes", 10 )] __description__ = """Androidfilehost.com hoster plugin""" __license__ = "GPLv3" __authors__ = [("zapp-brannigan", "fuerst.reinje@web.de")] NAME_PATTERN = r'<br />(?P<N>.*?)</h1>' SIZE_PATTERN = r'<h4>size</h4>\s*<p>(?P<S>[\d.,]+)(?P<U>[\w^_]+)</p>' HASHSUM_PATTERN = r'<h4>(?P<H>.*?)</h4>\s*<p><code>(?P<D>.*?)</code></p>' OFFLINE_PATTERN = r'404 not found' WAIT_PATTERN = r'users must wait <strong>(\d+) secs' def setup(self): self.multiDL = True self.resume_download = True self.chunk_limit = 1 def handle_free(self, pyfile): wait = re.search(self.WAIT_PATTERN, self.data) self.log_debug("Waiting time: %s seconds" % wait.group(1)) fid = re.search(r'id="fid" value="(\d+)" />', self.data).group(1) self.log_debug("FID: %s" % fid) html = self.load("https://www.androidfilehost.com/libs/otf/mirrors.otf.php", post={'submit': 'submit', 'action': 'getdownloadmirrors', 'fid' : fid}) self.link = re.findall('"url":"(.*?)"', html)[0].replace("\\", "") mirror_host = self.link.split("/")[2] self.log_debug("Mirror Host: %s" % mirror_host) html = self.load("https://www.androidfilehost.com/libs/otf/stats.otf.php", get={'fid' : fid, 'w' : 'download', 'mirror': mirror_host})
identifier_body
AndroidfilehostCom.py
# -*- coding: utf-8 -* # # Test links: # https://www.androidfilehost.com/?fid=95916177934518197 import re from module.plugins.internal.SimpleHoster import SimpleHoster class AndroidfilehostCom(SimpleHoster): __name__ = "AndroidfilehostCom" __type__ = "hoster" __version__ = "0.05" __status__ = "testing" __pattern__ = r'https?://(?:www\.)?androidfilehost\.com/\?fid=\d+' __config__ = [("activated" , "bool", "Activated" , True), ("use_premium" , "bool", "Use premium account if available" , True), ("fallback" , "bool", "Fallback to free download if premium fails" , True), ("chk_filesize", "bool", "Check file size" , True), ("max_wait" , "int" , "Reconnect if waiting time is greater than minutes", 10 )] __description__ = """Androidfilehost.com hoster plugin""" __license__ = "GPLv3" __authors__ = [("zapp-brannigan", "fuerst.reinje@web.de")] NAME_PATTERN = r'<br />(?P<N>.*?)</h1>' SIZE_PATTERN = r'<h4>size</h4>\s*<p>(?P<S>[\d.,]+)(?P<U>[\w^_]+)</p>' HASHSUM_PATTERN = r'<h4>(?P<H>.*?)</h4>\s*<p><code>(?P<D>.*?)</code></p>' OFFLINE_PATTERN = r'404 not found' WAIT_PATTERN = r'users must wait <strong>(\d+) secs' def setup(self): self.multiDL = True self.resume_download = True self.chunk_limit = 1 def handle_free(self, pyfile): wait = re.search(self.WAIT_PATTERN, self.data) self.log_debug("Waiting time: %s seconds" % wait.group(1)) fid = re.search(r'id="fid" value="(\d+)" />', self.data).group(1) self.log_debug("FID: %s" % fid)
'fid' : fid}) self.link = re.findall('"url":"(.*?)"', html)[0].replace("\\", "") mirror_host = self.link.split("/")[2] self.log_debug("Mirror Host: %s" % mirror_host) html = self.load("https://www.androidfilehost.com/libs/otf/stats.otf.php", get={'fid' : fid, 'w' : 'download', 'mirror': mirror_host})
html = self.load("https://www.androidfilehost.com/libs/otf/mirrors.otf.php", post={'submit': 'submit', 'action': 'getdownloadmirrors',
random_line_split
commands.rs
#![allow(dead_code)] extern crate jam; extern crate cgmath; extern crate time; extern crate glutin; extern crate image; extern crate gfx_device_gl; #[macro_use] extern crate aphid; use std::f64::consts::PI; use std::path::{Path, PathBuf}; use cgmath::Rad; use aphid::{HashSet, Seconds}; use jam::color; use jam::{Vec3, Vec2, JamResult, Dimensions, Color, rgb, Camera, InputState, FontDirectory}; use jam::render::*; use jam::render::gfx::{Renderer, GeometryBuffer, OpenGLRenderer, construct_opengl_renderer}; use aphid::HashMap; fn main() { let resources_path = PathBuf::from("resources"); let shader_pair = ShaderPair::for_paths("resources/shader/fat.vert", "resources/shader/fat.frag"); let texture_dir = TextureDirectory::for_path("resources/textures", hashset!["png".into()]); let font_dir = FontDirectory::for_path("resources/fonts"); let file_resources = FileResources { resources: resources_path, shader_pair : shader_pair, texture_directory: texture_dir, font_directory: font_dir, }; println!("creating renderer"); let renderer = construct_opengl_renderer(file_resources, (800, 600), true, "commands example".into()).expect("a renderer"); println!("done creating renderer"); let mut app = App { name: "mixalot".into(), camera: Camera { at: Vec3::new(0.0, 0.0, 0.0), pitch: Rad(PI / 4.0_f64), viewport: Dimensions { pixels: (800,600), points: (800,600), }, points_per_unit: 16.0 * 1.0, }, zoom: 1.0, points_per_unit: 16.0, n: 0, // frame counter renderer: renderer, geometry: HashMap::default(), }; app.run(); } struct App { name : String, camera : Camera, zoom : f64, points_per_unit : f64, n : u64, renderer: OpenGLRenderer, geometry : HashMap<String, GeometryBuffer<gfx_device_gl::Resources>>, } impl App { fn run(&mut self) { let mut last_time = time::precise_time_ns(); 'main: loop { let (dimensions, input_state) = self.renderer.begin_frame(rgb(132, 193, 255)); if input_state.close { break; } // println!("dimensions -> {:?}", dimensions); let time = time::precise_time_ns(); let delta_time = ((time - last_time) as f64) / 1_000_000.0; self.update(&input_state, dimensions, delta_time); let res = self.render().expect("successful rendering"); last_time = time; } } fn units_per_point(&self) -> f64 { 1.0 / self.points_per_unit } fn
(&self) -> GeometryTesselator { let upp = self.units_per_point(); let tesselator_scale = Vec3::new(upp, upp, upp); GeometryTesselator::new(tesselator_scale) } fn update(&mut self, input_state:&InputState, dimensions:Dimensions, delta_time: Seconds) { use glutin::VirtualKeyCode; self.n += 1; self.camera.at = Vec3::new(17.0, 0.0, 17.0); // self.camera.at = Vec3::new(8.0, 0.0, 8.0); self.camera.points_per_unit = self.points_per_unit * self.zoom; self.camera.viewport = dimensions; // println!("Camera viewpoinrt -> {:?}", self.camera.viewport); // let (mx, my) = input_state.mouse.at; // let mouse_at = self.camera.ui_line_segment_for_mouse_position(mx, my); if input_state.keys.pushed.contains(&VirtualKeyCode::P) { // println!("take a screenshot!"); // let image = self.renderer.screenshot(); // let mut output = std::fs::file::create(&path::new("screenshot.png")).unwrap(); // image.save(&mut output, image::imageformat::png).unwrap(); } } fn render(&mut self) -> JamResult<()> { // use jam::font::FontDescription; // let font_description = FontDescription { family: "Roboto-Medium".into(), pixel_size: (32f64 * self.camera.viewport.scale()) as u32 }; // let loaded = self.renderer.load_font(&font_description); // match loaded { // Err(e) => println!("font load error -> {:?}", e), // Ok(_) => (), // } // println!("render with delta -> {:?}", delta_time); let colors = vec![color::WHITE, color::BLUE, color::RED]; // let (w, h) = self.camera.viewport.pixels; // let line = self.camera.ray_for_mouse_position((w / 2) as i32, (h / 2) as i32); // println!("forward line -> {:?}", line); let an = self.n / 60; let on_second = (self.n % 60) == 0; let raster_color = colors[(((an / 16) % 16) % 3) as usize]; // cycles every 16 seconds if on_second && an % 5 == 0 { // every fifth second let column = (an / 4) % 4; let name : String = format!("zone_{}", column); println!("delete {}", name); let pred : Box<Fn(&String) -> bool> = Box::new(move |key| key.starts_with(&name)); let keys_to_delete : Vec<_>= self.geometry.keys().filter(|e| pred(e)).cloned().collect(); for key in keys_to_delete.iter() { self.geometry.remove(key); } } // k.starts_with(&prefix) let n = (((an % 16) as f64) / 16.0 * 255.0) as u8; let mut t = self.tesselator(); let mut vertices = Vec::new(); let cache = &mut self.geometry; let camera = &self.camera; // this closure shit is just dangerous // render a grid of various bits of geo for i in 0..16 { let xo = i % 4; let zo = i / 4; let name : String = format!("zone_{}_{}", xo, zo); if (an % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); let geo = self.renderer.draw_vertices(&vertices, Uniforms { transform : down_size_m4(camera.view_projection().into()), color: color::WHITE, }, Blend::None)?; cache.insert(name, geo); } else if ((an+8) % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); cache.insert(name, self.renderer.upload(&vertices)); } else { let rem = (xo + zo) % 3; let color = match rem { 0 => color::rgba(255,255,255, 128), 1 => color::rgba(255,255,255, 50), _ => color::WHITE, }; if let Some(geo) = cache.get(&name) { let blend = match rem { 0 => Blend::Alpha, 1 => Blend::Add, _ => Blend::None, }; self.renderer.draw(geo, Uniforms { transform: down_size_m4(self.camera.view_projection().into()), color: color, },blend)?; } } } // draw ui text // if let Some((font, layer)) = self.renderer.get_font(&font_description) { // // println!("ok we got a font to use to draw layer -> {:?}", layer); // let scale = 1.0 / self.camera.viewport.scale(); // let mut t = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0)); // // let texture_region = TextureRegion { // u_min: 0, // u_max: 128, // v_min: 0, // v_max: 128, // texture_size: 1024, // }; // t.color = color::WHITE.float_raw(); // t.draw_ui(&mut vertices, &texture_region, 0, 20.0, 20.0, 0.0, 1.0); // // let at = Vec2::new(0.0, 400.0); // t.color = color::BLACK.float_raw(); // text::render_text( // "Why oh why does a silly cow fly, you idiot.\n\nGo die in a pie.\n\nPls.", // font, // layer, // at, // -1.0, // i assume this is because our coordinate system is hosed ... // scale, // &t, // &mut vertices, // Some(300.0) // ); // // frame.draw_vertices(&vertices, Uniforms { // transform : down_size_m4(self.camera.ui_projection().into()), // color: color::WHITE, // }, Blend::Alpha); // } self.renderer.finish_frame().expect("a finished frame"); Ok(()) } } fn raster(t: &mut GeometryTesselator, vertices: &mut Vec<Vertex>, color:Color, x:f64, z:f64) { vertices.clear(); let texture_region = TextureRegion { u_min: 0, u_max: 128, v_min: 0, v_max: 128, layer: 0, texture_size: 1024, }; let texture_region_small = TextureRegion { u_min: 16, u_max: 32, v_min: 16, v_max: 32, layer: 0, texture_size: 1024, }; t.color = color.float_raw(); // .h_flip().v_flip() t.draw_floor_tile(vertices, &texture_region, x, 0.0, z, 0.0); t.color = color::RED.float_raw(); t.draw_wall_tile(vertices, &texture_region_small, x, 0.0, z, 0.0); t.color = color::GREEN.float_raw(); t.draw_floor_centre_anchored(vertices, &texture_region_small, x + 2.0, 0.0, z + 2.0, 0.1); t.color = color::YELLOW.float_raw(); t.draw_floor_centre_anchored_rotated(vertices, &texture_region_small, x + 4.0, 0.0, z + 4.0, 0.0, 0.1); t.color = color::RED.float_raw(); t.draw_wall_base_anchored(vertices, &texture_region_small, x + 3.0, 0.0, z, 0.0); t.color = color::YELLOW.float_raw(); t.draw_wall_centre_anchored(vertices, &texture_region_small, x + 5.0, 1.0, z, 0.0); }
tesselator
identifier_name
commands.rs
#![allow(dead_code)] extern crate jam; extern crate cgmath; extern crate time; extern crate glutin; extern crate image; extern crate gfx_device_gl; #[macro_use] extern crate aphid; use std::f64::consts::PI; use std::path::{Path, PathBuf}; use cgmath::Rad; use aphid::{HashSet, Seconds}; use jam::color; use jam::{Vec3, Vec2, JamResult, Dimensions, Color, rgb, Camera, InputState, FontDirectory}; use jam::render::*; use jam::render::gfx::{Renderer, GeometryBuffer, OpenGLRenderer, construct_opengl_renderer}; use aphid::HashMap; fn main() { let resources_path = PathBuf::from("resources"); let shader_pair = ShaderPair::for_paths("resources/shader/fat.vert", "resources/shader/fat.frag"); let texture_dir = TextureDirectory::for_path("resources/textures", hashset!["png".into()]); let font_dir = FontDirectory::for_path("resources/fonts"); let file_resources = FileResources { resources: resources_path, shader_pair : shader_pair, texture_directory: texture_dir, font_directory: font_dir, }; println!("creating renderer"); let renderer = construct_opengl_renderer(file_resources, (800, 600), true, "commands example".into()).expect("a renderer"); println!("done creating renderer"); let mut app = App { name: "mixalot".into(), camera: Camera { at: Vec3::new(0.0, 0.0, 0.0), pitch: Rad(PI / 4.0_f64), viewport: Dimensions { pixels: (800,600), points: (800,600), }, points_per_unit: 16.0 * 1.0, }, zoom: 1.0, points_per_unit: 16.0, n: 0, // frame counter renderer: renderer, geometry: HashMap::default(), }; app.run(); } struct App { name : String, camera : Camera, zoom : f64, points_per_unit : f64, n : u64, renderer: OpenGLRenderer, geometry : HashMap<String, GeometryBuffer<gfx_device_gl::Resources>>, } impl App { fn run(&mut self)
fn units_per_point(&self) -> f64 { 1.0 / self.points_per_unit } fn tesselator(&self) -> GeometryTesselator { let upp = self.units_per_point(); let tesselator_scale = Vec3::new(upp, upp, upp); GeometryTesselator::new(tesselator_scale) } fn update(&mut self, input_state:&InputState, dimensions:Dimensions, delta_time: Seconds) { use glutin::VirtualKeyCode; self.n += 1; self.camera.at = Vec3::new(17.0, 0.0, 17.0); // self.camera.at = Vec3::new(8.0, 0.0, 8.0); self.camera.points_per_unit = self.points_per_unit * self.zoom; self.camera.viewport = dimensions; // println!("Camera viewpoinrt -> {:?}", self.camera.viewport); // let (mx, my) = input_state.mouse.at; // let mouse_at = self.camera.ui_line_segment_for_mouse_position(mx, my); if input_state.keys.pushed.contains(&VirtualKeyCode::P) { // println!("take a screenshot!"); // let image = self.renderer.screenshot(); // let mut output = std::fs::file::create(&path::new("screenshot.png")).unwrap(); // image.save(&mut output, image::imageformat::png).unwrap(); } } fn render(&mut self) -> JamResult<()> { // use jam::font::FontDescription; // let font_description = FontDescription { family: "Roboto-Medium".into(), pixel_size: (32f64 * self.camera.viewport.scale()) as u32 }; // let loaded = self.renderer.load_font(&font_description); // match loaded { // Err(e) => println!("font load error -> {:?}", e), // Ok(_) => (), // } // println!("render with delta -> {:?}", delta_time); let colors = vec![color::WHITE, color::BLUE, color::RED]; // let (w, h) = self.camera.viewport.pixels; // let line = self.camera.ray_for_mouse_position((w / 2) as i32, (h / 2) as i32); // println!("forward line -> {:?}", line); let an = self.n / 60; let on_second = (self.n % 60) == 0; let raster_color = colors[(((an / 16) % 16) % 3) as usize]; // cycles every 16 seconds if on_second && an % 5 == 0 { // every fifth second let column = (an / 4) % 4; let name : String = format!("zone_{}", column); println!("delete {}", name); let pred : Box<Fn(&String) -> bool> = Box::new(move |key| key.starts_with(&name)); let keys_to_delete : Vec<_>= self.geometry.keys().filter(|e| pred(e)).cloned().collect(); for key in keys_to_delete.iter() { self.geometry.remove(key); } } // k.starts_with(&prefix) let n = (((an % 16) as f64) / 16.0 * 255.0) as u8; let mut t = self.tesselator(); let mut vertices = Vec::new(); let cache = &mut self.geometry; let camera = &self.camera; // this closure shit is just dangerous // render a grid of various bits of geo for i in 0..16 { let xo = i % 4; let zo = i / 4; let name : String = format!("zone_{}_{}", xo, zo); if (an % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); let geo = self.renderer.draw_vertices(&vertices, Uniforms { transform : down_size_m4(camera.view_projection().into()), color: color::WHITE, }, Blend::None)?; cache.insert(name, geo); } else if ((an+8) % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); cache.insert(name, self.renderer.upload(&vertices)); } else { let rem = (xo + zo) % 3; let color = match rem { 0 => color::rgba(255,255,255, 128), 1 => color::rgba(255,255,255, 50), _ => color::WHITE, }; if let Some(geo) = cache.get(&name) { let blend = match rem { 0 => Blend::Alpha, 1 => Blend::Add, _ => Blend::None, }; self.renderer.draw(geo, Uniforms { transform: down_size_m4(self.camera.view_projection().into()), color: color, },blend)?; } } } // draw ui text // if let Some((font, layer)) = self.renderer.get_font(&font_description) { // // println!("ok we got a font to use to draw layer -> {:?}", layer); // let scale = 1.0 / self.camera.viewport.scale(); // let mut t = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0)); // // let texture_region = TextureRegion { // u_min: 0, // u_max: 128, // v_min: 0, // v_max: 128, // texture_size: 1024, // }; // t.color = color::WHITE.float_raw(); // t.draw_ui(&mut vertices, &texture_region, 0, 20.0, 20.0, 0.0, 1.0); // // let at = Vec2::new(0.0, 400.0); // t.color = color::BLACK.float_raw(); // text::render_text( // "Why oh why does a silly cow fly, you idiot.\n\nGo die in a pie.\n\nPls.", // font, // layer, // at, // -1.0, // i assume this is because our coordinate system is hosed ... // scale, // &t, // &mut vertices, // Some(300.0) // ); // // frame.draw_vertices(&vertices, Uniforms { // transform : down_size_m4(self.camera.ui_projection().into()), // color: color::WHITE, // }, Blend::Alpha); // } self.renderer.finish_frame().expect("a finished frame"); Ok(()) } } fn raster(t: &mut GeometryTesselator, vertices: &mut Vec<Vertex>, color:Color, x:f64, z:f64) { vertices.clear(); let texture_region = TextureRegion { u_min: 0, u_max: 128, v_min: 0, v_max: 128, layer: 0, texture_size: 1024, }; let texture_region_small = TextureRegion { u_min: 16, u_max: 32, v_min: 16, v_max: 32, layer: 0, texture_size: 1024, }; t.color = color.float_raw(); // .h_flip().v_flip() t.draw_floor_tile(vertices, &texture_region, x, 0.0, z, 0.0); t.color = color::RED.float_raw(); t.draw_wall_tile(vertices, &texture_region_small, x, 0.0, z, 0.0); t.color = color::GREEN.float_raw(); t.draw_floor_centre_anchored(vertices, &texture_region_small, x + 2.0, 0.0, z + 2.0, 0.1); t.color = color::YELLOW.float_raw(); t.draw_floor_centre_anchored_rotated(vertices, &texture_region_small, x + 4.0, 0.0, z + 4.0, 0.0, 0.1); t.color = color::RED.float_raw(); t.draw_wall_base_anchored(vertices, &texture_region_small, x + 3.0, 0.0, z, 0.0); t.color = color::YELLOW.float_raw(); t.draw_wall_centre_anchored(vertices, &texture_region_small, x + 5.0, 1.0, z, 0.0); }
{ let mut last_time = time::precise_time_ns(); 'main: loop { let (dimensions, input_state) = self.renderer.begin_frame(rgb(132, 193, 255)); if input_state.close { break; } // println!("dimensions -> {:?}", dimensions); let time = time::precise_time_ns(); let delta_time = ((time - last_time) as f64) / 1_000_000.0; self.update(&input_state, dimensions, delta_time); let res = self.render().expect("successful rendering"); last_time = time; } }
identifier_body
commands.rs
#![allow(dead_code)] extern crate jam; extern crate cgmath; extern crate time; extern crate glutin; extern crate image; extern crate gfx_device_gl; #[macro_use] extern crate aphid; use std::f64::consts::PI; use std::path::{Path, PathBuf}; use cgmath::Rad; use aphid::{HashSet, Seconds}; use jam::color; use jam::{Vec3, Vec2, JamResult, Dimensions, Color, rgb, Camera, InputState, FontDirectory}; use jam::render::*; use jam::render::gfx::{Renderer, GeometryBuffer, OpenGLRenderer, construct_opengl_renderer}; use aphid::HashMap; fn main() { let resources_path = PathBuf::from("resources"); let shader_pair = ShaderPair::for_paths("resources/shader/fat.vert", "resources/shader/fat.frag"); let texture_dir = TextureDirectory::for_path("resources/textures", hashset!["png".into()]); let font_dir = FontDirectory::for_path("resources/fonts"); let file_resources = FileResources { resources: resources_path, shader_pair : shader_pair, texture_directory: texture_dir, font_directory: font_dir, }; println!("creating renderer"); let renderer = construct_opengl_renderer(file_resources, (800, 600), true, "commands example".into()).expect("a renderer"); println!("done creating renderer"); let mut app = App { name: "mixalot".into(), camera: Camera { at: Vec3::new(0.0, 0.0, 0.0), pitch: Rad(PI / 4.0_f64), viewport: Dimensions { pixels: (800,600), points: (800,600), }, points_per_unit: 16.0 * 1.0, }, zoom: 1.0, points_per_unit: 16.0, n: 0, // frame counter renderer: renderer, geometry: HashMap::default(), }; app.run(); } struct App { name : String, camera : Camera, zoom : f64, points_per_unit : f64, n : u64, renderer: OpenGLRenderer, geometry : HashMap<String, GeometryBuffer<gfx_device_gl::Resources>>, } impl App { fn run(&mut self) { let mut last_time = time::precise_time_ns(); 'main: loop { let (dimensions, input_state) = self.renderer.begin_frame(rgb(132, 193, 255)); if input_state.close { break; } // println!("dimensions -> {:?}", dimensions); let time = time::precise_time_ns(); let delta_time = ((time - last_time) as f64) / 1_000_000.0; self.update(&input_state, dimensions, delta_time); let res = self.render().expect("successful rendering"); last_time = time; } } fn units_per_point(&self) -> f64 { 1.0 / self.points_per_unit } fn tesselator(&self) -> GeometryTesselator { let upp = self.units_per_point(); let tesselator_scale = Vec3::new(upp, upp, upp); GeometryTesselator::new(tesselator_scale) } fn update(&mut self, input_state:&InputState, dimensions:Dimensions, delta_time: Seconds) { use glutin::VirtualKeyCode; self.n += 1; self.camera.at = Vec3::new(17.0, 0.0, 17.0); // self.camera.at = Vec3::new(8.0, 0.0, 8.0); self.camera.points_per_unit = self.points_per_unit * self.zoom; self.camera.viewport = dimensions; // println!("Camera viewpoinrt -> {:?}", self.camera.viewport); // let (mx, my) = input_state.mouse.at; // let mouse_at = self.camera.ui_line_segment_for_mouse_position(mx, my); if input_state.keys.pushed.contains(&VirtualKeyCode::P) { // println!("take a screenshot!"); // let image = self.renderer.screenshot(); // let mut output = std::fs::file::create(&path::new("screenshot.png")).unwrap(); // image.save(&mut output, image::imageformat::png).unwrap(); } } fn render(&mut self) -> JamResult<()> { // use jam::font::FontDescription; // let font_description = FontDescription { family: "Roboto-Medium".into(), pixel_size: (32f64 * self.camera.viewport.scale()) as u32 }; // let loaded = self.renderer.load_font(&font_description); // match loaded { // Err(e) => println!("font load error -> {:?}", e), // Ok(_) => (), // } // println!("render with delta -> {:?}", delta_time); let colors = vec![color::WHITE, color::BLUE, color::RED]; // let (w, h) = self.camera.viewport.pixels; // let line = self.camera.ray_for_mouse_position((w / 2) as i32, (h / 2) as i32); // println!("forward line -> {:?}", line); let an = self.n / 60; let on_second = (self.n % 60) == 0; let raster_color = colors[(((an / 16) % 16) % 3) as usize]; // cycles every 16 seconds if on_second && an % 5 == 0 { // every fifth second let column = (an / 4) % 4; let name : String = format!("zone_{}", column); println!("delete {}", name); let pred : Box<Fn(&String) -> bool> = Box::new(move |key| key.starts_with(&name)); let keys_to_delete : Vec<_>= self.geometry.keys().filter(|e| pred(e)).cloned().collect(); for key in keys_to_delete.iter() { self.geometry.remove(key); } } // k.starts_with(&prefix) let n = (((an % 16) as f64) / 16.0 * 255.0) as u8; let mut t = self.tesselator(); let mut vertices = Vec::new(); let cache = &mut self.geometry; let camera = &self.camera; // this closure shit is just dangerous // render a grid of various bits of geo for i in 0..16 { let xo = i % 4; let zo = i / 4; let name : String = format!("zone_{}_{}", xo, zo); if (an % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); let geo = self.renderer.draw_vertices(&vertices, Uniforms { transform : down_size_m4(camera.view_projection().into()), color: color::WHITE, }, Blend::None)?; cache.insert(name, geo); } else if ((an+8) % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); cache.insert(name, self.renderer.upload(&vertices)); } else { let rem = (xo + zo) % 3; let color = match rem { 0 => color::rgba(255,255,255, 128), 1 => color::rgba(255,255,255, 50), _ => color::WHITE, }; if let Some(geo) = cache.get(&name)
} } // draw ui text // if let Some((font, layer)) = self.renderer.get_font(&font_description) { // // println!("ok we got a font to use to draw layer -> {:?}", layer); // let scale = 1.0 / self.camera.viewport.scale(); // let mut t = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0)); // // let texture_region = TextureRegion { // u_min: 0, // u_max: 128, // v_min: 0, // v_max: 128, // texture_size: 1024, // }; // t.color = color::WHITE.float_raw(); // t.draw_ui(&mut vertices, &texture_region, 0, 20.0, 20.0, 0.0, 1.0); // // let at = Vec2::new(0.0, 400.0); // t.color = color::BLACK.float_raw(); // text::render_text( // "Why oh why does a silly cow fly, you idiot.\n\nGo die in a pie.\n\nPls.", // font, // layer, // at, // -1.0, // i assume this is because our coordinate system is hosed ... // scale, // &t, // &mut vertices, // Some(300.0) // ); // // frame.draw_vertices(&vertices, Uniforms { // transform : down_size_m4(self.camera.ui_projection().into()), // color: color::WHITE, // }, Blend::Alpha); // } self.renderer.finish_frame().expect("a finished frame"); Ok(()) } } fn raster(t: &mut GeometryTesselator, vertices: &mut Vec<Vertex>, color:Color, x:f64, z:f64) { vertices.clear(); let texture_region = TextureRegion { u_min: 0, u_max: 128, v_min: 0, v_max: 128, layer: 0, texture_size: 1024, }; let texture_region_small = TextureRegion { u_min: 16, u_max: 32, v_min: 16, v_max: 32, layer: 0, texture_size: 1024, }; t.color = color.float_raw(); // .h_flip().v_flip() t.draw_floor_tile(vertices, &texture_region, x, 0.0, z, 0.0); t.color = color::RED.float_raw(); t.draw_wall_tile(vertices, &texture_region_small, x, 0.0, z, 0.0); t.color = color::GREEN.float_raw(); t.draw_floor_centre_anchored(vertices, &texture_region_small, x + 2.0, 0.0, z + 2.0, 0.1); t.color = color::YELLOW.float_raw(); t.draw_floor_centre_anchored_rotated(vertices, &texture_region_small, x + 4.0, 0.0, z + 4.0, 0.0, 0.1); t.color = color::RED.float_raw(); t.draw_wall_base_anchored(vertices, &texture_region_small, x + 3.0, 0.0, z, 0.0); t.color = color::YELLOW.float_raw(); t.draw_wall_centre_anchored(vertices, &texture_region_small, x + 5.0, 1.0, z, 0.0); }
{ let blend = match rem { 0 => Blend::Alpha, 1 => Blend::Add, _ => Blend::None, }; self.renderer.draw(geo, Uniforms { transform: down_size_m4(self.camera.view_projection().into()), color: color, },blend)?; }
conditional_block
commands.rs
#![allow(dead_code)] extern crate jam; extern crate cgmath; extern crate time; extern crate glutin; extern crate image; extern crate gfx_device_gl; #[macro_use] extern crate aphid; use std::f64::consts::PI; use std::path::{Path, PathBuf}; use cgmath::Rad; use aphid::{HashSet, Seconds}; use jam::color; use jam::{Vec3, Vec2, JamResult, Dimensions, Color, rgb, Camera, InputState, FontDirectory}; use jam::render::*; use jam::render::gfx::{Renderer, GeometryBuffer, OpenGLRenderer, construct_opengl_renderer}; use aphid::HashMap; fn main() { let resources_path = PathBuf::from("resources"); let shader_pair = ShaderPair::for_paths("resources/shader/fat.vert", "resources/shader/fat.frag"); let texture_dir = TextureDirectory::for_path("resources/textures", hashset!["png".into()]); let font_dir = FontDirectory::for_path("resources/fonts"); let file_resources = FileResources { resources: resources_path, shader_pair : shader_pair, texture_directory: texture_dir, font_directory: font_dir, }; println!("creating renderer"); let renderer = construct_opengl_renderer(file_resources, (800, 600), true, "commands example".into()).expect("a renderer"); println!("done creating renderer"); let mut app = App { name: "mixalot".into(), camera: Camera { at: Vec3::new(0.0, 0.0, 0.0), pitch: Rad(PI / 4.0_f64), viewport: Dimensions { pixels: (800,600), points: (800,600), }, points_per_unit: 16.0 * 1.0, }, zoom: 1.0, points_per_unit: 16.0, n: 0, // frame counter renderer: renderer, geometry: HashMap::default(), }; app.run(); } struct App { name : String, camera : Camera, zoom : f64, points_per_unit : f64, n : u64, renderer: OpenGLRenderer, geometry : HashMap<String, GeometryBuffer<gfx_device_gl::Resources>>, } impl App { fn run(&mut self) { let mut last_time = time::precise_time_ns(); 'main: loop { let (dimensions, input_state) = self.renderer.begin_frame(rgb(132, 193, 255)); if input_state.close { break; } // println!("dimensions -> {:?}", dimensions); let time = time::precise_time_ns(); let delta_time = ((time - last_time) as f64) / 1_000_000.0; self.update(&input_state, dimensions, delta_time); let res = self.render().expect("successful rendering"); last_time = time; } } fn units_per_point(&self) -> f64 { 1.0 / self.points_per_unit } fn tesselator(&self) -> GeometryTesselator { let upp = self.units_per_point(); let tesselator_scale = Vec3::new(upp, upp, upp); GeometryTesselator::new(tesselator_scale) } fn update(&mut self, input_state:&InputState, dimensions:Dimensions, delta_time: Seconds) { use glutin::VirtualKeyCode; self.n += 1; self.camera.at = Vec3::new(17.0, 0.0, 17.0); // self.camera.at = Vec3::new(8.0, 0.0, 8.0); self.camera.points_per_unit = self.points_per_unit * self.zoom; self.camera.viewport = dimensions; // println!("Camera viewpoinrt -> {:?}", self.camera.viewport); // let (mx, my) = input_state.mouse.at; // let mouse_at = self.camera.ui_line_segment_for_mouse_position(mx, my); if input_state.keys.pushed.contains(&VirtualKeyCode::P) { // println!("take a screenshot!"); // let image = self.renderer.screenshot(); // let mut output = std::fs::file::create(&path::new("screenshot.png")).unwrap(); // image.save(&mut output, image::imageformat::png).unwrap(); } } fn render(&mut self) -> JamResult<()> { // use jam::font::FontDescription; // let font_description = FontDescription { family: "Roboto-Medium".into(), pixel_size: (32f64 * self.camera.viewport.scale()) as u32 }; // let loaded = self.renderer.load_font(&font_description); // match loaded { // Err(e) => println!("font load error -> {:?}", e), // Ok(_) => (), // } // println!("render with delta -> {:?}", delta_time); let colors = vec![color::WHITE, color::BLUE, color::RED]; // let (w, h) = self.camera.viewport.pixels; // let line = self.camera.ray_for_mouse_position((w / 2) as i32, (h / 2) as i32); // println!("forward line -> {:?}", line); let an = self.n / 60; let on_second = (self.n % 60) == 0; let raster_color = colors[(((an / 16) % 16) % 3) as usize]; // cycles every 16 seconds if on_second && an % 5 == 0 { // every fifth second let column = (an / 4) % 4; let name : String = format!("zone_{}", column); println!("delete {}", name); let pred : Box<Fn(&String) -> bool> = Box::new(move |key| key.starts_with(&name)); let keys_to_delete : Vec<_>= self.geometry.keys().filter(|e| pred(e)).cloned().collect(); for key in keys_to_delete.iter() { self.geometry.remove(key); } } // k.starts_with(&prefix) let n = (((an % 16) as f64) / 16.0 * 255.0) as u8; let mut t = self.tesselator(); let mut vertices = Vec::new(); let cache = &mut self.geometry; let camera = &self.camera; // this closure shit is just dangerous // render a grid of various bits of geo for i in 0..16 { let xo = i % 4; let zo = i / 4; let name : String = format!("zone_{}_{}", xo, zo); if (an % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); let geo = self.renderer.draw_vertices(&vertices, Uniforms { transform : down_size_m4(camera.view_projection().into()), color: color::WHITE, }, Blend::None)?; cache.insert(name, geo); } else if ((an+8) % 16) == i && on_second { raster(&mut t, &mut vertices, raster_color, (xo * 9) as f64, (zo * 9) as f64); cache.insert(name, self.renderer.upload(&vertices)); } else { let rem = (xo + zo) % 3; let color = match rem { 0 => color::rgba(255,255,255, 128), 1 => color::rgba(255,255,255, 50), _ => color::WHITE, }; if let Some(geo) = cache.get(&name) { let blend = match rem { 0 => Blend::Alpha, 1 => Blend::Add, _ => Blend::None, }; self.renderer.draw(geo, Uniforms { transform: down_size_m4(self.camera.view_projection().into()), color: color, },blend)?; } } } // draw ui text // if let Some((font, layer)) = self.renderer.get_font(&font_description) { // // println!("ok we got a font to use to draw layer -> {:?}", layer); // let scale = 1.0 / self.camera.viewport.scale(); // let mut t = GeometryTesselator::new(Vec3::new(1.0, 1.0, 1.0)); // // let texture_region = TextureRegion { // u_min: 0, // u_max: 128, // v_min: 0, // v_max: 128, // texture_size: 1024, // }; // t.color = color::WHITE.float_raw(); // t.draw_ui(&mut vertices, &texture_region, 0, 20.0, 20.0, 0.0, 1.0); // // let at = Vec2::new(0.0, 400.0); // t.color = color::BLACK.float_raw(); // text::render_text( // "Why oh why does a silly cow fly, you idiot.\n\nGo die in a pie.\n\nPls.", // font, // layer, // at, // -1.0, // i assume this is because our coordinate system is hosed ... // scale, // &t, // &mut vertices, // Some(300.0)
// // frame.draw_vertices(&vertices, Uniforms { // transform : down_size_m4(self.camera.ui_projection().into()), // color: color::WHITE, // }, Blend::Alpha); // } self.renderer.finish_frame().expect("a finished frame"); Ok(()) } } fn raster(t: &mut GeometryTesselator, vertices: &mut Vec<Vertex>, color:Color, x:f64, z:f64) { vertices.clear(); let texture_region = TextureRegion { u_min: 0, u_max: 128, v_min: 0, v_max: 128, layer: 0, texture_size: 1024, }; let texture_region_small = TextureRegion { u_min: 16, u_max: 32, v_min: 16, v_max: 32, layer: 0, texture_size: 1024, }; t.color = color.float_raw(); // .h_flip().v_flip() t.draw_floor_tile(vertices, &texture_region, x, 0.0, z, 0.0); t.color = color::RED.float_raw(); t.draw_wall_tile(vertices, &texture_region_small, x, 0.0, z, 0.0); t.color = color::GREEN.float_raw(); t.draw_floor_centre_anchored(vertices, &texture_region_small, x + 2.0, 0.0, z + 2.0, 0.1); t.color = color::YELLOW.float_raw(); t.draw_floor_centre_anchored_rotated(vertices, &texture_region_small, x + 4.0, 0.0, z + 4.0, 0.0, 0.1); t.color = color::RED.float_raw(); t.draw_wall_base_anchored(vertices, &texture_region_small, x + 3.0, 0.0, z, 0.0); t.color = color::YELLOW.float_raw(); t.draw_wall_centre_anchored(vertices, &texture_region_small, x + 5.0, 1.0, z, 0.0); }
// );
random_line_split
importer.py
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import time from operator import itemgetter from sqlalchemy.sql import func, select from indico.core.db.sqlalchemy import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.modules.groups import GroupProxy from indico_migrate.logger import logger_proxy from indico_migrate.util import convert_to_unicode class Importer(object): step_name = '' #: Specify plugins that need to be loaded for the import (e.g. to access its .settings property) plugins = frozenset() print_info = logger_proxy('info') print_success = logger_proxy('success') print_warning = logger_proxy('warning') print_error = logger_proxy('error') print_log = logger_proxy('log') def __init__(self, logger, app, sqlalchemy_uri, zodb_root, verbose, dblog, default_group_provider, tz, **kwargs): self.sqlalchemy_uri = sqlalchemy_uri self.quiet = not verbose self.dblog = dblog self.zodb_root = zodb_root self.app = app self.tz = tz self.default_group_provider = default_group_provider self.logger = logger self.initialize_global_ns(Importer._global_ns) def initialize_global_ns(self, g): pass @property def log_prefix(self): return '%[cyan]{:<14}%[reset]'.format('[%[grey!]{}%[cyan]]'.format(self.step_name)) @property def makac_info(self): return self.zodb_root['MaKaCInfo']['main'] @property def global_ns(self): return Importer._global_ns def __repr__(self): return '<{}({})>'.format(type(self).__name__, self.sqlalchemy_uri) def flushing_iterator(self, iterable, n=5000): """Iterates over `iterable` and flushes the ZODB cache every `n` items. :param iterable: an iterable object :param n: number of items to flush after """ conn = self.zodb_root._p_jar for i, item in enumerate(iterable, 1): yield item if i % n == 0: conn.sync() def convert_principal(self, old_principal): """Converts a legacy principal to PrincipalMixin style""" if old_principal.__class__.__name__ == 'Avatar': principal = self.global_ns.avatar_merged_user.get(old_principal.id) if not principal and 'email' in old_principal.__dict__: email = convert_to_unicode(old_principal.__dict__['email']).lower() principal = self.global_ns.users_by_primary_email.get( email, self.global_ns.users_by_secondary_email.get(email)) if principal is not None: self.print_warning('Using {} for {} (matched via {})'.format(principal, old_principal, email)) if not principal:
return principal elif old_principal.__class__.__name__ == 'Group': assert int(old_principal.id) in self.global_ns.all_groups return GroupProxy(int(old_principal.id)) elif old_principal.__class__.__name__ in {'CERNGroup', 'LDAPGroup', 'NiceGroup'}: return GroupProxy(old_principal.id, self.default_group_provider) def convert_principal_list(self, opt): """Convert ACL principals to new objects""" return set(filter(None, (self.convert_principal(principal) for principal in opt._PluginOption__value))) def fix_sequences(self, schema=None, tables=None): for name, cls in sorted(db.Model._decl_class_registry.iteritems(), key=itemgetter(0)): table = getattr(cls, '__table__', None) if table is None: continue elif schema is not None and table.schema != schema: continue elif tables is not None and cls.__tablename__ not in tables: continue # Check if we have a single autoincrementing primary key candidates = [col for col in table.c if col.autoincrement and col.primary_key] if len(candidates) != 1 or not isinstance(candidates[0].type, db.Integer): continue serial_col = candidates[0] sequence_name = '{}.{}_{}_seq'.format(table.schema, cls.__tablename__, serial_col.name) query = select([func.setval(sequence_name, func.max(serial_col) + 1)], table) db.session.execute(query) db.session.commit() def protection_from_ac(self, target, ac, acl_attr='acl', ac_attr='allowed', allow_public=False): """Convert AccessController data to ProtectionMixin style. This needs to run inside the context of `patch_default_group_provider`. :param target: The new object that uses ProtectionMixin :param ac: The old AccessController :param acl_attr: The attribute name for the acl of `target` :param ac_attr: The attribute name for the acl in `ac` :param allow_public: If the object allows `ProtectionMode.public`. Otherwise, public is converted to inheriting. """ if ac._accessProtection == -1: target.protection_mode = ProtectionMode.public if allow_public else ProtectionMode.inheriting elif ac._accessProtection == 0: target.protection_mode = ProtectionMode.inheriting elif ac._accessProtection == 1: target.protection_mode = ProtectionMode.protected acl = getattr(target, acl_attr) for principal in getattr(ac, ac_attr): principal = self.convert_principal(principal) assert principal is not None acl.add(principal) else: raise ValueError('Unexpected protection: {}'.format(ac._accessProtection)) class TopLevelMigrationStep(Importer): def run(self): start = time.time() self.pre_migrate() try: self.migrate() finally: self.post_migrate() self.print_log('%[cyan]{:.06f} seconds%[reset]\a'.format((time.time() - start))) def pre_migrate(self): pass def migrate(self): raise NotImplementedError def post_migrate(self): pass
self.print_error("User {} doesn't exist".format(old_principal.id))
conditional_block
importer.py
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import time from operator import itemgetter from sqlalchemy.sql import func, select from indico.core.db.sqlalchemy import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.modules.groups import GroupProxy from indico_migrate.logger import logger_proxy from indico_migrate.util import convert_to_unicode class Importer(object): step_name = '' #: Specify plugins that need to be loaded for the import (e.g. to access its .settings property) plugins = frozenset() print_info = logger_proxy('info') print_success = logger_proxy('success') print_warning = logger_proxy('warning') print_error = logger_proxy('error') print_log = logger_proxy('log') def __init__(self, logger, app, sqlalchemy_uri, zodb_root, verbose, dblog, default_group_provider, tz, **kwargs): self.sqlalchemy_uri = sqlalchemy_uri self.quiet = not verbose self.dblog = dblog self.zodb_root = zodb_root self.app = app self.tz = tz self.default_group_provider = default_group_provider self.logger = logger self.initialize_global_ns(Importer._global_ns) def initialize_global_ns(self, g): pass @property def log_prefix(self): return '%[cyan]{:<14}%[reset]'.format('[%[grey!]{}%[cyan]]'.format(self.step_name)) @property def makac_info(self): return self.zodb_root['MaKaCInfo']['main'] @property def global_ns(self): return Importer._global_ns def __repr__(self): return '<{}({})>'.format(type(self).__name__, self.sqlalchemy_uri) def flushing_iterator(self, iterable, n=5000): """Iterates over `iterable` and flushes the ZODB cache every `n` items. :param iterable: an iterable object :param n: number of items to flush after """ conn = self.zodb_root._p_jar for i, item in enumerate(iterable, 1): yield item if i % n == 0: conn.sync() def convert_principal(self, old_principal): """Converts a legacy principal to PrincipalMixin style""" if old_principal.__class__.__name__ == 'Avatar': principal = self.global_ns.avatar_merged_user.get(old_principal.id) if not principal and 'email' in old_principal.__dict__: email = convert_to_unicode(old_principal.__dict__['email']).lower() principal = self.global_ns.users_by_primary_email.get( email, self.global_ns.users_by_secondary_email.get(email)) if principal is not None: self.print_warning('Using {} for {} (matched via {})'.format(principal, old_principal, email)) if not principal: self.print_error("User {} doesn't exist".format(old_principal.id)) return principal elif old_principal.__class__.__name__ == 'Group': assert int(old_principal.id) in self.global_ns.all_groups return GroupProxy(int(old_principal.id)) elif old_principal.__class__.__name__ in {'CERNGroup', 'LDAPGroup', 'NiceGroup'}: return GroupProxy(old_principal.id, self.default_group_provider) def convert_principal_list(self, opt): """Convert ACL principals to new objects""" return set(filter(None, (self.convert_principal(principal) for principal in opt._PluginOption__value))) def fix_sequences(self, schema=None, tables=None): for name, cls in sorted(db.Model._decl_class_registry.iteritems(), key=itemgetter(0)): table = getattr(cls, '__table__', None) if table is None: continue elif schema is not None and table.schema != schema: continue elif tables is not None and cls.__tablename__ not in tables:
if len(candidates) != 1 or not isinstance(candidates[0].type, db.Integer): continue serial_col = candidates[0] sequence_name = '{}.{}_{}_seq'.format(table.schema, cls.__tablename__, serial_col.name) query = select([func.setval(sequence_name, func.max(serial_col) + 1)], table) db.session.execute(query) db.session.commit() def protection_from_ac(self, target, ac, acl_attr='acl', ac_attr='allowed', allow_public=False): """Convert AccessController data to ProtectionMixin style. This needs to run inside the context of `patch_default_group_provider`. :param target: The new object that uses ProtectionMixin :param ac: The old AccessController :param acl_attr: The attribute name for the acl of `target` :param ac_attr: The attribute name for the acl in `ac` :param allow_public: If the object allows `ProtectionMode.public`. Otherwise, public is converted to inheriting. """ if ac._accessProtection == -1: target.protection_mode = ProtectionMode.public if allow_public else ProtectionMode.inheriting elif ac._accessProtection == 0: target.protection_mode = ProtectionMode.inheriting elif ac._accessProtection == 1: target.protection_mode = ProtectionMode.protected acl = getattr(target, acl_attr) for principal in getattr(ac, ac_attr): principal = self.convert_principal(principal) assert principal is not None acl.add(principal) else: raise ValueError('Unexpected protection: {}'.format(ac._accessProtection)) class TopLevelMigrationStep(Importer): def run(self): start = time.time() self.pre_migrate() try: self.migrate() finally: self.post_migrate() self.print_log('%[cyan]{:.06f} seconds%[reset]\a'.format((time.time() - start))) def pre_migrate(self): pass def migrate(self): raise NotImplementedError def post_migrate(self): pass
continue # Check if we have a single autoincrementing primary key candidates = [col for col in table.c if col.autoincrement and col.primary_key]
random_line_split
importer.py
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import time from operator import itemgetter from sqlalchemy.sql import func, select from indico.core.db.sqlalchemy import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.modules.groups import GroupProxy from indico_migrate.logger import logger_proxy from indico_migrate.util import convert_to_unicode class Importer(object): step_name = '' #: Specify plugins that need to be loaded for the import (e.g. to access its .settings property) plugins = frozenset() print_info = logger_proxy('info') print_success = logger_proxy('success') print_warning = logger_proxy('warning') print_error = logger_proxy('error') print_log = logger_proxy('log') def __init__(self, logger, app, sqlalchemy_uri, zodb_root, verbose, dblog, default_group_provider, tz, **kwargs): self.sqlalchemy_uri = sqlalchemy_uri self.quiet = not verbose self.dblog = dblog self.zodb_root = zodb_root self.app = app self.tz = tz self.default_group_provider = default_group_provider self.logger = logger self.initialize_global_ns(Importer._global_ns) def initialize_global_ns(self, g): pass @property def log_prefix(self): return '%[cyan]{:<14}%[reset]'.format('[%[grey!]{}%[cyan]]'.format(self.step_name)) @property def makac_info(self): return self.zodb_root['MaKaCInfo']['main'] @property def global_ns(self): return Importer._global_ns def __repr__(self): return '<{}({})>'.format(type(self).__name__, self.sqlalchemy_uri) def flushing_iterator(self, iterable, n=5000): """Iterates over `iterable` and flushes the ZODB cache every `n` items. :param iterable: an iterable object :param n: number of items to flush after """ conn = self.zodb_root._p_jar for i, item in enumerate(iterable, 1): yield item if i % n == 0: conn.sync() def convert_principal(self, old_principal): """Converts a legacy principal to PrincipalMixin style""" if old_principal.__class__.__name__ == 'Avatar': principal = self.global_ns.avatar_merged_user.get(old_principal.id) if not principal and 'email' in old_principal.__dict__: email = convert_to_unicode(old_principal.__dict__['email']).lower() principal = self.global_ns.users_by_primary_email.get( email, self.global_ns.users_by_secondary_email.get(email)) if principal is not None: self.print_warning('Using {} for {} (matched via {})'.format(principal, old_principal, email)) if not principal: self.print_error("User {} doesn't exist".format(old_principal.id)) return principal elif old_principal.__class__.__name__ == 'Group': assert int(old_principal.id) in self.global_ns.all_groups return GroupProxy(int(old_principal.id)) elif old_principal.__class__.__name__ in {'CERNGroup', 'LDAPGroup', 'NiceGroup'}: return GroupProxy(old_principal.id, self.default_group_provider) def convert_principal_list(self, opt): """Convert ACL principals to new objects""" return set(filter(None, (self.convert_principal(principal) for principal in opt._PluginOption__value))) def fix_sequences(self, schema=None, tables=None): for name, cls in sorted(db.Model._decl_class_registry.iteritems(), key=itemgetter(0)): table = getattr(cls, '__table__', None) if table is None: continue elif schema is not None and table.schema != schema: continue elif tables is not None and cls.__tablename__ not in tables: continue # Check if we have a single autoincrementing primary key candidates = [col for col in table.c if col.autoincrement and col.primary_key] if len(candidates) != 1 or not isinstance(candidates[0].type, db.Integer): continue serial_col = candidates[0] sequence_name = '{}.{}_{}_seq'.format(table.schema, cls.__tablename__, serial_col.name) query = select([func.setval(sequence_name, func.max(serial_col) + 1)], table) db.session.execute(query) db.session.commit() def protection_from_ac(self, target, ac, acl_attr='acl', ac_attr='allowed', allow_public=False): """Convert AccessController data to ProtectionMixin style. This needs to run inside the context of `patch_default_group_provider`. :param target: The new object that uses ProtectionMixin :param ac: The old AccessController :param acl_attr: The attribute name for the acl of `target` :param ac_attr: The attribute name for the acl in `ac` :param allow_public: If the object allows `ProtectionMode.public`. Otherwise, public is converted to inheriting. """ if ac._accessProtection == -1: target.protection_mode = ProtectionMode.public if allow_public else ProtectionMode.inheriting elif ac._accessProtection == 0: target.protection_mode = ProtectionMode.inheriting elif ac._accessProtection == 1: target.protection_mode = ProtectionMode.protected acl = getattr(target, acl_attr) for principal in getattr(ac, ac_attr): principal = self.convert_principal(principal) assert principal is not None acl.add(principal) else: raise ValueError('Unexpected protection: {}'.format(ac._accessProtection)) class TopLevelMigrationStep(Importer): def run(self): start = time.time() self.pre_migrate() try: self.migrate() finally: self.post_migrate() self.print_log('%[cyan]{:.06f} seconds%[reset]\a'.format((time.time() - start))) def
(self): pass def migrate(self): raise NotImplementedError def post_migrate(self): pass
pre_migrate
identifier_name
importer.py
# This file is part of Indico. # Copyright (C) 2002 - 2017 European Organization for Nuclear Research (CERN). # # Indico 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. # # Indico 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 Indico; if not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals import time from operator import itemgetter from sqlalchemy.sql import func, select from indico.core.db.sqlalchemy import db from indico.core.db.sqlalchemy.protection import ProtectionMode from indico.modules.groups import GroupProxy from indico_migrate.logger import logger_proxy from indico_migrate.util import convert_to_unicode class Importer(object): step_name = '' #: Specify plugins that need to be loaded for the import (e.g. to access its .settings property) plugins = frozenset() print_info = logger_proxy('info') print_success = logger_proxy('success') print_warning = logger_proxy('warning') print_error = logger_proxy('error') print_log = logger_proxy('log') def __init__(self, logger, app, sqlalchemy_uri, zodb_root, verbose, dblog, default_group_provider, tz, **kwargs): self.sqlalchemy_uri = sqlalchemy_uri self.quiet = not verbose self.dblog = dblog self.zodb_root = zodb_root self.app = app self.tz = tz self.default_group_provider = default_group_provider self.logger = logger self.initialize_global_ns(Importer._global_ns) def initialize_global_ns(self, g): pass @property def log_prefix(self): return '%[cyan]{:<14}%[reset]'.format('[%[grey!]{}%[cyan]]'.format(self.step_name)) @property def makac_info(self): return self.zodb_root['MaKaCInfo']['main'] @property def global_ns(self): return Importer._global_ns def __repr__(self): return '<{}({})>'.format(type(self).__name__, self.sqlalchemy_uri) def flushing_iterator(self, iterable, n=5000): """Iterates over `iterable` and flushes the ZODB cache every `n` items. :param iterable: an iterable object :param n: number of items to flush after """ conn = self.zodb_root._p_jar for i, item in enumerate(iterable, 1): yield item if i % n == 0: conn.sync() def convert_principal(self, old_principal): """Converts a legacy principal to PrincipalMixin style""" if old_principal.__class__.__name__ == 'Avatar': principal = self.global_ns.avatar_merged_user.get(old_principal.id) if not principal and 'email' in old_principal.__dict__: email = convert_to_unicode(old_principal.__dict__['email']).lower() principal = self.global_ns.users_by_primary_email.get( email, self.global_ns.users_by_secondary_email.get(email)) if principal is not None: self.print_warning('Using {} for {} (matched via {})'.format(principal, old_principal, email)) if not principal: self.print_error("User {} doesn't exist".format(old_principal.id)) return principal elif old_principal.__class__.__name__ == 'Group': assert int(old_principal.id) in self.global_ns.all_groups return GroupProxy(int(old_principal.id)) elif old_principal.__class__.__name__ in {'CERNGroup', 'LDAPGroup', 'NiceGroup'}: return GroupProxy(old_principal.id, self.default_group_provider) def convert_principal_list(self, opt): """Convert ACL principals to new objects""" return set(filter(None, (self.convert_principal(principal) for principal in opt._PluginOption__value))) def fix_sequences(self, schema=None, tables=None): for name, cls in sorted(db.Model._decl_class_registry.iteritems(), key=itemgetter(0)): table = getattr(cls, '__table__', None) if table is None: continue elif schema is not None and table.schema != schema: continue elif tables is not None and cls.__tablename__ not in tables: continue # Check if we have a single autoincrementing primary key candidates = [col for col in table.c if col.autoincrement and col.primary_key] if len(candidates) != 1 or not isinstance(candidates[0].type, db.Integer): continue serial_col = candidates[0] sequence_name = '{}.{}_{}_seq'.format(table.schema, cls.__tablename__, serial_col.name) query = select([func.setval(sequence_name, func.max(serial_col) + 1)], table) db.session.execute(query) db.session.commit() def protection_from_ac(self, target, ac, acl_attr='acl', ac_attr='allowed', allow_public=False): """Convert AccessController data to ProtectionMixin style. This needs to run inside the context of `patch_default_group_provider`. :param target: The new object that uses ProtectionMixin :param ac: The old AccessController :param acl_attr: The attribute name for the acl of `target` :param ac_attr: The attribute name for the acl in `ac` :param allow_public: If the object allows `ProtectionMode.public`. Otherwise, public is converted to inheriting. """ if ac._accessProtection == -1: target.protection_mode = ProtectionMode.public if allow_public else ProtectionMode.inheriting elif ac._accessProtection == 0: target.protection_mode = ProtectionMode.inheriting elif ac._accessProtection == 1: target.protection_mode = ProtectionMode.protected acl = getattr(target, acl_attr) for principal in getattr(ac, ac_attr): principal = self.convert_principal(principal) assert principal is not None acl.add(principal) else: raise ValueError('Unexpected protection: {}'.format(ac._accessProtection)) class TopLevelMigrationStep(Importer): def run(self): start = time.time() self.pre_migrate() try: self.migrate() finally: self.post_migrate() self.print_log('%[cyan]{:.06f} seconds%[reset]\a'.format((time.time() - start))) def pre_migrate(self): pass def migrate(self):
def post_migrate(self): pass
raise NotImplementedError
identifier_body
all_b.js
var searchData= [ ['magenta',['magenta',['../_logger_8cpp.html#a9c3c2560b6f423f7902776457532fdba',1,'Logger.cpp']]], ['maxsamples',['maxsamples',['../class_audio_signal.html#a5d68faf1ab7f19197b93cc2cc0a7e645',1,'AudioSignal']]], ['mps_5fvt',['mps_vt',['../struct_h_r_t_f_model.html#ae01efd7375e498a14624bbeebb93fa82a14e4aa4784083d62a00452f4d32b4098',1,'HRTFModel']]], ['mute',['mute',['../class_channel.html#a88f542e0f6d1e1d384ad8bf79a9e305b',1,'Channel']]], ['mutecheckbox',['mutecheckbox',['../class_channel.html#a0e7f90da49f291a7bac498e11e886fbd',1,'Channel']]], ['muted',['muted',['../class_channel.html#ada7e3a050c346ad283ad302745f03f3c',1,'Channel']]]
];
random_line_split
user.ts
import {Injectable} from 'angular2/core'; import {HttpService} from '../services/http'; import {Model} from './model'; @Injectable() export class
extends Model { public firstName: string = ""; public lastName: string = ""; public email: string = ""; public password: string = ""; public constructor(private httpService: HttpService) { super(); } public getAuthToken() { return this.httpService.getAuthToken(); } public setAuthToken(token: string) { this.httpService.setAuthToken(token); } public register() { let params = this.buildParams([ 'firstName', 'lastName', 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/register", params); } public login() { let params = this.buildParams([ 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/login", params); } public logout() { return this.httpService.sendAuthRequest("POST", '/auth/logout'); } }
User
identifier_name
user.ts
import {Injectable} from 'angular2/core'; import {HttpService} from '../services/http'; import {Model} from './model'; @Injectable() export class User extends Model { public firstName: string = ""; public lastName: string = ""; public email: string = ""; public password: string = ""; public constructor(private httpService: HttpService) { super(); } public getAuthToken()
public setAuthToken(token: string) { this.httpService.setAuthToken(token); } public register() { let params = this.buildParams([ 'firstName', 'lastName', 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/register", params); } public login() { let params = this.buildParams([ 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/login", params); } public logout() { return this.httpService.sendAuthRequest("POST", '/auth/logout'); } }
{ return this.httpService.getAuthToken(); }
identifier_body
user.ts
import {Injectable} from 'angular2/core'; import {HttpService} from '../services/http'; import {Model} from './model'; @Injectable()
export class User extends Model { public firstName: string = ""; public lastName: string = ""; public email: string = ""; public password: string = ""; public constructor(private httpService: HttpService) { super(); } public getAuthToken() { return this.httpService.getAuthToken(); } public setAuthToken(token: string) { this.httpService.setAuthToken(token); } public register() { let params = this.buildParams([ 'firstName', 'lastName', 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/register", params); } public login() { let params = this.buildParams([ 'email', 'password' ]); return this.httpService.sendRequest("POST", "/auth/login", params); } public logout() { return this.httpService.sendAuthRequest("POST", '/auth/logout'); } }
random_line_split
_context.py
from __future__ import annotations from collections import defaultdict from collections.abc import Generator, Iterable, Mapping, MutableMapping from contextlib import contextmanager import logging import re import textwrap from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple from markdown_it.rules_block.html_block import HTML_SEQUENCES from mdformat import codepoints from mdformat._compat import Literal from mdformat._conf import DEFAULT_OPTS from mdformat.renderer._util import ( RE_CHAR_REFERENCE, decimalify_leading, decimalify_trailing, escape_asterisk_emphasis, escape_underscore_emphasis, get_list_marker_type, is_tight_list, is_tight_list_item, longest_consecutive_sequence, maybe_add_link_brackets, ) from mdformat.renderer.typing import Postprocess, Render if TYPE_CHECKING: from mdformat.renderer import RenderTreeNode LOGGER = logging.getLogger(__name__) # A marker used to point a location where word wrap is allowed # to occur. WRAP_POINT = "\x00" # A marker used to indicate location of a character that should be preserved # during word wrap. Should be converted to the actual character after wrap. PRESERVE_CHAR = "\x00" def make_render_children(separator: str) -> Render: def render_children( node: RenderTreeNode, context: RenderContext, ) -> str: return separator.join(child.render(context) for child in node.children) return render_children def hr(node: RenderTreeNode, context: RenderContext) -> str: thematic_break_width = 70 return "_" * thematic_break_width def code_inline(node: RenderTreeNode, context: RenderContext) -> str: code = node.content all_chars_are_whitespace = not code.strip() longest_backtick_seq = longest_consecutive_sequence(code, "`") if longest_backtick_seq: separator = "`" * (longest_backtick_seq + 1) return f"{separator} {code} {separator}" if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace: return f"` {code} `" return f"`{code}`" def html_block(node: RenderTreeNode, context: RenderContext) -> str: content = node.content.rstrip("\n") # Need to strip leading spaces because we do so for regular Markdown too. # Without the stripping the raw HTML and Markdown get unaligned and # semantic may change. content = content.lstrip() return content def html_inline(node: RenderTreeNode, context: RenderContext) -> str: return node.content def _in_block(block_name: str, node: RenderTreeNode) -> bool: while node.parent: if node.parent.type == block_name: return True node = node.parent return False def hardbreak(node: RenderTreeNode, context: RenderContext) -> str: if _in_block("heading", node): return "<br /> " return "\\" + "\n" def softbreak(node: RenderTreeNode, context: RenderContext) -> str: if context.do_wrap and _in_block("paragraph", node): return WRAP_POINT return "\n" def text(node: RenderTreeNode, context: RenderContext) -> str: """Process a text token. Text should always be a child of an inline token. An inline token should always be enclosed by a heading or a paragraph. """ text = node.content # Escape backslash to prevent it from making unintended escapes. # This escape has to be first, else we start multiplying backslashes. text = text.replace("\\", "\\\\") text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker. text = escape_underscore_emphasis(text) # Escape emphasis/strong marker. text = text.replace("[", "\\[") # Escape link label enclosure text = text.replace("]", "\\]") # Escape link label enclosure text = text.replace("<", "\\<") # Escape URI enclosure text = text.replace("`", "\\`") # Escape code span marker # Escape "&" if it starts a sequence that can be interpreted as # a character reference. text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text) # The parser can give us consecutive newlines which can break # the markdown structure. Replace two or more consecutive newlines # with newline character's decimal reference. text = text.replace("\n\n", "&#10;&#10;") # If the last character is a "!" and the token next up is a link, we # have to escape the "!" or else the link will be interpreted as image. next_sibling = node.next_sibling if text.endswith("!") and next_sibling and next_sibling.type == "link": text = text[:-1] + "\\!" if context.do_wrap and _in_block("paragraph", node): text = re.sub(r"\s+", WRAP_POINT, text) return text def fence(node: RenderTreeNode, context: RenderContext) -> str: info_str = node.info.strip() lang = info_str.split(maxsplit=1)[0] if info_str else "" code_block = node.content # Info strings of backtick code fences cannot contain backticks. # If that is the case, we make a tilde code fence instead. fence_char = "~" if "`" in info_str else "`" # Format the code block using enabled codeformatter funcs if lang in context.options.get("codeformatters", {}): fmt_func = context.options["codeformatters"][lang] try: code_block = fmt_func(code_block, info_str) except Exception: # Swallow exceptions so that formatter errors (e.g. due to # invalid code) do not crash mdformat. assert node.map is not None, "A fence token must have `map` attribute set" filename = context.options.get("mdformat", {}).get("filename", "") warn_msg = ( f"Failed formatting content of a {lang} code block " f"(line {node.map[0] + 1} before formatting)" ) if filename: warn_msg += f". Filename: {filename}" LOGGER.warning(warn_msg) # The code block must not include as long or longer sequence of `fence_char`s # as the fence string itself fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1) fence_str = fence_char * fence_len return f"{fence_str}{info_str}\n{code_block}{fence_str}" def code_block(node: RenderTreeNode, context: RenderContext) -> str: return fence(node, context) def image(node: RenderTreeNode, context: RenderContext) -> str: description = _render_inline_as_text(node, context) if context.do_wrap: # Prevent line breaks description = description.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if description.lower() == ref_label_repr: return f"![{description}]" return f"![{description}][{ref_label_repr}]" uri = node.attrs["src"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is not None: return f'![{description}]({uri} "{title}")' return f"![{description}]({uri})" def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str: """Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. """ def text_renderer(node: RenderTreeNode, context: RenderContext) -> str: return node.content def image_renderer(node: RenderTreeNode, context: RenderContext) -> str: return _render_inline_as_text(node, context) inline_renderers: Mapping[str, Render] = defaultdict( lambda: make_render_children(""), { "text": text_renderer, "image": image_renderer, "link": link, "softbreak": softbreak, }, ) inline_context = RenderContext( inline_renderers, context.postprocessors, context.options, context.env ) return make_render_children("")(node, inline_context) def link(node: RenderTreeNode, context: RenderContext) -> str: if node.info == "auto": autolink_url = node.attrs["href"] assert isinstance(autolink_url, str) # The parser adds a "mailto:" prefix to autolink email href. We remove the # prefix if it wasn't there in the source. if autolink_url.startswith("mailto:") and not node.children[ 0 ].content.startswith("mailto:"): autolink_url = autolink_url[7:] return "<" + autolink_url + ">" text = "".join(child.render(context) for child in node.children) if context.do_wrap: # Prevent line breaks text = text.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if text.lower() == ref_label_repr: return f"[{text}]" return f"[{text}][{ref_label_repr}]" uri = node.attrs["href"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is None: return f"[{text}]({uri})" assert isinstance(title, str) title = title.replace('"', '\\"') return f'[{text}]({uri} "{title}")' def em(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def strong(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def heading(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) if node.markup == "=": prefix = "# " elif node.markup == "-": prefix = "## " else: # ATX heading prefix = node.markup + " " # There can be newlines in setext headers, but we make an ATX # header always. Convert newlines to spaces. text = text.replace("\n", " ") # If the text ends in a sequence of hashes (#), the hashes will be # interpreted as an optional closing sequence of the heading, and # will not be rendered. Escape a line ending hash to prevent this. if text.endswith("#"): text = text[:-1] + "\\#" return prefix + text def blockquote(node: RenderTreeNode, context: RenderContext) -> str: marker = "> " with context.indented(len(marker)): text = make_render_children(separator="\n\n")(node, context) lines = text.splitlines() if not lines: return ">" quoted_lines = (f"{marker}{line}" if line else ">" for line in lines) quoted_str = "\n".join(quoted_lines) return quoted_str def _wrap(text: str, *, width: int | Literal["no"]) -> str: """Wrap text at locations pointed by `WRAP_POINT`s. Converts `WRAP_POINT`s to either a space or newline character, thus wrapping the text. Already existing whitespace will be preserved as is. """ text, replacements = _prepare_wrap(text) if width == "no": return _recover_preserve_chars(text, replacements) wrapper = textwrap.TextWrapper( break_long_words=False, break_on_hyphens=False, width=width, expand_tabs=False, replace_whitespace=False, ) wrapped = wrapper.fill(text) wrapped = _recover_preserve_chars(wrapped, replacements) return " " + wrapped if text.startswith(" ") else wrapped def _prepare_wrap(text: str) -> tuple[str, str]: """Prepare text for wrap. Convert `WRAP_POINT`s to spaces. Convert whitespace to `PRESERVE_CHAR`s. Return a tuple with the prepared string, and another string consisting of replacement characters for `PRESERVE_CHAR`s. """ result = "" replacements = "" for c in text: if c == WRAP_POINT: if not result or result[-1] != " ": result += " " elif c in codepoints.UNICODE_WHITESPACE: result += PRESERVE_CHAR replacements += c else: result += c return result, replacements def _recover_preserve_chars(text: str, replacements: str) -> str: replacement_iterator = iter(replacements) return "".join( next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text ) def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901 inline_node = node.children[0] text = inline_node.render(context) if context.do_wrap: wrap_mode = context.options["mdformat"]["wrap"] if isinstance(wrap_mode, int): wrap_mode -= context.env["indent_width"] wrap_mode = max(1, wrap_mode) text = _wrap(text, width=wrap_mode) # A paragraph can start or end in whitespace e.g. if the whitespace was # in decimal representation form. We need to re-decimalify it, one reason being # to enable "empty" paragraphs with whitespace only. text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text) text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text) lines = text.split("\n") for i in range(len(lines)): # Strip whitespace to prevent issues like a line starting tab that is # interpreted as start of a code block. lines[i] = lines[i].strip() # If a line looks like an ATX heading, escape the first hash. if re.match(r"#{1,6}( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with ">" # (otherwise it will be interpreted as a block quote). if lines[i].startswith(">"): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with "*", "-" or "+" # followed by a space, tab, or end of line. # (otherwise it will be interpreted as list item). if re.match(r"[-*+]( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # If a line starts with a number followed by "." or ")" followed by # a space, tab or end of line, escape the "." or ")" or it will be # interpreted as ordered list item. if re.match(r"[0-9]+\)( |\t|$)", lines[i]): lines[i] = lines[i].replace(")", "\\)", 1) if re.match(r"[0-9]+\.( |\t|$)", lines[i]): lines[i] = lines[i].replace(".", "\\.", 1) # Consecutive "-", "*" or "_" sequences can be interpreted as thematic # break. Escape them. space_removed = lines[i].replace(" ", "").replace("\t", "") if len(space_removed) >= 3: if all(c == "*" for c in space_removed): lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover elif all(c == "-" for c in space_removed): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "_" for c in space_removed): lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover # A stripped line where all characters are "=" or "-" will be # interpreted as a setext heading. Escape. stripped = lines[i].strip(" \t") if all(c == "-" for c in stripped): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "=" for c in stripped): lines[i] = lines[i].replace("=", "\\=", 1) # Check if the line could be interpreted as an HTML block. # If yes, prefix it with 4 spaces to prevent this. for html_seq_tuple in HTML_SEQUENCES: can_break_paragraph = html_seq_tuple[2] opening_re = html_seq_tuple[0] if can_break_paragraph and opening_re.search(lines[i]): lines[i] = f" {lines[i]}" break text = "\n".join(lines) return text def list_item(node: RenderTreeNode, context: RenderContext) -> str: """Return one list item as string. This returns just the content. List item markers and indentation are added in `bullet_list` and `ordered_list` renderers. """ block_separator = "\n" if is_tight_list_item(node) else "\n\n" text = make_render_children(block_separator)(node, context) if not text.strip(): return "" return text def bullet_list(node: RenderTreeNode, context: RenderContext) -> str: marker_type = get_list_marker_type(node) first_line_indent = " " indent = " " * len(marker_type + first_line_indent) block_separator = "\n" if is_tight_list(node) else "\n\n" with context.indented(len(indent)): text = "" for child_idx, child in enumerate(node.children): list_item = child.render(context) formatted_lines = [] line_iterator = iter(list_item.split("\n")) first_line = next(line_iterator) formatted_lines.append( f"{marker_type}{first_line_indent}{first_line}" if first_line else marker_type ) for line in line_iterator: formatted_lines.append(f"{indent}{line}" if line else "") text += "\n".join(formatted_lines) if child_idx != len(node.children) - 1: text += block_separator return text def ordered_list(node: RenderTreeNode, context: RenderContext) -> str: consecutive_numbering = context.options.get("mdformat", {}).get( "number", DEFAULT_OPTS["number"] ) marker_type = get_list_marker_type(node) first_line_indent = " " block_separator = "\n" if is_tight_list(node) else "\n\n" list_len = len(node.children) starting_number = node.attrs.get("start") if starting_number is None: starting_number = 1 assert isinstance(starting_number, int) if consecutive_numbering: indent_width = len( f"{list_len + starting_number - 1}{marker_type}{first_line_indent}" ) else: indent_width = len(f"{starting_number}{marker_type}{first_line_indent}") text = "" with context.indented(indent_width): for list_item_index, list_item in enumerate(node.children): list_item_text = list_item.render(context) formatted_lines = [] line_iterator = iter(list_item_text.split("\n")) first_line = next(line_iterator) if consecutive_numbering: # Prefix first line of the list item with consecutive numbering, # padded with zeros to make all markers of even length. # E.g. # 002. This is the first list item # 003. Second item # ... # 112. Last item number = starting_number + list_item_index pad = len(str(list_len + starting_number - 1)) number_str = str(number).rjust(pad, "0") formatted_lines.append( f"{number_str}{marker_type}{first_line_indent}{first_line}" if first_line else f"{number_str}{marker_type}" ) else: # Prefix first line of first item with the starting number of the # list. Prefix following list items with the number one # prefixed by zeros to make the list item marker of even length # with the first one. # E.g. # 5321. This is the first list item # 0001. Second item # 0001. Third item first_item_marker = f"{starting_number}{marker_type}" other_item_marker = ( "0" * (len(str(starting_number)) - 1) + "1" + marker_type ) if list_item_index == 0: formatted_lines.append( f"{first_item_marker}{first_line_indent}{first_line}" if first_line else first_item_marker ) else: formatted_lines.append( f"{other_item_marker}{first_line_indent}{first_line}" if first_line else other_item_marker ) for line in line_iterator: formatted_lines.append(" " * indent_width + line if line else "") text += "\n".join(formatted_lines) if list_item_index != len(node.children) - 1: text += block_separator return text DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType( { "inline": make_render_children(""), "root": make_render_children("\n\n"), "hr": hr, "code_inline": code_inline, "html_block": html_block, "html_inline": html_inline, "hardbreak": hardbreak, "softbreak": softbreak, "text": text, "fence": fence, "code_block": code_block, "link": link, "image": image, "em": em, "strong": strong, "heading": heading, "blockquote": blockquote, "paragraph": paragraph, "bullet_list": bullet_list, "ordered_list": ordered_list, "list_item": list_item, } ) class RenderContext(NamedTuple): """A collection of data that is passed as input to `Render` and `Postprocess` functions.""" renderers: Mapping[str, Render] postprocessors: Mapping[str, Iterable[Postprocess]] options: Mapping[str, Any] env: MutableMapping @contextmanager def indented(self, width: int) -> Generator[None, None, None]: self.env["indent_width"] += width try: yield finally: self.env["indent_width"] -= width @property def do_wrap(self) -> bool: wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"]) return isinstance(wrap_mode, int) or wrap_mode == "no" def
(self, *syntax_names: str) -> RenderContext: renderers = dict(self.renderers) for syntax in syntax_names: if syntax in DEFAULT_RENDERERS: renderers[syntax] = DEFAULT_RENDERERS[syntax] else: renderers.pop(syntax, None) return RenderContext( MappingProxyType(renderers), self.postprocessors, self.options, self.env )
with_default_renderer_for
identifier_name
_context.py
from __future__ import annotations from collections import defaultdict from collections.abc import Generator, Iterable, Mapping, MutableMapping from contextlib import contextmanager import logging import re import textwrap from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple from markdown_it.rules_block.html_block import HTML_SEQUENCES from mdformat import codepoints from mdformat._compat import Literal from mdformat._conf import DEFAULT_OPTS from mdformat.renderer._util import ( RE_CHAR_REFERENCE, decimalify_leading, decimalify_trailing, escape_asterisk_emphasis, escape_underscore_emphasis, get_list_marker_type, is_tight_list, is_tight_list_item, longest_consecutive_sequence, maybe_add_link_brackets, ) from mdformat.renderer.typing import Postprocess, Render if TYPE_CHECKING: from mdformat.renderer import RenderTreeNode LOGGER = logging.getLogger(__name__) # A marker used to point a location where word wrap is allowed # to occur. WRAP_POINT = "\x00" # A marker used to indicate location of a character that should be preserved # during word wrap. Should be converted to the actual character after wrap. PRESERVE_CHAR = "\x00" def make_render_children(separator: str) -> Render: def render_children( node: RenderTreeNode, context: RenderContext, ) -> str: return separator.join(child.render(context) for child in node.children) return render_children def hr(node: RenderTreeNode, context: RenderContext) -> str: thematic_break_width = 70 return "_" * thematic_break_width def code_inline(node: RenderTreeNode, context: RenderContext) -> str: code = node.content all_chars_are_whitespace = not code.strip() longest_backtick_seq = longest_consecutive_sequence(code, "`") if longest_backtick_seq: separator = "`" * (longest_backtick_seq + 1) return f"{separator} {code} {separator}" if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace: return f"` {code} `" return f"`{code}`" def html_block(node: RenderTreeNode, context: RenderContext) -> str: content = node.content.rstrip("\n") # Need to strip leading spaces because we do so for regular Markdown too. # Without the stripping the raw HTML and Markdown get unaligned and # semantic may change. content = content.lstrip() return content def html_inline(node: RenderTreeNode, context: RenderContext) -> str: return node.content def _in_block(block_name: str, node: RenderTreeNode) -> bool: while node.parent: if node.parent.type == block_name: return True node = node.parent return False def hardbreak(node: RenderTreeNode, context: RenderContext) -> str: if _in_block("heading", node): return "<br /> " return "\\" + "\n" def softbreak(node: RenderTreeNode, context: RenderContext) -> str: if context.do_wrap and _in_block("paragraph", node): return WRAP_POINT return "\n" def text(node: RenderTreeNode, context: RenderContext) -> str: """Process a text token. Text should always be a child of an inline token. An inline token should always be enclosed by a heading or a paragraph. """ text = node.content # Escape backslash to prevent it from making unintended escapes. # This escape has to be first, else we start multiplying backslashes. text = text.replace("\\", "\\\\") text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker. text = escape_underscore_emphasis(text) # Escape emphasis/strong marker. text = text.replace("[", "\\[") # Escape link label enclosure text = text.replace("]", "\\]") # Escape link label enclosure text = text.replace("<", "\\<") # Escape URI enclosure text = text.replace("`", "\\`") # Escape code span marker # Escape "&" if it starts a sequence that can be interpreted as # a character reference. text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text) # The parser can give us consecutive newlines which can break # the markdown structure. Replace two or more consecutive newlines # with newline character's decimal reference. text = text.replace("\n\n", "&#10;&#10;") # If the last character is a "!" and the token next up is a link, we # have to escape the "!" or else the link will be interpreted as image. next_sibling = node.next_sibling if text.endswith("!") and next_sibling and next_sibling.type == "link": text = text[:-1] + "\\!" if context.do_wrap and _in_block("paragraph", node): text = re.sub(r"\s+", WRAP_POINT, text) return text def fence(node: RenderTreeNode, context: RenderContext) -> str: info_str = node.info.strip() lang = info_str.split(maxsplit=1)[0] if info_str else "" code_block = node.content # Info strings of backtick code fences cannot contain backticks. # If that is the case, we make a tilde code fence instead. fence_char = "~" if "`" in info_str else "`" # Format the code block using enabled codeformatter funcs if lang in context.options.get("codeformatters", {}): fmt_func = context.options["codeformatters"][lang] try: code_block = fmt_func(code_block, info_str) except Exception: # Swallow exceptions so that formatter errors (e.g. due to # invalid code) do not crash mdformat. assert node.map is not None, "A fence token must have `map` attribute set" filename = context.options.get("mdformat", {}).get("filename", "") warn_msg = ( f"Failed formatting content of a {lang} code block " f"(line {node.map[0] + 1} before formatting)" ) if filename: warn_msg += f". Filename: {filename}" LOGGER.warning(warn_msg) # The code block must not include as long or longer sequence of `fence_char`s # as the fence string itself fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1) fence_str = fence_char * fence_len return f"{fence_str}{info_str}\n{code_block}{fence_str}" def code_block(node: RenderTreeNode, context: RenderContext) -> str: return fence(node, context) def image(node: RenderTreeNode, context: RenderContext) -> str: description = _render_inline_as_text(node, context) if context.do_wrap: # Prevent line breaks description = description.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if description.lower() == ref_label_repr: return f"![{description}]" return f"![{description}][{ref_label_repr}]" uri = node.attrs["src"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is not None: return f'![{description}]({uri} "{title}")' return f"![{description}]({uri})" def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str: """Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. """ def text_renderer(node: RenderTreeNode, context: RenderContext) -> str: return node.content def image_renderer(node: RenderTreeNode, context: RenderContext) -> str: return _render_inline_as_text(node, context) inline_renderers: Mapping[str, Render] = defaultdict( lambda: make_render_children(""), { "text": text_renderer, "image": image_renderer, "link": link, "softbreak": softbreak, }, ) inline_context = RenderContext( inline_renderers, context.postprocessors, context.options, context.env ) return make_render_children("")(node, inline_context) def link(node: RenderTreeNode, context: RenderContext) -> str: if node.info == "auto": autolink_url = node.attrs["href"] assert isinstance(autolink_url, str) # The parser adds a "mailto:" prefix to autolink email href. We remove the # prefix if it wasn't there in the source. if autolink_url.startswith("mailto:") and not node.children[ 0 ].content.startswith("mailto:"): autolink_url = autolink_url[7:] return "<" + autolink_url + ">" text = "".join(child.render(context) for child in node.children) if context.do_wrap: # Prevent line breaks text = text.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if text.lower() == ref_label_repr: return f"[{text}]" return f"[{text}][{ref_label_repr}]" uri = node.attrs["href"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is None: return f"[{text}]({uri})" assert isinstance(title, str) title = title.replace('"', '\\"') return f'[{text}]({uri} "{title}")' def em(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def strong(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def heading(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) if node.markup == "=": prefix = "# " elif node.markup == "-": prefix = "## " else: # ATX heading prefix = node.markup + " " # There can be newlines in setext headers, but we make an ATX # header always. Convert newlines to spaces. text = text.replace("\n", " ") # If the text ends in a sequence of hashes (#), the hashes will be # interpreted as an optional closing sequence of the heading, and # will not be rendered. Escape a line ending hash to prevent this. if text.endswith("#"): text = text[:-1] + "\\#" return prefix + text def blockquote(node: RenderTreeNode, context: RenderContext) -> str: marker = "> " with context.indented(len(marker)): text = make_render_children(separator="\n\n")(node, context) lines = text.splitlines() if not lines: return ">" quoted_lines = (f"{marker}{line}" if line else ">" for line in lines) quoted_str = "\n".join(quoted_lines) return quoted_str def _wrap(text: str, *, width: int | Literal["no"]) -> str: """Wrap text at locations pointed by `WRAP_POINT`s. Converts `WRAP_POINT`s to either a space or newline character, thus wrapping the text. Already existing whitespace will be preserved as is. """ text, replacements = _prepare_wrap(text) if width == "no": return _recover_preserve_chars(text, replacements) wrapper = textwrap.TextWrapper( break_long_words=False, break_on_hyphens=False, width=width, expand_tabs=False, replace_whitespace=False, ) wrapped = wrapper.fill(text) wrapped = _recover_preserve_chars(wrapped, replacements) return " " + wrapped if text.startswith(" ") else wrapped def _prepare_wrap(text: str) -> tuple[str, str]: """Prepare text for wrap. Convert `WRAP_POINT`s to spaces. Convert whitespace to `PRESERVE_CHAR`s. Return a tuple with the prepared string, and another string consisting of replacement characters for `PRESERVE_CHAR`s. """ result = "" replacements = "" for c in text: if c == WRAP_POINT: if not result or result[-1] != " ": result += " " elif c in codepoints.UNICODE_WHITESPACE: result += PRESERVE_CHAR replacements += c else: result += c return result, replacements def _recover_preserve_chars(text: str, replacements: str) -> str: replacement_iterator = iter(replacements) return "".join( next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text ) def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901 inline_node = node.children[0] text = inline_node.render(context) if context.do_wrap: wrap_mode = context.options["mdformat"]["wrap"] if isinstance(wrap_mode, int): wrap_mode -= context.env["indent_width"] wrap_mode = max(1, wrap_mode) text = _wrap(text, width=wrap_mode) # A paragraph can start or end in whitespace e.g. if the whitespace was # in decimal representation form. We need to re-decimalify it, one reason being # to enable "empty" paragraphs with whitespace only. text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text) text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text) lines = text.split("\n") for i in range(len(lines)): # Strip whitespace to prevent issues like a line starting tab that is # interpreted as start of a code block. lines[i] = lines[i].strip() # If a line looks like an ATX heading, escape the first hash. if re.match(r"#{1,6}( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with ">" # (otherwise it will be interpreted as a block quote). if lines[i].startswith(">"): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with "*", "-" or "+" # followed by a space, tab, or end of line. # (otherwise it will be interpreted as list item). if re.match(r"[-*+]( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # If a line starts with a number followed by "." or ")" followed by # a space, tab or end of line, escape the "." or ")" or it will be # interpreted as ordered list item. if re.match(r"[0-9]+\)( |\t|$)", lines[i]): lines[i] = lines[i].replace(")", "\\)", 1) if re.match(r"[0-9]+\.( |\t|$)", lines[i]): lines[i] = lines[i].replace(".", "\\.", 1) # Consecutive "-", "*" or "_" sequences can be interpreted as thematic # break. Escape them. space_removed = lines[i].replace(" ", "").replace("\t", "") if len(space_removed) >= 3: if all(c == "*" for c in space_removed): lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover elif all(c == "-" for c in space_removed): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "_" for c in space_removed): lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover # A stripped line where all characters are "=" or "-" will be # interpreted as a setext heading. Escape. stripped = lines[i].strip(" \t") if all(c == "-" for c in stripped): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "=" for c in stripped): lines[i] = lines[i].replace("=", "\\=", 1) # Check if the line could be interpreted as an HTML block. # If yes, prefix it with 4 spaces to prevent this. for html_seq_tuple in HTML_SEQUENCES: can_break_paragraph = html_seq_tuple[2] opening_re = html_seq_tuple[0] if can_break_paragraph and opening_re.search(lines[i]): lines[i] = f" {lines[i]}" break text = "\n".join(lines) return text def list_item(node: RenderTreeNode, context: RenderContext) -> str: """Return one list item as string. This returns just the content. List item markers and indentation are added in `bullet_list` and `ordered_list` renderers. """ block_separator = "\n" if is_tight_list_item(node) else "\n\n" text = make_render_children(block_separator)(node, context) if not text.strip(): return "" return text def bullet_list(node: RenderTreeNode, context: RenderContext) -> str:
def ordered_list(node: RenderTreeNode, context: RenderContext) -> str: consecutive_numbering = context.options.get("mdformat", {}).get( "number", DEFAULT_OPTS["number"] ) marker_type = get_list_marker_type(node) first_line_indent = " " block_separator = "\n" if is_tight_list(node) else "\n\n" list_len = len(node.children) starting_number = node.attrs.get("start") if starting_number is None: starting_number = 1 assert isinstance(starting_number, int) if consecutive_numbering: indent_width = len( f"{list_len + starting_number - 1}{marker_type}{first_line_indent}" ) else: indent_width = len(f"{starting_number}{marker_type}{first_line_indent}") text = "" with context.indented(indent_width): for list_item_index, list_item in enumerate(node.children): list_item_text = list_item.render(context) formatted_lines = [] line_iterator = iter(list_item_text.split("\n")) first_line = next(line_iterator) if consecutive_numbering: # Prefix first line of the list item with consecutive numbering, # padded with zeros to make all markers of even length. # E.g. # 002. This is the first list item # 003. Second item # ... # 112. Last item number = starting_number + list_item_index pad = len(str(list_len + starting_number - 1)) number_str = str(number).rjust(pad, "0") formatted_lines.append( f"{number_str}{marker_type}{first_line_indent}{first_line}" if first_line else f"{number_str}{marker_type}" ) else: # Prefix first line of first item with the starting number of the # list. Prefix following list items with the number one # prefixed by zeros to make the list item marker of even length # with the first one. # E.g. # 5321. This is the first list item # 0001. Second item # 0001. Third item first_item_marker = f"{starting_number}{marker_type}" other_item_marker = ( "0" * (len(str(starting_number)) - 1) + "1" + marker_type ) if list_item_index == 0: formatted_lines.append( f"{first_item_marker}{first_line_indent}{first_line}" if first_line else first_item_marker ) else: formatted_lines.append( f"{other_item_marker}{first_line_indent}{first_line}" if first_line else other_item_marker ) for line in line_iterator: formatted_lines.append(" " * indent_width + line if line else "") text += "\n".join(formatted_lines) if list_item_index != len(node.children) - 1: text += block_separator return text DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType( { "inline": make_render_children(""), "root": make_render_children("\n\n"), "hr": hr, "code_inline": code_inline, "html_block": html_block, "html_inline": html_inline, "hardbreak": hardbreak, "softbreak": softbreak, "text": text, "fence": fence, "code_block": code_block, "link": link, "image": image, "em": em, "strong": strong, "heading": heading, "blockquote": blockquote, "paragraph": paragraph, "bullet_list": bullet_list, "ordered_list": ordered_list, "list_item": list_item, } ) class RenderContext(NamedTuple): """A collection of data that is passed as input to `Render` and `Postprocess` functions.""" renderers: Mapping[str, Render] postprocessors: Mapping[str, Iterable[Postprocess]] options: Mapping[str, Any] env: MutableMapping @contextmanager def indented(self, width: int) -> Generator[None, None, None]: self.env["indent_width"] += width try: yield finally: self.env["indent_width"] -= width @property def do_wrap(self) -> bool: wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"]) return isinstance(wrap_mode, int) or wrap_mode == "no" def with_default_renderer_for(self, *syntax_names: str) -> RenderContext: renderers = dict(self.renderers) for syntax in syntax_names: if syntax in DEFAULT_RENDERERS: renderers[syntax] = DEFAULT_RENDERERS[syntax] else: renderers.pop(syntax, None) return RenderContext( MappingProxyType(renderers), self.postprocessors, self.options, self.env )
marker_type = get_list_marker_type(node) first_line_indent = " " indent = " " * len(marker_type + first_line_indent) block_separator = "\n" if is_tight_list(node) else "\n\n" with context.indented(len(indent)): text = "" for child_idx, child in enumerate(node.children): list_item = child.render(context) formatted_lines = [] line_iterator = iter(list_item.split("\n")) first_line = next(line_iterator) formatted_lines.append( f"{marker_type}{first_line_indent}{first_line}" if first_line else marker_type ) for line in line_iterator: formatted_lines.append(f"{indent}{line}" if line else "") text += "\n".join(formatted_lines) if child_idx != len(node.children) - 1: text += block_separator return text
identifier_body
_context.py
from __future__ import annotations from collections import defaultdict from collections.abc import Generator, Iterable, Mapping, MutableMapping from contextlib import contextmanager import logging import re import textwrap from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple from markdown_it.rules_block.html_block import HTML_SEQUENCES from mdformat import codepoints from mdformat._compat import Literal from mdformat._conf import DEFAULT_OPTS from mdformat.renderer._util import ( RE_CHAR_REFERENCE, decimalify_leading, decimalify_trailing, escape_asterisk_emphasis, escape_underscore_emphasis, get_list_marker_type, is_tight_list, is_tight_list_item, longest_consecutive_sequence, maybe_add_link_brackets, ) from mdformat.renderer.typing import Postprocess, Render
if TYPE_CHECKING: from mdformat.renderer import RenderTreeNode LOGGER = logging.getLogger(__name__) # A marker used to point a location where word wrap is allowed # to occur. WRAP_POINT = "\x00" # A marker used to indicate location of a character that should be preserved # during word wrap. Should be converted to the actual character after wrap. PRESERVE_CHAR = "\x00" def make_render_children(separator: str) -> Render: def render_children( node: RenderTreeNode, context: RenderContext, ) -> str: return separator.join(child.render(context) for child in node.children) return render_children def hr(node: RenderTreeNode, context: RenderContext) -> str: thematic_break_width = 70 return "_" * thematic_break_width def code_inline(node: RenderTreeNode, context: RenderContext) -> str: code = node.content all_chars_are_whitespace = not code.strip() longest_backtick_seq = longest_consecutive_sequence(code, "`") if longest_backtick_seq: separator = "`" * (longest_backtick_seq + 1) return f"{separator} {code} {separator}" if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace: return f"` {code} `" return f"`{code}`" def html_block(node: RenderTreeNode, context: RenderContext) -> str: content = node.content.rstrip("\n") # Need to strip leading spaces because we do so for regular Markdown too. # Without the stripping the raw HTML and Markdown get unaligned and # semantic may change. content = content.lstrip() return content def html_inline(node: RenderTreeNode, context: RenderContext) -> str: return node.content def _in_block(block_name: str, node: RenderTreeNode) -> bool: while node.parent: if node.parent.type == block_name: return True node = node.parent return False def hardbreak(node: RenderTreeNode, context: RenderContext) -> str: if _in_block("heading", node): return "<br /> " return "\\" + "\n" def softbreak(node: RenderTreeNode, context: RenderContext) -> str: if context.do_wrap and _in_block("paragraph", node): return WRAP_POINT return "\n" def text(node: RenderTreeNode, context: RenderContext) -> str: """Process a text token. Text should always be a child of an inline token. An inline token should always be enclosed by a heading or a paragraph. """ text = node.content # Escape backslash to prevent it from making unintended escapes. # This escape has to be first, else we start multiplying backslashes. text = text.replace("\\", "\\\\") text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker. text = escape_underscore_emphasis(text) # Escape emphasis/strong marker. text = text.replace("[", "\\[") # Escape link label enclosure text = text.replace("]", "\\]") # Escape link label enclosure text = text.replace("<", "\\<") # Escape URI enclosure text = text.replace("`", "\\`") # Escape code span marker # Escape "&" if it starts a sequence that can be interpreted as # a character reference. text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text) # The parser can give us consecutive newlines which can break # the markdown structure. Replace two or more consecutive newlines # with newline character's decimal reference. text = text.replace("\n\n", "&#10;&#10;") # If the last character is a "!" and the token next up is a link, we # have to escape the "!" or else the link will be interpreted as image. next_sibling = node.next_sibling if text.endswith("!") and next_sibling and next_sibling.type == "link": text = text[:-1] + "\\!" if context.do_wrap and _in_block("paragraph", node): text = re.sub(r"\s+", WRAP_POINT, text) return text def fence(node: RenderTreeNode, context: RenderContext) -> str: info_str = node.info.strip() lang = info_str.split(maxsplit=1)[0] if info_str else "" code_block = node.content # Info strings of backtick code fences cannot contain backticks. # If that is the case, we make a tilde code fence instead. fence_char = "~" if "`" in info_str else "`" # Format the code block using enabled codeformatter funcs if lang in context.options.get("codeformatters", {}): fmt_func = context.options["codeformatters"][lang] try: code_block = fmt_func(code_block, info_str) except Exception: # Swallow exceptions so that formatter errors (e.g. due to # invalid code) do not crash mdformat. assert node.map is not None, "A fence token must have `map` attribute set" filename = context.options.get("mdformat", {}).get("filename", "") warn_msg = ( f"Failed formatting content of a {lang} code block " f"(line {node.map[0] + 1} before formatting)" ) if filename: warn_msg += f". Filename: {filename}" LOGGER.warning(warn_msg) # The code block must not include as long or longer sequence of `fence_char`s # as the fence string itself fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1) fence_str = fence_char * fence_len return f"{fence_str}{info_str}\n{code_block}{fence_str}" def code_block(node: RenderTreeNode, context: RenderContext) -> str: return fence(node, context) def image(node: RenderTreeNode, context: RenderContext) -> str: description = _render_inline_as_text(node, context) if context.do_wrap: # Prevent line breaks description = description.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if description.lower() == ref_label_repr: return f"![{description}]" return f"![{description}][{ref_label_repr}]" uri = node.attrs["src"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is not None: return f'![{description}]({uri} "{title}")' return f"![{description}]({uri})" def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str: """Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. """ def text_renderer(node: RenderTreeNode, context: RenderContext) -> str: return node.content def image_renderer(node: RenderTreeNode, context: RenderContext) -> str: return _render_inline_as_text(node, context) inline_renderers: Mapping[str, Render] = defaultdict( lambda: make_render_children(""), { "text": text_renderer, "image": image_renderer, "link": link, "softbreak": softbreak, }, ) inline_context = RenderContext( inline_renderers, context.postprocessors, context.options, context.env ) return make_render_children("")(node, inline_context) def link(node: RenderTreeNode, context: RenderContext) -> str: if node.info == "auto": autolink_url = node.attrs["href"] assert isinstance(autolink_url, str) # The parser adds a "mailto:" prefix to autolink email href. We remove the # prefix if it wasn't there in the source. if autolink_url.startswith("mailto:") and not node.children[ 0 ].content.startswith("mailto:"): autolink_url = autolink_url[7:] return "<" + autolink_url + ">" text = "".join(child.render(context) for child in node.children) if context.do_wrap: # Prevent line breaks text = text.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if text.lower() == ref_label_repr: return f"[{text}]" return f"[{text}][{ref_label_repr}]" uri = node.attrs["href"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is None: return f"[{text}]({uri})" assert isinstance(title, str) title = title.replace('"', '\\"') return f'[{text}]({uri} "{title}")' def em(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def strong(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def heading(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) if node.markup == "=": prefix = "# " elif node.markup == "-": prefix = "## " else: # ATX heading prefix = node.markup + " " # There can be newlines in setext headers, but we make an ATX # header always. Convert newlines to spaces. text = text.replace("\n", " ") # If the text ends in a sequence of hashes (#), the hashes will be # interpreted as an optional closing sequence of the heading, and # will not be rendered. Escape a line ending hash to prevent this. if text.endswith("#"): text = text[:-1] + "\\#" return prefix + text def blockquote(node: RenderTreeNode, context: RenderContext) -> str: marker = "> " with context.indented(len(marker)): text = make_render_children(separator="\n\n")(node, context) lines = text.splitlines() if not lines: return ">" quoted_lines = (f"{marker}{line}" if line else ">" for line in lines) quoted_str = "\n".join(quoted_lines) return quoted_str def _wrap(text: str, *, width: int | Literal["no"]) -> str: """Wrap text at locations pointed by `WRAP_POINT`s. Converts `WRAP_POINT`s to either a space or newline character, thus wrapping the text. Already existing whitespace will be preserved as is. """ text, replacements = _prepare_wrap(text) if width == "no": return _recover_preserve_chars(text, replacements) wrapper = textwrap.TextWrapper( break_long_words=False, break_on_hyphens=False, width=width, expand_tabs=False, replace_whitespace=False, ) wrapped = wrapper.fill(text) wrapped = _recover_preserve_chars(wrapped, replacements) return " " + wrapped if text.startswith(" ") else wrapped def _prepare_wrap(text: str) -> tuple[str, str]: """Prepare text for wrap. Convert `WRAP_POINT`s to spaces. Convert whitespace to `PRESERVE_CHAR`s. Return a tuple with the prepared string, and another string consisting of replacement characters for `PRESERVE_CHAR`s. """ result = "" replacements = "" for c in text: if c == WRAP_POINT: if not result or result[-1] != " ": result += " " elif c in codepoints.UNICODE_WHITESPACE: result += PRESERVE_CHAR replacements += c else: result += c return result, replacements def _recover_preserve_chars(text: str, replacements: str) -> str: replacement_iterator = iter(replacements) return "".join( next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text ) def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901 inline_node = node.children[0] text = inline_node.render(context) if context.do_wrap: wrap_mode = context.options["mdformat"]["wrap"] if isinstance(wrap_mode, int): wrap_mode -= context.env["indent_width"] wrap_mode = max(1, wrap_mode) text = _wrap(text, width=wrap_mode) # A paragraph can start or end in whitespace e.g. if the whitespace was # in decimal representation form. We need to re-decimalify it, one reason being # to enable "empty" paragraphs with whitespace only. text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text) text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text) lines = text.split("\n") for i in range(len(lines)): # Strip whitespace to prevent issues like a line starting tab that is # interpreted as start of a code block. lines[i] = lines[i].strip() # If a line looks like an ATX heading, escape the first hash. if re.match(r"#{1,6}( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with ">" # (otherwise it will be interpreted as a block quote). if lines[i].startswith(">"): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with "*", "-" or "+" # followed by a space, tab, or end of line. # (otherwise it will be interpreted as list item). if re.match(r"[-*+]( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # If a line starts with a number followed by "." or ")" followed by # a space, tab or end of line, escape the "." or ")" or it will be # interpreted as ordered list item. if re.match(r"[0-9]+\)( |\t|$)", lines[i]): lines[i] = lines[i].replace(")", "\\)", 1) if re.match(r"[0-9]+\.( |\t|$)", lines[i]): lines[i] = lines[i].replace(".", "\\.", 1) # Consecutive "-", "*" or "_" sequences can be interpreted as thematic # break. Escape them. space_removed = lines[i].replace(" ", "").replace("\t", "") if len(space_removed) >= 3: if all(c == "*" for c in space_removed): lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover elif all(c == "-" for c in space_removed): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "_" for c in space_removed): lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover # A stripped line where all characters are "=" or "-" will be # interpreted as a setext heading. Escape. stripped = lines[i].strip(" \t") if all(c == "-" for c in stripped): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "=" for c in stripped): lines[i] = lines[i].replace("=", "\\=", 1) # Check if the line could be interpreted as an HTML block. # If yes, prefix it with 4 spaces to prevent this. for html_seq_tuple in HTML_SEQUENCES: can_break_paragraph = html_seq_tuple[2] opening_re = html_seq_tuple[0] if can_break_paragraph and opening_re.search(lines[i]): lines[i] = f" {lines[i]}" break text = "\n".join(lines) return text def list_item(node: RenderTreeNode, context: RenderContext) -> str: """Return one list item as string. This returns just the content. List item markers and indentation are added in `bullet_list` and `ordered_list` renderers. """ block_separator = "\n" if is_tight_list_item(node) else "\n\n" text = make_render_children(block_separator)(node, context) if not text.strip(): return "" return text def bullet_list(node: RenderTreeNode, context: RenderContext) -> str: marker_type = get_list_marker_type(node) first_line_indent = " " indent = " " * len(marker_type + first_line_indent) block_separator = "\n" if is_tight_list(node) else "\n\n" with context.indented(len(indent)): text = "" for child_idx, child in enumerate(node.children): list_item = child.render(context) formatted_lines = [] line_iterator = iter(list_item.split("\n")) first_line = next(line_iterator) formatted_lines.append( f"{marker_type}{first_line_indent}{first_line}" if first_line else marker_type ) for line in line_iterator: formatted_lines.append(f"{indent}{line}" if line else "") text += "\n".join(formatted_lines) if child_idx != len(node.children) - 1: text += block_separator return text def ordered_list(node: RenderTreeNode, context: RenderContext) -> str: consecutive_numbering = context.options.get("mdformat", {}).get( "number", DEFAULT_OPTS["number"] ) marker_type = get_list_marker_type(node) first_line_indent = " " block_separator = "\n" if is_tight_list(node) else "\n\n" list_len = len(node.children) starting_number = node.attrs.get("start") if starting_number is None: starting_number = 1 assert isinstance(starting_number, int) if consecutive_numbering: indent_width = len( f"{list_len + starting_number - 1}{marker_type}{first_line_indent}" ) else: indent_width = len(f"{starting_number}{marker_type}{first_line_indent}") text = "" with context.indented(indent_width): for list_item_index, list_item in enumerate(node.children): list_item_text = list_item.render(context) formatted_lines = [] line_iterator = iter(list_item_text.split("\n")) first_line = next(line_iterator) if consecutive_numbering: # Prefix first line of the list item with consecutive numbering, # padded with zeros to make all markers of even length. # E.g. # 002. This is the first list item # 003. Second item # ... # 112. Last item number = starting_number + list_item_index pad = len(str(list_len + starting_number - 1)) number_str = str(number).rjust(pad, "0") formatted_lines.append( f"{number_str}{marker_type}{first_line_indent}{first_line}" if first_line else f"{number_str}{marker_type}" ) else: # Prefix first line of first item with the starting number of the # list. Prefix following list items with the number one # prefixed by zeros to make the list item marker of even length # with the first one. # E.g. # 5321. This is the first list item # 0001. Second item # 0001. Third item first_item_marker = f"{starting_number}{marker_type}" other_item_marker = ( "0" * (len(str(starting_number)) - 1) + "1" + marker_type ) if list_item_index == 0: formatted_lines.append( f"{first_item_marker}{first_line_indent}{first_line}" if first_line else first_item_marker ) else: formatted_lines.append( f"{other_item_marker}{first_line_indent}{first_line}" if first_line else other_item_marker ) for line in line_iterator: formatted_lines.append(" " * indent_width + line if line else "") text += "\n".join(formatted_lines) if list_item_index != len(node.children) - 1: text += block_separator return text DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType( { "inline": make_render_children(""), "root": make_render_children("\n\n"), "hr": hr, "code_inline": code_inline, "html_block": html_block, "html_inline": html_inline, "hardbreak": hardbreak, "softbreak": softbreak, "text": text, "fence": fence, "code_block": code_block, "link": link, "image": image, "em": em, "strong": strong, "heading": heading, "blockquote": blockquote, "paragraph": paragraph, "bullet_list": bullet_list, "ordered_list": ordered_list, "list_item": list_item, } ) class RenderContext(NamedTuple): """A collection of data that is passed as input to `Render` and `Postprocess` functions.""" renderers: Mapping[str, Render] postprocessors: Mapping[str, Iterable[Postprocess]] options: Mapping[str, Any] env: MutableMapping @contextmanager def indented(self, width: int) -> Generator[None, None, None]: self.env["indent_width"] += width try: yield finally: self.env["indent_width"] -= width @property def do_wrap(self) -> bool: wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"]) return isinstance(wrap_mode, int) or wrap_mode == "no" def with_default_renderer_for(self, *syntax_names: str) -> RenderContext: renderers = dict(self.renderers) for syntax in syntax_names: if syntax in DEFAULT_RENDERERS: renderers[syntax] = DEFAULT_RENDERERS[syntax] else: renderers.pop(syntax, None) return RenderContext( MappingProxyType(renderers), self.postprocessors, self.options, self.env )
random_line_split
_context.py
from __future__ import annotations from collections import defaultdict from collections.abc import Generator, Iterable, Mapping, MutableMapping from contextlib import contextmanager import logging import re import textwrap from types import MappingProxyType from typing import TYPE_CHECKING, Any, NamedTuple from markdown_it.rules_block.html_block import HTML_SEQUENCES from mdformat import codepoints from mdformat._compat import Literal from mdformat._conf import DEFAULT_OPTS from mdformat.renderer._util import ( RE_CHAR_REFERENCE, decimalify_leading, decimalify_trailing, escape_asterisk_emphasis, escape_underscore_emphasis, get_list_marker_type, is_tight_list, is_tight_list_item, longest_consecutive_sequence, maybe_add_link_brackets, ) from mdformat.renderer.typing import Postprocess, Render if TYPE_CHECKING: from mdformat.renderer import RenderTreeNode LOGGER = logging.getLogger(__name__) # A marker used to point a location where word wrap is allowed # to occur. WRAP_POINT = "\x00" # A marker used to indicate location of a character that should be preserved # during word wrap. Should be converted to the actual character after wrap. PRESERVE_CHAR = "\x00" def make_render_children(separator: str) -> Render: def render_children( node: RenderTreeNode, context: RenderContext, ) -> str: return separator.join(child.render(context) for child in node.children) return render_children def hr(node: RenderTreeNode, context: RenderContext) -> str: thematic_break_width = 70 return "_" * thematic_break_width def code_inline(node: RenderTreeNode, context: RenderContext) -> str: code = node.content all_chars_are_whitespace = not code.strip() longest_backtick_seq = longest_consecutive_sequence(code, "`") if longest_backtick_seq: separator = "`" * (longest_backtick_seq + 1) return f"{separator} {code} {separator}" if code.startswith(" ") and code.endswith(" ") and not all_chars_are_whitespace: return f"` {code} `" return f"`{code}`" def html_block(node: RenderTreeNode, context: RenderContext) -> str: content = node.content.rstrip("\n") # Need to strip leading spaces because we do so for regular Markdown too. # Without the stripping the raw HTML and Markdown get unaligned and # semantic may change. content = content.lstrip() return content def html_inline(node: RenderTreeNode, context: RenderContext) -> str: return node.content def _in_block(block_name: str, node: RenderTreeNode) -> bool: while node.parent: if node.parent.type == block_name: return True node = node.parent return False def hardbreak(node: RenderTreeNode, context: RenderContext) -> str: if _in_block("heading", node): return "<br /> " return "\\" + "\n" def softbreak(node: RenderTreeNode, context: RenderContext) -> str: if context.do_wrap and _in_block("paragraph", node): return WRAP_POINT return "\n" def text(node: RenderTreeNode, context: RenderContext) -> str: """Process a text token. Text should always be a child of an inline token. An inline token should always be enclosed by a heading or a paragraph. """ text = node.content # Escape backslash to prevent it from making unintended escapes. # This escape has to be first, else we start multiplying backslashes. text = text.replace("\\", "\\\\") text = escape_asterisk_emphasis(text) # Escape emphasis/strong marker. text = escape_underscore_emphasis(text) # Escape emphasis/strong marker. text = text.replace("[", "\\[") # Escape link label enclosure text = text.replace("]", "\\]") # Escape link label enclosure text = text.replace("<", "\\<") # Escape URI enclosure text = text.replace("`", "\\`") # Escape code span marker # Escape "&" if it starts a sequence that can be interpreted as # a character reference. text = RE_CHAR_REFERENCE.sub(r"\\\g<0>", text) # The parser can give us consecutive newlines which can break # the markdown structure. Replace two or more consecutive newlines # with newline character's decimal reference. text = text.replace("\n\n", "&#10;&#10;") # If the last character is a "!" and the token next up is a link, we # have to escape the "!" or else the link will be interpreted as image. next_sibling = node.next_sibling if text.endswith("!") and next_sibling and next_sibling.type == "link": text = text[:-1] + "\\!" if context.do_wrap and _in_block("paragraph", node): text = re.sub(r"\s+", WRAP_POINT, text) return text def fence(node: RenderTreeNode, context: RenderContext) -> str: info_str = node.info.strip() lang = info_str.split(maxsplit=1)[0] if info_str else "" code_block = node.content # Info strings of backtick code fences cannot contain backticks. # If that is the case, we make a tilde code fence instead. fence_char = "~" if "`" in info_str else "`" # Format the code block using enabled codeformatter funcs if lang in context.options.get("codeformatters", {}): fmt_func = context.options["codeformatters"][lang] try: code_block = fmt_func(code_block, info_str) except Exception: # Swallow exceptions so that formatter errors (e.g. due to # invalid code) do not crash mdformat. assert node.map is not None, "A fence token must have `map` attribute set" filename = context.options.get("mdformat", {}).get("filename", "") warn_msg = ( f"Failed formatting content of a {lang} code block " f"(line {node.map[0] + 1} before formatting)" ) if filename: warn_msg += f". Filename: {filename}" LOGGER.warning(warn_msg) # The code block must not include as long or longer sequence of `fence_char`s # as the fence string itself fence_len = max(3, longest_consecutive_sequence(code_block, fence_char) + 1) fence_str = fence_char * fence_len return f"{fence_str}{info_str}\n{code_block}{fence_str}" def code_block(node: RenderTreeNode, context: RenderContext) -> str: return fence(node, context) def image(node: RenderTreeNode, context: RenderContext) -> str: description = _render_inline_as_text(node, context) if context.do_wrap: # Prevent line breaks description = description.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if description.lower() == ref_label_repr: return f"![{description}]" return f"![{description}][{ref_label_repr}]" uri = node.attrs["src"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is not None: return f'![{description}]({uri} "{title}")' return f"![{description}]({uri})" def _render_inline_as_text(node: RenderTreeNode, context: RenderContext) -> str: """Special kludge for image `alt` attributes to conform CommonMark spec. Don't try to use it! Spec requires to show `alt` content with stripped markup, instead of simple escaping. """ def text_renderer(node: RenderTreeNode, context: RenderContext) -> str: return node.content def image_renderer(node: RenderTreeNode, context: RenderContext) -> str: return _render_inline_as_text(node, context) inline_renderers: Mapping[str, Render] = defaultdict( lambda: make_render_children(""), { "text": text_renderer, "image": image_renderer, "link": link, "softbreak": softbreak, }, ) inline_context = RenderContext( inline_renderers, context.postprocessors, context.options, context.env ) return make_render_children("")(node, inline_context) def link(node: RenderTreeNode, context: RenderContext) -> str: if node.info == "auto": autolink_url = node.attrs["href"] assert isinstance(autolink_url, str) # The parser adds a "mailto:" prefix to autolink email href. We remove the # prefix if it wasn't there in the source. if autolink_url.startswith("mailto:") and not node.children[ 0 ].content.startswith("mailto:"): autolink_url = autolink_url[7:] return "<" + autolink_url + ">" text = "".join(child.render(context) for child in node.children) if context.do_wrap: # Prevent line breaks text = text.replace(WRAP_POINT, " ") ref_label = node.meta.get("label") if ref_label: context.env["used_refs"].add(ref_label) ref_label_repr = ref_label.lower() if text.lower() == ref_label_repr: return f"[{text}]" return f"[{text}][{ref_label_repr}]" uri = node.attrs["href"] assert isinstance(uri, str) uri = maybe_add_link_brackets(uri) title = node.attrs.get("title") if title is None: return f"[{text}]({uri})" assert isinstance(title, str) title = title.replace('"', '\\"') return f'[{text}]({uri} "{title}")' def em(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def strong(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) indicator = node.markup return indicator + text + indicator def heading(node: RenderTreeNode, context: RenderContext) -> str: text = make_render_children(separator="")(node, context) if node.markup == "=": prefix = "# " elif node.markup == "-": prefix = "## " else: # ATX heading prefix = node.markup + " " # There can be newlines in setext headers, but we make an ATX # header always. Convert newlines to spaces. text = text.replace("\n", " ") # If the text ends in a sequence of hashes (#), the hashes will be # interpreted as an optional closing sequence of the heading, and # will not be rendered. Escape a line ending hash to prevent this. if text.endswith("#"): text = text[:-1] + "\\#" return prefix + text def blockquote(node: RenderTreeNode, context: RenderContext) -> str: marker = "> " with context.indented(len(marker)): text = make_render_children(separator="\n\n")(node, context) lines = text.splitlines() if not lines: return ">" quoted_lines = (f"{marker}{line}" if line else ">" for line in lines) quoted_str = "\n".join(quoted_lines) return quoted_str def _wrap(text: str, *, width: int | Literal["no"]) -> str: """Wrap text at locations pointed by `WRAP_POINT`s. Converts `WRAP_POINT`s to either a space or newline character, thus wrapping the text. Already existing whitespace will be preserved as is. """ text, replacements = _prepare_wrap(text) if width == "no": return _recover_preserve_chars(text, replacements) wrapper = textwrap.TextWrapper( break_long_words=False, break_on_hyphens=False, width=width, expand_tabs=False, replace_whitespace=False, ) wrapped = wrapper.fill(text) wrapped = _recover_preserve_chars(wrapped, replacements) return " " + wrapped if text.startswith(" ") else wrapped def _prepare_wrap(text: str) -> tuple[str, str]: """Prepare text for wrap. Convert `WRAP_POINT`s to spaces. Convert whitespace to `PRESERVE_CHAR`s. Return a tuple with the prepared string, and another string consisting of replacement characters for `PRESERVE_CHAR`s. """ result = "" replacements = "" for c in text: if c == WRAP_POINT: if not result or result[-1] != " ": result += " " elif c in codepoints.UNICODE_WHITESPACE: result += PRESERVE_CHAR replacements += c else: result += c return result, replacements def _recover_preserve_chars(text: str, replacements: str) -> str: replacement_iterator = iter(replacements) return "".join( next(replacement_iterator) if c == PRESERVE_CHAR else c for c in text ) def paragraph(node: RenderTreeNode, context: RenderContext) -> str: # noqa: C901 inline_node = node.children[0] text = inline_node.render(context) if context.do_wrap: wrap_mode = context.options["mdformat"]["wrap"] if isinstance(wrap_mode, int): wrap_mode -= context.env["indent_width"] wrap_mode = max(1, wrap_mode) text = _wrap(text, width=wrap_mode) # A paragraph can start or end in whitespace e.g. if the whitespace was # in decimal representation form. We need to re-decimalify it, one reason being # to enable "empty" paragraphs with whitespace only. text = decimalify_leading(codepoints.UNICODE_WHITESPACE, text) text = decimalify_trailing(codepoints.UNICODE_WHITESPACE, text) lines = text.split("\n") for i in range(len(lines)): # Strip whitespace to prevent issues like a line starting tab that is # interpreted as start of a code block. lines[i] = lines[i].strip() # If a line looks like an ATX heading, escape the first hash. if re.match(r"#{1,6}( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with ">" # (otherwise it will be interpreted as a block quote). if lines[i].startswith(">"): lines[i] = f"\\{lines[i]}" # Make sure a paragraph line does not start with "*", "-" or "+" # followed by a space, tab, or end of line. # (otherwise it will be interpreted as list item). if re.match(r"[-*+]( |\t|$)", lines[i]): lines[i] = f"\\{lines[i]}" # If a line starts with a number followed by "." or ")" followed by # a space, tab or end of line, escape the "." or ")" or it will be # interpreted as ordered list item. if re.match(r"[0-9]+\)( |\t|$)", lines[i]): lines[i] = lines[i].replace(")", "\\)", 1) if re.match(r"[0-9]+\.( |\t|$)", lines[i]): lines[i] = lines[i].replace(".", "\\.", 1) # Consecutive "-", "*" or "_" sequences can be interpreted as thematic # break. Escape them. space_removed = lines[i].replace(" ", "").replace("\t", "") if len(space_removed) >= 3: if all(c == "*" for c in space_removed): lines[i] = lines[i].replace("*", "\\*", 1) # pragma: no cover elif all(c == "-" for c in space_removed): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "_" for c in space_removed): lines[i] = lines[i].replace("_", "\\_", 1) # pragma: no cover # A stripped line where all characters are "=" or "-" will be # interpreted as a setext heading. Escape. stripped = lines[i].strip(" \t") if all(c == "-" for c in stripped): lines[i] = lines[i].replace("-", "\\-", 1) elif all(c == "=" for c in stripped): lines[i] = lines[i].replace("=", "\\=", 1) # Check if the line could be interpreted as an HTML block. # If yes, prefix it with 4 spaces to prevent this. for html_seq_tuple in HTML_SEQUENCES: can_break_paragraph = html_seq_tuple[2] opening_re = html_seq_tuple[0] if can_break_paragraph and opening_re.search(lines[i]): lines[i] = f" {lines[i]}" break text = "\n".join(lines) return text def list_item(node: RenderTreeNode, context: RenderContext) -> str: """Return one list item as string. This returns just the content. List item markers and indentation are added in `bullet_list` and `ordered_list` renderers. """ block_separator = "\n" if is_tight_list_item(node) else "\n\n" text = make_render_children(block_separator)(node, context) if not text.strip(): return "" return text def bullet_list(node: RenderTreeNode, context: RenderContext) -> str: marker_type = get_list_marker_type(node) first_line_indent = " " indent = " " * len(marker_type + first_line_indent) block_separator = "\n" if is_tight_list(node) else "\n\n" with context.indented(len(indent)): text = "" for child_idx, child in enumerate(node.children): list_item = child.render(context) formatted_lines = [] line_iterator = iter(list_item.split("\n")) first_line = next(line_iterator) formatted_lines.append( f"{marker_type}{first_line_indent}{first_line}" if first_line else marker_type ) for line in line_iterator: formatted_lines.append(f"{indent}{line}" if line else "") text += "\n".join(formatted_lines) if child_idx != len(node.children) - 1: text += block_separator return text def ordered_list(node: RenderTreeNode, context: RenderContext) -> str: consecutive_numbering = context.options.get("mdformat", {}).get( "number", DEFAULT_OPTS["number"] ) marker_type = get_list_marker_type(node) first_line_indent = " " block_separator = "\n" if is_tight_list(node) else "\n\n" list_len = len(node.children) starting_number = node.attrs.get("start") if starting_number is None: starting_number = 1 assert isinstance(starting_number, int) if consecutive_numbering: indent_width = len( f"{list_len + starting_number - 1}{marker_type}{first_line_indent}" ) else: indent_width = len(f"{starting_number}{marker_type}{first_line_indent}") text = "" with context.indented(indent_width): for list_item_index, list_item in enumerate(node.children): list_item_text = list_item.render(context) formatted_lines = [] line_iterator = iter(list_item_text.split("\n")) first_line = next(line_iterator) if consecutive_numbering: # Prefix first line of the list item with consecutive numbering, # padded with zeros to make all markers of even length. # E.g. # 002. This is the first list item # 003. Second item # ... # 112. Last item number = starting_number + list_item_index pad = len(str(list_len + starting_number - 1)) number_str = str(number).rjust(pad, "0") formatted_lines.append( f"{number_str}{marker_type}{first_line_indent}{first_line}" if first_line else f"{number_str}{marker_type}" ) else: # Prefix first line of first item with the starting number of the # list. Prefix following list items with the number one # prefixed by zeros to make the list item marker of even length # with the first one. # E.g. # 5321. This is the first list item # 0001. Second item # 0001. Third item first_item_marker = f"{starting_number}{marker_type}" other_item_marker = ( "0" * (len(str(starting_number)) - 1) + "1" + marker_type ) if list_item_index == 0: formatted_lines.append( f"{first_item_marker}{first_line_indent}{first_line}" if first_line else first_item_marker ) else: formatted_lines.append( f"{other_item_marker}{first_line_indent}{first_line}" if first_line else other_item_marker ) for line in line_iterator: formatted_lines.append(" " * indent_width + line if line else "") text += "\n".join(formatted_lines) if list_item_index != len(node.children) - 1: text += block_separator return text DEFAULT_RENDERERS: Mapping[str, Render] = MappingProxyType( { "inline": make_render_children(""), "root": make_render_children("\n\n"), "hr": hr, "code_inline": code_inline, "html_block": html_block, "html_inline": html_inline, "hardbreak": hardbreak, "softbreak": softbreak, "text": text, "fence": fence, "code_block": code_block, "link": link, "image": image, "em": em, "strong": strong, "heading": heading, "blockquote": blockquote, "paragraph": paragraph, "bullet_list": bullet_list, "ordered_list": ordered_list, "list_item": list_item, } ) class RenderContext(NamedTuple): """A collection of data that is passed as input to `Render` and `Postprocess` functions.""" renderers: Mapping[str, Render] postprocessors: Mapping[str, Iterable[Postprocess]] options: Mapping[str, Any] env: MutableMapping @contextmanager def indented(self, width: int) -> Generator[None, None, None]: self.env["indent_width"] += width try: yield finally: self.env["indent_width"] -= width @property def do_wrap(self) -> bool: wrap_mode = self.options.get("mdformat", {}).get("wrap", DEFAULT_OPTS["wrap"]) return isinstance(wrap_mode, int) or wrap_mode == "no" def with_default_renderer_for(self, *syntax_names: str) -> RenderContext: renderers = dict(self.renderers) for syntax in syntax_names: if syntax in DEFAULT_RENDERERS: renderers[syntax] = DEFAULT_RENDERERS[syntax] else:
return RenderContext( MappingProxyType(renderers), self.postprocessors, self.options, self.env )
renderers.pop(syntax, None)
conditional_block
stats.rs
use clap::ArgMatches; use chrono::Local; use serde_json; use serde::ser::{MapVisitor, Serialize, Serializer}; use ilc_base; use ilc_ops::stats::Stats; use Environment; use Cli; use error; struct StatFormat { version: String, master_hash: Option<String>, time: String, stats: Stats, } impl Serialize for StatFormat { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer
} pub fn output_as_json(args: &ArgMatches, cli: &Cli, stats: Stats) -> ilc_base::Result<()> { let e = Environment(args); // let count = value_t!(args, "count", usize).unwrap_or(usize::MAX); // let mut stats: Vec<(String, Person)> = stats.into_iter().collect(); // stats.sort_by(|&(_, ref a), &(_, ref b)| b.words.cmp(&a.words)); // for &(ref name, ref stat) in stats.iter().take(count) { let format = StatFormat { version: cli.version.clone(), master_hash: cli.master_hash.clone(), time: Local::now().to_rfc2822(), stats: stats, }; serde_json::to_writer_pretty(&mut e.output(), &format).unwrap_or_else(|e| error(Box::new(e))); /* write!(&mut *e.output(), * "{}:\n\tTotal lines: {}\n\tLines without alphabetic characters: {}\n\tTotal \ * words: {}\n\tWords per line: {}\n", * name, * stat.lines, * stat.lines - stat.alpha_lines, * stat.words, * stat.words as f32 / stat.lines as f32) * .unwrap_or_else(|e| error(Box::new(e))); */ // } Ok(()) }
{ struct Visitor<'a>(&'a StatFormat); impl<'a> MapVisitor for Visitor<'a> { fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error> where S: Serializer { try!(s.serialize_struct_elt("version", &self.0.version)); if let &Some(ref h) = &self.0.master_hash { try!(s.serialize_struct_elt("master_hash", h)); } try!(s.serialize_struct_elt("time", &self.0.time)); try!(s.serialize_struct_elt("stats", &self.0.stats)); Ok(None) } fn len(&self) -> Option<usize> { Some(4) } } s.serialize_struct("StatFormat", Visitor(self)) }
identifier_body
stats.rs
use clap::ArgMatches; use chrono::Local; use serde_json; use serde::ser::{MapVisitor, Serialize, Serializer}; use ilc_base; use ilc_ops::stats::Stats; use Environment; use Cli; use error; struct StatFormat { version: String, master_hash: Option<String>, time: String, stats: Stats, } impl Serialize for StatFormat { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer { struct Visitor<'a>(&'a StatFormat); impl<'a> MapVisitor for Visitor<'a> { fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error> where S: Serializer { try!(s.serialize_struct_elt("version", &self.0.version)); if let &Some(ref h) = &self.0.master_hash
try!(s.serialize_struct_elt("time", &self.0.time)); try!(s.serialize_struct_elt("stats", &self.0.stats)); Ok(None) } fn len(&self) -> Option<usize> { Some(4) } } s.serialize_struct("StatFormat", Visitor(self)) } } pub fn output_as_json(args: &ArgMatches, cli: &Cli, stats: Stats) -> ilc_base::Result<()> { let e = Environment(args); // let count = value_t!(args, "count", usize).unwrap_or(usize::MAX); // let mut stats: Vec<(String, Person)> = stats.into_iter().collect(); // stats.sort_by(|&(_, ref a), &(_, ref b)| b.words.cmp(&a.words)); // for &(ref name, ref stat) in stats.iter().take(count) { let format = StatFormat { version: cli.version.clone(), master_hash: cli.master_hash.clone(), time: Local::now().to_rfc2822(), stats: stats, }; serde_json::to_writer_pretty(&mut e.output(), &format).unwrap_or_else(|e| error(Box::new(e))); /* write!(&mut *e.output(), * "{}:\n\tTotal lines: {}\n\tLines without alphabetic characters: {}\n\tTotal \ * words: {}\n\tWords per line: {}\n", * name, * stat.lines, * stat.lines - stat.alpha_lines, * stat.words, * stat.words as f32 / stat.lines as f32) * .unwrap_or_else(|e| error(Box::new(e))); */ // } Ok(()) }
{ try!(s.serialize_struct_elt("master_hash", h)); }
conditional_block
stats.rs
use clap::ArgMatches; use chrono::Local; use serde_json; use serde::ser::{MapVisitor, Serialize, Serializer}; use ilc_base; use ilc_ops::stats::Stats; use Environment; use Cli; use error; struct StatFormat { version: String, master_hash: Option<String>, time: String, stats: Stats, } impl Serialize for StatFormat { fn
<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer { struct Visitor<'a>(&'a StatFormat); impl<'a> MapVisitor for Visitor<'a> { fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error> where S: Serializer { try!(s.serialize_struct_elt("version", &self.0.version)); if let &Some(ref h) = &self.0.master_hash { try!(s.serialize_struct_elt("master_hash", h)); } try!(s.serialize_struct_elt("time", &self.0.time)); try!(s.serialize_struct_elt("stats", &self.0.stats)); Ok(None) } fn len(&self) -> Option<usize> { Some(4) } } s.serialize_struct("StatFormat", Visitor(self)) } } pub fn output_as_json(args: &ArgMatches, cli: &Cli, stats: Stats) -> ilc_base::Result<()> { let e = Environment(args); // let count = value_t!(args, "count", usize).unwrap_or(usize::MAX); // let mut stats: Vec<(String, Person)> = stats.into_iter().collect(); // stats.sort_by(|&(_, ref a), &(_, ref b)| b.words.cmp(&a.words)); // for &(ref name, ref stat) in stats.iter().take(count) { let format = StatFormat { version: cli.version.clone(), master_hash: cli.master_hash.clone(), time: Local::now().to_rfc2822(), stats: stats, }; serde_json::to_writer_pretty(&mut e.output(), &format).unwrap_or_else(|e| error(Box::new(e))); /* write!(&mut *e.output(), * "{}:\n\tTotal lines: {}\n\tLines without alphabetic characters: {}\n\tTotal \ * words: {}\n\tWords per line: {}\n", * name, * stat.lines, * stat.lines - stat.alpha_lines, * stat.words, * stat.words as f32 / stat.lines as f32) * .unwrap_or_else(|e| error(Box::new(e))); */ // } Ok(()) }
serialize
identifier_name
stats.rs
use clap::ArgMatches;
use serde_json; use serde::ser::{MapVisitor, Serialize, Serializer}; use ilc_base; use ilc_ops::stats::Stats; use Environment; use Cli; use error; struct StatFormat { version: String, master_hash: Option<String>, time: String, stats: Stats, } impl Serialize for StatFormat { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer { struct Visitor<'a>(&'a StatFormat); impl<'a> MapVisitor for Visitor<'a> { fn visit<S>(&mut self, s: &mut S) -> Result<Option<()>, S::Error> where S: Serializer { try!(s.serialize_struct_elt("version", &self.0.version)); if let &Some(ref h) = &self.0.master_hash { try!(s.serialize_struct_elt("master_hash", h)); } try!(s.serialize_struct_elt("time", &self.0.time)); try!(s.serialize_struct_elt("stats", &self.0.stats)); Ok(None) } fn len(&self) -> Option<usize> { Some(4) } } s.serialize_struct("StatFormat", Visitor(self)) } } pub fn output_as_json(args: &ArgMatches, cli: &Cli, stats: Stats) -> ilc_base::Result<()> { let e = Environment(args); // let count = value_t!(args, "count", usize).unwrap_or(usize::MAX); // let mut stats: Vec<(String, Person)> = stats.into_iter().collect(); // stats.sort_by(|&(_, ref a), &(_, ref b)| b.words.cmp(&a.words)); // for &(ref name, ref stat) in stats.iter().take(count) { let format = StatFormat { version: cli.version.clone(), master_hash: cli.master_hash.clone(), time: Local::now().to_rfc2822(), stats: stats, }; serde_json::to_writer_pretty(&mut e.output(), &format).unwrap_or_else(|e| error(Box::new(e))); /* write!(&mut *e.output(), * "{}:\n\tTotal lines: {}\n\tLines without alphabetic characters: {}\n\tTotal \ * words: {}\n\tWords per line: {}\n", * name, * stat.lines, * stat.lines - stat.alpha_lines, * stat.words, * stat.words as f32 / stat.lines as f32) * .unwrap_or_else(|e| error(Box::new(e))); */ // } Ok(()) }
use chrono::Local;
random_line_split
herald-vote.js
jQuery(document).ready(function($) { $('#addmoreitem').click(function() { var lastid = $('.uploadevent').last().attr('id'); for(var i = 1; i < 5; i++)
r({ format: "yyyy-mm-dd" }); $('#vote_type1').click(function(){ $('#vote_limit_number_div').remove(); }); $('#vote_type2').click(function(){ var divnum = $('#vote_limit_number_div'); if(!divnum.length){ var addHtml = '<div class="form-group" id="vote_limit_number_div"><br><label for="vote-topic">限投票数:</label><input type="text" name="vote_limit_number" class="form-control" placeholder="限投票数"></div>'; $('#vote_num_more').append(addHtml); } }); $('.vote-item-more-info').click(function() { alert('ss'); }); }); $(document).ready(function(){ $("#votepostuploader").uploadFile({ url:"/herald_vote/index.php/Admin/Index/addVotePost/", allowedTypes:"jpg,png,gif,jpeg,mp4", fileName:"vote_post", showAbort:true, uploadButtonClass:"btn btn-success", onSuccess:function(files,data,xhr){ var uploadid = $('#uploadid').val(); var inputid = '#vote_item_attach_'+uploadid; var btnid = '#'+uploadid; $(inputid).val(data); $(btnid).html('添加成功').removeClass('btn-info').removeAttr('data-target').addClass('btn-success').attr('disabled', 'disabled');; } }); $('#vote_post_name').click(function() { $('#uploadid').val(0); }); $('body').on('click','.uploadevent', function() { var upid = $(this).attr('id'); $('#uploadid').val(upid); }); // $('.uploadevent').click(function() { // var upid = $(this).attr('id'); // $('#uploadid').val(upid); // }); $('.delete_vote').click(function() { var delid = $(this).attr('id'); $.ajax({ url: '/herald_vote/index.php/Admin/Index/deleteVote/', type: 'post', data: {'vote_id': delid}, success:function(data){ $('#vote_info_tr_'+delid).hide("slow"); }, }) }); });
{ var addId = Number(lastid)+Number(i); var addHtml = '<div class="panel-group" id="accordion"><div class="panel panel-default"><div class="panel-heading"><div class="input-group"><input type="text" name="vote_item_name['+addId+']" class="form-control" placeholder="选项'+addId+'"><div class="input-group-btn"><a type="button" class="btn btn-default uploadevent" data-toggle="collapse" data-parent="#accordion" href="#add_info_'+addId+'">添加详情</a></div></div></div><div id="add_info_'+addId+'" class="panel-collapse collapse"><div class="panel-body"><input type="hidden" name="vote_item_attach['+addId+']" id="vote_item_attach_'+addId+'"><button type="button" class="btn btn-info uploadevent" tabindex="-1" data-toggle="modal" data-target="#model_upload" id="'+addId+'">上传附件</button><br><br><textarea class="form-control" rows="2" name="vote_item_description['+addId+']" placeholder="选项描述"></textarea></div></div></div></div>'; $('#vote-item').append(addHtml); if(addId == 20){ $('#addmoreitem').css({ display: 'none' }); } } }); $('.date').datepicke
conditional_block
description.ts
// (C) Copyright 2015 Martin Dougiamas // // 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, OnInit, Injector } from '@angular/core'; import { CoreLoggerProvider } from '@providers/logger'; import { CoreQuestionBaseComponent } from '@core/question/classes/base-question-component'; /** * Component to render a description question. */ @Component({ selector: 'addon-qtype-description', templateUrl: 'addon-qtype-description.html' }) export class AddonQtypeDescriptionComponent extends CoreQuestionBaseComponent implements OnInit { constructor(logger: CoreLoggerProvider, injector: Injector) { super(logger, 'AddonQtypeDescriptionComponent', injector); } /** * Component being initialized. */ ngOnInit(): void { const questionEl = this.initComponent(); if (questionEl) { // Get the "seen" hidden input. const input = <HTMLInputElement> questionEl.querySelector('input[type="hidden"][name*=seen]'); if (input)
} } }
{ this.question.seenInput = { name: input.name, value: input.value }; }
conditional_block
description.ts
// (C) Copyright 2015 Martin Dougiamas // // 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.
import { Component, OnInit, Injector } from '@angular/core'; import { CoreLoggerProvider } from '@providers/logger'; import { CoreQuestionBaseComponent } from '@core/question/classes/base-question-component'; /** * Component to render a description question. */ @Component({ selector: 'addon-qtype-description', templateUrl: 'addon-qtype-description.html' }) export class AddonQtypeDescriptionComponent extends CoreQuestionBaseComponent implements OnInit { constructor(logger: CoreLoggerProvider, injector: Injector) { super(logger, 'AddonQtypeDescriptionComponent', injector); } /** * Component being initialized. */ ngOnInit(): void { const questionEl = this.initComponent(); if (questionEl) { // Get the "seen" hidden input. const input = <HTMLInputElement> questionEl.querySelector('input[type="hidden"][name*=seen]'); if (input) { this.question.seenInput = { name: input.name, value: input.value }; } } } }
// See the License for the specific language governing permissions and // limitations under the License.
random_line_split
description.ts
// (C) Copyright 2015 Martin Dougiamas // // 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, OnInit, Injector } from '@angular/core'; import { CoreLoggerProvider } from '@providers/logger'; import { CoreQuestionBaseComponent } from '@core/question/classes/base-question-component'; /** * Component to render a description question. */ @Component({ selector: 'addon-qtype-description', templateUrl: 'addon-qtype-description.html' }) export class AddonQtypeDescriptionComponent extends CoreQuestionBaseComponent implements OnInit { constructor(logger: CoreLoggerProvider, injector: Injector) { super(logger, 'AddonQtypeDescriptionComponent', injector); } /** * Component being initialized. */
(): void { const questionEl = this.initComponent(); if (questionEl) { // Get the "seen" hidden input. const input = <HTMLInputElement> questionEl.querySelector('input[type="hidden"][name*=seen]'); if (input) { this.question.seenInput = { name: input.name, value: input.value }; } } } }
ngOnInit
identifier_name
WorksForSaleRail.tsx
import { ContextModule } from "@artsy/cohesion" import { WorksForSaleRail_artist } from "v2/__generated__/WorksForSaleRail_artist.graphql" import { WorksForSaleRailRendererQuery } from "v2/__generated__/WorksForSaleRailRendererQuery.graphql" import { SystemContext } from "v2/Artsy" import { track } from "v2/Artsy/Analytics" import * as Schema from "v2/Artsy/Analytics/Schema" import { renderWithLoadProgress } from "v2/Artsy/Relay/renderWithLoadProgress" import { SystemQueryRenderer } from "v2/Artsy/Relay/SystemQueryRenderer" import FillwidthItem from "v2/Components/Artwork/FillwidthItem" import { Carousel } from "v2/Components/Carousel" import React, { useContext } from "react" import { createFragmentContainer, graphql } from "react-relay" import { get } from "v2/Utils/get" interface WorksForSaleRailProps { artist: WorksForSaleRail_artist } const HEIGHT = 150 const WorksForSaleRail: React.FC< WorksForSaleRailProps & { onArtworkClicked: () => void } > = ({ artist, onArtworkClicked }) => { const { user, mediator } = useContext(SystemContext) const artistData = get(artist, a => a.artworksConnection.edges, []) return ( <Carousel data-test={ContextModule.worksForSaleRail} arrowHeight={HEIGHT}> {artistData.map(artwork => { return ( <FillwidthItem key={artwork.node.id} artwork={artwork.node} contextModule={ContextModule.worksForSaleRail} imageHeight={HEIGHT} user={user} mediator={mediator} onClick={onArtworkClicked} lazyLoad /> ) })} </Carousel> ) } @track({ context_module: Schema.ContextModule.WorksForSale, }) class WorksForSaleRailWithTracking extends React.Component< WorksForSaleRailProps > { @track({ type: Schema.Type.Thumbnail, action_type: Schema.ActionType.Click, }) trackArtworkClicked()
render() { return ( <WorksForSaleRail {...this.props} onArtworkClicked={this.trackArtworkClicked.bind(this)} /> ) } } export const WorksForSaleRailFragmentContainer = createFragmentContainer( WorksForSaleRailWithTracking, { artist: graphql` fragment WorksForSaleRail_artist on Artist { artworksConnection(first: 20, sort: AVAILABILITY_ASC) { edges { node { id ...FillwidthItem_artwork } } } ...FollowArtistButton_artist } `, } ) export const WorksForSaleRailQueryRenderer: React.FC<{ artistID: string }> = ({ artistID }) => { const { relayEnvironment } = useContext(SystemContext) return ( <SystemQueryRenderer<WorksForSaleRailRendererQuery> environment={relayEnvironment} query={graphql` query WorksForSaleRailRendererQuery($artistID: String!) { artist(id: $artistID) { ...WorksForSaleRail_artist } } `} variables={{ artistID }} render={renderWithLoadProgress(WorksForSaleRailFragmentContainer)} /> ) }
{ // noop }
identifier_body
WorksForSaleRail.tsx
import { ContextModule } from "@artsy/cohesion" import { WorksForSaleRail_artist } from "v2/__generated__/WorksForSaleRail_artist.graphql" import { WorksForSaleRailRendererQuery } from "v2/__generated__/WorksForSaleRailRendererQuery.graphql" import { SystemContext } from "v2/Artsy" import { track } from "v2/Artsy/Analytics" import * as Schema from "v2/Artsy/Analytics/Schema" import { renderWithLoadProgress } from "v2/Artsy/Relay/renderWithLoadProgress" import { SystemQueryRenderer } from "v2/Artsy/Relay/SystemQueryRenderer" import FillwidthItem from "v2/Components/Artwork/FillwidthItem" import { Carousel } from "v2/Components/Carousel" import React, { useContext } from "react" import { createFragmentContainer, graphql } from "react-relay" import { get } from "v2/Utils/get" interface WorksForSaleRailProps { artist: WorksForSaleRail_artist } const HEIGHT = 150 const WorksForSaleRail: React.FC< WorksForSaleRailProps & { onArtworkClicked: () => void } > = ({ artist, onArtworkClicked }) => { const { user, mediator } = useContext(SystemContext) const artistData = get(artist, a => a.artworksConnection.edges, []) return ( <Carousel data-test={ContextModule.worksForSaleRail} arrowHeight={HEIGHT}> {artistData.map(artwork => { return ( <FillwidthItem key={artwork.node.id} artwork={artwork.node} contextModule={ContextModule.worksForSaleRail} imageHeight={HEIGHT} user={user} mediator={mediator} onClick={onArtworkClicked} lazyLoad /> ) })} </Carousel> ) } @track({ context_module: Schema.ContextModule.WorksForSale, }) class WorksForSaleRailWithTracking extends React.Component< WorksForSaleRailProps > { @track({ type: Schema.Type.Thumbnail, action_type: Schema.ActionType.Click, }) trackArtworkClicked() { // noop }
() { return ( <WorksForSaleRail {...this.props} onArtworkClicked={this.trackArtworkClicked.bind(this)} /> ) } } export const WorksForSaleRailFragmentContainer = createFragmentContainer( WorksForSaleRailWithTracking, { artist: graphql` fragment WorksForSaleRail_artist on Artist { artworksConnection(first: 20, sort: AVAILABILITY_ASC) { edges { node { id ...FillwidthItem_artwork } } } ...FollowArtistButton_artist } `, } ) export const WorksForSaleRailQueryRenderer: React.FC<{ artistID: string }> = ({ artistID }) => { const { relayEnvironment } = useContext(SystemContext) return ( <SystemQueryRenderer<WorksForSaleRailRendererQuery> environment={relayEnvironment} query={graphql` query WorksForSaleRailRendererQuery($artistID: String!) { artist(id: $artistID) { ...WorksForSaleRail_artist } } `} variables={{ artistID }} render={renderWithLoadProgress(WorksForSaleRailFragmentContainer)} /> ) }
render
identifier_name
WorksForSaleRail.tsx
import { ContextModule } from "@artsy/cohesion" import { WorksForSaleRail_artist } from "v2/__generated__/WorksForSaleRail_artist.graphql" import { WorksForSaleRailRendererQuery } from "v2/__generated__/WorksForSaleRailRendererQuery.graphql" import { SystemContext } from "v2/Artsy" import { track } from "v2/Artsy/Analytics" import * as Schema from "v2/Artsy/Analytics/Schema" import { renderWithLoadProgress } from "v2/Artsy/Relay/renderWithLoadProgress" import { SystemQueryRenderer } from "v2/Artsy/Relay/SystemQueryRenderer" import FillwidthItem from "v2/Components/Artwork/FillwidthItem" import { Carousel } from "v2/Components/Carousel" import React, { useContext } from "react" import { createFragmentContainer, graphql } from "react-relay" import { get } from "v2/Utils/get" interface WorksForSaleRailProps { artist: WorksForSaleRail_artist } const HEIGHT = 150 const WorksForSaleRail: React.FC< WorksForSaleRailProps & { onArtworkClicked: () => void } > = ({ artist, onArtworkClicked }) => { const { user, mediator } = useContext(SystemContext) const artistData = get(artist, a => a.artworksConnection.edges, []) return ( <Carousel data-test={ContextModule.worksForSaleRail} arrowHeight={HEIGHT}> {artistData.map(artwork => { return ( <FillwidthItem key={artwork.node.id} artwork={artwork.node} contextModule={ContextModule.worksForSaleRail} imageHeight={HEIGHT} user={user} mediator={mediator} onClick={onArtworkClicked} lazyLoad /> ) })} </Carousel> ) } @track({ context_module: Schema.ContextModule.WorksForSale, }) class WorksForSaleRailWithTracking extends React.Component< WorksForSaleRailProps > { @track({ type: Schema.Type.Thumbnail, action_type: Schema.ActionType.Click, }) trackArtworkClicked() { // noop }
{...this.props} onArtworkClicked={this.trackArtworkClicked.bind(this)} /> ) } } export const WorksForSaleRailFragmentContainer = createFragmentContainer( WorksForSaleRailWithTracking, { artist: graphql` fragment WorksForSaleRail_artist on Artist { artworksConnection(first: 20, sort: AVAILABILITY_ASC) { edges { node { id ...FillwidthItem_artwork } } } ...FollowArtistButton_artist } `, } ) export const WorksForSaleRailQueryRenderer: React.FC<{ artistID: string }> = ({ artistID }) => { const { relayEnvironment } = useContext(SystemContext) return ( <SystemQueryRenderer<WorksForSaleRailRendererQuery> environment={relayEnvironment} query={graphql` query WorksForSaleRailRendererQuery($artistID: String!) { artist(id: $artistID) { ...WorksForSaleRail_artist } } `} variables={{ artistID }} render={renderWithLoadProgress(WorksForSaleRailFragmentContainer)} /> ) }
render() { return ( <WorksForSaleRail
random_line_split
ng_style.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core'; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * <some-element [ngStyle]="objExp">...</some-element> * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.<unit>` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ @Directive({selector: '[ngStyle]'}) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string}|null = null; private _differ: KeyValueDiffer<string, string|number>|null = null; constructor( private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2) {} @Input('ngStyle') set ngStyle(values: {[klass: string]: any}|null) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle!); if (changes)
} } private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void { const [name, unit] = nameAndUnit.split('.'); value = value != null && unit ? `${value}${unit}` : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value as string); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } } private _applyChanges(changes: KeyValueChanges<string, string|number>): void { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } }
{ this._applyChanges(changes); }
conditional_block
ng_style.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core'; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * <some-element [ngStyle]="objExp">...</some-element> * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.<unit>` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ @Directive({selector: '[ngStyle]'}) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string}|null = null; private _differ: KeyValueDiffer<string, string|number>|null = null; constructor( private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2) {} @Input('ngStyle') set
(values: {[klass: string]: any}|null) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle!); if (changes) { this._applyChanges(changes); } } } private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void { const [name, unit] = nameAndUnit.split('.'); value = value != null && unit ? `${value}${unit}` : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value as string); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } } private _applyChanges(changes: KeyValueChanges<string, string|number>): void { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } }
ngStyle
identifier_name
ng_style.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core'; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * <some-element [ngStyle]="objExp">...</some-element> * ``` * * @description *
* The key is a style name, with an optional `.<unit>` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ @Directive({selector: '[ngStyle]'}) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string}|null = null; private _differ: KeyValueDiffer<string, string|number>|null = null; constructor( private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2) {} @Input('ngStyle') set ngStyle(values: {[klass: string]: any}|null) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle!); if (changes) { this._applyChanges(changes); } } } private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void { const [name, unit] = nameAndUnit.split('.'); value = value != null && unit ? `${value}${unit}` : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value as string); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } } private _applyChanges(changes: KeyValueChanges<string, string|number>): void { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } }
* An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs.
random_line_split
ng_style.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core'; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * <some-element [ngStyle]="objExp">...</some-element> * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.<unit>` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ @Directive({selector: '[ngStyle]'}) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string}|null = null; private _differ: KeyValueDiffer<string, string|number>|null = null; constructor( private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2)
@Input('ngStyle') set ngStyle(values: {[klass: string]: any}|null) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle!); if (changes) { this._applyChanges(changes); } } } private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void { const [name, unit] = nameAndUnit.split('.'); value = value != null && unit ? `${value}${unit}` : value; if (value != null) { this._renderer.setStyle(this._ngEl.nativeElement, name, value as string); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name); } } private _applyChanges(changes: KeyValueChanges<string, string|number>): void { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } }
{}
identifier_body
GreekItalic.js
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/STIX/General/Italic/GreekItalic.js * * Copyright (c) 2009-2013 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-italic'], { 0x1D6E2: [667,0,717,35,685], // MATHEMATICAL ITALIC CAPITAL ALPHA 0x1D6E3: [653,0,696,38,686], // MATHEMATICAL ITALIC CAPITAL BETA 0x1D6E4: [653,0,616,38,721], // MATHEMATICAL ITALIC CAPITAL GAMMA 0x1D6E5: [667,0,596,30,556], // MATHEMATICAL ITALIC CAPITAL DELTA 0x1D6E6: [653,0,714,38,734], // MATHEMATICAL ITALIC CAPITAL EPSILON 0x1D6E7: [653,0,772,60,802], // MATHEMATICAL ITALIC CAPITAL ZETA 0x1D6E8: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL ETA 0x1D6E9: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA 0x1D6EA: [653,0,480,38,530], // MATHEMATICAL ITALIC CAPITAL IOTA 0x1D6EB: [653,0,762,38,802], // MATHEMATICAL ITALIC CAPITAL KAPPA
0x1D6EC: [667,0,718,35,686], // MATHEMATICAL ITALIC CAPITAL LAMDA 0x1D6ED: [653,0,1005,38,1055], // MATHEMATICAL ITALIC CAPITAL MU 0x1D6EE: [653,0,851,38,901], // MATHEMATICAL ITALIC CAPITAL NU 0x1D6EF: [653,0,706,52,741], // MATHEMATICAL ITALIC CAPITAL XI 0x1D6F0: [669,11,732,50,712], // MATHEMATICAL ITALIC CAPITAL OMICRON 0x1D6F1: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL PI 0x1D6F2: [653,0,594,38,704], // MATHEMATICAL ITALIC CAPITAL RHO 0x1D6F3: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA SYMBOL 0x1D6F4: [653,0,735,58,760], // MATHEMATICAL ITALIC CAPITAL SIGMA 0x1D6F5: [653,0,550,25,670], // MATHEMATICAL ITALIC CAPITAL TAU 0x1D6F6: [668,0,613,28,743], // MATHEMATICAL ITALIC CAPITAL UPSILON 0x1D6F7: [653,0,772,25,747], // MATHEMATICAL ITALIC CAPITAL PHI 0x1D6F8: [653,0,790,25,810], // MATHEMATICAL ITALIC CAPITAL CHI 0x1D6F9: [667,0,670,28,743], // MATHEMATICAL ITALIC CAPITAL PSI 0x1D6FA: [666,0,800,32,777], // MATHEMATICAL ITALIC CAPITAL OMEGA 0x1D6FB: [653,15,627,42,600], // MATHEMATICAL ITALIC NABLA 0x1D6FC: [441,10,524,40,529], // MATHEMATICAL ITALIC SMALL ALPHA 0x1D6FD: [668,183,493,25,518], // MATHEMATICAL ITALIC SMALL BETA 0x1D6FE: [441,187,428,35,458], // MATHEMATICAL ITALIC SMALL GAMMA 0x1D6FF: [668,11,463,40,451], // MATHEMATICAL ITALIC SMALL DELTA 0x1D700: [441,11,484,25,444], // MATHEMATICAL ITALIC SMALL EPSILON 0x1D701: [668,183,435,40,480], // MATHEMATICAL ITALIC SMALL ZETA 0x1D702: [441,183,460,30,455], // MATHEMATICAL ITALIC SMALL ETA 0x1D703: [668,11,484,40,474], // MATHEMATICAL ITALIC SMALL THETA 0x1D704: [441,11,267,50,227], // MATHEMATICAL ITALIC SMALL IOTA 0x1D705: [441,0,534,50,549], // MATHEMATICAL ITALIC SMALL KAPPA 0x1D706: [668,16,541,50,511], // MATHEMATICAL ITALIC SMALL LAMDA 0x1D707: [428,183,579,30,549], // MATHEMATICAL ITALIC SMALL MU 0x1D708: [446,9,452,50,462], // MATHEMATICAL ITALIC SMALL NU 0x1D709: [668,183,433,25,443], // MATHEMATICAL ITALIC SMALL XI 0x1D70A: [441,11,458,40,438], // MATHEMATICAL ITALIC SMALL OMICRON 0x1D70B: [428,13,558,35,568], // MATHEMATICAL ITALIC SMALL PI 0x1D70C: [441,183,502,30,472], // MATHEMATICAL ITALIC SMALL RHO 0x1D70D: [490,183,439,35,464], // MATHEMATICAL ITALIC SMALL FINAL SIGMA 0x1D70E: [428,11,537,40,547], // MATHEMATICAL ITALIC SMALL SIGMA 0x1D70F: [428,5,442,30,472], // MATHEMATICAL ITALIC SMALL TAU 0x1D710: [439,11,460,30,445], // MATHEMATICAL ITALIC SMALL UPSILON 0x1D711: [441,183,666,50,631], // MATHEMATICAL ITALIC SMALL PHI 0x1D712: [441,202,595,30,645], // MATHEMATICAL ITALIC SMALL CHI 0x1D713: [441,183,661,30,711], // MATHEMATICAL ITALIC SMALL PSI 0x1D714: [441,11,681,20,661], // MATHEMATICAL ITALIC SMALL OMEGA 0x1D715: [668,11,471,40,471], // MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL 0x1D716: [441,11,430,40,430], // MATHEMATICAL ITALIC EPSILON SYMBOL 0x1D717: [678,10,554,20,507], // MATHEMATICAL ITALIC THETA SYMBOL 0x1D718: [441,13,561,12,587], // MATHEMATICAL ITALIC KAPPA SYMBOL 0x1D719: [668,183,645,40,620], // MATHEMATICAL ITALIC PHI SYMBOL 0x1D71A: [441,187,509,40,489], // MATHEMATICAL ITALIC RHO SYMBOL 0x1D71B: [428,11,856,30,866] // MATHEMATICAL ITALIC PI SYMBOL } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Italic/GreekItalic.js");
random_line_split
extjs-components.ts
/* eslint-disable no-param-reassign */ // import * as _ from 'lodash'; import { ComponentAPI } from './component'; import { FormFieldBaseAPI } from './form-field-base'; import { BoundListAPI } from './boundlist'; import { ButtonAPI } from './button'; import { CheckBoxAPI } from './checkbox'; import { ComboBoxAPI } from './combobox'; import { FormAPI } from './form'; import { GridColumnAPI } from './gridcolumn'; import { TabAPI } from './tab'; import { TableViewAPI } from './tableview'; import { TabPanelAPI } from './tabpanel'; import { TextFieldAPI } from './textfield'; import { TreeViewAPI } from './treeview'; export class ExtJsCmpAPI { static component = ComponentAPI; static formFieldBase = FormFieldBaseAPI; static boundlist = BoundListAPI; static button = ButtonAPI; static checkbox = CheckBoxAPI; static combobox = ComboBoxAPI;
static tableview = TableViewAPI; static tabpanel = TabPanelAPI; static textfield = TextFieldAPI; static treeview = TreeViewAPI; }
static form = FormAPI; static gridcolumn = GridColumnAPI; static tab = TabAPI;
random_line_split
extjs-components.ts
/* eslint-disable no-param-reassign */ // import * as _ from 'lodash'; import { ComponentAPI } from './component'; import { FormFieldBaseAPI } from './form-field-base'; import { BoundListAPI } from './boundlist'; import { ButtonAPI } from './button'; import { CheckBoxAPI } from './checkbox'; import { ComboBoxAPI } from './combobox'; import { FormAPI } from './form'; import { GridColumnAPI } from './gridcolumn'; import { TabAPI } from './tab'; import { TableViewAPI } from './tableview'; import { TabPanelAPI } from './tabpanel'; import { TextFieldAPI } from './textfield'; import { TreeViewAPI } from './treeview'; export class
{ static component = ComponentAPI; static formFieldBase = FormFieldBaseAPI; static boundlist = BoundListAPI; static button = ButtonAPI; static checkbox = CheckBoxAPI; static combobox = ComboBoxAPI; static form = FormAPI; static gridcolumn = GridColumnAPI; static tab = TabAPI; static tableview = TableViewAPI; static tabpanel = TabPanelAPI; static textfield = TextFieldAPI; static treeview = TreeViewAPI; }
ExtJsCmpAPI
identifier_name
minusAssign.js
/* | Ast minus assignment ( -= ) */ /* | The jion definition. */ if( JION ) { throw{ id : 'jion$ast_minusAssign', attributes :
type : require( '../typemaps/astExpression' ) }, right : { comment : 'right-hand side', type : require( '../typemaps/astExpression' ) } } }; } /* | Capsule */ (function() { 'use strict'; var ast_minusAssign, prototype; ast_minusAssign = require( '../this' )( module, 'ouroboros' ); prototype = ast_minusAssign.prototype; /**/if( CHECK ) /**/{ /**/ var /**/ util; /**/ /**/ util = require( 'util' ); /**/ /*** / **** | Custom inspect **** / ***/ prototype.inspect = /**/ function( /**/ depth, /**/ opts /**/ ) /**/ { /**/ var /**/ postfix, /**/ result; /**/ /**/ if( !opts.ast ) /**/ { /**/ result = 'ast{ '; /**/ /**/ postfix = ' }'; /**/ } /**/ else /**/ { /**/ result = postfix = ''; /**/ } /**/ /**/ opts.ast = true; /**/ /**/ result += '( ' + util.inspect( this.left, opts ) + ' )'; /**/ /**/ result += ' -= '; /**/ /**/ result += '( ' + util.inspect( this.right, opts ) + ' )'; /**/ /**/ return result + postfix; /**/ }; /**/} } )( );
{ left : { comment : 'left-hand side',
random_line_split
minusAssign.js
/* | Ast minus assignment ( -= ) */ /* | The jion definition. */ if( JION )
/* | Capsule */ (function() { 'use strict'; var ast_minusAssign, prototype; ast_minusAssign = require( '../this' )( module, 'ouroboros' ); prototype = ast_minusAssign.prototype; /**/if( CHECK ) /**/{ /**/ var /**/ util; /**/ /**/ util = require( 'util' ); /**/ /*** / **** | Custom inspect **** / ***/ prototype.inspect = /**/ function( /**/ depth, /**/ opts /**/ ) /**/ { /**/ var /**/ postfix, /**/ result; /**/ /**/ if( !opts.ast ) /**/ { /**/ result = 'ast{ '; /**/ /**/ postfix = ' }'; /**/ } /**/ else /**/ { /**/ result = postfix = ''; /**/ } /**/ /**/ opts.ast = true; /**/ /**/ result += '( ' + util.inspect( this.left, opts ) + ' )'; /**/ /**/ result += ' -= '; /**/ /**/ result += '( ' + util.inspect( this.right, opts ) + ' )'; /**/ /**/ return result + postfix; /**/ }; /**/} } )( );
{ throw{ id : 'jion$ast_minusAssign', attributes : { left : { comment : 'left-hand side', type : require( '../typemaps/astExpression' ) }, right : { comment : 'right-hand side', type : require( '../typemaps/astExpression' ) } } }; }
conditional_block
triple-slash-reference.ts
import * as ts from 'typescript'; import { ElementKind } from '../constants'; import { create_element, is_element, IElement,
types?: string; } export interface ITripleSlashReference extends IElement<ElementKind.TripleSlashReference>, ITripleSlashReferenceOptions {} export const create_triple_slash_reference = ( options: ITripleSlashReferenceOptions, ): ITripleSlashReference => ({ ...create_element(ElementKind.TripleSlashReference), ...options, }); export const is_triple_slash_reference = ( value: any, ): value is ITripleSlashReference => is_element(value) && value.kind === ElementKind.TripleSlashReference; /** * @hidden */ export const transform_triple_slash_reference = ( element: ITripleSlashReference, _path: IElement<any>[], ) => ts.addSyntheticTrailingComment( /* node */ ts.createOmittedExpression(), /* kind */ ts.SyntaxKind.SingleLineCommentTrivia, /* text */ element.path !== undefined ? `/ <reference path="${element.path}" />` : `/ <reference types="${element.types}" />`, /* hasTrailingNewLine */ false, );
IElementOptions, } from '../element'; export interface ITripleSlashReferenceOptions extends IElementOptions { path?: string;
random_line_split
test.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
function content_test() { window.addEventListener('message', function(event) { var msg = event.data; if (msg == 'original') { console.log('VICTIM: No content changed.'); chrome.test.succeed(); } else { console.log('VICTIM: Detected injected content - ' + msg); chrome.test.fail('Content changed: ' + msg); } }, false); chrome.test.getConfig(function(config) { chrome.test.log("Creating tab..."); var test_url = ("http://a.com:PORT/extensions/api_test" + "/content_scripts/other_extensions/iframe_content.html#" + escape(chrome.extension.getURL("test.html"))) .replace(/PORT/, config.testServer.port); console.log('Opening frame: ' + test_url); document.getElementById('content_frame').src = test_url; }); } ]);
// Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. chrome.test.runTests([
random_line_split
test.js
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. chrome.test.runTests([ function content_test() { window.addEventListener('message', function(event) { var msg = event.data; if (msg == 'original')
else { console.log('VICTIM: Detected injected content - ' + msg); chrome.test.fail('Content changed: ' + msg); } }, false); chrome.test.getConfig(function(config) { chrome.test.log("Creating tab..."); var test_url = ("http://a.com:PORT/extensions/api_test" + "/content_scripts/other_extensions/iframe_content.html#" + escape(chrome.extension.getURL("test.html"))) .replace(/PORT/, config.testServer.port); console.log('Opening frame: ' + test_url); document.getElementById('content_frame').src = test_url; }); } ]);
{ console.log('VICTIM: No content changed.'); chrome.test.succeed(); }
conditional_block
private_export.ts
/** * @license
*/ export {Animation as ɵAnimation} from './dsl/animation'; export {AnimationStyleNormalizer as ɵAnimationStyleNormalizer, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer} from './dsl/style_normalization/animation_style_normalizer'; export {WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer} from './dsl/style_normalization/web_animations_style_normalizer'; export {NoopAnimationDriver as ɵNoopAnimationDriver} from './render/animation_driver'; export {AnimationEngine as ɵAnimationEngine} from './render/animation_engine_next'; export {CssKeyframesDriver as ɵCssKeyframesDriver} from './render/css_keyframes/css_keyframes_driver'; export {CssKeyframesPlayer as ɵCssKeyframesPlayer} from './render/css_keyframes/css_keyframes_player'; export {containsElement as ɵcontainsElement, invokeQuery as ɵinvokeQuery, matchesElement as ɵmatchesElement, validateStyleProperty as ɵvalidateStyleProperty} from './render/shared'; export {WebAnimationsDriver as ɵWebAnimationsDriver, supportsWebAnimations as ɵsupportsWebAnimations} from './render/web_animations/web_animations_driver'; export {WebAnimationsPlayer as ɵWebAnimationsPlayer} from './render/web_animations/web_animations_player'; export {allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge} from './util';
* Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license
random_line_split
AngularHelpers.ts
/// <reference path="../../../lib/DefinitelyTyped/angularjs/angular.d.ts"/> /// <reference path="../../_all.d.ts"/> import AdhHttp = require("../Http/Http"); export var recursionHelper = ($compile) => { return { /** * Manually compiles the element, fixing the recursion loop. * @param element * @param [link] A post-link function, or an object with function(s) registered via pre and post properties. * @returns An object containing the linking functions. */ compile: (element, link) => { // Normalize the link parameter if (jQuery.isFunction(link)) { link = {post: link}; } // Break the recursion loop by removing the contents var contents = element.contents().remove(); var compiledContents; return { pre: (link && link.pre) ? link.pre : null, /** * Compiles and re-adds the contents */ post: function(scope, element) { // Compile the contents if (!compiledContents) { compiledContents = $compile(contents); } // Re-add the compiled contents to the element compiledContents(scope, (clone) => { element.append(clone); }); // Call the post-linking function, if any if (link && link.post) { link.post.apply(null, arguments); } } }; } }; }; export var lastVersion = ( $compile : angular.ICompileService, adhHttp : AdhHttp.Service<any> ) => { return { restrict: "E", scope: { itemPath: "@" }, transclude: true, template: "<adh-inject></adh-inject>", link: (scope) => { adhHttp.getNewestVersionPathNoFork(scope.itemPath).then( (versionPath) => { scope.versionPath = versionPath; }); } }; }; /** * Recompiles children on every change of `value`. `value` is available in * child scope as `key`. * * Example: * * <adh-recompile-on-change data-value="{{proposalPath}}" data-key="path"> * <adh-proposal path="{{path}}"></adh-proposal> * </adh-recompile-on-change> */ export var recompileOnChange = ($compile : angular.ICompileService) => { return { restrict: "E", compile: (element, link) => { if (jQuery.isFunction(link)) { link = {post: link}; } var contents = element.contents().remove(); var compiledContents; return { pre: (link && link.pre) ? link.pre : null, post: function(scope : angular.IScope, element, attrs) { var innerScope : angular.IScope; if (!compiledContents) { compiledContents = $compile(contents); } scope.$watch(() => attrs["value"], (value) => { if (typeof innerScope !== "undefined") { innerScope.$destroy(); element.contents().remove(); } innerScope = scope.$new(); if (typeof attrs["key"] !== "undefined") { innerScope[attrs["key"]] = value; } compiledContents(innerScope, (clone) => { element.append(clone); }); }); if (link && link.post) { link.post.apply(null, arguments); } } }; } }; }; /** * Like ngIf, but does not remove the directive when * the condition switches back to false. * * NOTE: for simplicity, this can currently only used * as a wrapper element (not as attibute). */ export var waitForCondition = () => { return { restrict: "E", scope: { condition: "=" }, transclude: true, template: "<ng-transclude data-ng-if=\"wasTrueOnce\"></ng-transclude>", link: (scope, element, attrs) => { scope.$watch("condition", (value) => { if (value) { scope.wasTrueOnce = true; } }); } }; }; /** * Make sure the view value is loaded correctly on input fields * * Can be used to work around issues with browser autofill. * * Inspired by https://stackoverflow.com/questions/14965968 */ export var inputSync = ($timeout : angular.ITimeoutService) => { return { restrict : "A", require: "ngModel", link : (scope, element, attrs, ngModel) => { $timeout(() => { if (ngModel.$viewValue !== element.val()) { ngModel.$setViewValue(element.val()); } }, 500); } }; }; export var showError = (form : angular.IFormController, field : angular.INgModelController, errorName : string) : boolean => { return field.$error[errorName] && (form.$submitted || field.$dirty); }; /** * Wrapper around clickable element that adds a sglclick event. * * sglclick is triggered on a click event that is not followed * by another click or dblclick event within given timeout. */ export var singleClickWrapperFactory = ($timeout : angular.ITimeoutService) => { return (clickable, timeout : number = 200) => { var clicked = 0; var callbacks : Function[] = []; var triggerSingleClick = (event) => { callbacks.forEach((callback) => callback(event)); }; clickable.on("click", (event) => { clicked += 1; $timeout(() => { if (clicked === 1) { triggerSingleClick(event); } clicked = 0; }, timeout); }); clickable.on("dblclick", (event) => { clicked = 0; }); return { on: (eventName : string, callback : Function) : void => { if (eventName === "sglclick") { callbacks.push(callback); } else { clickable.on(eventName, callback); } } }; }; }; /** * Return the first element within a form that has an error. * * Will also search through all subforms. * Used to scroll to that element on submit atempt. */ export var getFirstFormError = (form, element) => { var getErrorControllers = (ctrl) => { if (ctrl.hasOwnProperty("$modelValue")) { return [ctrl]; } else
}; var errorControllers = getErrorControllers(form); var names = _.unique(_.map(errorControllers, "$name")); var selector = _.map(names, (name) => "[name=\"" + name + "\"]").join(", "); return element.find(selector).first(); }; export var submitIfValid = ( $q : angular.IQService ) => ( scope : {errors : AdhHttp.IBackendErrorItem[]}, element, form : angular.IFormController, submitFn : () => any ) : angular.IPromise<any> => { var container = element.parents("[data-du-scroll-container]"); if (form.$valid) { return $q.when(submitFn()) .then((result) => { scope.errors = []; return result; }, (errors : AdhHttp.IBackendErrorItem[]) => { // FIXME this also happens in resourceWidgets. Should not do any harm though. scope.errors = errors; if (container.length > 0) { container.scrollTopAnimated(0); } throw errors; }); } else { container.scrollToElementAnimated(getFirstFormError(form, element), 20); return $q.reject([]); } }; export var moduleName = "adhAngularHelpers"; export var register = (angular) => { angular .module(moduleName, [ AdhHttp.moduleName ]) .filter("join", () => (list : any[], separator : string = ", ") : string => list.join(separator)) .filter("signum", () => (n : number) : string => (typeof n === "number") ? (n > 0 ? "+" + n.toString() : n.toString()) : "0") .factory("adhRecursionHelper", ["$compile", recursionHelper]) .factory("adhShowError", () => showError) .factory("adhSingleClickWrapper", ["$timeout", singleClickWrapperFactory]) .factory("adhSubmitIfValid", ["$q", submitIfValid]) .directive("adhRecompileOnChange", ["$compile", recompileOnChange]) .directive("adhLastVersion", ["$compile", "adhHttp", lastVersion]) .directive("adhWait", waitForCondition) .directive("adhInputSync", ["$timeout" , inputSync]); };
{ var childCtrls = _.flatten(_.values(ctrl.$error)); return _.flatten(_.map(childCtrls, getErrorControllers)); }
conditional_block
AngularHelpers.ts
/// <reference path="../../../lib/DefinitelyTyped/angularjs/angular.d.ts"/> /// <reference path="../../_all.d.ts"/> import AdhHttp = require("../Http/Http"); export var recursionHelper = ($compile) => { return { /** * Manually compiles the element, fixing the recursion loop. * @param element * @param [link] A post-link function, or an object with function(s) registered via pre and post properties. * @returns An object containing the linking functions. */ compile: (element, link) => { // Normalize the link parameter if (jQuery.isFunction(link)) { link = {post: link}; } // Break the recursion loop by removing the contents var contents = element.contents().remove(); var compiledContents; return { pre: (link && link.pre) ? link.pre : null, /** * Compiles and re-adds the contents */ post: function(scope, element) { // Compile the contents if (!compiledContents) { compiledContents = $compile(contents); } // Re-add the compiled contents to the element compiledContents(scope, (clone) => { element.append(clone); }); // Call the post-linking function, if any if (link && link.post) { link.post.apply(null, arguments); } } }; } }; }; export var lastVersion = ( $compile : angular.ICompileService, adhHttp : AdhHttp.Service<any> ) => {
restrict: "E", scope: { itemPath: "@" }, transclude: true, template: "<adh-inject></adh-inject>", link: (scope) => { adhHttp.getNewestVersionPathNoFork(scope.itemPath).then( (versionPath) => { scope.versionPath = versionPath; }); } }; }; /** * Recompiles children on every change of `value`. `value` is available in * child scope as `key`. * * Example: * * <adh-recompile-on-change data-value="{{proposalPath}}" data-key="path"> * <adh-proposal path="{{path}}"></adh-proposal> * </adh-recompile-on-change> */ export var recompileOnChange = ($compile : angular.ICompileService) => { return { restrict: "E", compile: (element, link) => { if (jQuery.isFunction(link)) { link = {post: link}; } var contents = element.contents().remove(); var compiledContents; return { pre: (link && link.pre) ? link.pre : null, post: function(scope : angular.IScope, element, attrs) { var innerScope : angular.IScope; if (!compiledContents) { compiledContents = $compile(contents); } scope.$watch(() => attrs["value"], (value) => { if (typeof innerScope !== "undefined") { innerScope.$destroy(); element.contents().remove(); } innerScope = scope.$new(); if (typeof attrs["key"] !== "undefined") { innerScope[attrs["key"]] = value; } compiledContents(innerScope, (clone) => { element.append(clone); }); }); if (link && link.post) { link.post.apply(null, arguments); } } }; } }; }; /** * Like ngIf, but does not remove the directive when * the condition switches back to false. * * NOTE: for simplicity, this can currently only used * as a wrapper element (not as attibute). */ export var waitForCondition = () => { return { restrict: "E", scope: { condition: "=" }, transclude: true, template: "<ng-transclude data-ng-if=\"wasTrueOnce\"></ng-transclude>", link: (scope, element, attrs) => { scope.$watch("condition", (value) => { if (value) { scope.wasTrueOnce = true; } }); } }; }; /** * Make sure the view value is loaded correctly on input fields * * Can be used to work around issues with browser autofill. * * Inspired by https://stackoverflow.com/questions/14965968 */ export var inputSync = ($timeout : angular.ITimeoutService) => { return { restrict : "A", require: "ngModel", link : (scope, element, attrs, ngModel) => { $timeout(() => { if (ngModel.$viewValue !== element.val()) { ngModel.$setViewValue(element.val()); } }, 500); } }; }; export var showError = (form : angular.IFormController, field : angular.INgModelController, errorName : string) : boolean => { return field.$error[errorName] && (form.$submitted || field.$dirty); }; /** * Wrapper around clickable element that adds a sglclick event. * * sglclick is triggered on a click event that is not followed * by another click or dblclick event within given timeout. */ export var singleClickWrapperFactory = ($timeout : angular.ITimeoutService) => { return (clickable, timeout : number = 200) => { var clicked = 0; var callbacks : Function[] = []; var triggerSingleClick = (event) => { callbacks.forEach((callback) => callback(event)); }; clickable.on("click", (event) => { clicked += 1; $timeout(() => { if (clicked === 1) { triggerSingleClick(event); } clicked = 0; }, timeout); }); clickable.on("dblclick", (event) => { clicked = 0; }); return { on: (eventName : string, callback : Function) : void => { if (eventName === "sglclick") { callbacks.push(callback); } else { clickable.on(eventName, callback); } } }; }; }; /** * Return the first element within a form that has an error. * * Will also search through all subforms. * Used to scroll to that element on submit atempt. */ export var getFirstFormError = (form, element) => { var getErrorControllers = (ctrl) => { if (ctrl.hasOwnProperty("$modelValue")) { return [ctrl]; } else { var childCtrls = _.flatten(_.values(ctrl.$error)); return _.flatten(_.map(childCtrls, getErrorControllers)); } }; var errorControllers = getErrorControllers(form); var names = _.unique(_.map(errorControllers, "$name")); var selector = _.map(names, (name) => "[name=\"" + name + "\"]").join(", "); return element.find(selector).first(); }; export var submitIfValid = ( $q : angular.IQService ) => ( scope : {errors : AdhHttp.IBackendErrorItem[]}, element, form : angular.IFormController, submitFn : () => any ) : angular.IPromise<any> => { var container = element.parents("[data-du-scroll-container]"); if (form.$valid) { return $q.when(submitFn()) .then((result) => { scope.errors = []; return result; }, (errors : AdhHttp.IBackendErrorItem[]) => { // FIXME this also happens in resourceWidgets. Should not do any harm though. scope.errors = errors; if (container.length > 0) { container.scrollTopAnimated(0); } throw errors; }); } else { container.scrollToElementAnimated(getFirstFormError(form, element), 20); return $q.reject([]); } }; export var moduleName = "adhAngularHelpers"; export var register = (angular) => { angular .module(moduleName, [ AdhHttp.moduleName ]) .filter("join", () => (list : any[], separator : string = ", ") : string => list.join(separator)) .filter("signum", () => (n : number) : string => (typeof n === "number") ? (n > 0 ? "+" + n.toString() : n.toString()) : "0") .factory("adhRecursionHelper", ["$compile", recursionHelper]) .factory("adhShowError", () => showError) .factory("adhSingleClickWrapper", ["$timeout", singleClickWrapperFactory]) .factory("adhSubmitIfValid", ["$q", submitIfValid]) .directive("adhRecompileOnChange", ["$compile", recompileOnChange]) .directive("adhLastVersion", ["$compile", "adhHttp", lastVersion]) .directive("adhWait", waitForCondition) .directive("adhInputSync", ["$timeout" , inputSync]); };
return {
random_line_split
mir.rs
/// /////////////////////////////////////////////////////////////////////////// /// File: Annealing/Solver/MIPS.rs /// /////////////////////////////////////////////////////////////////////////// /// Copyright 2017 Giovanni Mazzeo /// /// 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. /// /////////////////////////////////////////////////////////////////////////// /// **************************************************************************** /// ***************************************************************************** /// ** /// Multiple Independent Run (MIR) /// * /// ***************************************************************************** /// **************************************************************************** use annealing::solver::Solver; use annealing::problem::Problem; use annealing::cooler::{Cooler, StepsCooler, TimeCooler}; use annealing::solver::common; use annealing::solver::common::MrResult; use res_emitters; use res_emitters::Emitter; use annealing::solver::common::IntermediateResults; use shared::TunerParameter; use time; use CoolingSchedule; use EnergyType; use pbr; use rand; use libc; use num_cpus; use rand::{Rng, thread_rng}; use rand::distributions::{Range, IndependentSample}; use ansi_term::Colour::Green; use std::collections::HashMap; use pbr::{ProgressBar, MultiBar}; use std::thread; use std::sync::mpsc::channel; #[derive(Debug, Clone)] pub struct Mir { pub tuner_params: TunerParameter, pub res_emitter: Emitter, } impl Solver for Mir { fn solve(&mut self, problem: &mut Problem, num_workers: usize) -> MrResult
}
{ let cooler = StepsCooler { max_steps: self.tuner_params.max_step, min_temp: self.tuner_params.min_temp.unwrap(), max_temp: self.tuner_params.max_temp.unwrap(), }; ("{}",Green.paint("\n-------------------------------------------------------------------------------------------------------------------")); println!( "{} Initialization Phase: Evaluation of Energy for Default Parameters", Green.paint("[TUNER]") ); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------")); let mut elapsed_steps = common::SharedGenericCounter::new(); // Creation of the pool of Initial States. It will be composed by the initial default state // given by the user and by other num_workers-1 states generated in a random way let mut initial_state = problem.initial_state(); let mut initial_states_pool = common::StatesPool::new(); initial_states_pool.push(initial_state.clone()); for i in 1..num_workers { initial_states_pool.push(problem.rand_state()); } // Create a muti-bar let mut mb = MultiBar::new(); let threads_res = common::ThreadsResults::new(); let mut overall_start_time = time::precise_time_ns(); let handles: Vec<_> = (0..num_workers).map(|worker_nr| { let mut pb=mb.create_bar((self.tuner_params.max_step) as u64); pb.show_message = true; let (mut master_state_c, mut problem_c) = (initial_state.clone(), problem.clone()); let (elapsed_steps_c, initial_states_pool_c, threads_res_c) = (elapsed_steps.clone(), initial_states_pool.clone(), threads_res.clone()); let nrg_type = self.clone().tuner_params.energy; let max_steps= self.clone().tuner_params.max_step; let cooling_sched= self.clone().tuner_params.cooling; let max_temp=self.tuner_params.max_temp.unwrap().clone(); let cooler_c=cooler.clone(); let is=initial_state.clone(); let mut res_emitter=self.clone().res_emitter; /************************************************************************************************************/ thread::spawn(move || { let mut attempted = 0; let mut total_improves = 0; let mut subsequent_improves = 0; let mut accepted = 0; let mut rejected = 0; let mut temperature = common::Temperature::new(max_temp, cooler_c.clone(), cooling_sched); let mut worker_elapsed_steps=0; let mut rng = thread_rng(); let mut start_time = time::precise_time_ns(); let mut worker_state=initial_states_pool_c.remove_one().unwrap(); let mut worker_nrg = match problem_c.energy(&worker_state.clone(), worker_nr) { Some(nrg) => nrg, None => panic!("The initial configuration does not allow to calculate the energy"), }; let mut last_nrg=worker_nrg; let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; let time_2_complete_hrs = ((elapsed_time as f64) * max_steps as f64) / 3600.0; let range = Range::new(0.0, 1.0); let temperature_c=temperature.clone(); let (tx, rx) = channel::<IntermediateResults>(); // Spawn the thread that will take care of writing results into a CSV file thread::spawn(move || loop { let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; match rx.recv() { Ok(res) => { res_emitter.send_update(temperature_c.get(), elapsed_time, 0.0, res.last_nrg, &res.last_state, res.best_nrg, &res.best_state, worker_elapsed_steps,res.tid); } Err(e) => {} } }); /************************************************************************************************************/ let threads_res=common::ThreadsResults::new(); loop{ if worker_elapsed_steps > max_steps || rejected>300{ break; } elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; //let time_2_complete_mins=exec_time*(((max_steps/num_workers) - worker_elapsed_steps) as f64) / 60.0; println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); println!("{} TID[{}] - Completed Steps: {:.2} - Percentage of Completion: {:.2}% - Estimated \ time to Complete: {:.2} Hrs", Green.paint("[TUNER]"), worker_nr, worker_elapsed_steps, (worker_elapsed_steps as f64 / (cooler_c.max_steps/num_workers) as f64) * 100.0, elapsed_time); println!("{} Total Accepted Solutions: {:?} - Current Temperature: {:.2} - Elapsed \ Time: {:.2} s", Green.paint("[TUNER]"), accepted, temperature.get(), elapsed_time); println!("{} Accepted State: {:?}", Green.paint("[TUNER]"), worker_state); println!("{} Accepted Energy: {:.4} - Last Measured Energy: {:.4}", Green.paint("[TUNER]"), worker_nrg, last_nrg); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); pb.message(&format!("TID [{}] - Status - ", worker_nr)); pb.inc(); let mut last_state=worker_state.clone(); worker_state = { let next_state = problem_c.new_state(&worker_state,max_steps,worker_elapsed_steps); let accepted_state = match problem_c.energy(&next_state.clone(), worker_nr) { Some(new_energy) => { last_nrg = new_energy; println!("Thread : {:?} - Step: {:?} - State: {:?} - Energy: {:?}",worker_nr,worker_elapsed_steps,next_state,new_energy); let de = match nrg_type { EnergyType::throughput => new_energy - worker_nrg, EnergyType::latency => -(new_energy - worker_nrg), }; if de > 0.0 || range.ind_sample(&mut rng) <= (de / temperature.get()).exp() { accepted+=1; worker_nrg = new_energy; if de > 0.0 { rejected=0; total_improves = total_improves + 1; subsequent_improves = subsequent_improves + 1; } next_state } else { rejected+=1; worker_state } } None => { println!("{} The current configuration parameters cannot be evaluated. \ Skip!", Green.paint("[TUNER]")); worker_state } }; accepted_state }; let intermediate_res=IntermediateResults{ last_nrg: last_nrg, last_state:last_state.clone(), best_nrg: worker_nrg, best_state: worker_state.clone(), tid: worker_nr }; tx.send(intermediate_res); worker_elapsed_steps+=1; temperature.update(worker_elapsed_steps); } let res=common::MrResult{ energy: worker_nrg, state: worker_state, }; threads_res_c.push(res); pb.finish_print(&format!("Child Thread [{}] Terminated the Execution", worker_nr)); }) }).collect(); mb.listen(); // Wait for all threads to complete before start a search in a new set of neighborhoods. for h in handles { h.join().unwrap(); } /// ********************************************************************************************************* // Get results of worker threads (each one will put its best evaluated energy) and // choose between them which one will be the best one. let mut workers_res = threads_res.get_coll(); let first_elem = workers_res.pop().unwrap(); let mut best_energy = first_elem.energy; let mut best_state = first_elem.state; for elem in workers_res.iter() { let diff = match self.tuner_params.energy { EnergyType::throughput => elem.energy - best_energy, EnergyType::latency => -(elem.energy - best_energy), }; if diff > 0.0 { best_energy = elem.clone().energy; best_state = elem.clone().state; } } MrResult { energy: best_energy, state: best_state, } }
identifier_body
mir.rs
/// /////////////////////////////////////////////////////////////////////////// /// File: Annealing/Solver/MIPS.rs /// /////////////////////////////////////////////////////////////////////////// /// Copyright 2017 Giovanni Mazzeo /// /// 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. /// /////////////////////////////////////////////////////////////////////////// /// **************************************************************************** /// ***************************************************************************** /// ** /// Multiple Independent Run (MIR) /// * /// ***************************************************************************** /// **************************************************************************** use annealing::solver::Solver; use annealing::problem::Problem; use annealing::cooler::{Cooler, StepsCooler, TimeCooler}; use annealing::solver::common; use annealing::solver::common::MrResult; use res_emitters; use res_emitters::Emitter; use annealing::solver::common::IntermediateResults; use shared::TunerParameter; use time; use CoolingSchedule; use EnergyType; use pbr; use rand; use libc; use num_cpus; use rand::{Rng, thread_rng}; use rand::distributions::{Range, IndependentSample}; use ansi_term::Colour::Green; use std::collections::HashMap; use pbr::{ProgressBar, MultiBar}; use std::thread; use std::sync::mpsc::channel; #[derive(Debug, Clone)] pub struct Mir { pub tuner_params: TunerParameter, pub res_emitter: Emitter, } impl Solver for Mir { fn
(&mut self, problem: &mut Problem, num_workers: usize) -> MrResult { let cooler = StepsCooler { max_steps: self.tuner_params.max_step, min_temp: self.tuner_params.min_temp.unwrap(), max_temp: self.tuner_params.max_temp.unwrap(), }; ("{}",Green.paint("\n-------------------------------------------------------------------------------------------------------------------")); println!( "{} Initialization Phase: Evaluation of Energy for Default Parameters", Green.paint("[TUNER]") ); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------")); let mut elapsed_steps = common::SharedGenericCounter::new(); // Creation of the pool of Initial States. It will be composed by the initial default state // given by the user and by other num_workers-1 states generated in a random way let mut initial_state = problem.initial_state(); let mut initial_states_pool = common::StatesPool::new(); initial_states_pool.push(initial_state.clone()); for i in 1..num_workers { initial_states_pool.push(problem.rand_state()); } // Create a muti-bar let mut mb = MultiBar::new(); let threads_res = common::ThreadsResults::new(); let mut overall_start_time = time::precise_time_ns(); let handles: Vec<_> = (0..num_workers).map(|worker_nr| { let mut pb=mb.create_bar((self.tuner_params.max_step) as u64); pb.show_message = true; let (mut master_state_c, mut problem_c) = (initial_state.clone(), problem.clone()); let (elapsed_steps_c, initial_states_pool_c, threads_res_c) = (elapsed_steps.clone(), initial_states_pool.clone(), threads_res.clone()); let nrg_type = self.clone().tuner_params.energy; let max_steps= self.clone().tuner_params.max_step; let cooling_sched= self.clone().tuner_params.cooling; let max_temp=self.tuner_params.max_temp.unwrap().clone(); let cooler_c=cooler.clone(); let is=initial_state.clone(); let mut res_emitter=self.clone().res_emitter; /************************************************************************************************************/ thread::spawn(move || { let mut attempted = 0; let mut total_improves = 0; let mut subsequent_improves = 0; let mut accepted = 0; let mut rejected = 0; let mut temperature = common::Temperature::new(max_temp, cooler_c.clone(), cooling_sched); let mut worker_elapsed_steps=0; let mut rng = thread_rng(); let mut start_time = time::precise_time_ns(); let mut worker_state=initial_states_pool_c.remove_one().unwrap(); let mut worker_nrg = match problem_c.energy(&worker_state.clone(), worker_nr) { Some(nrg) => nrg, None => panic!("The initial configuration does not allow to calculate the energy"), }; let mut last_nrg=worker_nrg; let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; let time_2_complete_hrs = ((elapsed_time as f64) * max_steps as f64) / 3600.0; let range = Range::new(0.0, 1.0); let temperature_c=temperature.clone(); let (tx, rx) = channel::<IntermediateResults>(); // Spawn the thread that will take care of writing results into a CSV file thread::spawn(move || loop { let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; match rx.recv() { Ok(res) => { res_emitter.send_update(temperature_c.get(), elapsed_time, 0.0, res.last_nrg, &res.last_state, res.best_nrg, &res.best_state, worker_elapsed_steps,res.tid); } Err(e) => {} } }); /************************************************************************************************************/ let threads_res=common::ThreadsResults::new(); loop{ if worker_elapsed_steps > max_steps || rejected>300{ break; } elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; //let time_2_complete_mins=exec_time*(((max_steps/num_workers) - worker_elapsed_steps) as f64) / 60.0; println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); println!("{} TID[{}] - Completed Steps: {:.2} - Percentage of Completion: {:.2}% - Estimated \ time to Complete: {:.2} Hrs", Green.paint("[TUNER]"), worker_nr, worker_elapsed_steps, (worker_elapsed_steps as f64 / (cooler_c.max_steps/num_workers) as f64) * 100.0, elapsed_time); println!("{} Total Accepted Solutions: {:?} - Current Temperature: {:.2} - Elapsed \ Time: {:.2} s", Green.paint("[TUNER]"), accepted, temperature.get(), elapsed_time); println!("{} Accepted State: {:?}", Green.paint("[TUNER]"), worker_state); println!("{} Accepted Energy: {:.4} - Last Measured Energy: {:.4}", Green.paint("[TUNER]"), worker_nrg, last_nrg); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); pb.message(&format!("TID [{}] - Status - ", worker_nr)); pb.inc(); let mut last_state=worker_state.clone(); worker_state = { let next_state = problem_c.new_state(&worker_state,max_steps,worker_elapsed_steps); let accepted_state = match problem_c.energy(&next_state.clone(), worker_nr) { Some(new_energy) => { last_nrg = new_energy; println!("Thread : {:?} - Step: {:?} - State: {:?} - Energy: {:?}",worker_nr,worker_elapsed_steps,next_state,new_energy); let de = match nrg_type { EnergyType::throughput => new_energy - worker_nrg, EnergyType::latency => -(new_energy - worker_nrg), }; if de > 0.0 || range.ind_sample(&mut rng) <= (de / temperature.get()).exp() { accepted+=1; worker_nrg = new_energy; if de > 0.0 { rejected=0; total_improves = total_improves + 1; subsequent_improves = subsequent_improves + 1; } next_state } else { rejected+=1; worker_state } } None => { println!("{} The current configuration parameters cannot be evaluated. \ Skip!", Green.paint("[TUNER]")); worker_state } }; accepted_state }; let intermediate_res=IntermediateResults{ last_nrg: last_nrg, last_state:last_state.clone(), best_nrg: worker_nrg, best_state: worker_state.clone(), tid: worker_nr }; tx.send(intermediate_res); worker_elapsed_steps+=1; temperature.update(worker_elapsed_steps); } let res=common::MrResult{ energy: worker_nrg, state: worker_state, }; threads_res_c.push(res); pb.finish_print(&format!("Child Thread [{}] Terminated the Execution", worker_nr)); }) }).collect(); mb.listen(); // Wait for all threads to complete before start a search in a new set of neighborhoods. for h in handles { h.join().unwrap(); } /// ********************************************************************************************************* // Get results of worker threads (each one will put its best evaluated energy) and // choose between them which one will be the best one. let mut workers_res = threads_res.get_coll(); let first_elem = workers_res.pop().unwrap(); let mut best_energy = first_elem.energy; let mut best_state = first_elem.state; for elem in workers_res.iter() { let diff = match self.tuner_params.energy { EnergyType::throughput => elem.energy - best_energy, EnergyType::latency => -(elem.energy - best_energy), }; if diff > 0.0 { best_energy = elem.clone().energy; best_state = elem.clone().state; } } MrResult { energy: best_energy, state: best_state, } } }
solve
identifier_name
mir.rs
/// /////////////////////////////////////////////////////////////////////////// /// File: Annealing/Solver/MIPS.rs /// /////////////////////////////////////////////////////////////////////////// /// Copyright 2017 Giovanni Mazzeo /// /// 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. /// /////////////////////////////////////////////////////////////////////////// /// **************************************************************************** /// ***************************************************************************** /// ** /// Multiple Independent Run (MIR) /// * /// ***************************************************************************** /// **************************************************************************** use annealing::solver::Solver; use annealing::problem::Problem; use annealing::cooler::{Cooler, StepsCooler, TimeCooler}; use annealing::solver::common; use annealing::solver::common::MrResult; use res_emitters; use res_emitters::Emitter; use annealing::solver::common::IntermediateResults; use shared::TunerParameter; use time; use CoolingSchedule; use EnergyType; use pbr; use rand; use libc; use num_cpus; use rand::{Rng, thread_rng}; use rand::distributions::{Range, IndependentSample}; use ansi_term::Colour::Green; use std::collections::HashMap; use pbr::{ProgressBar, MultiBar}; use std::thread; use std::sync::mpsc::channel; #[derive(Debug, Clone)] pub struct Mir { pub tuner_params: TunerParameter, pub res_emitter: Emitter, } impl Solver for Mir { fn solve(&mut self, problem: &mut Problem, num_workers: usize) -> MrResult { let cooler = StepsCooler { max_steps: self.tuner_params.max_step, min_temp: self.tuner_params.min_temp.unwrap(), max_temp: self.tuner_params.max_temp.unwrap(), }; ("{}",Green.paint("\n-------------------------------------------------------------------------------------------------------------------")); println!( "{} Initialization Phase: Evaluation of Energy for Default Parameters", Green.paint("[TUNER]") ); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------")); let mut elapsed_steps = common::SharedGenericCounter::new(); // Creation of the pool of Initial States. It will be composed by the initial default state // given by the user and by other num_workers-1 states generated in a random way let mut initial_state = problem.initial_state(); let mut initial_states_pool = common::StatesPool::new(); initial_states_pool.push(initial_state.clone()); for i in 1..num_workers { initial_states_pool.push(problem.rand_state()); } // Create a muti-bar let mut mb = MultiBar::new(); let threads_res = common::ThreadsResults::new(); let mut overall_start_time = time::precise_time_ns(); let handles: Vec<_> = (0..num_workers).map(|worker_nr| { let mut pb=mb.create_bar((self.tuner_params.max_step) as u64); pb.show_message = true; let (mut master_state_c, mut problem_c) = (initial_state.clone(), problem.clone()); let (elapsed_steps_c, initial_states_pool_c, threads_res_c) = (elapsed_steps.clone(), initial_states_pool.clone(), threads_res.clone()); let nrg_type = self.clone().tuner_params.energy; let max_steps= self.clone().tuner_params.max_step; let cooling_sched= self.clone().tuner_params.cooling; let max_temp=self.tuner_params.max_temp.unwrap().clone(); let cooler_c=cooler.clone(); let is=initial_state.clone(); let mut res_emitter=self.clone().res_emitter; /************************************************************************************************************/ thread::spawn(move || { let mut attempted = 0; let mut total_improves = 0; let mut subsequent_improves = 0; let mut accepted = 0; let mut rejected = 0; let mut temperature = common::Temperature::new(max_temp, cooler_c.clone(), cooling_sched); let mut worker_elapsed_steps=0; let mut rng = thread_rng(); let mut start_time = time::precise_time_ns(); let mut worker_state=initial_states_pool_c.remove_one().unwrap(); let mut worker_nrg = match problem_c.energy(&worker_state.clone(), worker_nr) { Some(nrg) => nrg, None => panic!("The initial configuration does not allow to calculate the energy"), }; let mut last_nrg=worker_nrg; let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; let time_2_complete_hrs = ((elapsed_time as f64) * max_steps as f64) / 3600.0; let range = Range::new(0.0, 1.0); let temperature_c=temperature.clone(); let (tx, rx) = channel::<IntermediateResults>(); // Spawn the thread that will take care of writing results into a CSV file thread::spawn(move || loop { let mut elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; match rx.recv() { Ok(res) => { res_emitter.send_update(temperature_c.get(), elapsed_time, 0.0, res.last_nrg, &res.last_state, res.best_nrg, &res.best_state, worker_elapsed_steps,res.tid); } Err(e) => {} } }); /************************************************************************************************************/ let threads_res=common::ThreadsResults::new(); loop{ if worker_elapsed_steps > max_steps || rejected>300{ break; } elapsed_time = (time::precise_time_ns() - start_time) as f64 / 1000000000.0f64; //let time_2_complete_mins=exec_time*(((max_steps/num_workers) - worker_elapsed_steps) as f64) / 60.0; println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); println!("{} TID[{}] - Completed Steps: {:.2} - Percentage of Completion: {:.2}% - Estimated \ time to Complete: {:.2} Hrs", Green.paint("[TUNER]"), worker_nr, worker_elapsed_steps, (worker_elapsed_steps as f64 / (cooler_c.max_steps/num_workers) as f64) * 100.0, elapsed_time); println!("{} Total Accepted Solutions: {:?} - Current Temperature: {:.2} - Elapsed \ Time: {:.2} s", Green.paint("[TUNER]"), accepted, temperature.get(), elapsed_time); println!("{} Accepted State: {:?}", Green.paint("[TUNER]"), worker_state); println!("{} Accepted Energy: {:.4} - Last Measured Energy: {:.4}", Green.paint("[TUNER]"),
worker_nrg, last_nrg); println!("{}",Green.paint("-------------------------------------------------------------------------------------------------------------------------------------------------------")); pb.message(&format!("TID [{}] - Status - ", worker_nr)); pb.inc(); let mut last_state=worker_state.clone(); worker_state = { let next_state = problem_c.new_state(&worker_state,max_steps,worker_elapsed_steps); let accepted_state = match problem_c.energy(&next_state.clone(), worker_nr) { Some(new_energy) => { last_nrg = new_energy; println!("Thread : {:?} - Step: {:?} - State: {:?} - Energy: {:?}",worker_nr,worker_elapsed_steps,next_state,new_energy); let de = match nrg_type { EnergyType::throughput => new_energy - worker_nrg, EnergyType::latency => -(new_energy - worker_nrg), }; if de > 0.0 || range.ind_sample(&mut rng) <= (de / temperature.get()).exp() { accepted+=1; worker_nrg = new_energy; if de > 0.0 { rejected=0; total_improves = total_improves + 1; subsequent_improves = subsequent_improves + 1; } next_state } else { rejected+=1; worker_state } } None => { println!("{} The current configuration parameters cannot be evaluated. \ Skip!", Green.paint("[TUNER]")); worker_state } }; accepted_state }; let intermediate_res=IntermediateResults{ last_nrg: last_nrg, last_state:last_state.clone(), best_nrg: worker_nrg, best_state: worker_state.clone(), tid: worker_nr }; tx.send(intermediate_res); worker_elapsed_steps+=1; temperature.update(worker_elapsed_steps); } let res=common::MrResult{ energy: worker_nrg, state: worker_state, }; threads_res_c.push(res); pb.finish_print(&format!("Child Thread [{}] Terminated the Execution", worker_nr)); }) }).collect(); mb.listen(); // Wait for all threads to complete before start a search in a new set of neighborhoods. for h in handles { h.join().unwrap(); } /// ********************************************************************************************************* // Get results of worker threads (each one will put its best evaluated energy) and // choose between them which one will be the best one. let mut workers_res = threads_res.get_coll(); let first_elem = workers_res.pop().unwrap(); let mut best_energy = first_elem.energy; let mut best_state = first_elem.state; for elem in workers_res.iter() { let diff = match self.tuner_params.energy { EnergyType::throughput => elem.energy - best_energy, EnergyType::latency => -(elem.energy - best_energy), }; if diff > 0.0 { best_energy = elem.clone().energy; best_state = elem.clone().state; } } MrResult { energy: best_energy, state: best_state, } } }
random_line_split
base.py
# -*- coding: utf-8 -*- # TODO: # * Move/rename namespace polluting attributes # * Documentation # * Make backends optional: Meta.backends = (path, modelinstance/model, view) import hashlib from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.datastructures import SortedDict from django.utils.functional import curry from django.contrib.sites.models import Site from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.utils.safestring import mark_safe from django.core.cache import cache from django.utils.encoding import iri_to_uri from rollyourown.seo.utils import NotSet, Literal from rollyourown.seo.options import Options from rollyourown.seo.fields import MetadataField, Tag, MetaTag, KeywordTag, Raw from rollyourown.seo.backends import backend_registry, RESERVED_FIELD_NAMES registry = SortedDict() class FormattedMetadata(object): """ Allows convenient access to selected metadata. Metadata for each field may be sourced from any one of the relevant instances passed. """ def __init__(self, metadata, instances, path, site=None, language=None): self.__metadata = metadata if metadata._meta.use_cache: if metadata._meta.use_sites and site: hexpath = hashlib.md5(iri_to_uri(site.domain+path)).hexdigest() else: hexpath = hashlib.md5(iri_to_uri(path)).hexdigest() if metadata._meta.use_i18n: self.__cache_prefix = 'rollyourown.seo.%s.%s.%s' % (self.__metadata.__class__.__name__, hexpath, language) else: self.__cache_prefix = 'rollyourown.seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath) else: self.__cache_prefix = None self.__instances_original = instances self.__instances_cache = [] def __instances(self): """ Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. """ for instance in self.__instances_cache: yield instance for instance in self.__instances_original: self.__instances_cache.append(instance) yield instance def _resolve_value(self, name): """ Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ for instance in self.__instances(): value = instance._resolve_value(name) if value: return value # Otherwise, return an appropriate default value (populate_from) # TODO: This is duplicated in meta_models. Move this to a common home. if name in self.__metadata._meta.elements: populate_from = self.__metadata._meta.elements[name].populate_from if callable(populate_from): return populate_from(None) elif isinstance(populate_from, Literal): return populate_from.value elif populate_from is not NotSet: return self._resolve_value(populate_from) def __getattr__(self, name): # If caching is enabled, work out a key if self.__cache_prefix: cache_key = '%s.%s' % (self.__cache_prefix, name) value = cache.get(cache_key) else: cache_key = None value = None # Look for a group called "name" if name in self.__metadata._meta.groups: if value is not None: return value or None value = '\n'.join(unicode(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) for f in self.__metadata._meta.groups[name]).strip() # Look for an element called "name" elif name in self.__metadata._meta.elements: if value is not None: return BoundMetadataField(self.__metadata._meta.elements[name], value or None) value = self._resolve_value(name) if cache_key is not None: cache.set(cache_key, value or '') return BoundMetadataField(self.__metadata._meta.elements[name], value) else: raise AttributeError if cache_key is not None: cache.set(cache_key, value or '') return value or None def __unicode__(self): """ String version of this object is the html output of head elements. """ if self.__cache_prefix is not None: value = cache.get(self.__cache_prefix) else: value = None if value is None: value = mark_safe(u'\n'.join(unicode(getattr(self, f)) for f,e in self.__metadata._meta.elements.items() if e.head)) if self.__cache_prefix is not None: cache.set(self.__cache_prefix, value or '') return value class BoundMetadataField(object): """ An object to help provide templates with access to a "bound" metadata field. """ def __init__(self, field, value): self.field = field if value: self.value = field.clean(value) else: self.value = None def __unicode__(self): if self.value: return mark_safe(self.field.render(self.value)) else: return u"" def __str__(self): return self.__unicode__().encode("ascii", "ignore")
if bases == (object,): return type.__new__(cls, name, bases, attrs) # Save options as a dict for now (we will be editing them) # TODO: Is this necessary, should we bother relaying Django Meta options? Meta = attrs.pop('Meta', {}) if Meta: Meta = Meta.__dict__.copy() # Remove our options from Meta, so Django won't complain help_text = attrs.pop('HelpText', {}) # TODO: Is this necessary if help_text: help_text = help_text.__dict__.copy() options = Options(Meta, help_text) # Collect and sort our elements elements = [(key, attrs.pop(key)) for key, obj in attrs.items() if isinstance(obj, MetadataField)] elements.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) elements = SortedDict(elements) # Validation: # TODO: Write a test framework for seo.Metadata validation # Check that no group names clash with element names for key,members in options.groups.items(): assert key not in elements, "Group name '%s' clashes with field name" % key for member in members: assert member in elements, "Group member '%s' is not a valid field" % member # Check that the names of the elements are not going to clash with a model field for key in elements: assert key not in RESERVED_FIELD_NAMES, "Field name '%s' is not allowed" % key # Preprocessing complete, here is the new class new_class = type.__new__(cls, name, bases, attrs) options.metadata = new_class new_class._meta = options # Some useful attributes options._update_from_name(name) options._register_elements(elements) try: for backend_name in options.backends: new_class._meta._add_backend(backend_registry[backend_name]) for backend_name in options.backends: backend_registry[backend_name].validate(options) except KeyError: raise Exception('Metadata backend "%s" is not installed.' % backend_name) #new_class._meta._add_backend(PathBackend) #new_class._meta._add_backend(ModelInstanceBackend) #new_class._meta._add_backend(ModelBackend) #new_class._meta._add_backend(ViewBackend) registry[name] = new_class return new_class # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_formatted_data(cls, path, context=None, site=None, language=None): """ Return an object to conveniently access the appropriate values. """ return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context } for model in cls._meta.models.values(): for instance in model.objects.get_instances(path, site, language, backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance class Metadata(object): __metaclass__ = MetadataBase def _get_metadata_model(name=None): # Find registered Metadata object if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = u'Try using the name "%s" or simply leaving it out altogether.'% registry.keys()[0] else: valid_names = u"Valid names are " + u", ".join(u'"%s"' % k for k in registry.keys()) raise Exception(u"Metadata definition with name \"%s\" does not exist.\n%s" % (name, valid_names)) else: assert len(registry) == 1, "You must have exactly one Metadata class, if using get_metadata() without a 'name' parameter." return registry.values()[0] def get_metadata(path, name=None, context=None, site=None, language=None): metadata = _get_metadata_model(name) return metadata._get_formatted_data(path, context, site, language) def get_linked_metadata(obj, name=None, context=None, site=None, language=None): """ Gets metadata linked from the given object. """ # XXX Check that 'modelinstance' and 'model' metadata are installed in backends # I believe that get_model() would return None if not Metadata = _get_metadata_model(name) InstanceMetadata = Metadata._meta.get_model('modelinstance') ModelMetadata = Metadata._meta.get_model('model') content_type = ContentType.objects.get_for_model(obj) instances = [] if InstanceMetadata is not None: try: instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk) except InstanceMetadata.DoesNotExist: instance_md = InstanceMetadata(_content_object=obj) instances.append(instance_md) if ModelMetadata is not None: try: model_md = ModelMetadata.objects.get(_content_type=content_type) except ModelMetadata.DoesNotExist: model_md = ModelMetadata(_content_type=content_type) instances.append(model_md) return FormattedMetadata(Metadata, instances, '', site, language) def create_metadata_instance(metadata_class, instance): # If this instance is marked as handled, don't do anything # This typically means that the django admin will add metadata # using eg an inline. if getattr(instance, '_MetadataFormset__seo_metadata_handled', False): return metadata = None content_type = ContentType.objects.get_for_model(instance) # If this object does not define a path, don't worry about automatic update try: path = instance.get_absolute_url() except AttributeError: return # Look for an existing object with this path language = getattr(instance, '_language', None) site = getattr(instance, '_site', None) for md in metadata_class.objects.get_instances(path, site, language): # If another object has the same path, remove the path. # It's harsh, but we need a unique path and will assume the other # link is outdated. if md._content_type != content_type or md._object_id != instance.pk: md._path = md._content_object.get_absolute_url() md.save() # Move on, this metadata instance isn't for us md = None else: # This is our instance! metadata = md # If the path-based search didn't work, look for (or create) an existing # instance linked to this object. if not metadata: metadata, md_created = metadata_class.objects.get_or_create(_content_type=content_type, _object_id=instance.pk) metadata._path = path metadata.save() def populate_metadata(model, MetadataClass): """ For a given model and metadata class, ensure there is metadata for every instance. """ content_type = ContentType.objects.get_for_model(model) for instance in model.objects.all(): create_metadata_instance(MetadataClass, instance) def _update_callback(model_class, sender, instance, created, **kwargs): """ Callback to be attached to a post_save signal, updating the relevant metadata, or just creating an entry. NB: It is theoretically possible that this code will lead to two instances with the same generic foreign key. If you have non-overlapping URLs, then this shouldn't happen. I've held it to be more important to avoid double path entries. """ create_metadata_instance(model_class, instance) def _delete_callback(model_class, sender, instance, **kwargs): content_type = ContentType.objects.get_for_model(instance) model_class.objects.filter(_content_type=content_type, _object_id=instance.pk).delete() def register_signals(): for metadata_class in registry.values(): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = curry(_update_callback, model_class=model_instance) delete_callback = curry(_delete_callback, model_class=model_instance) ## Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False)
class MetadataBase(type): def __new__(cls, name, bases, attrs): # TODO: Think of a better test to avoid processing Metadata parent class
random_line_split
base.py
# -*- coding: utf-8 -*- # TODO: # * Move/rename namespace polluting attributes # * Documentation # * Make backends optional: Meta.backends = (path, modelinstance/model, view) import hashlib from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.datastructures import SortedDict from django.utils.functional import curry from django.contrib.sites.models import Site from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.utils.safestring import mark_safe from django.core.cache import cache from django.utils.encoding import iri_to_uri from rollyourown.seo.utils import NotSet, Literal from rollyourown.seo.options import Options from rollyourown.seo.fields import MetadataField, Tag, MetaTag, KeywordTag, Raw from rollyourown.seo.backends import backend_registry, RESERVED_FIELD_NAMES registry = SortedDict() class FormattedMetadata(object): """ Allows convenient access to selected metadata. Metadata for each field may be sourced from any one of the relevant instances passed. """ def __init__(self, metadata, instances, path, site=None, language=None): self.__metadata = metadata if metadata._meta.use_cache: if metadata._meta.use_sites and site: hexpath = hashlib.md5(iri_to_uri(site.domain+path)).hexdigest() else: hexpath = hashlib.md5(iri_to_uri(path)).hexdigest() if metadata._meta.use_i18n: self.__cache_prefix = 'rollyourown.seo.%s.%s.%s' % (self.__metadata.__class__.__name__, hexpath, language) else: self.__cache_prefix = 'rollyourown.seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath) else: self.__cache_prefix = None self.__instances_original = instances self.__instances_cache = [] def __instances(self): """ Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. """ for instance in self.__instances_cache: yield instance for instance in self.__instances_original: self.__instances_cache.append(instance) yield instance def _resolve_value(self, name): """ Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ for instance in self.__instances(): value = instance._resolve_value(name) if value: return value # Otherwise, return an appropriate default value (populate_from) # TODO: This is duplicated in meta_models. Move this to a common home. if name in self.__metadata._meta.elements: populate_from = self.__metadata._meta.elements[name].populate_from if callable(populate_from): return populate_from(None) elif isinstance(populate_from, Literal): return populate_from.value elif populate_from is not NotSet: return self._resolve_value(populate_from) def __getattr__(self, name): # If caching is enabled, work out a key if self.__cache_prefix: cache_key = '%s.%s' % (self.__cache_prefix, name) value = cache.get(cache_key) else: cache_key = None value = None # Look for a group called "name" if name in self.__metadata._meta.groups: if value is not None: return value or None value = '\n'.join(unicode(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) for f in self.__metadata._meta.groups[name]).strip() # Look for an element called "name" elif name in self.__metadata._meta.elements: if value is not None: return BoundMetadataField(self.__metadata._meta.elements[name], value or None) value = self._resolve_value(name) if cache_key is not None: cache.set(cache_key, value or '') return BoundMetadataField(self.__metadata._meta.elements[name], value) else: raise AttributeError if cache_key is not None: cache.set(cache_key, value or '') return value or None def __unicode__(self): """ String version of this object is the html output of head elements. """ if self.__cache_prefix is not None: value = cache.get(self.__cache_prefix) else: value = None if value is None: value = mark_safe(u'\n'.join(unicode(getattr(self, f)) for f,e in self.__metadata._meta.elements.items() if e.head)) if self.__cache_prefix is not None: cache.set(self.__cache_prefix, value or '') return value class BoundMetadataField(object): """ An object to help provide templates with access to a "bound" metadata field. """ def __init__(self, field, value): self.field = field if value: self.value = field.clean(value) else: self.value = None def __unicode__(self): if self.value: return mark_safe(self.field.render(self.value)) else: return u"" def
(self): return self.__unicode__().encode("ascii", "ignore") class MetadataBase(type): def __new__(cls, name, bases, attrs): # TODO: Think of a better test to avoid processing Metadata parent class if bases == (object,): return type.__new__(cls, name, bases, attrs) # Save options as a dict for now (we will be editing them) # TODO: Is this necessary, should we bother relaying Django Meta options? Meta = attrs.pop('Meta', {}) if Meta: Meta = Meta.__dict__.copy() # Remove our options from Meta, so Django won't complain help_text = attrs.pop('HelpText', {}) # TODO: Is this necessary if help_text: help_text = help_text.__dict__.copy() options = Options(Meta, help_text) # Collect and sort our elements elements = [(key, attrs.pop(key)) for key, obj in attrs.items() if isinstance(obj, MetadataField)] elements.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) elements = SortedDict(elements) # Validation: # TODO: Write a test framework for seo.Metadata validation # Check that no group names clash with element names for key,members in options.groups.items(): assert key not in elements, "Group name '%s' clashes with field name" % key for member in members: assert member in elements, "Group member '%s' is not a valid field" % member # Check that the names of the elements are not going to clash with a model field for key in elements: assert key not in RESERVED_FIELD_NAMES, "Field name '%s' is not allowed" % key # Preprocessing complete, here is the new class new_class = type.__new__(cls, name, bases, attrs) options.metadata = new_class new_class._meta = options # Some useful attributes options._update_from_name(name) options._register_elements(elements) try: for backend_name in options.backends: new_class._meta._add_backend(backend_registry[backend_name]) for backend_name in options.backends: backend_registry[backend_name].validate(options) except KeyError: raise Exception('Metadata backend "%s" is not installed.' % backend_name) #new_class._meta._add_backend(PathBackend) #new_class._meta._add_backend(ModelInstanceBackend) #new_class._meta._add_backend(ModelBackend) #new_class._meta._add_backend(ViewBackend) registry[name] = new_class return new_class # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_formatted_data(cls, path, context=None, site=None, language=None): """ Return an object to conveniently access the appropriate values. """ return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context } for model in cls._meta.models.values(): for instance in model.objects.get_instances(path, site, language, backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance class Metadata(object): __metaclass__ = MetadataBase def _get_metadata_model(name=None): # Find registered Metadata object if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = u'Try using the name "%s" or simply leaving it out altogether.'% registry.keys()[0] else: valid_names = u"Valid names are " + u", ".join(u'"%s"' % k for k in registry.keys()) raise Exception(u"Metadata definition with name \"%s\" does not exist.\n%s" % (name, valid_names)) else: assert len(registry) == 1, "You must have exactly one Metadata class, if using get_metadata() without a 'name' parameter." return registry.values()[0] def get_metadata(path, name=None, context=None, site=None, language=None): metadata = _get_metadata_model(name) return metadata._get_formatted_data(path, context, site, language) def get_linked_metadata(obj, name=None, context=None, site=None, language=None): """ Gets metadata linked from the given object. """ # XXX Check that 'modelinstance' and 'model' metadata are installed in backends # I believe that get_model() would return None if not Metadata = _get_metadata_model(name) InstanceMetadata = Metadata._meta.get_model('modelinstance') ModelMetadata = Metadata._meta.get_model('model') content_type = ContentType.objects.get_for_model(obj) instances = [] if InstanceMetadata is not None: try: instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk) except InstanceMetadata.DoesNotExist: instance_md = InstanceMetadata(_content_object=obj) instances.append(instance_md) if ModelMetadata is not None: try: model_md = ModelMetadata.objects.get(_content_type=content_type) except ModelMetadata.DoesNotExist: model_md = ModelMetadata(_content_type=content_type) instances.append(model_md) return FormattedMetadata(Metadata, instances, '', site, language) def create_metadata_instance(metadata_class, instance): # If this instance is marked as handled, don't do anything # This typically means that the django admin will add metadata # using eg an inline. if getattr(instance, '_MetadataFormset__seo_metadata_handled', False): return metadata = None content_type = ContentType.objects.get_for_model(instance) # If this object does not define a path, don't worry about automatic update try: path = instance.get_absolute_url() except AttributeError: return # Look for an existing object with this path language = getattr(instance, '_language', None) site = getattr(instance, '_site', None) for md in metadata_class.objects.get_instances(path, site, language): # If another object has the same path, remove the path. # It's harsh, but we need a unique path and will assume the other # link is outdated. if md._content_type != content_type or md._object_id != instance.pk: md._path = md._content_object.get_absolute_url() md.save() # Move on, this metadata instance isn't for us md = None else: # This is our instance! metadata = md # If the path-based search didn't work, look for (or create) an existing # instance linked to this object. if not metadata: metadata, md_created = metadata_class.objects.get_or_create(_content_type=content_type, _object_id=instance.pk) metadata._path = path metadata.save() def populate_metadata(model, MetadataClass): """ For a given model and metadata class, ensure there is metadata for every instance. """ content_type = ContentType.objects.get_for_model(model) for instance in model.objects.all(): create_metadata_instance(MetadataClass, instance) def _update_callback(model_class, sender, instance, created, **kwargs): """ Callback to be attached to a post_save signal, updating the relevant metadata, or just creating an entry. NB: It is theoretically possible that this code will lead to two instances with the same generic foreign key. If you have non-overlapping URLs, then this shouldn't happen. I've held it to be more important to avoid double path entries. """ create_metadata_instance(model_class, instance) def _delete_callback(model_class, sender, instance, **kwargs): content_type = ContentType.objects.get_for_model(instance) model_class.objects.filter(_content_type=content_type, _object_id=instance.pk).delete() def register_signals(): for metadata_class in registry.values(): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = curry(_update_callback, model_class=model_instance) delete_callback = curry(_delete_callback, model_class=model_instance) ## Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False)
__str__
identifier_name
base.py
# -*- coding: utf-8 -*- # TODO: # * Move/rename namespace polluting attributes # * Documentation # * Make backends optional: Meta.backends = (path, modelinstance/model, view) import hashlib from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.datastructures import SortedDict from django.utils.functional import curry from django.contrib.sites.models import Site from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.utils.safestring import mark_safe from django.core.cache import cache from django.utils.encoding import iri_to_uri from rollyourown.seo.utils import NotSet, Literal from rollyourown.seo.options import Options from rollyourown.seo.fields import MetadataField, Tag, MetaTag, KeywordTag, Raw from rollyourown.seo.backends import backend_registry, RESERVED_FIELD_NAMES registry = SortedDict() class FormattedMetadata(object): """ Allows convenient access to selected metadata. Metadata for each field may be sourced from any one of the relevant instances passed. """ def __init__(self, metadata, instances, path, site=None, language=None): self.__metadata = metadata if metadata._meta.use_cache: if metadata._meta.use_sites and site: hexpath = hashlib.md5(iri_to_uri(site.domain+path)).hexdigest() else: hexpath = hashlib.md5(iri_to_uri(path)).hexdigest() if metadata._meta.use_i18n: self.__cache_prefix = 'rollyourown.seo.%s.%s.%s' % (self.__metadata.__class__.__name__, hexpath, language) else: self.__cache_prefix = 'rollyourown.seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath) else: self.__cache_prefix = None self.__instances_original = instances self.__instances_cache = [] def __instances(self): """ Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. """ for instance in self.__instances_cache: yield instance for instance in self.__instances_original: self.__instances_cache.append(instance) yield instance def _resolve_value(self, name): """ Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ for instance in self.__instances(): value = instance._resolve_value(name) if value: return value # Otherwise, return an appropriate default value (populate_from) # TODO: This is duplicated in meta_models. Move this to a common home. if name in self.__metadata._meta.elements: populate_from = self.__metadata._meta.elements[name].populate_from if callable(populate_from): return populate_from(None) elif isinstance(populate_from, Literal): return populate_from.value elif populate_from is not NotSet: return self._resolve_value(populate_from) def __getattr__(self, name): # If caching is enabled, work out a key if self.__cache_prefix: cache_key = '%s.%s' % (self.__cache_prefix, name) value = cache.get(cache_key) else: cache_key = None value = None # Look for a group called "name" if name in self.__metadata._meta.groups: if value is not None: return value or None value = '\n'.join(unicode(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) for f in self.__metadata._meta.groups[name]).strip() # Look for an element called "name" elif name in self.__metadata._meta.elements: if value is not None: return BoundMetadataField(self.__metadata._meta.elements[name], value or None) value = self._resolve_value(name) if cache_key is not None: cache.set(cache_key, value or '') return BoundMetadataField(self.__metadata._meta.elements[name], value) else: raise AttributeError if cache_key is not None: cache.set(cache_key, value or '') return value or None def __unicode__(self): """ String version of this object is the html output of head elements. """ if self.__cache_prefix is not None: value = cache.get(self.__cache_prefix) else: value = None if value is None: value = mark_safe(u'\n'.join(unicode(getattr(self, f)) for f,e in self.__metadata._meta.elements.items() if e.head)) if self.__cache_prefix is not None: cache.set(self.__cache_prefix, value or '') return value class BoundMetadataField(object): """ An object to help provide templates with access to a "bound" metadata field. """ def __init__(self, field, value): self.field = field if value: self.value = field.clean(value) else: self.value = None def __unicode__(self): if self.value: return mark_safe(self.field.render(self.value)) else: return u"" def __str__(self): return self.__unicode__().encode("ascii", "ignore") class MetadataBase(type): def __new__(cls, name, bases, attrs): # TODO: Think of a better test to avoid processing Metadata parent class if bases == (object,): return type.__new__(cls, name, bases, attrs) # Save options as a dict for now (we will be editing them) # TODO: Is this necessary, should we bother relaying Django Meta options? Meta = attrs.pop('Meta', {}) if Meta: Meta = Meta.__dict__.copy() # Remove our options from Meta, so Django won't complain help_text = attrs.pop('HelpText', {}) # TODO: Is this necessary if help_text: help_text = help_text.__dict__.copy() options = Options(Meta, help_text) # Collect and sort our elements elements = [(key, attrs.pop(key)) for key, obj in attrs.items() if isinstance(obj, MetadataField)] elements.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) elements = SortedDict(elements) # Validation: # TODO: Write a test framework for seo.Metadata validation # Check that no group names clash with element names for key,members in options.groups.items(): assert key not in elements, "Group name '%s' clashes with field name" % key for member in members: assert member in elements, "Group member '%s' is not a valid field" % member # Check that the names of the elements are not going to clash with a model field for key in elements: assert key not in RESERVED_FIELD_NAMES, "Field name '%s' is not allowed" % key # Preprocessing complete, here is the new class new_class = type.__new__(cls, name, bases, attrs) options.metadata = new_class new_class._meta = options # Some useful attributes options._update_from_name(name) options._register_elements(elements) try: for backend_name in options.backends: new_class._meta._add_backend(backend_registry[backend_name]) for backend_name in options.backends: backend_registry[backend_name].validate(options) except KeyError: raise Exception('Metadata backend "%s" is not installed.' % backend_name) #new_class._meta._add_backend(PathBackend) #new_class._meta._add_backend(ModelInstanceBackend) #new_class._meta._add_backend(ModelBackend) #new_class._meta._add_backend(ViewBackend) registry[name] = new_class return new_class # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_formatted_data(cls, path, context=None, site=None, language=None): """ Return an object to conveniently access the appropriate values. """ return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context } for model in cls._meta.models.values(): for instance in model.objects.get_instances(path, site, language, backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance class Metadata(object): __metaclass__ = MetadataBase def _get_metadata_model(name=None): # Find registered Metadata object if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = u'Try using the name "%s" or simply leaving it out altogether.'% registry.keys()[0] else: valid_names = u"Valid names are " + u", ".join(u'"%s"' % k for k in registry.keys()) raise Exception(u"Metadata definition with name \"%s\" does not exist.\n%s" % (name, valid_names)) else: assert len(registry) == 1, "You must have exactly one Metadata class, if using get_metadata() without a 'name' parameter." return registry.values()[0] def get_metadata(path, name=None, context=None, site=None, language=None): metadata = _get_metadata_model(name) return metadata._get_formatted_data(path, context, site, language) def get_linked_metadata(obj, name=None, context=None, site=None, language=None): """ Gets metadata linked from the given object. """ # XXX Check that 'modelinstance' and 'model' metadata are installed in backends # I believe that get_model() would return None if not Metadata = _get_metadata_model(name) InstanceMetadata = Metadata._meta.get_model('modelinstance') ModelMetadata = Metadata._meta.get_model('model') content_type = ContentType.objects.get_for_model(obj) instances = [] if InstanceMetadata is not None: try: instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk) except InstanceMetadata.DoesNotExist: instance_md = InstanceMetadata(_content_object=obj) instances.append(instance_md) if ModelMetadata is not None: try: model_md = ModelMetadata.objects.get(_content_type=content_type) except ModelMetadata.DoesNotExist: model_md = ModelMetadata(_content_type=content_type) instances.append(model_md) return FormattedMetadata(Metadata, instances, '', site, language) def create_metadata_instance(metadata_class, instance): # If this instance is marked as handled, don't do anything # This typically means that the django admin will add metadata # using eg an inline. if getattr(instance, '_MetadataFormset__seo_metadata_handled', False): return metadata = None content_type = ContentType.objects.get_for_model(instance) # If this object does not define a path, don't worry about automatic update try: path = instance.get_absolute_url() except AttributeError: return # Look for an existing object with this path language = getattr(instance, '_language', None) site = getattr(instance, '_site', None) for md in metadata_class.objects.get_instances(path, site, language): # If another object has the same path, remove the path. # It's harsh, but we need a unique path and will assume the other # link is outdated. if md._content_type != content_type or md._object_id != instance.pk: md._path = md._content_object.get_absolute_url() md.save() # Move on, this metadata instance isn't for us md = None else: # This is our instance! metadata = md # If the path-based search didn't work, look for (or create) an existing # instance linked to this object. if not metadata:
def populate_metadata(model, MetadataClass): """ For a given model and metadata class, ensure there is metadata for every instance. """ content_type = ContentType.objects.get_for_model(model) for instance in model.objects.all(): create_metadata_instance(MetadataClass, instance) def _update_callback(model_class, sender, instance, created, **kwargs): """ Callback to be attached to a post_save signal, updating the relevant metadata, or just creating an entry. NB: It is theoretically possible that this code will lead to two instances with the same generic foreign key. If you have non-overlapping URLs, then this shouldn't happen. I've held it to be more important to avoid double path entries. """ create_metadata_instance(model_class, instance) def _delete_callback(model_class, sender, instance, **kwargs): content_type = ContentType.objects.get_for_model(instance) model_class.objects.filter(_content_type=content_type, _object_id=instance.pk).delete() def register_signals(): for metadata_class in registry.values(): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = curry(_update_callback, model_class=model_instance) delete_callback = curry(_delete_callback, model_class=model_instance) ## Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False)
metadata, md_created = metadata_class.objects.get_or_create(_content_type=content_type, _object_id=instance.pk) metadata._path = path metadata.save()
conditional_block
base.py
# -*- coding: utf-8 -*- # TODO: # * Move/rename namespace polluting attributes # * Documentation # * Make backends optional: Meta.backends = (path, modelinstance/model, view) import hashlib from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.datastructures import SortedDict from django.utils.functional import curry from django.contrib.sites.models import Site from django.contrib.contenttypes.models import ContentType from django.conf import settings from django.utils.safestring import mark_safe from django.core.cache import cache from django.utils.encoding import iri_to_uri from rollyourown.seo.utils import NotSet, Literal from rollyourown.seo.options import Options from rollyourown.seo.fields import MetadataField, Tag, MetaTag, KeywordTag, Raw from rollyourown.seo.backends import backend_registry, RESERVED_FIELD_NAMES registry = SortedDict() class FormattedMetadata(object): """ Allows convenient access to selected metadata. Metadata for each field may be sourced from any one of the relevant instances passed. """ def __init__(self, metadata, instances, path, site=None, language=None): self.__metadata = metadata if metadata._meta.use_cache: if metadata._meta.use_sites and site: hexpath = hashlib.md5(iri_to_uri(site.domain+path)).hexdigest() else: hexpath = hashlib.md5(iri_to_uri(path)).hexdigest() if metadata._meta.use_i18n: self.__cache_prefix = 'rollyourown.seo.%s.%s.%s' % (self.__metadata.__class__.__name__, hexpath, language) else: self.__cache_prefix = 'rollyourown.seo.%s.%s' % (self.__metadata.__class__.__name__, hexpath) else: self.__cache_prefix = None self.__instances_original = instances self.__instances_cache = [] def __instances(self): """ Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. """ for instance in self.__instances_cache: yield instance for instance in self.__instances_original: self.__instances_cache.append(instance) yield instance def _resolve_value(self, name):
def __getattr__(self, name): # If caching is enabled, work out a key if self.__cache_prefix: cache_key = '%s.%s' % (self.__cache_prefix, name) value = cache.get(cache_key) else: cache_key = None value = None # Look for a group called "name" if name in self.__metadata._meta.groups: if value is not None: return value or None value = '\n'.join(unicode(BoundMetadataField(self.__metadata._meta.elements[f], self._resolve_value(f))) for f in self.__metadata._meta.groups[name]).strip() # Look for an element called "name" elif name in self.__metadata._meta.elements: if value is not None: return BoundMetadataField(self.__metadata._meta.elements[name], value or None) value = self._resolve_value(name) if cache_key is not None: cache.set(cache_key, value or '') return BoundMetadataField(self.__metadata._meta.elements[name], value) else: raise AttributeError if cache_key is not None: cache.set(cache_key, value or '') return value or None def __unicode__(self): """ String version of this object is the html output of head elements. """ if self.__cache_prefix is not None: value = cache.get(self.__cache_prefix) else: value = None if value is None: value = mark_safe(u'\n'.join(unicode(getattr(self, f)) for f,e in self.__metadata._meta.elements.items() if e.head)) if self.__cache_prefix is not None: cache.set(self.__cache_prefix, value or '') return value class BoundMetadataField(object): """ An object to help provide templates with access to a "bound" metadata field. """ def __init__(self, field, value): self.field = field if value: self.value = field.clean(value) else: self.value = None def __unicode__(self): if self.value: return mark_safe(self.field.render(self.value)) else: return u"" def __str__(self): return self.__unicode__().encode("ascii", "ignore") class MetadataBase(type): def __new__(cls, name, bases, attrs): # TODO: Think of a better test to avoid processing Metadata parent class if bases == (object,): return type.__new__(cls, name, bases, attrs) # Save options as a dict for now (we will be editing them) # TODO: Is this necessary, should we bother relaying Django Meta options? Meta = attrs.pop('Meta', {}) if Meta: Meta = Meta.__dict__.copy() # Remove our options from Meta, so Django won't complain help_text = attrs.pop('HelpText', {}) # TODO: Is this necessary if help_text: help_text = help_text.__dict__.copy() options = Options(Meta, help_text) # Collect and sort our elements elements = [(key, attrs.pop(key)) for key, obj in attrs.items() if isinstance(obj, MetadataField)] elements.sort(lambda x, y: cmp(x[1].creation_counter, y[1].creation_counter)) elements = SortedDict(elements) # Validation: # TODO: Write a test framework for seo.Metadata validation # Check that no group names clash with element names for key,members in options.groups.items(): assert key not in elements, "Group name '%s' clashes with field name" % key for member in members: assert member in elements, "Group member '%s' is not a valid field" % member # Check that the names of the elements are not going to clash with a model field for key in elements: assert key not in RESERVED_FIELD_NAMES, "Field name '%s' is not allowed" % key # Preprocessing complete, here is the new class new_class = type.__new__(cls, name, bases, attrs) options.metadata = new_class new_class._meta = options # Some useful attributes options._update_from_name(name) options._register_elements(elements) try: for backend_name in options.backends: new_class._meta._add_backend(backend_registry[backend_name]) for backend_name in options.backends: backend_registry[backend_name].validate(options) except KeyError: raise Exception('Metadata backend "%s" is not installed.' % backend_name) #new_class._meta._add_backend(PathBackend) #new_class._meta._add_backend(ModelInstanceBackend) #new_class._meta._add_backend(ModelBackend) #new_class._meta._add_backend(ViewBackend) registry[name] = new_class return new_class # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_formatted_data(cls, path, context=None, site=None, language=None): """ Return an object to conveniently access the appropriate values. """ return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, site, language) # TODO: Move this function out of the way (subclasses will want to define their own attributes) def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. """ backend_context = {'view_context': context } for model in cls._meta.models.values(): for instance in model.objects.get_instances(path, site, language, backend_context) or []: if hasattr(instance, '_process_context'): instance._process_context(backend_context) yield instance class Metadata(object): __metaclass__ = MetadataBase def _get_metadata_model(name=None): # Find registered Metadata object if name is not None: try: return registry[name] except KeyError: if len(registry) == 1: valid_names = u'Try using the name "%s" or simply leaving it out altogether.'% registry.keys()[0] else: valid_names = u"Valid names are " + u", ".join(u'"%s"' % k for k in registry.keys()) raise Exception(u"Metadata definition with name \"%s\" does not exist.\n%s" % (name, valid_names)) else: assert len(registry) == 1, "You must have exactly one Metadata class, if using get_metadata() without a 'name' parameter." return registry.values()[0] def get_metadata(path, name=None, context=None, site=None, language=None): metadata = _get_metadata_model(name) return metadata._get_formatted_data(path, context, site, language) def get_linked_metadata(obj, name=None, context=None, site=None, language=None): """ Gets metadata linked from the given object. """ # XXX Check that 'modelinstance' and 'model' metadata are installed in backends # I believe that get_model() would return None if not Metadata = _get_metadata_model(name) InstanceMetadata = Metadata._meta.get_model('modelinstance') ModelMetadata = Metadata._meta.get_model('model') content_type = ContentType.objects.get_for_model(obj) instances = [] if InstanceMetadata is not None: try: instance_md = InstanceMetadata.objects.get(_content_type=content_type, _object_id=obj.pk) except InstanceMetadata.DoesNotExist: instance_md = InstanceMetadata(_content_object=obj) instances.append(instance_md) if ModelMetadata is not None: try: model_md = ModelMetadata.objects.get(_content_type=content_type) except ModelMetadata.DoesNotExist: model_md = ModelMetadata(_content_type=content_type) instances.append(model_md) return FormattedMetadata(Metadata, instances, '', site, language) def create_metadata_instance(metadata_class, instance): # If this instance is marked as handled, don't do anything # This typically means that the django admin will add metadata # using eg an inline. if getattr(instance, '_MetadataFormset__seo_metadata_handled', False): return metadata = None content_type = ContentType.objects.get_for_model(instance) # If this object does not define a path, don't worry about automatic update try: path = instance.get_absolute_url() except AttributeError: return # Look for an existing object with this path language = getattr(instance, '_language', None) site = getattr(instance, '_site', None) for md in metadata_class.objects.get_instances(path, site, language): # If another object has the same path, remove the path. # It's harsh, but we need a unique path and will assume the other # link is outdated. if md._content_type != content_type or md._object_id != instance.pk: md._path = md._content_object.get_absolute_url() md.save() # Move on, this metadata instance isn't for us md = None else: # This is our instance! metadata = md # If the path-based search didn't work, look for (or create) an existing # instance linked to this object. if not metadata: metadata, md_created = metadata_class.objects.get_or_create(_content_type=content_type, _object_id=instance.pk) metadata._path = path metadata.save() def populate_metadata(model, MetadataClass): """ For a given model and metadata class, ensure there is metadata for every instance. """ content_type = ContentType.objects.get_for_model(model) for instance in model.objects.all(): create_metadata_instance(MetadataClass, instance) def _update_callback(model_class, sender, instance, created, **kwargs): """ Callback to be attached to a post_save signal, updating the relevant metadata, or just creating an entry. NB: It is theoretically possible that this code will lead to two instances with the same generic foreign key. If you have non-overlapping URLs, then this shouldn't happen. I've held it to be more important to avoid double path entries. """ create_metadata_instance(model_class, instance) def _delete_callback(model_class, sender, instance, **kwargs): content_type = ContentType.objects.get_for_model(instance) model_class.objects.filter(_content_type=content_type, _object_id=instance.pk).delete() def register_signals(): for metadata_class in registry.values(): model_instance = metadata_class._meta.get_model('modelinstance') if model_instance is not None: update_callback = curry(_update_callback, model_class=model_instance) delete_callback = curry(_delete_callback, model_class=model_instance) ## Connect the models listed in settings to the update callback. for model in metadata_class._meta.seo_models: models.signals.post_save.connect(update_callback, sender=model, weak=False) models.signals.pre_delete.connect(delete_callback, sender=model, weak=False)
""" Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ for instance in self.__instances(): value = instance._resolve_value(name) if value: return value # Otherwise, return an appropriate default value (populate_from) # TODO: This is duplicated in meta_models. Move this to a common home. if name in self.__metadata._meta.elements: populate_from = self.__metadata._meta.elements[name].populate_from if callable(populate_from): return populate_from(None) elif isinstance(populate_from, Literal): return populate_from.value elif populate_from is not NotSet: return self._resolve_value(populate_from)
identifier_body
cli.rs
extern crate tetrs; use std::io::prelude::*; // FIXME! Little hack to clear the screen :) extern "C" { fn system(s: *const u8); } fn clear_screen() { unsafe { system("@clear||cls\0".as_ptr()); }} #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum Input { None, Left, Right, RotateCW, RotateCCW, SoftDrop, HardDrop, Gravity, Quit, Help, Invalid, } fn input() -> Input
fn bot(state: &mut tetrs::State) -> bool { let weights = tetrs::Weights::default(); let bot = tetrs::PlayI::play(&weights, state.well(), *state.player().unwrap()); if bot.play.len() == 0 { state.hard_drop(); return false; } let mut result = true; for play in bot.play { use tetrs::Play; result &= match play { Play::MoveLeft => state.move_left(), Play::MoveRight => state.move_right(), Play::RotateCW => state.rotate_cw(), Play::RotateCCW => state.rotate_ccw(), Play::SoftDrop => state.soft_drop(), Play::HardDrop => state.hard_drop(), Play::Idle => true, }; if !result { break; } } result } static TILESET: [char; 32] = [ 'O', 'I', 'S', 'Z', 'L', 'J', 'T', 'x', '_', '_', '_', '_', '_', '_', '_', 'x', 'O', 'I', 'S', 'Z', 'L', 'J', 'T', '□', '.', '_', ' ', 'x', 'x', 'x', 'x', 'x', ]; fn draw(scene: &tetrs::Scene) { for row in 0..scene.height() { print!("|"); let line = scene.line(row); for &tile in line { let tile: u8 = tile.into(); let c = TILESET[(tile >> 3) as usize]; print!("{}", c); } print!("|\n"); } print!("+"); for _ in 0..scene.width() { print!("-"); } print!("+\n"); } const WELCOME_MESSAGE: &'static str = " Welcome to Adventure Tetrs! After the playing field is shown, you will be asked for input. >>> A, Q, LEFT Move the piece to the left. >>> D, RIGHT Move the piece to the right. >>> CW, RR, ROT Rotate the piece clockwise. >>> CCW, RL Rotate the piece counter-clockwise. >>> S, DOWN, SOFT, SOFT DROP Soft drop, move the piece down once. >>> W, Z, DROP, HARD DROP Hard drop, drops the piece down and locks into place. >>> G, GRAVITY Apply gravity, same as a soft drop. >>> QUIT, QUTI Quit the game. >>> H, HELP Print this help message. "; fn main() { clear_screen(); println!("{}", WELCOME_MESSAGE); use tetrs::Bag; let mut state = tetrs::State::new(10, 22); let mut bag = tetrs::OfficialBag::default(); let mut next_piece = bag.next(state.well()).unwrap(); state.spawn(next_piece); loop { draw(&state.scene()); // Check for pieces in the spawning area if state.is_game_over() { println!("Game Over!"); break; } match input() { Input::None => bot(&mut state), Input::Quit => break, Input::Left => state.move_left(), Input::Right => state.move_right(), Input::RotateCW => state.rotate_cw(), Input::RotateCCW => state.rotate_ccw(), Input::SoftDrop => state.soft_drop(), Input::HardDrop => state.hard_drop(), Input::Gravity => state.gravity(), _ => true, }; // Spawn a new piece as needed if state.player().is_none() { next_piece = bag.next(state.well()).unwrap(); if state.spawn(next_piece) { println!("Game Over!"); break; } } state.clear_lines(|_| ()); clear_screen(); } println!("Thanks for playing!"); }
{ print!(">>> "); std::io::stdout().flush().unwrap(); let mut action = String::new(); std::io::stdin().read_line(&mut action).unwrap(); match &*action.trim().to_uppercase() { "" => Input::None, "A" | "Q" | "LEFT" => Input::Left, "D" | "RIGHT" => Input::Right, "CW" | "RR" | "ROT" => Input::RotateCW, "CCW" | "RL" => Input::RotateCCW, "S" | "DOWN" | "SOFT" | "SOFT DROP" => Input::SoftDrop, "W" | "Z" | "DROP" | "HARD DROP" => Input::HardDrop, "G" | "GRAVITY" => Input::Gravity, "QUIT" | "QUTI" => Input::Quit, "H" | "HELP" => Input::Help, _ => Input::Invalid, } }
identifier_body
cli.rs
extern crate tetrs; use std::io::prelude::*; // FIXME! Little hack to clear the screen :) extern "C" { fn system(s: *const u8); } fn clear_screen() { unsafe { system("@clear||cls\0".as_ptr()); }} #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum
{ None, Left, Right, RotateCW, RotateCCW, SoftDrop, HardDrop, Gravity, Quit, Help, Invalid, } fn input() -> Input { print!(">>> "); std::io::stdout().flush().unwrap(); let mut action = String::new(); std::io::stdin().read_line(&mut action).unwrap(); match &*action.trim().to_uppercase() { "" => Input::None, "A" | "Q" | "LEFT" => Input::Left, "D" | "RIGHT" => Input::Right, "CW" | "RR" | "ROT" => Input::RotateCW, "CCW" | "RL" => Input::RotateCCW, "S" | "DOWN" | "SOFT" | "SOFT DROP" => Input::SoftDrop, "W" | "Z" | "DROP" | "HARD DROP" => Input::HardDrop, "G" | "GRAVITY" => Input::Gravity, "QUIT" | "QUTI" => Input::Quit, "H" | "HELP" => Input::Help, _ => Input::Invalid, } } fn bot(state: &mut tetrs::State) -> bool { let weights = tetrs::Weights::default(); let bot = tetrs::PlayI::play(&weights, state.well(), *state.player().unwrap()); if bot.play.len() == 0 { state.hard_drop(); return false; } let mut result = true; for play in bot.play { use tetrs::Play; result &= match play { Play::MoveLeft => state.move_left(), Play::MoveRight => state.move_right(), Play::RotateCW => state.rotate_cw(), Play::RotateCCW => state.rotate_ccw(), Play::SoftDrop => state.soft_drop(), Play::HardDrop => state.hard_drop(), Play::Idle => true, }; if !result { break; } } result } static TILESET: [char; 32] = [ 'O', 'I', 'S', 'Z', 'L', 'J', 'T', 'x', '_', '_', '_', '_', '_', '_', '_', 'x', 'O', 'I', 'S', 'Z', 'L', 'J', 'T', '□', '.', '_', ' ', 'x', 'x', 'x', 'x', 'x', ]; fn draw(scene: &tetrs::Scene) { for row in 0..scene.height() { print!("|"); let line = scene.line(row); for &tile in line { let tile: u8 = tile.into(); let c = TILESET[(tile >> 3) as usize]; print!("{}", c); } print!("|\n"); } print!("+"); for _ in 0..scene.width() { print!("-"); } print!("+\n"); } const WELCOME_MESSAGE: &'static str = " Welcome to Adventure Tetrs! After the playing field is shown, you will be asked for input. >>> A, Q, LEFT Move the piece to the left. >>> D, RIGHT Move the piece to the right. >>> CW, RR, ROT Rotate the piece clockwise. >>> CCW, RL Rotate the piece counter-clockwise. >>> S, DOWN, SOFT, SOFT DROP Soft drop, move the piece down once. >>> W, Z, DROP, HARD DROP Hard drop, drops the piece down and locks into place. >>> G, GRAVITY Apply gravity, same as a soft drop. >>> QUIT, QUTI Quit the game. >>> H, HELP Print this help message. "; fn main() { clear_screen(); println!("{}", WELCOME_MESSAGE); use tetrs::Bag; let mut state = tetrs::State::new(10, 22); let mut bag = tetrs::OfficialBag::default(); let mut next_piece = bag.next(state.well()).unwrap(); state.spawn(next_piece); loop { draw(&state.scene()); // Check for pieces in the spawning area if state.is_game_over() { println!("Game Over!"); break; } match input() { Input::None => bot(&mut state), Input::Quit => break, Input::Left => state.move_left(), Input::Right => state.move_right(), Input::RotateCW => state.rotate_cw(), Input::RotateCCW => state.rotate_ccw(), Input::SoftDrop => state.soft_drop(), Input::HardDrop => state.hard_drop(), Input::Gravity => state.gravity(), _ => true, }; // Spawn a new piece as needed if state.player().is_none() { next_piece = bag.next(state.well()).unwrap(); if state.spawn(next_piece) { println!("Game Over!"); break; } } state.clear_lines(|_| ()); clear_screen(); } println!("Thanks for playing!"); }
Input
identifier_name
cli.rs
extern crate tetrs; use std::io::prelude::*; // FIXME! Little hack to clear the screen :) extern "C" { fn system(s: *const u8); } fn clear_screen() { unsafe { system("@clear||cls\0".as_ptr()); }} #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum Input { None, Left, Right, RotateCW, RotateCCW, SoftDrop, HardDrop, Gravity, Quit, Help, Invalid, } fn input() -> Input { print!(">>> "); std::io::stdout().flush().unwrap(); let mut action = String::new(); std::io::stdin().read_line(&mut action).unwrap(); match &*action.trim().to_uppercase() { "" => Input::None, "A" | "Q" | "LEFT" => Input::Left, "D" | "RIGHT" => Input::Right, "CW" | "RR" | "ROT" => Input::RotateCW, "CCW" | "RL" => Input::RotateCCW, "S" | "DOWN" | "SOFT" | "SOFT DROP" => Input::SoftDrop, "W" | "Z" | "DROP" | "HARD DROP" => Input::HardDrop, "G" | "GRAVITY" => Input::Gravity, "QUIT" | "QUTI" => Input::Quit,
"H" | "HELP" => Input::Help, _ => Input::Invalid, } } fn bot(state: &mut tetrs::State) -> bool { let weights = tetrs::Weights::default(); let bot = tetrs::PlayI::play(&weights, state.well(), *state.player().unwrap()); if bot.play.len() == 0 { state.hard_drop(); return false; } let mut result = true; for play in bot.play { use tetrs::Play; result &= match play { Play::MoveLeft => state.move_left(), Play::MoveRight => state.move_right(), Play::RotateCW => state.rotate_cw(), Play::RotateCCW => state.rotate_ccw(), Play::SoftDrop => state.soft_drop(), Play::HardDrop => state.hard_drop(), Play::Idle => true, }; if !result { break; } } result } static TILESET: [char; 32] = [ 'O', 'I', 'S', 'Z', 'L', 'J', 'T', 'x', '_', '_', '_', '_', '_', '_', '_', 'x', 'O', 'I', 'S', 'Z', 'L', 'J', 'T', '□', '.', '_', ' ', 'x', 'x', 'x', 'x', 'x', ]; fn draw(scene: &tetrs::Scene) { for row in 0..scene.height() { print!("|"); let line = scene.line(row); for &tile in line { let tile: u8 = tile.into(); let c = TILESET[(tile >> 3) as usize]; print!("{}", c); } print!("|\n"); } print!("+"); for _ in 0..scene.width() { print!("-"); } print!("+\n"); } const WELCOME_MESSAGE: &'static str = " Welcome to Adventure Tetrs! After the playing field is shown, you will be asked for input. >>> A, Q, LEFT Move the piece to the left. >>> D, RIGHT Move the piece to the right. >>> CW, RR, ROT Rotate the piece clockwise. >>> CCW, RL Rotate the piece counter-clockwise. >>> S, DOWN, SOFT, SOFT DROP Soft drop, move the piece down once. >>> W, Z, DROP, HARD DROP Hard drop, drops the piece down and locks into place. >>> G, GRAVITY Apply gravity, same as a soft drop. >>> QUIT, QUTI Quit the game. >>> H, HELP Print this help message. "; fn main() { clear_screen(); println!("{}", WELCOME_MESSAGE); use tetrs::Bag; let mut state = tetrs::State::new(10, 22); let mut bag = tetrs::OfficialBag::default(); let mut next_piece = bag.next(state.well()).unwrap(); state.spawn(next_piece); loop { draw(&state.scene()); // Check for pieces in the spawning area if state.is_game_over() { println!("Game Over!"); break; } match input() { Input::None => bot(&mut state), Input::Quit => break, Input::Left => state.move_left(), Input::Right => state.move_right(), Input::RotateCW => state.rotate_cw(), Input::RotateCCW => state.rotate_ccw(), Input::SoftDrop => state.soft_drop(), Input::HardDrop => state.hard_drop(), Input::Gravity => state.gravity(), _ => true, }; // Spawn a new piece as needed if state.player().is_none() { next_piece = bag.next(state.well()).unwrap(); if state.spawn(next_piece) { println!("Game Over!"); break; } } state.clear_lines(|_| ()); clear_screen(); } println!("Thanks for playing!"); }
random_line_split
main.py
import sys def row_matrix_to_col_matrix(row_matrix): col_matrix = [] for c in range(len(row_matrix)): col_matrix.append([]) for r in range(len(row_matrix)): for c in range(len(row_matrix)): col_matrix[c].append(row_matrix[r][c]) return col_matrix def col_matrix_to_row_matrix(col_matrix): row_matrix = [] for r in range(len(col_matrix)): row_matrix.append([]) for c in range(len(col_matrix)): for r in range(len(col_matrix)): row_matrix[r].append(col_matrix[c][r]) return row_matrix def matrix_compare(a, b): length = min(len(a), len(b)) index = 0 while index < length: if a[index] != b[index]: return a[index] - b[index] index += 1
for test in test_cases: test = test.strip() if len(test) == 0: continue m = row_matrix_to_col_matrix([[int(i) for i in s.strip().split(' ')] for s in test.split('|')]) print(' | '.join([' '.join([str(e) for e in r]) for r in col_matrix_to_row_matrix(sorted(m, cmp=matrix_compare))])) test_cases.close() if __name__ == '__main__': main()
return 0 def main(): test_cases = open(sys.argv[1], 'r')
random_line_split
main.py
import sys def row_matrix_to_col_matrix(row_matrix):
def col_matrix_to_row_matrix(col_matrix): row_matrix = [] for r in range(len(col_matrix)): row_matrix.append([]) for c in range(len(col_matrix)): for r in range(len(col_matrix)): row_matrix[r].append(col_matrix[c][r]) return row_matrix def matrix_compare(a, b): length = min(len(a), len(b)) index = 0 while index < length: if a[index] != b[index]: return a[index] - b[index] index += 1 return 0 def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() if len(test) == 0: continue m = row_matrix_to_col_matrix([[int(i) for i in s.strip().split(' ')] for s in test.split('|')]) print(' | '.join([' '.join([str(e) for e in r]) for r in col_matrix_to_row_matrix(sorted(m, cmp=matrix_compare))])) test_cases.close() if __name__ == '__main__': main()
col_matrix = [] for c in range(len(row_matrix)): col_matrix.append([]) for r in range(len(row_matrix)): for c in range(len(row_matrix)): col_matrix[c].append(row_matrix[r][c]) return col_matrix
identifier_body
main.py
import sys def row_matrix_to_col_matrix(row_matrix): col_matrix = [] for c in range(len(row_matrix)): col_matrix.append([]) for r in range(len(row_matrix)): for c in range(len(row_matrix)): col_matrix[c].append(row_matrix[r][c]) return col_matrix def col_matrix_to_row_matrix(col_matrix): row_matrix = [] for r in range(len(col_matrix)): row_matrix.append([]) for c in range(len(col_matrix)): for r in range(len(col_matrix)): row_matrix[r].append(col_matrix[c][r]) return row_matrix def
(a, b): length = min(len(a), len(b)) index = 0 while index < length: if a[index] != b[index]: return a[index] - b[index] index += 1 return 0 def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases: test = test.strip() if len(test) == 0: continue m = row_matrix_to_col_matrix([[int(i) for i in s.strip().split(' ')] for s in test.split('|')]) print(' | '.join([' '.join([str(e) for e in r]) for r in col_matrix_to_row_matrix(sorted(m, cmp=matrix_compare))])) test_cases.close() if __name__ == '__main__': main()
matrix_compare
identifier_name
main.py
import sys def row_matrix_to_col_matrix(row_matrix): col_matrix = [] for c in range(len(row_matrix)): col_matrix.append([]) for r in range(len(row_matrix)): for c in range(len(row_matrix)): col_matrix[c].append(row_matrix[r][c]) return col_matrix def col_matrix_to_row_matrix(col_matrix): row_matrix = [] for r in range(len(col_matrix)): row_matrix.append([]) for c in range(len(col_matrix)): for r in range(len(col_matrix)): row_matrix[r].append(col_matrix[c][r]) return row_matrix def matrix_compare(a, b): length = min(len(a), len(b)) index = 0 while index < length: if a[index] != b[index]: return a[index] - b[index] index += 1 return 0 def main(): test_cases = open(sys.argv[1], 'r') for test in test_cases:
test_cases.close() if __name__ == '__main__': main()
test = test.strip() if len(test) == 0: continue m = row_matrix_to_col_matrix([[int(i) for i in s.strip().split(' ')] for s in test.split('|')]) print(' | '.join([' '.join([str(e) for e in r]) for r in col_matrix_to_row_matrix(sorted(m, cmp=matrix_compare))]))
conditional_block
index.tsx
import React from 'react' import onClickOutside from 'react-onclickoutside' import isEqual from 'lodash/isEqual' import styled, { ThemeProvider } from 'styled-components' import { StatefulUIElement } from 'src/util/ui-logic' import ListPickerLogic, { ListPickerDependencies, ListPickerEvent, ListPickerState, } from 'src/custom-lists/ui/CollectionPicker/logic' import { PickerSearchInput } from 'src/common-ui/GenericPicker/components/SearchInput' import AddNewEntry from 'src/common-ui/GenericPicker/components/AddNewEntry' import LoadingIndicator from 'src/common-ui/components/LoadingIndicator' import EntryResultsList from 'src/common-ui/GenericPicker/components/EntryResultsList' import EntryRow, { IconStyleWrapper, ActOnAllTabsButton, } from 'src/common-ui/GenericPicker/components/EntryRow' import { KeyEvent, DisplayEntry } from 'src/common-ui/GenericPicker/types' import * as Colors from 'src/common-ui/components/design-library/colors' import { fontSizeNormal } from 'src/common-ui/components/design-library/typography' import ButtonTooltip from 'src/common-ui/components/button-tooltip' import { EntrySelectedList } from './components/EntrySelectedList' import { ListResultItem } from './components/ListResultItem' import { collections, contentSharing, } from 'src/util/remote-functions-background' class ListPicker extends StatefulUIElement< ListPickerDependencies, ListPickerState, ListPickerEvent > { static defaultProps: Partial<ListPickerDependencies> = { queryEntries: (query) => collections.searchForListSuggestions({ query }), loadDefaultSuggestions: collections.fetchInitialListSuggestions, loadRemoteListNames: async () => { const remoteLists = await contentSharing.getAllRemoteLists() return remoteLists.map((list) => list.name) }, } constructor(props: ListPickerDependencies) { super(props, new ListPickerLogic(props)) } searchInputPlaceholder = this.props.searchInputPlaceholder ?? 'Add to Collection' removeToolTipText = this.props.removeToolTipText ?? 'Remove from list' componentDidUpdate( prevProps: ListPickerDependencies, prevState: ListPickerState, ) { if (prevProps.query !== this.props.query) { this.processEvent('searchInputChanged', { query: this.props.query }) } const prev = prevState.selectedEntries const curr = this.state.selectedEntries if (prev.length !== curr.length || !isEqual(prev, curr)) { this.props.onSelectedEntriesChange?.({ selectedEntries: this.state.selectedEntries, }) } } private isListRemote = (name: string): boolean => this.state.remoteLists.has(name) handleClickOutside = (e) => { if (this.props.onClickOutside) { this.props.onClickOutside(e) } } handleSetSearchInputRef = (ref: HTMLInputElement) => this.processEvent('setSearchInputRef', { ref }) handleOuterSearchBoxClick = () => this.processEvent('focusInput', {}) handleSearchInputChanged = (query: string) => { this.props.onSearchInputChange?.({ query }) return this.processEvent('searchInputChanged', { query }) } handleSelectedListPress = (list: string) => this.processEvent('selectedEntryPress', { entry: list }) handleResultListPress = (list: DisplayEntry) => this.processEvent('resultEntryPress', { entry: list }) handleResultListAllPress = (list: DisplayEntry) => this.processEvent('resultEntryAllPress', { entry: list }) handleNewListAllPress = () => this.processEvent('newEntryAllPress', { entry: this.state.newEntryName, }) handleResultListFocus = (list: DisplayEntry, index?: number) => this.processEvent('resultEntryFocus', { entry: list, index }) handleNewListPress = () => this.processEvent('newEntryPress', { entry: this.state.newEntryName }) handleKeyPress = (key: KeyEvent) => this.processEvent('keyPress', { key }) renderListRow = (list: DisplayEntry, index: number) => ( <EntryRow onPress={this.handleResultListPress} onPressActOnAll={ this.props.actOnAllTabs ? (t) => this.handleResultListAllPress(t) : undefined } onFocus={this.handleResultListFocus} key={`ListKeyName-${list.name}`} index={index} name={list.name} selected={list.selected} focused={list.focused} remote={this.isListRemote(list.name)} resultItem={<ListResultItem>{list.name}</ListResultItem>} removeTooltipText={this.removeToolTipText} actOnAllTooltipText="Add all tabs in window to list"
this.props.actOnAllTabs && ( <IconStyleWrapper show> <ButtonTooltip tooltipText="List all tabs in window" position="left" > <ActOnAllTabsButton size={20} onClick={this.handleNewListAllPress} /> </ButtonTooltip> </IconStyleWrapper> ) renderEmptyList() { if (this.state.newEntryName !== '') { return } return ( <EmptyListsView> <strong>No Collections yet</strong> <br /> Add new collections <br /> via the search bar </EmptyListsView> ) } renderMainContent() { if (this.state.loadingSuggestions) { return ( <LoadingBox> <LoadingIndicator /> </LoadingBox> ) } return ( <> <PickerSearchInput searchInputPlaceholder={this.searchInputPlaceholder} showPlaceholder={this.state.selectedEntries.length === 0} searchInputRef={this.handleSetSearchInputRef} onChange={this.handleSearchInputChanged} onKeyPress={this.handleKeyPress} value={this.state.query} loading={this.state.loadingQueryResults} before={ <EntrySelectedList dataAttributeName="list-name" entriesSelected={this.state.selectedEntries} onPress={this.handleSelectedListPress} /> } /> <EntryResultsList entries={this.state.displayEntries} renderEntryRow={this.renderListRow} emptyView={this.renderEmptyList()} id="listResults" /> {this.state.newEntryName !== '' && ( <AddNewEntry resultItem={ <ListResultItem> {this.state.newEntryName} </ListResultItem> } onPress={this.handleNewListPress} > {this.renderNewListAllTabsButton()} </AddNewEntry> )} </> ) } render() { return ( <ThemeProvider theme={Colors.lightTheme}> <OuterSearchBox onKeyPress={this.handleKeyPress} onClick={this.handleOuterSearchBoxClick} > {this.renderMainContent()} {this.props.children} </OuterSearchBox> </ThemeProvider> ) } } const LoadingBox = styled.div` display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; ` const OuterSearchBox = styled.div` background: ${(props) => props.theme.background}; padding-top: 8px; padding-bottom: 8px; border-radius: 3px; ` const EmptyListsView = styled.div` color: ${(props) => props.theme.tag.text}; padding: 10px 15px; font-weight: 400; font-size: ${fontSizeNormal}px; text-align: center; ` export default onClickOutside(ListPicker)
/> ) renderNewListAllTabsButton = () =>
random_line_split
index.tsx
import React from 'react' import onClickOutside from 'react-onclickoutside' import isEqual from 'lodash/isEqual' import styled, { ThemeProvider } from 'styled-components' import { StatefulUIElement } from 'src/util/ui-logic' import ListPickerLogic, { ListPickerDependencies, ListPickerEvent, ListPickerState, } from 'src/custom-lists/ui/CollectionPicker/logic' import { PickerSearchInput } from 'src/common-ui/GenericPicker/components/SearchInput' import AddNewEntry from 'src/common-ui/GenericPicker/components/AddNewEntry' import LoadingIndicator from 'src/common-ui/components/LoadingIndicator' import EntryResultsList from 'src/common-ui/GenericPicker/components/EntryResultsList' import EntryRow, { IconStyleWrapper, ActOnAllTabsButton, } from 'src/common-ui/GenericPicker/components/EntryRow' import { KeyEvent, DisplayEntry } from 'src/common-ui/GenericPicker/types' import * as Colors from 'src/common-ui/components/design-library/colors' import { fontSizeNormal } from 'src/common-ui/components/design-library/typography' import ButtonTooltip from 'src/common-ui/components/button-tooltip' import { EntrySelectedList } from './components/EntrySelectedList' import { ListResultItem } from './components/ListResultItem' import { collections, contentSharing, } from 'src/util/remote-functions-background' class ListPicker extends StatefulUIElement< ListPickerDependencies, ListPickerState, ListPickerEvent > { static defaultProps: Partial<ListPickerDependencies> = { queryEntries: (query) => collections.searchForListSuggestions({ query }), loadDefaultSuggestions: collections.fetchInitialListSuggestions, loadRemoteListNames: async () => { const remoteLists = await contentSharing.getAllRemoteLists() return remoteLists.map((list) => list.name) }, } constructor(props: ListPickerDependencies) { super(props, new ListPickerLogic(props)) } searchInputPlaceholder = this.props.searchInputPlaceholder ?? 'Add to Collection' removeToolTipText = this.props.removeToolTipText ?? 'Remove from list' componentDidUpdate( prevProps: ListPickerDependencies, prevState: ListPickerState, )
private isListRemote = (name: string): boolean => this.state.remoteLists.has(name) handleClickOutside = (e) => { if (this.props.onClickOutside) { this.props.onClickOutside(e) } } handleSetSearchInputRef = (ref: HTMLInputElement) => this.processEvent('setSearchInputRef', { ref }) handleOuterSearchBoxClick = () => this.processEvent('focusInput', {}) handleSearchInputChanged = (query: string) => { this.props.onSearchInputChange?.({ query }) return this.processEvent('searchInputChanged', { query }) } handleSelectedListPress = (list: string) => this.processEvent('selectedEntryPress', { entry: list }) handleResultListPress = (list: DisplayEntry) => this.processEvent('resultEntryPress', { entry: list }) handleResultListAllPress = (list: DisplayEntry) => this.processEvent('resultEntryAllPress', { entry: list }) handleNewListAllPress = () => this.processEvent('newEntryAllPress', { entry: this.state.newEntryName, }) handleResultListFocus = (list: DisplayEntry, index?: number) => this.processEvent('resultEntryFocus', { entry: list, index }) handleNewListPress = () => this.processEvent('newEntryPress', { entry: this.state.newEntryName }) handleKeyPress = (key: KeyEvent) => this.processEvent('keyPress', { key }) renderListRow = (list: DisplayEntry, index: number) => ( <EntryRow onPress={this.handleResultListPress} onPressActOnAll={ this.props.actOnAllTabs ? (t) => this.handleResultListAllPress(t) : undefined } onFocus={this.handleResultListFocus} key={`ListKeyName-${list.name}`} index={index} name={list.name} selected={list.selected} focused={list.focused} remote={this.isListRemote(list.name)} resultItem={<ListResultItem>{list.name}</ListResultItem>} removeTooltipText={this.removeToolTipText} actOnAllTooltipText="Add all tabs in window to list" /> ) renderNewListAllTabsButton = () => this.props.actOnAllTabs && ( <IconStyleWrapper show> <ButtonTooltip tooltipText="List all tabs in window" position="left" > <ActOnAllTabsButton size={20} onClick={this.handleNewListAllPress} /> </ButtonTooltip> </IconStyleWrapper> ) renderEmptyList() { if (this.state.newEntryName !== '') { return } return ( <EmptyListsView> <strong>No Collections yet</strong> <br /> Add new collections <br /> via the search bar </EmptyListsView> ) } renderMainContent() { if (this.state.loadingSuggestions) { return ( <LoadingBox> <LoadingIndicator /> </LoadingBox> ) } return ( <> <PickerSearchInput searchInputPlaceholder={this.searchInputPlaceholder} showPlaceholder={this.state.selectedEntries.length === 0} searchInputRef={this.handleSetSearchInputRef} onChange={this.handleSearchInputChanged} onKeyPress={this.handleKeyPress} value={this.state.query} loading={this.state.loadingQueryResults} before={ <EntrySelectedList dataAttributeName="list-name" entriesSelected={this.state.selectedEntries} onPress={this.handleSelectedListPress} /> } /> <EntryResultsList entries={this.state.displayEntries} renderEntryRow={this.renderListRow} emptyView={this.renderEmptyList()} id="listResults" /> {this.state.newEntryName !== '' && ( <AddNewEntry resultItem={ <ListResultItem> {this.state.newEntryName} </ListResultItem> } onPress={this.handleNewListPress} > {this.renderNewListAllTabsButton()} </AddNewEntry> )} </> ) } render() { return ( <ThemeProvider theme={Colors.lightTheme}> <OuterSearchBox onKeyPress={this.handleKeyPress} onClick={this.handleOuterSearchBoxClick} > {this.renderMainContent()} {this.props.children} </OuterSearchBox> </ThemeProvider> ) } } const LoadingBox = styled.div` display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; ` const OuterSearchBox = styled.div` background: ${(props) => props.theme.background}; padding-top: 8px; padding-bottom: 8px; border-radius: 3px; ` const EmptyListsView = styled.div` color: ${(props) => props.theme.tag.text}; padding: 10px 15px; font-weight: 400; font-size: ${fontSizeNormal}px; text-align: center; ` export default onClickOutside(ListPicker)
{ if (prevProps.query !== this.props.query) { this.processEvent('searchInputChanged', { query: this.props.query }) } const prev = prevState.selectedEntries const curr = this.state.selectedEntries if (prev.length !== curr.length || !isEqual(prev, curr)) { this.props.onSelectedEntriesChange?.({ selectedEntries: this.state.selectedEntries, }) } }
identifier_body
index.tsx
import React from 'react' import onClickOutside from 'react-onclickoutside' import isEqual from 'lodash/isEqual' import styled, { ThemeProvider } from 'styled-components' import { StatefulUIElement } from 'src/util/ui-logic' import ListPickerLogic, { ListPickerDependencies, ListPickerEvent, ListPickerState, } from 'src/custom-lists/ui/CollectionPicker/logic' import { PickerSearchInput } from 'src/common-ui/GenericPicker/components/SearchInput' import AddNewEntry from 'src/common-ui/GenericPicker/components/AddNewEntry' import LoadingIndicator from 'src/common-ui/components/LoadingIndicator' import EntryResultsList from 'src/common-ui/GenericPicker/components/EntryResultsList' import EntryRow, { IconStyleWrapper, ActOnAllTabsButton, } from 'src/common-ui/GenericPicker/components/EntryRow' import { KeyEvent, DisplayEntry } from 'src/common-ui/GenericPicker/types' import * as Colors from 'src/common-ui/components/design-library/colors' import { fontSizeNormal } from 'src/common-ui/components/design-library/typography' import ButtonTooltip from 'src/common-ui/components/button-tooltip' import { EntrySelectedList } from './components/EntrySelectedList' import { ListResultItem } from './components/ListResultItem' import { collections, contentSharing, } from 'src/util/remote-functions-background' class ListPicker extends StatefulUIElement< ListPickerDependencies, ListPickerState, ListPickerEvent > { static defaultProps: Partial<ListPickerDependencies> = { queryEntries: (query) => collections.searchForListSuggestions({ query }), loadDefaultSuggestions: collections.fetchInitialListSuggestions, loadRemoteListNames: async () => { const remoteLists = await contentSharing.getAllRemoteLists() return remoteLists.map((list) => list.name) }, } constructor(props: ListPickerDependencies) { super(props, new ListPickerLogic(props)) } searchInputPlaceholder = this.props.searchInputPlaceholder ?? 'Add to Collection' removeToolTipText = this.props.removeToolTipText ?? 'Remove from list' componentDidUpdate( prevProps: ListPickerDependencies, prevState: ListPickerState, ) { if (prevProps.query !== this.props.query) { this.processEvent('searchInputChanged', { query: this.props.query }) } const prev = prevState.selectedEntries const curr = this.state.selectedEntries if (prev.length !== curr.length || !isEqual(prev, curr)) { this.props.onSelectedEntriesChange?.({ selectedEntries: this.state.selectedEntries, }) } } private isListRemote = (name: string): boolean => this.state.remoteLists.has(name) handleClickOutside = (e) => { if (this.props.onClickOutside) { this.props.onClickOutside(e) } } handleSetSearchInputRef = (ref: HTMLInputElement) => this.processEvent('setSearchInputRef', { ref }) handleOuterSearchBoxClick = () => this.processEvent('focusInput', {}) handleSearchInputChanged = (query: string) => { this.props.onSearchInputChange?.({ query }) return this.processEvent('searchInputChanged', { query }) } handleSelectedListPress = (list: string) => this.processEvent('selectedEntryPress', { entry: list }) handleResultListPress = (list: DisplayEntry) => this.processEvent('resultEntryPress', { entry: list }) handleResultListAllPress = (list: DisplayEntry) => this.processEvent('resultEntryAllPress', { entry: list }) handleNewListAllPress = () => this.processEvent('newEntryAllPress', { entry: this.state.newEntryName, }) handleResultListFocus = (list: DisplayEntry, index?: number) => this.processEvent('resultEntryFocus', { entry: list, index }) handleNewListPress = () => this.processEvent('newEntryPress', { entry: this.state.newEntryName }) handleKeyPress = (key: KeyEvent) => this.processEvent('keyPress', { key }) renderListRow = (list: DisplayEntry, index: number) => ( <EntryRow onPress={this.handleResultListPress} onPressActOnAll={ this.props.actOnAllTabs ? (t) => this.handleResultListAllPress(t) : undefined } onFocus={this.handleResultListFocus} key={`ListKeyName-${list.name}`} index={index} name={list.name} selected={list.selected} focused={list.focused} remote={this.isListRemote(list.name)} resultItem={<ListResultItem>{list.name}</ListResultItem>} removeTooltipText={this.removeToolTipText} actOnAllTooltipText="Add all tabs in window to list" /> ) renderNewListAllTabsButton = () => this.props.actOnAllTabs && ( <IconStyleWrapper show> <ButtonTooltip tooltipText="List all tabs in window" position="left" > <ActOnAllTabsButton size={20} onClick={this.handleNewListAllPress} /> </ButtonTooltip> </IconStyleWrapper> ) renderEmptyList() {
(this.state.newEntryName !== '') { return } return ( <EmptyListsView> <strong>No Collections yet</strong> <br /> Add new collections <br /> via the search bar </EmptyListsView> ) } renderMainContent() { if (this.state.loadingSuggestions) { return ( <LoadingBox> <LoadingIndicator /> </LoadingBox> ) } return ( <> <PickerSearchInput searchInputPlaceholder={this.searchInputPlaceholder} showPlaceholder={this.state.selectedEntries.length === 0} searchInputRef={this.handleSetSearchInputRef} onChange={this.handleSearchInputChanged} onKeyPress={this.handleKeyPress} value={this.state.query} loading={this.state.loadingQueryResults} before={ <EntrySelectedList dataAttributeName="list-name" entriesSelected={this.state.selectedEntries} onPress={this.handleSelectedListPress} /> } /> <EntryResultsList entries={this.state.displayEntries} renderEntryRow={this.renderListRow} emptyView={this.renderEmptyList()} id="listResults" /> {this.state.newEntryName !== '' && ( <AddNewEntry resultItem={ <ListResultItem> {this.state.newEntryName} </ListResultItem> } onPress={this.handleNewListPress} > {this.renderNewListAllTabsButton()} </AddNewEntry> )} </> ) } render() { return ( <ThemeProvider theme={Colors.lightTheme}> <OuterSearchBox onKeyPress={this.handleKeyPress} onClick={this.handleOuterSearchBoxClick} > {this.renderMainContent()} {this.props.children} </OuterSearchBox> </ThemeProvider> ) } } const LoadingBox = styled.div` display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; ` const OuterSearchBox = styled.div` background: ${(props) => props.theme.background}; padding-top: 8px; padding-bottom: 8px; border-radius: 3px; ` const EmptyListsView = styled.div` color: ${(props) => props.theme.tag.text}; padding: 10px 15px; font-weight: 400; font-size: ${fontSizeNormal}px; text-align: center; ` export default onClickOutside(ListPicker)
if
identifier_name
index.tsx
import React from 'react' import onClickOutside from 'react-onclickoutside' import isEqual from 'lodash/isEqual' import styled, { ThemeProvider } from 'styled-components' import { StatefulUIElement } from 'src/util/ui-logic' import ListPickerLogic, { ListPickerDependencies, ListPickerEvent, ListPickerState, } from 'src/custom-lists/ui/CollectionPicker/logic' import { PickerSearchInput } from 'src/common-ui/GenericPicker/components/SearchInput' import AddNewEntry from 'src/common-ui/GenericPicker/components/AddNewEntry' import LoadingIndicator from 'src/common-ui/components/LoadingIndicator' import EntryResultsList from 'src/common-ui/GenericPicker/components/EntryResultsList' import EntryRow, { IconStyleWrapper, ActOnAllTabsButton, } from 'src/common-ui/GenericPicker/components/EntryRow' import { KeyEvent, DisplayEntry } from 'src/common-ui/GenericPicker/types' import * as Colors from 'src/common-ui/components/design-library/colors' import { fontSizeNormal } from 'src/common-ui/components/design-library/typography' import ButtonTooltip from 'src/common-ui/components/button-tooltip' import { EntrySelectedList } from './components/EntrySelectedList' import { ListResultItem } from './components/ListResultItem' import { collections, contentSharing, } from 'src/util/remote-functions-background' class ListPicker extends StatefulUIElement< ListPickerDependencies, ListPickerState, ListPickerEvent > { static defaultProps: Partial<ListPickerDependencies> = { queryEntries: (query) => collections.searchForListSuggestions({ query }), loadDefaultSuggestions: collections.fetchInitialListSuggestions, loadRemoteListNames: async () => { const remoteLists = await contentSharing.getAllRemoteLists() return remoteLists.map((list) => list.name) }, } constructor(props: ListPickerDependencies) { super(props, new ListPickerLogic(props)) } searchInputPlaceholder = this.props.searchInputPlaceholder ?? 'Add to Collection' removeToolTipText = this.props.removeToolTipText ?? 'Remove from list' componentDidUpdate( prevProps: ListPickerDependencies, prevState: ListPickerState, ) { if (prevProps.query !== this.props.query) { this.processEvent('searchInputChanged', { query: this.props.query }) } const prev = prevState.selectedEntries const curr = this.state.selectedEntries if (prev.length !== curr.length || !isEqual(prev, curr))
} private isListRemote = (name: string): boolean => this.state.remoteLists.has(name) handleClickOutside = (e) => { if (this.props.onClickOutside) { this.props.onClickOutside(e) } } handleSetSearchInputRef = (ref: HTMLInputElement) => this.processEvent('setSearchInputRef', { ref }) handleOuterSearchBoxClick = () => this.processEvent('focusInput', {}) handleSearchInputChanged = (query: string) => { this.props.onSearchInputChange?.({ query }) return this.processEvent('searchInputChanged', { query }) } handleSelectedListPress = (list: string) => this.processEvent('selectedEntryPress', { entry: list }) handleResultListPress = (list: DisplayEntry) => this.processEvent('resultEntryPress', { entry: list }) handleResultListAllPress = (list: DisplayEntry) => this.processEvent('resultEntryAllPress', { entry: list }) handleNewListAllPress = () => this.processEvent('newEntryAllPress', { entry: this.state.newEntryName, }) handleResultListFocus = (list: DisplayEntry, index?: number) => this.processEvent('resultEntryFocus', { entry: list, index }) handleNewListPress = () => this.processEvent('newEntryPress', { entry: this.state.newEntryName }) handleKeyPress = (key: KeyEvent) => this.processEvent('keyPress', { key }) renderListRow = (list: DisplayEntry, index: number) => ( <EntryRow onPress={this.handleResultListPress} onPressActOnAll={ this.props.actOnAllTabs ? (t) => this.handleResultListAllPress(t) : undefined } onFocus={this.handleResultListFocus} key={`ListKeyName-${list.name}`} index={index} name={list.name} selected={list.selected} focused={list.focused} remote={this.isListRemote(list.name)} resultItem={<ListResultItem>{list.name}</ListResultItem>} removeTooltipText={this.removeToolTipText} actOnAllTooltipText="Add all tabs in window to list" /> ) renderNewListAllTabsButton = () => this.props.actOnAllTabs && ( <IconStyleWrapper show> <ButtonTooltip tooltipText="List all tabs in window" position="left" > <ActOnAllTabsButton size={20} onClick={this.handleNewListAllPress} /> </ButtonTooltip> </IconStyleWrapper> ) renderEmptyList() { if (this.state.newEntryName !== '') { return } return ( <EmptyListsView> <strong>No Collections yet</strong> <br /> Add new collections <br /> via the search bar </EmptyListsView> ) } renderMainContent() { if (this.state.loadingSuggestions) { return ( <LoadingBox> <LoadingIndicator /> </LoadingBox> ) } return ( <> <PickerSearchInput searchInputPlaceholder={this.searchInputPlaceholder} showPlaceholder={this.state.selectedEntries.length === 0} searchInputRef={this.handleSetSearchInputRef} onChange={this.handleSearchInputChanged} onKeyPress={this.handleKeyPress} value={this.state.query} loading={this.state.loadingQueryResults} before={ <EntrySelectedList dataAttributeName="list-name" entriesSelected={this.state.selectedEntries} onPress={this.handleSelectedListPress} /> } /> <EntryResultsList entries={this.state.displayEntries} renderEntryRow={this.renderListRow} emptyView={this.renderEmptyList()} id="listResults" /> {this.state.newEntryName !== '' && ( <AddNewEntry resultItem={ <ListResultItem> {this.state.newEntryName} </ListResultItem> } onPress={this.handleNewListPress} > {this.renderNewListAllTabsButton()} </AddNewEntry> )} </> ) } render() { return ( <ThemeProvider theme={Colors.lightTheme}> <OuterSearchBox onKeyPress={this.handleKeyPress} onClick={this.handleOuterSearchBoxClick} > {this.renderMainContent()} {this.props.children} </OuterSearchBox> </ThemeProvider> ) } } const LoadingBox = styled.div` display: flex; align-items: center; justify-content: center; height: 100%; width: 100%; ` const OuterSearchBox = styled.div` background: ${(props) => props.theme.background}; padding-top: 8px; padding-bottom: 8px; border-radius: 3px; ` const EmptyListsView = styled.div` color: ${(props) => props.theme.tag.text}; padding: 10px 15px; font-weight: 400; font-size: ${fontSizeNormal}px; text-align: center; ` export default onClickOutside(ListPicker)
{ this.props.onSelectedEntriesChange?.({ selectedEntries: this.state.selectedEntries, }) }
conditional_block
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_attrs)] #[rustc_object_lifetime_default] struct A<T>(T); //~ ERROR None #[rustc_object_lifetime_default] struct B<'a,T>(&'a (), T); //~ ERROR None #[rustc_object_lifetime_default] struct C<'a,T:'a>(&'a T); //~ ERROR 'a #[rustc_object_lifetime_default] struct D<'a,'b,T:'a+'b>(&'a T, &'b T); //~ ERROR Ambiguous #[rustc_object_lifetime_default] struct E<'a,'b:'a,T:'b>(&'a T, &'b T); //~ ERROR 'b #[rustc_object_lifetime_default] struct F<'a,'b,T:'a,U:'b>(&'a T, &'b U); //~ ERROR 'a,'b #[rustc_object_lifetime_default] struct G<'a,'b,T:'a,U:'a+'b>(&'a T, &'b U); //~ ERROR 'a,Ambiguous fn main()
{ }
identifier_body
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_attrs)] #[rustc_object_lifetime_default] struct A<T>(T); //~ ERROR None #[rustc_object_lifetime_default] struct
<'a,T>(&'a (), T); //~ ERROR None #[rustc_object_lifetime_default] struct C<'a,T:'a>(&'a T); //~ ERROR 'a #[rustc_object_lifetime_default] struct D<'a,'b,T:'a+'b>(&'a T, &'b T); //~ ERROR Ambiguous #[rustc_object_lifetime_default] struct E<'a,'b:'a,T:'b>(&'a T, &'b T); //~ ERROR 'b #[rustc_object_lifetime_default] struct F<'a,'b,T:'a,U:'b>(&'a T, &'b U); //~ ERROR 'a,'b #[rustc_object_lifetime_default] struct G<'a,'b,T:'a,U:'a+'b>(&'a T, &'b U); //~ ERROR 'a,Ambiguous fn main() { }
B
identifier_name
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(rustc_attrs)] #[rustc_object_lifetime_default] struct A<T>(T); //~ ERROR None #[rustc_object_lifetime_default] struct B<'a,T>(&'a (), T); //~ ERROR None #[rustc_object_lifetime_default] struct C<'a,T:'a>(&'a T); //~ ERROR 'a #[rustc_object_lifetime_default] struct D<'a,'b,T:'a+'b>(&'a T, &'b T); //~ ERROR Ambiguous #[rustc_object_lifetime_default] struct E<'a,'b:'a,T:'b>(&'a T, &'b T); //~ ERROR 'b #[rustc_object_lifetime_default] struct F<'a,'b,T:'a,U:'b>(&'a T, &'b U); //~ ERROR 'a,'b #[rustc_object_lifetime_default] struct G<'a,'b,T:'a,U:'a+'b>(&'a T, &'b U); //~ ERROR 'a,Ambiguous
fn main() { }
random_line_split
AdhocQueryAdapter.js
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Promise from 'bluebird'; import BaseAdapter from './BaseAdapter'; import Config from 'config.json'; let baseUrl = Config.baseURL; let urls = { getDatabases: 'metastore/databases', setDatabases: 'metastore/databases/current', getCubes: 'metastore/cubes', query: 'queryapi/queries', // POST on this to execute, GET to fetch all getTables: 'metastore/nativetables', getSavedQueries: 'queryapi/savedqueries', parameters: 'queryapi/savedqueries/parameters', saveQuery: 'queryapi/savedqueries', // POST to save, PUT to update, {id} for GET runSavedQuery: 'queryapi/savedqueries' }; let AdhocQueryAdapter = { getDatabases (secretToken) { let url = baseUrl + urls.getDatabases; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, setDatabase (secretToken, database) { let url = baseUrl + urls.setDatabases; return BaseAdapter.put(url + '?sessionid=' + secretToken, database, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getCubes (secretToken) { let url = baseUrl + urls.getCubes; let postURL = "?"; if (Config.cubes_type) { postURL += "type=" + Config.cubes_type + "&" } postURL += "sessionid=" + secretToken; return BaseAdapter.get(url + postURL); }, getCubeDetails (secretToken, cubeName) { let url = baseUrl + urls.getCubes + '/' + cubeName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, executeQuery (secretToken, query, queryName) { let url = baseUrl + urls.query; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('query', query); formData.append('operation', 'EXECUTE'); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); if (queryName) formData.append('queryName', queryName); return BaseAdapter.post(url, formData, { headers: { 'Accept': 'application/json' } }); }, saveQuery (secretToken, user, query, options) { let queryToBeSaved = { savedQuery: { name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; let url = baseUrl + urls.saveQuery + '?sessionid=' + secretToken; return BaseAdapter.post(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, updateSavedQuery (secretToken, user, query, options, id) { let url = baseUrl + urls.saveQuery + '/' + id; let queryToBeSaved = { savedQuery: { owner: user, name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; return BaseAdapter.put(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getQueries (secretToken, email, options) { let queryOptions = {}; queryOptions.sessionid = secretToken; queryOptions.user = email; var state; if (options && options.state) { state = options.state.toUpperCase(); } let handlesUrl = baseUrl + urls.query + '?sessionid=' + secretToken + '&user=' + email; if (state) handlesUrl += '&state=' + state; return BaseAdapter.get(handlesUrl) .then(function (queryHandles) { // FIXME limiting to 10 for now // let handles = queryHandles.slice(0, 10); return Promise.all(queryHandles.map((q) => { let queryUrl = baseUrl + urls.query + '/' + q.queryHandle.handleId + '?sessionid=' + secretToken + '&queryHandle=' + q.queryHandle.handleId; return BaseAdapter.get(queryUrl); })); }); }, getQueryResult (secretToken, handle, queryMode) { // on page refresh, the store won't have queryMode so fetch query // this is needed as we won't know in which mode the query was fired if (!queryMode) { this.getQuery(secretToken, handle).then((query) => { queryMode = query.isPersistent; queryMode = queryMode ? 'PERSISTENT' : 'INMEMORY'; return this._inMemoryOrPersistent(secretToken, handle, queryMode); }); } else { return this._inMemoryOrPersistent(secretToken, handle, queryMode); } }, _inMemoryOrPersistent (secretToken, handle, queryMode) { return queryMode === 'PERSISTENT' ? this.getDownloadURL(secretToken, handle) : this.getInMemoryResults(secretToken, handle); }, getTables (secretToken, database) { let url = baseUrl + urls.getTables; return BaseAdapter.get(url + '?sessionid=' + secretToken + '&dbName=' + database); }, getTableDetails (secretToken, tableName, database) { let url = baseUrl + urls.getTables + '/' + database + '.' + tableName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, cancelQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle + '?sessionid=' + secretToken; return BaseAdapter.delete(url); },
(secretToken, handle) { let downloadURL = baseUrl + urls.query + '/' + handle + '/httpresultset?sessionid=' + secretToken; return Promise.resolve(downloadURL); }, getSavedQueryById (secretToken, id) { let url = baseUrl + urls.saveQuery + '/' + id; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getInMemoryResults (secretToken, handle) { let resultUrl = baseUrl + urls.query + '/' + handle + '/resultset'; let results = BaseAdapter.get(resultUrl + '?sessionid=' + secretToken); let metaUrl = baseUrl + urls.query + '/' + handle + '/resultsetmetadata'; let meta = BaseAdapter.get(metaUrl + '?sessionid=' + secretToken); return Promise.all([results, meta]); }, getSavedQueries (secretToken, user, options = {}) { let url = baseUrl + urls.getSavedQueries; return BaseAdapter.get( url + '?user=' + user + '&sessionid=' + secretToken + '&start=' + (options.offset || 0) + '&count=' + (options.pageSize || 10) ); }, getParams (secretToken, query) { let url = baseUrl + urls.parameters + '?sessionid=' + secretToken; let formData = new FormData(); formData.append('query', query); return BaseAdapter.post(url, formData); }, runSavedQuery (secretToken, id, params) { let queryParamString = BaseAdapter.jsonToQueryParams(params); let url = baseUrl + urls.runSavedQuery + '/' + id + queryParamString; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); return BaseAdapter.post(url, formData); } }; export default AdhocQueryAdapter;
getDownloadURL
identifier_name
AdhocQueryAdapter.js
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Promise from 'bluebird'; import BaseAdapter from './BaseAdapter'; import Config from 'config.json'; let baseUrl = Config.baseURL; let urls = { getDatabases: 'metastore/databases', setDatabases: 'metastore/databases/current', getCubes: 'metastore/cubes', query: 'queryapi/queries', // POST on this to execute, GET to fetch all getTables: 'metastore/nativetables', getSavedQueries: 'queryapi/savedqueries', parameters: 'queryapi/savedqueries/parameters', saveQuery: 'queryapi/savedqueries', // POST to save, PUT to update, {id} for GET runSavedQuery: 'queryapi/savedqueries' }; let AdhocQueryAdapter = { getDatabases (secretToken) { let url = baseUrl + urls.getDatabases; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, setDatabase (secretToken, database) { let url = baseUrl + urls.setDatabases; return BaseAdapter.put(url + '?sessionid=' + secretToken, database, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getCubes (secretToken) { let url = baseUrl + urls.getCubes; let postURL = "?"; if (Config.cubes_type) { postURL += "type=" + Config.cubes_type + "&" } postURL += "sessionid=" + secretToken; return BaseAdapter.get(url + postURL); }, getCubeDetails (secretToken, cubeName) { let url = baseUrl + urls.getCubes + '/' + cubeName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, executeQuery (secretToken, query, queryName) { let url = baseUrl + urls.query; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('query', query); formData.append('operation', 'EXECUTE'); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); if (queryName) formData.append('queryName', queryName); return BaseAdapter.post(url, formData, { headers: { 'Accept': 'application/json' } }); }, saveQuery (secretToken, user, query, options) { let queryToBeSaved = { savedQuery: { name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; let url = baseUrl + urls.saveQuery + '?sessionid=' + secretToken; return BaseAdapter.post(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, updateSavedQuery (secretToken, user, query, options, id) { let url = baseUrl + urls.saveQuery + '/' + id; let queryToBeSaved = { savedQuery: { owner: user, name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; return BaseAdapter.put(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getQueries (secretToken, email, options) { let queryOptions = {}; queryOptions.sessionid = secretToken; queryOptions.user = email; var state; if (options && options.state) { state = options.state.toUpperCase(); } let handlesUrl = baseUrl + urls.query + '?sessionid=' + secretToken + '&user=' + email; if (state) handlesUrl += '&state=' + state; return BaseAdapter.get(handlesUrl) .then(function (queryHandles) { // FIXME limiting to 10 for now // let handles = queryHandles.slice(0, 10); return Promise.all(queryHandles.map((q) => { let queryUrl = baseUrl + urls.query + '/' + q.queryHandle.handleId + '?sessionid=' + secretToken + '&queryHandle=' + q.queryHandle.handleId; return BaseAdapter.get(queryUrl); })); }); }, getQueryResult (secretToken, handle, queryMode) { // on page refresh, the store won't have queryMode so fetch query // this is needed as we won't know in which mode the query was fired if (!queryMode) { this.getQuery(secretToken, handle).then((query) => { queryMode = query.isPersistent; queryMode = queryMode ? 'PERSISTENT' : 'INMEMORY'; return this._inMemoryOrPersistent(secretToken, handle, queryMode); }); } else
}, _inMemoryOrPersistent (secretToken, handle, queryMode) { return queryMode === 'PERSISTENT' ? this.getDownloadURL(secretToken, handle) : this.getInMemoryResults(secretToken, handle); }, getTables (secretToken, database) { let url = baseUrl + urls.getTables; return BaseAdapter.get(url + '?sessionid=' + secretToken + '&dbName=' + database); }, getTableDetails (secretToken, tableName, database) { let url = baseUrl + urls.getTables + '/' + database + '.' + tableName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, cancelQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle + '?sessionid=' + secretToken; return BaseAdapter.delete(url); }, getDownloadURL (secretToken, handle) { let downloadURL = baseUrl + urls.query + '/' + handle + '/httpresultset?sessionid=' + secretToken; return Promise.resolve(downloadURL); }, getSavedQueryById (secretToken, id) { let url = baseUrl + urls.saveQuery + '/' + id; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getInMemoryResults (secretToken, handle) { let resultUrl = baseUrl + urls.query + '/' + handle + '/resultset'; let results = BaseAdapter.get(resultUrl + '?sessionid=' + secretToken); let metaUrl = baseUrl + urls.query + '/' + handle + '/resultsetmetadata'; let meta = BaseAdapter.get(metaUrl + '?sessionid=' + secretToken); return Promise.all([results, meta]); }, getSavedQueries (secretToken, user, options = {}) { let url = baseUrl + urls.getSavedQueries; return BaseAdapter.get( url + '?user=' + user + '&sessionid=' + secretToken + '&start=' + (options.offset || 0) + '&count=' + (options.pageSize || 10) ); }, getParams (secretToken, query) { let url = baseUrl + urls.parameters + '?sessionid=' + secretToken; let formData = new FormData(); formData.append('query', query); return BaseAdapter.post(url, formData); }, runSavedQuery (secretToken, id, params) { let queryParamString = BaseAdapter.jsonToQueryParams(params); let url = baseUrl + urls.runSavedQuery + '/' + id + queryParamString; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); return BaseAdapter.post(url, formData); } }; export default AdhocQueryAdapter;
{ return this._inMemoryOrPersistent(secretToken, handle, queryMode); }
conditional_block
AdhocQueryAdapter.js
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Promise from 'bluebird'; import BaseAdapter from './BaseAdapter'; import Config from 'config.json'; let baseUrl = Config.baseURL; let urls = { getDatabases: 'metastore/databases', setDatabases: 'metastore/databases/current', getCubes: 'metastore/cubes', query: 'queryapi/queries', // POST on this to execute, GET to fetch all getTables: 'metastore/nativetables', getSavedQueries: 'queryapi/savedqueries', parameters: 'queryapi/savedqueries/parameters', saveQuery: 'queryapi/savedqueries', // POST to save, PUT to update, {id} for GET runSavedQuery: 'queryapi/savedqueries' }; let AdhocQueryAdapter = { getDatabases (secretToken) { let url = baseUrl + urls.getDatabases; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, setDatabase (secretToken, database) { let url = baseUrl + urls.setDatabases; return BaseAdapter.put(url + '?sessionid=' + secretToken, database, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getCubes (secretToken) { let url = baseUrl + urls.getCubes; let postURL = "?"; if (Config.cubes_type) { postURL += "type=" + Config.cubes_type + "&" } postURL += "sessionid=" + secretToken; return BaseAdapter.get(url + postURL); }, getCubeDetails (secretToken, cubeName) { let url = baseUrl + urls.getCubes + '/' + cubeName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, executeQuery (secretToken, query, queryName) { let url = baseUrl + urls.query; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('query', query); formData.append('operation', 'EXECUTE'); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); if (queryName) formData.append('queryName', queryName); return BaseAdapter.post(url, formData, { headers: { 'Accept': 'application/json' } }); }, saveQuery (secretToken, user, query, options) { let queryToBeSaved = { savedQuery: { name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; let url = baseUrl + urls.saveQuery + '?sessionid=' + secretToken; return BaseAdapter.post(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, updateSavedQuery (secretToken, user, query, options, id) { let url = baseUrl + urls.saveQuery + '/' + id; let queryToBeSaved = { savedQuery: { owner: user, name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; return BaseAdapter.put(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getQueries (secretToken, email, options) { let queryOptions = {}; queryOptions.sessionid = secretToken; queryOptions.user = email; var state; if (options && options.state) { state = options.state.toUpperCase(); } let handlesUrl = baseUrl + urls.query + '?sessionid=' + secretToken + '&user=' + email; if (state) handlesUrl += '&state=' + state; return BaseAdapter.get(handlesUrl) .then(function (queryHandles) { // FIXME limiting to 10 for now // let handles = queryHandles.slice(0, 10); return Promise.all(queryHandles.map((q) => { let queryUrl = baseUrl + urls.query + '/' + q.queryHandle.handleId + '?sessionid=' + secretToken + '&queryHandle=' + q.queryHandle.handleId; return BaseAdapter.get(queryUrl); })); }); }, getQueryResult (secretToken, handle, queryMode) { // on page refresh, the store won't have queryMode so fetch query // this is needed as we won't know in which mode the query was fired if (!queryMode) { this.getQuery(secretToken, handle).then((query) => { queryMode = query.isPersistent; queryMode = queryMode ? 'PERSISTENT' : 'INMEMORY'; return this._inMemoryOrPersistent(secretToken, handle, queryMode); }); } else { return this._inMemoryOrPersistent(secretToken, handle, queryMode); } }, _inMemoryOrPersistent (secretToken, handle, queryMode) { return queryMode === 'PERSISTENT' ? this.getDownloadURL(secretToken, handle) : this.getInMemoryResults(secretToken, handle); }, getTables (secretToken, database) { let url = baseUrl + urls.getTables; return BaseAdapter.get(url + '?sessionid=' + secretToken + '&dbName=' + database); }, getTableDetails (secretToken, tableName, database) { let url = baseUrl + urls.getTables + '/' + database + '.' + tableName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, cancelQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle + '?sessionid=' + secretToken; return BaseAdapter.delete(url); }, getDownloadURL (secretToken, handle) {
return Promise.resolve(downloadURL); }, getSavedQueryById (secretToken, id) { let url = baseUrl + urls.saveQuery + '/' + id; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getInMemoryResults (secretToken, handle) { let resultUrl = baseUrl + urls.query + '/' + handle + '/resultset'; let results = BaseAdapter.get(resultUrl + '?sessionid=' + secretToken); let metaUrl = baseUrl + urls.query + '/' + handle + '/resultsetmetadata'; let meta = BaseAdapter.get(metaUrl + '?sessionid=' + secretToken); return Promise.all([results, meta]); }, getSavedQueries (secretToken, user, options = {}) { let url = baseUrl + urls.getSavedQueries; return BaseAdapter.get( url + '?user=' + user + '&sessionid=' + secretToken + '&start=' + (options.offset || 0) + '&count=' + (options.pageSize || 10) ); }, getParams (secretToken, query) { let url = baseUrl + urls.parameters + '?sessionid=' + secretToken; let formData = new FormData(); formData.append('query', query); return BaseAdapter.post(url, formData); }, runSavedQuery (secretToken, id, params) { let queryParamString = BaseAdapter.jsonToQueryParams(params); let url = baseUrl + urls.runSavedQuery + '/' + id + queryParamString; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); return BaseAdapter.post(url, formData); } }; export default AdhocQueryAdapter;
let downloadURL = baseUrl + urls.query + '/' + handle + '/httpresultset?sessionid=' + secretToken;
random_line_split
AdhocQueryAdapter.js
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import Promise from 'bluebird'; import BaseAdapter from './BaseAdapter'; import Config from 'config.json'; let baseUrl = Config.baseURL; let urls = { getDatabases: 'metastore/databases', setDatabases: 'metastore/databases/current', getCubes: 'metastore/cubes', query: 'queryapi/queries', // POST on this to execute, GET to fetch all getTables: 'metastore/nativetables', getSavedQueries: 'queryapi/savedqueries', parameters: 'queryapi/savedqueries/parameters', saveQuery: 'queryapi/savedqueries', // POST to save, PUT to update, {id} for GET runSavedQuery: 'queryapi/savedqueries' }; let AdhocQueryAdapter = { getDatabases (secretToken) { let url = baseUrl + urls.getDatabases; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, setDatabase (secretToken, database) { let url = baseUrl + urls.setDatabases; return BaseAdapter.put(url + '?sessionid=' + secretToken, database, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, getCubes (secretToken) { let url = baseUrl + urls.getCubes; let postURL = "?"; if (Config.cubes_type) { postURL += "type=" + Config.cubes_type + "&" } postURL += "sessionid=" + secretToken; return BaseAdapter.get(url + postURL); }, getCubeDetails (secretToken, cubeName) { let url = baseUrl + urls.getCubes + '/' + cubeName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, executeQuery (secretToken, query, queryName) { let url = baseUrl + urls.query; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('query', query); formData.append('operation', 'EXECUTE'); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); if (queryName) formData.append('queryName', queryName); return BaseAdapter.post(url, formData, { headers: { 'Accept': 'application/json' } }); }, saveQuery (secretToken, user, query, options) { let queryToBeSaved = { savedQuery: { name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; let url = baseUrl + urls.saveQuery + '?sessionid=' + secretToken; return BaseAdapter.post(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }, updateSavedQuery (secretToken, user, query, options, id)
, getQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getQueries (secretToken, email, options) { let queryOptions = {}; queryOptions.sessionid = secretToken; queryOptions.user = email; var state; if (options && options.state) { state = options.state.toUpperCase(); } let handlesUrl = baseUrl + urls.query + '?sessionid=' + secretToken + '&user=' + email; if (state) handlesUrl += '&state=' + state; return BaseAdapter.get(handlesUrl) .then(function (queryHandles) { // FIXME limiting to 10 for now // let handles = queryHandles.slice(0, 10); return Promise.all(queryHandles.map((q) => { let queryUrl = baseUrl + urls.query + '/' + q.queryHandle.handleId + '?sessionid=' + secretToken + '&queryHandle=' + q.queryHandle.handleId; return BaseAdapter.get(queryUrl); })); }); }, getQueryResult (secretToken, handle, queryMode) { // on page refresh, the store won't have queryMode so fetch query // this is needed as we won't know in which mode the query was fired if (!queryMode) { this.getQuery(secretToken, handle).then((query) => { queryMode = query.isPersistent; queryMode = queryMode ? 'PERSISTENT' : 'INMEMORY'; return this._inMemoryOrPersistent(secretToken, handle, queryMode); }); } else { return this._inMemoryOrPersistent(secretToken, handle, queryMode); } }, _inMemoryOrPersistent (secretToken, handle, queryMode) { return queryMode === 'PERSISTENT' ? this.getDownloadURL(secretToken, handle) : this.getInMemoryResults(secretToken, handle); }, getTables (secretToken, database) { let url = baseUrl + urls.getTables; return BaseAdapter.get(url + '?sessionid=' + secretToken + '&dbName=' + database); }, getTableDetails (secretToken, tableName, database) { let url = baseUrl + urls.getTables + '/' + database + '.' + tableName; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, cancelQuery (secretToken, handle) { let url = baseUrl + urls.query + '/' + handle + '?sessionid=' + secretToken; return BaseAdapter.delete(url); }, getDownloadURL (secretToken, handle) { let downloadURL = baseUrl + urls.query + '/' + handle + '/httpresultset?sessionid=' + secretToken; return Promise.resolve(downloadURL); }, getSavedQueryById (secretToken, id) { let url = baseUrl + urls.saveQuery + '/' + id; return BaseAdapter.get(url + '?sessionid=' + secretToken); }, getInMemoryResults (secretToken, handle) { let resultUrl = baseUrl + urls.query + '/' + handle + '/resultset'; let results = BaseAdapter.get(resultUrl + '?sessionid=' + secretToken); let metaUrl = baseUrl + urls.query + '/' + handle + '/resultsetmetadata'; let meta = BaseAdapter.get(metaUrl + '?sessionid=' + secretToken); return Promise.all([results, meta]); }, getSavedQueries (secretToken, user, options = {}) { let url = baseUrl + urls.getSavedQueries; return BaseAdapter.get( url + '?user=' + user + '&sessionid=' + secretToken + '&start=' + (options.offset || 0) + '&count=' + (options.pageSize || 10) ); }, getParams (secretToken, query) { let url = baseUrl + urls.parameters + '?sessionid=' + secretToken; let formData = new FormData(); formData.append('query', query); return BaseAdapter.post(url, formData); }, runSavedQuery (secretToken, id, params) { let queryParamString = BaseAdapter.jsonToQueryParams(params); let url = baseUrl + urls.runSavedQuery + '/' + id + queryParamString; let formData = new FormData(); formData.append('sessionid', secretToken); formData.append('conf', '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><conf></conf>'); return BaseAdapter.post(url, formData); } }; export default AdhocQueryAdapter;
{ let url = baseUrl + urls.saveQuery + '/' + id; let queryToBeSaved = { savedQuery: { owner: user, name: options.name || '', query: query, description: options.description || '', parameters: options.parameters || [] } }; return BaseAdapter.put(url, JSON.stringify(queryToBeSaved), { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }); }
identifier_body
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool
pub fn expand(item: &Yaml, benchmark: &mut Benchmark) { if let Some(with_items) = item["with_items"].as_vec() { let mut with_items_list = with_items.clone(); if let Some(shuffle) = item["shuffle"].as_bool() { if shuffle { let mut rng = thread_rng(); with_items_list.shuffle(&mut rng); } } for (index, with_item) in with_items_list.iter().enumerate() { let index = index as u32; let value: &str = with_item.as_str().unwrap_or(""); if INTERPOLATION_REGEX.is_match(value) { panic!("Interpolations not supported in 'with_items' children!"); } benchmark.push(Box::new(Request::new(item, Some(with_item.clone()), Some(index)))); } } } #[cfg(test)] mod tests { use super::*; #[test] fn expand_multi() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - 3"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); assert_eq!(is_that_you(&doc), true); assert_eq!(benchmark.len(), 3); } #[test] #[should_panic] fn runtime_expand() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
{ item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() }
identifier_body
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(item: &Yaml, benchmark: &mut Benchmark) { if let Some(with_items) = item["with_items"].as_vec() { let mut with_items_list = with_items.clone(); if let Some(shuffle) = item["shuffle"].as_bool() { if shuffle { let mut rng = thread_rng(); with_items_list.shuffle(&mut rng); } } for (index, with_item) in with_items_list.iter().enumerate() { let index = index as u32; let value: &str = with_item.as_str().unwrap_or(""); if INTERPOLATION_REGEX.is_match(value) { panic!("Interpolations not supported in 'with_items' children!"); } benchmark.push(Box::new(Request::new(item, Some(with_item.clone()), Some(index)))); } } } #[cfg(test)] mod tests { use super::*; #[test] fn expand_multi() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - 3"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); assert_eq!(is_that_you(&doc), true); assert_eq!(benchmark.len(), 3); } #[test] #[should_panic] fn
() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
runtime_expand
identifier_name
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(item: &Yaml, benchmark: &mut Benchmark) { if let Some(with_items) = item["with_items"].as_vec() { let mut with_items_list = with_items.clone(); if let Some(shuffle) = item["shuffle"].as_bool() { if shuffle { let mut rng = thread_rng(); with_items_list.shuffle(&mut rng); } } for (index, with_item) in with_items_list.iter().enumerate() { let index = index as u32; let value: &str = with_item.as_str().unwrap_or(""); if INTERPOLATION_REGEX.is_match(value)
benchmark.push(Box::new(Request::new(item, Some(with_item.clone()), Some(index)))); } } } #[cfg(test)] mod tests { use super::*; #[test] fn expand_multi() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - 3"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); assert_eq!(is_that_you(&doc), true); assert_eq!(benchmark.len(), 3); } #[test] #[should_panic] fn runtime_expand() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
{ panic!("Interpolations not supported in 'with_items' children!"); }
conditional_block
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(item: &Yaml, benchmark: &mut Benchmark) { if let Some(with_items) = item["with_items"].as_vec() { let mut with_items_list = with_items.clone(); if let Some(shuffle) = item["shuffle"].as_bool() { if shuffle { let mut rng = thread_rng(); with_items_list.shuffle(&mut rng); } } for (index, with_item) in with_items_list.iter().enumerate() { let index = index as u32; let value: &str = with_item.as_str().unwrap_or(""); if INTERPOLATION_REGEX.is_match(value) { panic!("Interpolations not supported in 'with_items' children!"); } benchmark.push(Box::new(Request::new(item, Some(with_item.clone()), Some(index)))); } } } #[cfg(test)] mod tests { use super::*; #[test] fn expand_multi() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - 3"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); assert_eq!(is_that_you(&doc), true); assert_eq!(benchmark.len(), 3); } #[test] #[should_panic]
let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
fn runtime_expand() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}";
random_line_split
test_color.py
import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound
class TestNearestColor: def test_exact(self): assert FindNearest(0,0,0).all_fast() == 0 for n,color in enumerate(color_html): # Ignoring duplicates if n not in (16, 21, 46, 51, 196, 201, 226, 231, 244): rgb = (int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)) assert FindNearest(*rgb).all_fast() == n def test_nearby(self): assert FindNearest(1,2,2).all_fast() == 0 assert FindNearest(7,7,9).all_fast() == 232 def test_simplecolor(self): assert FindNearest(1,2,4).only_basic() == 0 assert FindNearest(0,255,0).only_basic() == 2 assert FindNearest(100,100,0).only_basic() == 3 assert FindNearest(140,140,140).only_basic() == 7 class TestColorLoad: def test_rgb(self): blue = Color(0,0,255) # Red, Green, Blue assert blue.rgb == (0,0,255) def test_simple_name(self): green = Color.from_simple('green') assert green.number == 2 def test_different_names(self): assert Color('Dark Blue') == Color('Dark_Blue') assert Color('Dark_blue') == Color('Dark_Blue') assert Color('DARKBLUE') == Color('Dark_Blue') assert Color('DarkBlue') == Color('Dark_Blue') assert Color('Dark Green') == Color('Dark_Green') def test_loading_methods(self): assert Color("Yellow") == Color.from_full("Yellow") assert (Color.from_full("yellow").representation != Color.from_simple("yellow").representation) class TestANSIColor: @classmethod def setup_class(cls): ANSIStyle.use_color = True def test_ansi(self): assert str(ANSIStyle(fgcolor=Color('reset'))) == '\033[39m' assert str(ANSIStyle(fgcolor=Color.from_full('green'))) == '\033[38;5;2m' assert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m' class TestNearestColor: def test_allcolors(self): myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255) for r in myrange: for g in myrange: for b in myrange: near = FindNearest(r,g,b) assert near.all_slow() == near.all_fast(), 'Tested: {0}, {1}, {2}'.format(r,g,b)
from plumbum.colorlib.names import color_html, FindNearest
random_line_split
test_color.py
import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound from plumbum.colorlib.names import color_html, FindNearest class TestNearestColor: def test_exact(self): assert FindNearest(0,0,0).all_fast() == 0 for n,color in enumerate(color_html): # Ignoring duplicates if n not in (16, 21, 46, 51, 196, 201, 226, 231, 244): rgb = (int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)) assert FindNearest(*rgb).all_fast() == n def test_nearby(self): assert FindNearest(1,2,2).all_fast() == 0 assert FindNearest(7,7,9).all_fast() == 232 def test_simplecolor(self): assert FindNearest(1,2,4).only_basic() == 0 assert FindNearest(0,255,0).only_basic() == 2 assert FindNearest(100,100,0).only_basic() == 3 assert FindNearest(140,140,140).only_basic() == 7 class TestColorLoad: def test_rgb(self): blue = Color(0,0,255) # Red, Green, Blue assert blue.rgb == (0,0,255) def test_simple_name(self): green = Color.from_simple('green') assert green.number == 2 def test_different_names(self): assert Color('Dark Blue') == Color('Dark_Blue') assert Color('Dark_blue') == Color('Dark_Blue') assert Color('DARKBLUE') == Color('Dark_Blue') assert Color('DarkBlue') == Color('Dark_Blue') assert Color('Dark Green') == Color('Dark_Green') def test_loading_methods(self): assert Color("Yellow") == Color.from_full("Yellow") assert (Color.from_full("yellow").representation != Color.from_simple("yellow").representation) class TestANSIColor: @classmethod def setup_class(cls): ANSIStyle.use_color = True def test_ansi(self): assert str(ANSIStyle(fgcolor=Color('reset'))) == '\033[39m' assert str(ANSIStyle(fgcolor=Color.from_full('green'))) == '\033[38;5;2m' assert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m' class
: def test_allcolors(self): myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255) for r in myrange: for g in myrange: for b in myrange: near = FindNearest(r,g,b) assert near.all_slow() == near.all_fast(), 'Tested: {0}, {1}, {2}'.format(r,g,b)
TestNearestColor
identifier_name
test_color.py
import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound from plumbum.colorlib.names import color_html, FindNearest class TestNearestColor: def test_exact(self): assert FindNearest(0,0,0).all_fast() == 0 for n,color in enumerate(color_html): # Ignoring duplicates if n not in (16, 21, 46, 51, 196, 201, 226, 231, 244): rgb = (int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)) assert FindNearest(*rgb).all_fast() == n def test_nearby(self): assert FindNearest(1,2,2).all_fast() == 0 assert FindNearest(7,7,9).all_fast() == 232 def test_simplecolor(self): assert FindNearest(1,2,4).only_basic() == 0 assert FindNearest(0,255,0).only_basic() == 2 assert FindNearest(100,100,0).only_basic() == 3 assert FindNearest(140,140,140).only_basic() == 7 class TestColorLoad: def test_rgb(self): blue = Color(0,0,255) # Red, Green, Blue assert blue.rgb == (0,0,255) def test_simple_name(self): green = Color.from_simple('green') assert green.number == 2 def test_different_names(self): assert Color('Dark Blue') == Color('Dark_Blue') assert Color('Dark_blue') == Color('Dark_Blue') assert Color('DARKBLUE') == Color('Dark_Blue') assert Color('DarkBlue') == Color('Dark_Blue') assert Color('Dark Green') == Color('Dark_Green') def test_loading_methods(self):
class TestANSIColor: @classmethod def setup_class(cls): ANSIStyle.use_color = True def test_ansi(self): assert str(ANSIStyle(fgcolor=Color('reset'))) == '\033[39m' assert str(ANSIStyle(fgcolor=Color.from_full('green'))) == '\033[38;5;2m' assert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m' class TestNearestColor: def test_allcolors(self): myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255) for r in myrange: for g in myrange: for b in myrange: near = FindNearest(r,g,b) assert near.all_slow() == near.all_fast(), 'Tested: {0}, {1}, {2}'.format(r,g,b)
assert Color("Yellow") == Color.from_full("Yellow") assert (Color.from_full("yellow").representation != Color.from_simple("yellow").representation)
identifier_body
test_color.py
import pytest from plumbum.colorlib.styles import ANSIStyle, Color, AttributeNotFound, ColorNotFound from plumbum.colorlib.names import color_html, FindNearest class TestNearestColor: def test_exact(self): assert FindNearest(0,0,0).all_fast() == 0 for n,color in enumerate(color_html): # Ignoring duplicates if n not in (16, 21, 46, 51, 196, 201, 226, 231, 244): rgb = (int(color[1:3],16), int(color[3:5],16), int(color[5:7],16)) assert FindNearest(*rgb).all_fast() == n def test_nearby(self): assert FindNearest(1,2,2).all_fast() == 0 assert FindNearest(7,7,9).all_fast() == 232 def test_simplecolor(self): assert FindNearest(1,2,4).only_basic() == 0 assert FindNearest(0,255,0).only_basic() == 2 assert FindNearest(100,100,0).only_basic() == 3 assert FindNearest(140,140,140).only_basic() == 7 class TestColorLoad: def test_rgb(self): blue = Color(0,0,255) # Red, Green, Blue assert blue.rgb == (0,0,255) def test_simple_name(self): green = Color.from_simple('green') assert green.number == 2 def test_different_names(self): assert Color('Dark Blue') == Color('Dark_Blue') assert Color('Dark_blue') == Color('Dark_Blue') assert Color('DARKBLUE') == Color('Dark_Blue') assert Color('DarkBlue') == Color('Dark_Blue') assert Color('Dark Green') == Color('Dark_Green') def test_loading_methods(self): assert Color("Yellow") == Color.from_full("Yellow") assert (Color.from_full("yellow").representation != Color.from_simple("yellow").representation) class TestANSIColor: @classmethod def setup_class(cls): ANSIStyle.use_color = True def test_ansi(self): assert str(ANSIStyle(fgcolor=Color('reset'))) == '\033[39m' assert str(ANSIStyle(fgcolor=Color.from_full('green'))) == '\033[38;5;2m' assert str(ANSIStyle(fgcolor=Color.from_simple('red'))) == '\033[31m' class TestNearestColor: def test_allcolors(self): myrange = (0,1,2,5,17,39,48,73,82,140,193,210,240,244,250,254,255) for r in myrange: for g in myrange:
for b in myrange: near = FindNearest(r,g,b) assert near.all_slow() == near.all_fast(), 'Tested: {0}, {1}, {2}'.format(r,g,b)
conditional_block
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum TextureId { Stem, } impl rand::Rand for TextureId { fn rand<Rng: rand::Rng>(_: &mut Rng) -> Self { TextureId::Stem } } impl support::Texture for TextureId { fn to_fragment_shader(&self) -> String { match self { &TextureId::Stem => " #version 330 in vec2 f_texture_posn; out vec4 frag_color; // http://amindforeverprogramming.blogspot.ca/2013/07/random-floats-in-glsl-330.html uint hash( uint x ) { x += ( x << 10u ); x ^= ( x >> 6u ); x += ( x << 3u ); x ^= ( x >> 11u ); x += ( x << 15u ); return x; } float random( float f ) { const uint mantissaMask = 0x007FFFFFu; const uint one = 0x3F800000u; uint h = hash( floatBitsToUint( f ) ); h &= mantissaMask; h |= one; float r2 = uintBitsToFloat( h ); return r2 - 1.0; } void main() { float f = random(f_texture_posn.x * 1337 + f_texture_posn.y); frag_color = vec4(mix(vec3(0.0, 0.4, 0.0), vec3(0.4, 0.6, 0.1), f), 1); }".to_string() } } } fn rotate(degrees: f32) -> alphabet::Transform
fn scale(s: f32) -> alphabet::Transform { alphabet::Transform { rotation : 0.0, scale : Vector::new(s, s), } } fn new() -> grammar::T<TextureId> { let s = grammar::Nonterminal(0); let s2 = grammar::Nonterminal(1); let l = grammar::Nonterminal(2); let r = grammar::Nonterminal(3); let recurse = grammar::Nonterminal(4); let rotate = |degrees| alphabet::Terminal::Transform(rotate(degrees)); let scale = |s| alphabet::Terminal::Transform(scale(s)); let add_branch = || { alphabet::Terminal::AddBranch { texture_id : TextureId::Stem, width : 0.2, length : 1.0, } }; let rules = vec!( (vec!(add_branch()) , vec!(l, recurse, s2)), (vec!(add_branch(), add_branch()) , vec!(r, l)), (vec!(rotate( 25.0)) , vec!(recurse)), (vec!(rotate(-25.0)) , vec!(recurse)), (vec!(scale(0.5)) , vec!(s)), ); let rules = rules .into_iter() .map(|(actions, next)| grammar::RHS { actions: actions, next: next }) .collect(); grammar::T { rules: rules, } } pub fn main() { use cgmath::*; support::main(new()) }
{ alphabet::Transform { rotation : std::f32::consts::PI * degrees / 180.0, scale : Vector::new(1.0, 1.0), } }
identifier_body
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum
{ Stem, } impl rand::Rand for TextureId { fn rand<Rng: rand::Rng>(_: &mut Rng) -> Self { TextureId::Stem } } impl support::Texture for TextureId { fn to_fragment_shader(&self) -> String { match self { &TextureId::Stem => " #version 330 in vec2 f_texture_posn; out vec4 frag_color; // http://amindforeverprogramming.blogspot.ca/2013/07/random-floats-in-glsl-330.html uint hash( uint x ) { x += ( x << 10u ); x ^= ( x >> 6u ); x += ( x << 3u ); x ^= ( x >> 11u ); x += ( x << 15u ); return x; } float random( float f ) { const uint mantissaMask = 0x007FFFFFu; const uint one = 0x3F800000u; uint h = hash( floatBitsToUint( f ) ); h &= mantissaMask; h |= one; float r2 = uintBitsToFloat( h ); return r2 - 1.0; } void main() { float f = random(f_texture_posn.x * 1337 + f_texture_posn.y); frag_color = vec4(mix(vec3(0.0, 0.4, 0.0), vec3(0.4, 0.6, 0.1), f), 1); }".to_string() } } } fn rotate(degrees: f32) -> alphabet::Transform { alphabet::Transform { rotation : std::f32::consts::PI * degrees / 180.0, scale : Vector::new(1.0, 1.0), } } fn scale(s: f32) -> alphabet::Transform { alphabet::Transform { rotation : 0.0, scale : Vector::new(s, s), } } fn new() -> grammar::T<TextureId> { let s = grammar::Nonterminal(0); let s2 = grammar::Nonterminal(1); let l = grammar::Nonterminal(2); let r = grammar::Nonterminal(3); let recurse = grammar::Nonterminal(4); let rotate = |degrees| alphabet::Terminal::Transform(rotate(degrees)); let scale = |s| alphabet::Terminal::Transform(scale(s)); let add_branch = || { alphabet::Terminal::AddBranch { texture_id : TextureId::Stem, width : 0.2, length : 1.0, } }; let rules = vec!( (vec!(add_branch()) , vec!(l, recurse, s2)), (vec!(add_branch(), add_branch()) , vec!(r, l)), (vec!(rotate( 25.0)) , vec!(recurse)), (vec!(rotate(-25.0)) , vec!(recurse)), (vec!(scale(0.5)) , vec!(s)), ); let rules = rules .into_iter() .map(|(actions, next)| grammar::RHS { actions: actions, next: next }) .collect(); grammar::T { rules: rules, } } pub fn main() { use cgmath::*; support::main(new()) }
TextureId
identifier_name
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] enum TextureId { Stem, } impl rand::Rand for TextureId { fn rand<Rng: rand::Rng>(_: &mut Rng) -> Self { TextureId::Stem } } impl support::Texture for TextureId { fn to_fragment_shader(&self) -> String { match self { &TextureId::Stem => " #version 330 in vec2 f_texture_posn; out vec4 frag_color; // http://amindforeverprogramming.blogspot.ca/2013/07/random-floats-in-glsl-330.html uint hash( uint x ) { x += ( x << 10u ); x ^= ( x >> 6u ); x += ( x << 3u );
} float random( float f ) { const uint mantissaMask = 0x007FFFFFu; const uint one = 0x3F800000u; uint h = hash( floatBitsToUint( f ) ); h &= mantissaMask; h |= one; float r2 = uintBitsToFloat( h ); return r2 - 1.0; } void main() { float f = random(f_texture_posn.x * 1337 + f_texture_posn.y); frag_color = vec4(mix(vec3(0.0, 0.4, 0.0), vec3(0.4, 0.6, 0.1), f), 1); }".to_string() } } } fn rotate(degrees: f32) -> alphabet::Transform { alphabet::Transform { rotation : std::f32::consts::PI * degrees / 180.0, scale : Vector::new(1.0, 1.0), } } fn scale(s: f32) -> alphabet::Transform { alphabet::Transform { rotation : 0.0, scale : Vector::new(s, s), } } fn new() -> grammar::T<TextureId> { let s = grammar::Nonterminal(0); let s2 = grammar::Nonterminal(1); let l = grammar::Nonterminal(2); let r = grammar::Nonterminal(3); let recurse = grammar::Nonterminal(4); let rotate = |degrees| alphabet::Terminal::Transform(rotate(degrees)); let scale = |s| alphabet::Terminal::Transform(scale(s)); let add_branch = || { alphabet::Terminal::AddBranch { texture_id : TextureId::Stem, width : 0.2, length : 1.0, } }; let rules = vec!( (vec!(add_branch()) , vec!(l, recurse, s2)), (vec!(add_branch(), add_branch()) , vec!(r, l)), (vec!(rotate( 25.0)) , vec!(recurse)), (vec!(rotate(-25.0)) , vec!(recurse)), (vec!(scale(0.5)) , vec!(s)), ); let rules = rules .into_iter() .map(|(actions, next)| grammar::RHS { actions: actions, next: next }) .collect(); grammar::T { rules: rules, } } pub fn main() { use cgmath::*; support::main(new()) }
x ^= ( x >> 11u ); x += ( x << 15u ); return x;
random_line_split
config.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as np import math # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # region proposal network (RPN) or not __C.IS_RPN = False __C.FLIP_X = False __C.INPUT = 'COLOR' # multiscale training and testing __C.IS_MULTISCALE = True __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' __C.NET_NAME = 'CaffeNet' __C.SUBCLS_NAME = 'voxel_exemplars' # # Training options # __C.TRAIN = edict() __C.TRAIN.VISUALIZE = False __C.TRAIN.VERTEX_REG = False __C.TRAIN.GRID_SIZE = 256 __C.TRAIN.CHROMATIC = False # Scales to compute real features __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TRAIN.NUM_PER_OCTAVE = 4 # parameters for ROI generating __C.TRAIN.SPATIAL_SCALE = 0.0625 __C.TRAIN.KERNEL_SIZE = 5 # Aspect ratio to use during training __C.TRAIN.ASPECTS = (1, 0.75, 0.5, 0.25) # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 2 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = (0.5,) # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = (0.5,) __C.TRAIN.BG_THRESH_LO = (0.1,) # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to # be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = (0.5,) # Iterations between snapshots __C.TRAIN.SNAPSHOT_ITERS = 10000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required __C.TRAIN.USE_PREFETCH = False # Train using subclasses __C.TRAIN.SUBCLS = True # Train using viewpoint __C.TRAIN.VIEWPOINT = False # Threshold of ROIs in training RCNN __C.TRAIN.ROI_THRESHOLD = 0.1 # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 __C.TRAIN.RPN_BASE_SIZE = 16 __C.TRAIN.RPN_ASPECTS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3] # 7 aspects __C.TRAIN.RPN_SCALES = [2, 2.82842712, 4, 5.65685425, 8, 11.3137085, 16, 22.627417, 32, 45.254834] # 2**np.arange(1, 6, 0.5), 10 scales # # Testing options # __C.TEST = edict() __C.TEST.IS_PATCH = False; __C.TEST.VERTEX_REG = False __C.TEST.VISUALIZE = False # Scales to compute real features __C.TEST.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TEST.NUM_PER_OCTAVE = 4 # Aspect ratio to use during testing __C.TEST.ASPECTS = (1, 0.75, 0.5, 0.25) # parameters for ROI generating __C.TEST.SPATIAL_SCALE = 0.0625 __C.TEST.KERNEL_SIZE = 5 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.5 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Test using subclass __C.TEST.SUBCLS = True # Train using viewpoint __C.TEST.VIEWPOINT = False # Threshold of ROIs in testing __C.TEST.ROI_THRESHOLD = 0.1 __C.TEST.ROI_THRESHOLD_NUM = 80000 __C.TEST.ROI_NUM = 2000 __C.TEST.DET_THRESHOLD = 0.0001 ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 300 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TEST.RPN_MIN_SIZE = 16 # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1./16. # Pixel mean values (BGR order) as a (1, 1, 3) array # These are the values originally used for training VGG16 __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 def
(imdb, net): """Return the directory where experimental artifacts are placed. A canonical path is built using the name from an imdb and a network (if not None). """ path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if net is None: return path else: return osp.join(path, net.name) def _add_more_info(is_train): # compute all the scales if is_train: scales_base = __C.TRAIN.SCALES_BASE num_per_octave = __C.TRAIN.NUM_PER_OCTAVE else: scales_base = __C.TEST.SCALES_BASE num_per_octave = __C.TEST.NUM_PER_OCTAVE num_scale_base = len(scales_base) num = (num_scale_base - 1) * num_per_octave + 1 scales = [] for i in xrange(num): index_scale_base = i / num_per_octave sbase = scales_base[index_scale_base] j = i % num_per_octave if j == 0: scales.append(sbase) else: sbase_next = scales_base[index_scale_base+1] step = (sbase_next - sbase) / num_per_octave scales.append(sbase + j * step) if is_train: __C.TRAIN.SCALES = scales else: __C.TEST.SCALES = scales print scales # map the scales to scales for RoI pooling of classification if is_train: kernel_size = __C.TRAIN.KERNEL_SIZE / __C.TRAIN.SPATIAL_SCALE else: kernel_size = __C.TEST.KERNEL_SIZE / __C.TEST.SPATIAL_SCALE area = kernel_size * kernel_size scales = np.array(scales) areas = np.repeat(area, num) / (scales ** 2) scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1) if is_train: __C.TRAIN.SCALE_MAPPING = levels else: __C.TEST.SCALE_MAPPING = levels # compute width and height of grid box if is_train: area = __C.TRAIN.KERNEL_SIZE * __C.TRAIN.KERNEL_SIZE aspect = __C.TRAIN.ASPECTS # height / width else: area = __C.TEST.KERNEL_SIZE * __C.TEST.KERNEL_SIZE aspect = __C.TEST.ASPECTS # height / width num_aspect = len(aspect) widths = np.zeros((num_aspect), dtype=np.float32) heights = np.zeros((num_aspect), dtype=np.float32) for i in xrange(num_aspect): widths[i] = math.sqrt(area / aspect[i]) heights[i] = widths[i] * aspect[i] if is_train: __C.TRAIN.ASPECT_WIDTHS = widths __C.TRAIN.ASPECT_HEIGHTS = heights __C.TRAIN.RPN_SCALES = np.array(__C.TRAIN.RPN_SCALES) else: __C.TEST.ASPECT_WIDTHS = widths __C.TEST.ASPECT_HEIGHTS = heights def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too if type(b[k]) is not type(v): raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) _add_more_info(1) _add_more_info(0)
get_output_dir
identifier_name
config.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as np import math # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # region proposal network (RPN) or not __C.IS_RPN = False __C.FLIP_X = False __C.INPUT = 'COLOR' # multiscale training and testing __C.IS_MULTISCALE = True __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' __C.NET_NAME = 'CaffeNet' __C.SUBCLS_NAME = 'voxel_exemplars' # # Training options # __C.TRAIN = edict() __C.TRAIN.VISUALIZE = False __C.TRAIN.VERTEX_REG = False __C.TRAIN.GRID_SIZE = 256 __C.TRAIN.CHROMATIC = False # Scales to compute real features __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TRAIN.NUM_PER_OCTAVE = 4 # parameters for ROI generating __C.TRAIN.SPATIAL_SCALE = 0.0625 __C.TRAIN.KERNEL_SIZE = 5 # Aspect ratio to use during training __C.TRAIN.ASPECTS = (1, 0.75, 0.5, 0.25) # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 2 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = (0.5,) # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = (0.5,) __C.TRAIN.BG_THRESH_LO = (0.1,) # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to
__C.TRAIN.SNAPSHOT_ITERS = 10000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required __C.TRAIN.USE_PREFETCH = False # Train using subclasses __C.TRAIN.SUBCLS = True # Train using viewpoint __C.TRAIN.VIEWPOINT = False # Threshold of ROIs in training RCNN __C.TRAIN.ROI_THRESHOLD = 0.1 # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 __C.TRAIN.RPN_BASE_SIZE = 16 __C.TRAIN.RPN_ASPECTS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3] # 7 aspects __C.TRAIN.RPN_SCALES = [2, 2.82842712, 4, 5.65685425, 8, 11.3137085, 16, 22.627417, 32, 45.254834] # 2**np.arange(1, 6, 0.5), 10 scales # # Testing options # __C.TEST = edict() __C.TEST.IS_PATCH = False; __C.TEST.VERTEX_REG = False __C.TEST.VISUALIZE = False # Scales to compute real features __C.TEST.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TEST.NUM_PER_OCTAVE = 4 # Aspect ratio to use during testing __C.TEST.ASPECTS = (1, 0.75, 0.5, 0.25) # parameters for ROI generating __C.TEST.SPATIAL_SCALE = 0.0625 __C.TEST.KERNEL_SIZE = 5 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.5 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Test using subclass __C.TEST.SUBCLS = True # Train using viewpoint __C.TEST.VIEWPOINT = False # Threshold of ROIs in testing __C.TEST.ROI_THRESHOLD = 0.1 __C.TEST.ROI_THRESHOLD_NUM = 80000 __C.TEST.ROI_NUM = 2000 __C.TEST.DET_THRESHOLD = 0.0001 ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 300 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TEST.RPN_MIN_SIZE = 16 # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1./16. # Pixel mean values (BGR order) as a (1, 1, 3) array # These are the values originally used for training VGG16 __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 def get_output_dir(imdb, net): """Return the directory where experimental artifacts are placed. A canonical path is built using the name from an imdb and a network (if not None). """ path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if net is None: return path else: return osp.join(path, net.name) def _add_more_info(is_train): # compute all the scales if is_train: scales_base = __C.TRAIN.SCALES_BASE num_per_octave = __C.TRAIN.NUM_PER_OCTAVE else: scales_base = __C.TEST.SCALES_BASE num_per_octave = __C.TEST.NUM_PER_OCTAVE num_scale_base = len(scales_base) num = (num_scale_base - 1) * num_per_octave + 1 scales = [] for i in xrange(num): index_scale_base = i / num_per_octave sbase = scales_base[index_scale_base] j = i % num_per_octave if j == 0: scales.append(sbase) else: sbase_next = scales_base[index_scale_base+1] step = (sbase_next - sbase) / num_per_octave scales.append(sbase + j * step) if is_train: __C.TRAIN.SCALES = scales else: __C.TEST.SCALES = scales print scales # map the scales to scales for RoI pooling of classification if is_train: kernel_size = __C.TRAIN.KERNEL_SIZE / __C.TRAIN.SPATIAL_SCALE else: kernel_size = __C.TEST.KERNEL_SIZE / __C.TEST.SPATIAL_SCALE area = kernel_size * kernel_size scales = np.array(scales) areas = np.repeat(area, num) / (scales ** 2) scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1) if is_train: __C.TRAIN.SCALE_MAPPING = levels else: __C.TEST.SCALE_MAPPING = levels # compute width and height of grid box if is_train: area = __C.TRAIN.KERNEL_SIZE * __C.TRAIN.KERNEL_SIZE aspect = __C.TRAIN.ASPECTS # height / width else: area = __C.TEST.KERNEL_SIZE * __C.TEST.KERNEL_SIZE aspect = __C.TEST.ASPECTS # height / width num_aspect = len(aspect) widths = np.zeros((num_aspect), dtype=np.float32) heights = np.zeros((num_aspect), dtype=np.float32) for i in xrange(num_aspect): widths[i] = math.sqrt(area / aspect[i]) heights[i] = widths[i] * aspect[i] if is_train: __C.TRAIN.ASPECT_WIDTHS = widths __C.TRAIN.ASPECT_HEIGHTS = heights __C.TRAIN.RPN_SCALES = np.array(__C.TRAIN.RPN_SCALES) else: __C.TEST.ASPECT_WIDTHS = widths __C.TEST.ASPECT_HEIGHTS = heights def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too if type(b[k]) is not type(v): raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) _add_more_info(1) _add_more_info(0)
# be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = (0.5,) # Iterations between snapshots
random_line_split
config.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as np import math # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # region proposal network (RPN) or not __C.IS_RPN = False __C.FLIP_X = False __C.INPUT = 'COLOR' # multiscale training and testing __C.IS_MULTISCALE = True __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' __C.NET_NAME = 'CaffeNet' __C.SUBCLS_NAME = 'voxel_exemplars' # # Training options # __C.TRAIN = edict() __C.TRAIN.VISUALIZE = False __C.TRAIN.VERTEX_REG = False __C.TRAIN.GRID_SIZE = 256 __C.TRAIN.CHROMATIC = False # Scales to compute real features __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TRAIN.NUM_PER_OCTAVE = 4 # parameters for ROI generating __C.TRAIN.SPATIAL_SCALE = 0.0625 __C.TRAIN.KERNEL_SIZE = 5 # Aspect ratio to use during training __C.TRAIN.ASPECTS = (1, 0.75, 0.5, 0.25) # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 2 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = (0.5,) # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = (0.5,) __C.TRAIN.BG_THRESH_LO = (0.1,) # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to # be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = (0.5,) # Iterations between snapshots __C.TRAIN.SNAPSHOT_ITERS = 10000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required __C.TRAIN.USE_PREFETCH = False # Train using subclasses __C.TRAIN.SUBCLS = True # Train using viewpoint __C.TRAIN.VIEWPOINT = False # Threshold of ROIs in training RCNN __C.TRAIN.ROI_THRESHOLD = 0.1 # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 __C.TRAIN.RPN_BASE_SIZE = 16 __C.TRAIN.RPN_ASPECTS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3] # 7 aspects __C.TRAIN.RPN_SCALES = [2, 2.82842712, 4, 5.65685425, 8, 11.3137085, 16, 22.627417, 32, 45.254834] # 2**np.arange(1, 6, 0.5), 10 scales # # Testing options # __C.TEST = edict() __C.TEST.IS_PATCH = False; __C.TEST.VERTEX_REG = False __C.TEST.VISUALIZE = False # Scales to compute real features __C.TEST.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TEST.NUM_PER_OCTAVE = 4 # Aspect ratio to use during testing __C.TEST.ASPECTS = (1, 0.75, 0.5, 0.25) # parameters for ROI generating __C.TEST.SPATIAL_SCALE = 0.0625 __C.TEST.KERNEL_SIZE = 5 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.5 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Test using subclass __C.TEST.SUBCLS = True # Train using viewpoint __C.TEST.VIEWPOINT = False # Threshold of ROIs in testing __C.TEST.ROI_THRESHOLD = 0.1 __C.TEST.ROI_THRESHOLD_NUM = 80000 __C.TEST.ROI_NUM = 2000 __C.TEST.DET_THRESHOLD = 0.0001 ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 300 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TEST.RPN_MIN_SIZE = 16 # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1./16. # Pixel mean values (BGR order) as a (1, 1, 3) array # These are the values originally used for training VGG16 __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 def get_output_dir(imdb, net): """Return the directory where experimental artifacts are placed. A canonical path is built using the name from an imdb and a network (if not None). """ path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if net is None: return path else: return osp.join(path, net.name) def _add_more_info(is_train): # compute all the scales if is_train: scales_base = __C.TRAIN.SCALES_BASE num_per_octave = __C.TRAIN.NUM_PER_OCTAVE else: scales_base = __C.TEST.SCALES_BASE num_per_octave = __C.TEST.NUM_PER_OCTAVE num_scale_base = len(scales_base) num = (num_scale_base - 1) * num_per_octave + 1 scales = [] for i in xrange(num): index_scale_base = i / num_per_octave sbase = scales_base[index_scale_base] j = i % num_per_octave if j == 0: scales.append(sbase) else: sbase_next = scales_base[index_scale_base+1] step = (sbase_next - sbase) / num_per_octave scales.append(sbase + j * step) if is_train: __C.TRAIN.SCALES = scales else: __C.TEST.SCALES = scales print scales # map the scales to scales for RoI pooling of classification if is_train: kernel_size = __C.TRAIN.KERNEL_SIZE / __C.TRAIN.SPATIAL_SCALE else: kernel_size = __C.TEST.KERNEL_SIZE / __C.TEST.SPATIAL_SCALE area = kernel_size * kernel_size scales = np.array(scales) areas = np.repeat(area, num) / (scales ** 2) scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1) if is_train: __C.TRAIN.SCALE_MAPPING = levels else: __C.TEST.SCALE_MAPPING = levels # compute width and height of grid box if is_train: area = __C.TRAIN.KERNEL_SIZE * __C.TRAIN.KERNEL_SIZE aspect = __C.TRAIN.ASPECTS # height / width else: area = __C.TEST.KERNEL_SIZE * __C.TEST.KERNEL_SIZE aspect = __C.TEST.ASPECTS # height / width num_aspect = len(aspect) widths = np.zeros((num_aspect), dtype=np.float32) heights = np.zeros((num_aspect), dtype=np.float32) for i in xrange(num_aspect): widths[i] = math.sqrt(area / aspect[i]) heights[i] = widths[i] * aspect[i] if is_train: __C.TRAIN.ASPECT_WIDTHS = widths __C.TRAIN.ASPECT_HEIGHTS = heights __C.TRAIN.RPN_SCALES = np.array(__C.TRAIN.RPN_SCALES) else: __C.TEST.ASPECT_WIDTHS = widths __C.TEST.ASPECT_HEIGHTS = heights def _merge_a_into_b(a, b):
def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) _add_more_info(1) _add_more_info(0)
"""Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too if type(b[k]) is not type(v): raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v
identifier_body
config.py
# -------------------------------------------------------- # Fast R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick # -------------------------------------------------------- """Fast R-CNN config system. This file specifies default config options for Fast R-CNN. You should not change values in this file. Instead, you should write a config file (in yaml) and use cfg_from_file(yaml_file) to load it and override the default options. Most tools in $ROOT/tools take a --cfg option to specify an override file. - See tools/{train,test}_net.py for example code that uses cfg_from_file() - See experiments/cfgs/*.yml for example YAML config override files """ import os import os.path as osp import numpy as np import math # `pip install easydict` if you don't have it from easydict import EasyDict as edict __C = edict() # Consumers can get config by: # from fast_rcnn_config import cfg cfg = __C # region proposal network (RPN) or not __C.IS_RPN = False __C.FLIP_X = False __C.INPUT = 'COLOR' # multiscale training and testing __C.IS_MULTISCALE = True __C.IS_EXTRAPOLATING = True # __C.REGION_PROPOSAL = 'RPN' __C.NET_NAME = 'CaffeNet' __C.SUBCLS_NAME = 'voxel_exemplars' # # Training options # __C.TRAIN = edict() __C.TRAIN.VISUALIZE = False __C.TRAIN.VERTEX_REG = False __C.TRAIN.GRID_SIZE = 256 __C.TRAIN.CHROMATIC = False # Scales to compute real features __C.TRAIN.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TRAIN.NUM_PER_OCTAVE = 4 # parameters for ROI generating __C.TRAIN.SPATIAL_SCALE = 0.0625 __C.TRAIN.KERNEL_SIZE = 5 # Aspect ratio to use during training __C.TRAIN.ASPECTS = (1, 0.75, 0.5, 0.25) # Images to use per minibatch __C.TRAIN.IMS_PER_BATCH = 2 # Minibatch size (number of regions of interest [ROIs]) __C.TRAIN.BATCH_SIZE = 128 # Fraction of minibatch that is labeled foreground (i.e. class > 0) __C.TRAIN.FG_FRACTION = 0.25 # Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH) __C.TRAIN.FG_THRESH = (0.5,) # Overlap threshold for a ROI to be considered background (class = 0 if # overlap in [LO, HI)) __C.TRAIN.BG_THRESH_HI = (0.5,) __C.TRAIN.BG_THRESH_LO = (0.1,) # Use horizontally-flipped images during training? __C.TRAIN.USE_FLIPPED = True # Train bounding-box regressors __C.TRAIN.BBOX_REG = True # Overlap required between a ROI and ground-truth box in order for that ROI to # be used as a bounding-box regression training example __C.TRAIN.BBOX_THRESH = (0.5,) # Iterations between snapshots __C.TRAIN.SNAPSHOT_ITERS = 10000 # solver.prototxt specifies the snapshot path prefix, this adds an optional # infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel __C.TRAIN.SNAPSHOT_INFIX = '' # Use a prefetch thread in roi_data_layer.layer # So far I haven't found this useful; likely more engineering work is required __C.TRAIN.USE_PREFETCH = False # Train using subclasses __C.TRAIN.SUBCLS = True # Train using viewpoint __C.TRAIN.VIEWPOINT = False # Threshold of ROIs in training RCNN __C.TRAIN.ROI_THRESHOLD = 0.1 # IOU >= thresh: positive example __C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7 # IOU < thresh: negative example __C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.3 # If an anchor statisfied by positive and negative conditions set to negative __C.TRAIN.RPN_CLOBBER_POSITIVES = False # Max number of foreground examples __C.TRAIN.RPN_FG_FRACTION = 0.5 # Total number of examples __C.TRAIN.RPN_BATCHSIZE = 256 # NMS threshold used on RPN proposals __C.TRAIN.RPN_NMS_THRESH = 0.7 # Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TRAIN.RPN_PRE_NMS_TOP_N = 12000 # Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TRAIN.RPN_POST_NMS_TOP_N = 2000 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TRAIN.RPN_MIN_SIZE = 16 # Deprecated (outside weights) __C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (1.0, 1.0, 1.0, 1.0) # Give the positive RPN examples weight of p * 1 / {num positives} # and give negatives a weight of (1 - p) # Set to -1.0 to use uniform example weighting __C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0 __C.TRAIN.RPN_BASE_SIZE = 16 __C.TRAIN.RPN_ASPECTS = [0.25, 0.5, 0.75, 1, 1.5, 2, 3] # 7 aspects __C.TRAIN.RPN_SCALES = [2, 2.82842712, 4, 5.65685425, 8, 11.3137085, 16, 22.627417, 32, 45.254834] # 2**np.arange(1, 6, 0.5), 10 scales # # Testing options # __C.TEST = edict() __C.TEST.IS_PATCH = False; __C.TEST.VERTEX_REG = False __C.TEST.VISUALIZE = False # Scales to compute real features __C.TEST.SCALES_BASE = (0.25, 0.5, 1.0, 2.0, 3.0) # The number of scales per octave in the image pyramid # An octave is the set of scales up to half of the initial scale __C.TEST.NUM_PER_OCTAVE = 4 # Aspect ratio to use during testing __C.TEST.ASPECTS = (1, 0.75, 0.5, 0.25) # parameters for ROI generating __C.TEST.SPATIAL_SCALE = 0.0625 __C.TEST.KERNEL_SIZE = 5 # Overlap threshold used for non-maximum suppression (suppress boxes with # IoU >= this threshold) __C.TEST.NMS = 0.5 # Experimental: treat the (K+1) units in the cls_score layer as linear # predictors (trained, eg, with one-vs-rest SVMs). __C.TEST.SVM = False # Test using bounding-box regressors __C.TEST.BBOX_REG = True # Test using subclass __C.TEST.SUBCLS = True # Train using viewpoint __C.TEST.VIEWPOINT = False # Threshold of ROIs in testing __C.TEST.ROI_THRESHOLD = 0.1 __C.TEST.ROI_THRESHOLD_NUM = 80000 __C.TEST.ROI_NUM = 2000 __C.TEST.DET_THRESHOLD = 0.0001 ## NMS threshold used on RPN proposals __C.TEST.RPN_NMS_THRESH = 0.7 ## Number of top scoring boxes to keep before apply NMS to RPN proposals __C.TEST.RPN_PRE_NMS_TOP_N = 6000 ## Number of top scoring boxes to keep after applying NMS to RPN proposals __C.TEST.RPN_POST_NMS_TOP_N = 300 # Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale) __C.TEST.RPN_MIN_SIZE = 16 # # MISC # # The mapping from image coordinates to feature map coordinates might cause # some boxes that are distinct in image space to become identical in feature # coordinates. If DEDUP_BOXES > 0, then DEDUP_BOXES is used as the scale factor # for identifying duplicate boxes. # 1/16 is correct for {Alex,Caffe}Net, VGG_CNN_M_1024, and VGG16 __C.DEDUP_BOXES = 1./16. # Pixel mean values (BGR order) as a (1, 1, 3) array # These are the values originally used for training VGG16 __C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]]) # For reproducibility __C.RNG_SEED = 3 # A small number that's used many times __C.EPS = 1e-14 # Root directory of project __C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..')) # Place outputs under an experiments directory __C.EXP_DIR = 'default' # Use GPU implementation of non-maximum suppression __C.USE_GPU_NMS = True # Default GPU device id __C.GPU_ID = 0 def get_output_dir(imdb, net): """Return the directory where experimental artifacts are placed. A canonical path is built using the name from an imdb and a network (if not None). """ path = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name)) if net is None: return path else: return osp.join(path, net.name) def _add_more_info(is_train): # compute all the scales if is_train: scales_base = __C.TRAIN.SCALES_BASE num_per_octave = __C.TRAIN.NUM_PER_OCTAVE else: scales_base = __C.TEST.SCALES_BASE num_per_octave = __C.TEST.NUM_PER_OCTAVE num_scale_base = len(scales_base) num = (num_scale_base - 1) * num_per_octave + 1 scales = [] for i in xrange(num): index_scale_base = i / num_per_octave sbase = scales_base[index_scale_base] j = i % num_per_octave if j == 0: scales.append(sbase) else: sbase_next = scales_base[index_scale_base+1] step = (sbase_next - sbase) / num_per_octave scales.append(sbase + j * step) if is_train: __C.TRAIN.SCALES = scales else: __C.TEST.SCALES = scales print scales # map the scales to scales for RoI pooling of classification if is_train: kernel_size = __C.TRAIN.KERNEL_SIZE / __C.TRAIN.SPATIAL_SCALE else: kernel_size = __C.TEST.KERNEL_SIZE / __C.TEST.SPATIAL_SCALE area = kernel_size * kernel_size scales = np.array(scales) areas = np.repeat(area, num) / (scales ** 2) scaled_areas = areas[:, np.newaxis] * (scales[np.newaxis, :] ** 2) diff_areas = np.abs(scaled_areas - 224 * 224) levels = diff_areas.argmin(axis=1) if is_train: __C.TRAIN.SCALE_MAPPING = levels else: __C.TEST.SCALE_MAPPING = levels # compute width and height of grid box if is_train: area = __C.TRAIN.KERNEL_SIZE * __C.TRAIN.KERNEL_SIZE aspect = __C.TRAIN.ASPECTS # height / width else: area = __C.TEST.KERNEL_SIZE * __C.TEST.KERNEL_SIZE aspect = __C.TEST.ASPECTS # height / width num_aspect = len(aspect) widths = np.zeros((num_aspect), dtype=np.float32) heights = np.zeros((num_aspect), dtype=np.float32) for i in xrange(num_aspect):
if is_train: __C.TRAIN.ASPECT_WIDTHS = widths __C.TRAIN.ASPECT_HEIGHTS = heights __C.TRAIN.RPN_SCALES = np.array(__C.TRAIN.RPN_SCALES) else: __C.TEST.ASPECT_WIDTHS = widths __C.TEST.ASPECT_HEIGHTS = heights def _merge_a_into_b(a, b): """Merge config dictionary a into config dictionary b, clobbering the options in b whenever they are also specified in a. """ if type(a) is not edict: return for k, v in a.iteritems(): # a must specify keys that are in b if not b.has_key(k): raise KeyError('{} is not a valid config key'.format(k)) # the types must match, too if type(b[k]) is not type(v): raise ValueError(('Type mismatch ({} vs. {}) ' 'for config key: {}').format(type(b[k]), type(v), k)) # recursively merge dicts if type(v) is edict: try: _merge_a_into_b(a[k], b[k]) except: print('Error under config key: {}'.format(k)) raise else: b[k] = v def cfg_from_file(filename): """Load a config file and merge it into the default options.""" import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C) _add_more_info(1) _add_more_info(0)
widths[i] = math.sqrt(area / aspect[i]) heights[i] = widths[i] * aspect[i]
conditional_block
Capsule.py
## @file # generate capsule # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # from __future__ import absolute_import from .GenFdsGlobalVariable import GenFdsGlobalVariable, FindExtendTool from CommonDataClass.FdfClass import CapsuleClassObject import Common.LongFilePathOs as os from io import BytesIO from Common.Misc import SaveFileOnChange, PackRegistryFormatGuid import uuid from struct import pack from Common import EdkLogger from Common.BuildToolError import GENFDS_ERROR from Common.DataType import TAB_LINE_BREAK WIN_CERT_REVISION = 0x0200 WIN_CERT_TYPE_EFI_GUID = 0x0EF1 EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}') ## create inf file describes what goes into capsule and call GenFv to generate capsule # # class Capsule (CapsuleClassObject): ## The constructor # # @param self The object pointer # def __init__(self): CapsuleClassObject.__init__(self) # For GenFv self.BlockSize = None # For GenFv self.BlockNum = None self.CapsuleName = None ## Generate FMP capsule # # @retval string Generated Capsule file path # def GenFmpCapsule(self): # # Generate capsule header # typedef struct { # EFI_GUID CapsuleGuid; # UINT32 HeaderSize; # UINT32 Flags; # UINT32 CapsuleImageSize; # } EFI_CAPSULE_HEADER; # Header = BytesIO() # # Use FMP capsule GUID: 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A # Header.write(PackRegistryFormatGuid('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')) HdrSize = 0 if 'CAPSULE_HEADER_SIZE' in self.TokensDict: Header.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16))) HdrSize = int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16) else: Header.write(pack('=I', 0x20)) HdrSize = 0x20 Flags = 0 if 'CAPSULE_FLAGS' in self.TokensDict: for flag in self.TokensDict['CAPSULE_FLAGS'].split(','): flag = flag.strip() if flag == 'PopulateSystemTable': Flags |= 0x00010000 | 0x00020000 elif flag == 'PersistAcrossReset': Flags |= 0x00010000 elif flag == 'InitiateReset': Flags |= 0x00040000 Header.write(pack('=I', Flags)) # # typedef struct { # UINT32 Version; # UINT16 EmbeddedDriverCount; # UINT16 PayloadItemCount; # // UINT64 ItemOffsetList[]; # } EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER; # FwMgrHdr = BytesIO() if 'CAPSULE_HEADER_INIT_VERSION' in self.TokensDict: FwMgrHdr.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_INIT_VERSION'], 16))) else: FwMgrHdr.write(pack('=I', 0x00000001)) FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList), len(self.FmpPayloadList))) FwMgrHdrSize = 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList)) # # typedef struct _WIN_CERTIFICATE { # UINT32 dwLength; # UINT16 wRevision; # UINT16 wCertificateType; # //UINT8 bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE; # # typedef struct _WIN_CERTIFICATE_UEFI_GUID { # WIN_CERTIFICATE Hdr; # EFI_GUID CertType; # //UINT8 CertData[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE_UEFI_GUID; # # typedef struct { # UINT64 MonotonicCount; # WIN_CERTIFICATE_UEFI_GUID AuthInfo; # } EFI_FIRMWARE_IMAGE_AUTHENTICATION; # # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 { # EFI_GUID HashType; # UINT8 PublicKey[256]; # UINT8 Signature[256]; # } EFI_CERT_BLOCK_RSA_2048_SHA256; # PreSize = FwMgrHdrSize Content = BytesIO() for driver in self.CapsuleDataList: FileName = driver.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += os.path.getsize(FileName) File = open(FileName, 'rb') Content.write(File.read()) File.close() for fmp in self.FmpPayloadList: if fmp.Existed: FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) continue if fmp.ImageFile: for Obj in fmp.ImageFile: fmp.ImageFile = Obj.GenCapsuleSubItem() if fmp.VendorCodeFile: for Obj in fmp.VendorCodeFile: fmp.VendorCodeFile = Obj.GenCapsuleSubItem() if fmp.Certificate_Guid: ExternalTool, ExternalOption = FindExtendTool([], GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid) CmdOption = '' CapInputFile = fmp.ImageFile if not os.path.isabs(fmp.ImageFile): CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, fmp.ImageFile) CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.tmp' if ExternalTool is None: EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % fmp.Certificate_Guid) else: CmdOption += ExternalTool if ExternalOption: CmdOption = CmdOption + ' ' + ExternalOption CmdOption += ' -e ' + ' --monotonic-count ' + str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile CmdList = CmdOption.split() GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate FMP auth capsule") if uuid.UUID(fmp.Certificate_Guid) == EFI_CERT_TYPE_PKCS7_GUID: dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) - os.path.getsize(CapInputFile) else: dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256 fmp.ImageFile = CapOutputTmp AuthData = [fmp.MonotonicCount, dwLength, WIN_CERT_REVISION, WIN_CERT_TYPE_EFI_GUID, fmp.Certificate_Guid] fmp.Buffer = fmp.GenCapsuleSubItem(AuthData) else: fmp.Buffer = fmp.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue()) Header.write(pack('=I', HdrSize + BodySize)) # # The real capsule header structure is 28 bytes # Header.write('\x00'*(HdrSize-28)) Header.write(FwMgrHdr.getvalue()) Header.write(Content.getvalue()) # # Generate FMP capsule file # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.Cap' SaveFileOnChange(CapOutputFile, Header.getvalue(), True) return CapOutputFile ## Generate capsule # # @param self The object pointer # @retval string Generated Capsule file path # def GenCapsule(self): if self.UiCapsuleName.upper() + 'cap' in GenFdsGlobalVariable.ImageBinDict: return GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] GenFdsGlobalVariable.InfLogger( "\nGenerate %s Capsule" %self.UiCapsuleName) if ('CAPSULE_GUID' in self.TokensDict and uuid.UUID(self.TokensDict['CAPSULE_GUID']) == uuid.UUID('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')): return self.GenFmpCapsule() CapInfFile = self.GenCapInf() CapInfFile.writelines("[files]" + TAB_LINE_BREAK) CapFileList = [] for CapsuleDataObj in self.CapsuleDataList:
SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) CapInfFile.close() # # Call GenFv tool to generate capsule # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) CapOutputFile = CapOutputFile + '.Cap' GenFdsGlobalVariable.GenerateFirmwareVolume( CapOutputFile, [self.CapInfFileName], Capsule=True, FfsList=CapFileList ) GenFdsGlobalVariable.VerboseLogger( "\nGenerate %s Capsule Successfully" %self.UiCapsuleName) GenFdsGlobalVariable.SharpCounter = 0 GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] = CapOutputFile return CapOutputFile ## Generate inf file for capsule # # @param self The object pointer # @retval file inf file object # def GenCapInf(self): self.CapInfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') CapInfFile.writelines("[options]" + TAB_LINE_BREAK) for Item in self.TokensDict: CapInfFile.writelines("EFI_" + \ Item + \ ' = ' + \ self.TokensDict[Item] + \ TAB_LINE_BREAK) return CapInfFile
CapsuleDataObj.CapsuleName = self.CapsuleName FileName = CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName = None CapFileList.append(FileName) CapInfFile.writelines("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK)
conditional_block
Capsule.py
## @file # generate capsule # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # from __future__ import absolute_import from .GenFdsGlobalVariable import GenFdsGlobalVariable, FindExtendTool from CommonDataClass.FdfClass import CapsuleClassObject import Common.LongFilePathOs as os from io import BytesIO from Common.Misc import SaveFileOnChange, PackRegistryFormatGuid import uuid from struct import pack from Common import EdkLogger from Common.BuildToolError import GENFDS_ERROR from Common.DataType import TAB_LINE_BREAK WIN_CERT_REVISION = 0x0200 WIN_CERT_TYPE_EFI_GUID = 0x0EF1 EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}') ## create inf file describes what goes into capsule and call GenFv to generate capsule # # class Capsule (CapsuleClassObject): ## The constructor # # @param self The object pointer # def __init__(self): CapsuleClassObject.__init__(self) # For GenFv self.BlockSize = None # For GenFv self.BlockNum = None self.CapsuleName = None ## Generate FMP capsule # # @retval string Generated Capsule file path # def GenFmpCapsule(self): # # Generate capsule header # typedef struct { # EFI_GUID CapsuleGuid; # UINT32 HeaderSize; # UINT32 Flags; # UINT32 CapsuleImageSize; # } EFI_CAPSULE_HEADER; # Header = BytesIO() # # Use FMP capsule GUID: 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A # Header.write(PackRegistryFormatGuid('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')) HdrSize = 0 if 'CAPSULE_HEADER_SIZE' in self.TokensDict: Header.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16))) HdrSize = int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16) else: Header.write(pack('=I', 0x20)) HdrSize = 0x20 Flags = 0 if 'CAPSULE_FLAGS' in self.TokensDict: for flag in self.TokensDict['CAPSULE_FLAGS'].split(','): flag = flag.strip() if flag == 'PopulateSystemTable': Flags |= 0x00010000 | 0x00020000 elif flag == 'PersistAcrossReset': Flags |= 0x00010000 elif flag == 'InitiateReset': Flags |= 0x00040000 Header.write(pack('=I', Flags)) # # typedef struct { # UINT32 Version; # UINT16 EmbeddedDriverCount; # UINT16 PayloadItemCount; # // UINT64 ItemOffsetList[]; # } EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER; # FwMgrHdr = BytesIO() if 'CAPSULE_HEADER_INIT_VERSION' in self.TokensDict: FwMgrHdr.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_INIT_VERSION'], 16))) else: FwMgrHdr.write(pack('=I', 0x00000001)) FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList), len(self.FmpPayloadList))) FwMgrHdrSize = 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList)) # # typedef struct _WIN_CERTIFICATE { # UINT32 dwLength; # UINT16 wRevision; # UINT16 wCertificateType; # //UINT8 bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE; # # typedef struct _WIN_CERTIFICATE_UEFI_GUID { # WIN_CERTIFICATE Hdr; # EFI_GUID CertType; # //UINT8 CertData[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE_UEFI_GUID; # # typedef struct { # UINT64 MonotonicCount; # WIN_CERTIFICATE_UEFI_GUID AuthInfo; # } EFI_FIRMWARE_IMAGE_AUTHENTICATION; # # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 { # EFI_GUID HashType; # UINT8 PublicKey[256]; # UINT8 Signature[256]; # } EFI_CERT_BLOCK_RSA_2048_SHA256; # PreSize = FwMgrHdrSize Content = BytesIO() for driver in self.CapsuleDataList: FileName = driver.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += os.path.getsize(FileName) File = open(FileName, 'rb') Content.write(File.read()) File.close() for fmp in self.FmpPayloadList: if fmp.Existed: FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) continue if fmp.ImageFile: for Obj in fmp.ImageFile: fmp.ImageFile = Obj.GenCapsuleSubItem() if fmp.VendorCodeFile: for Obj in fmp.VendorCodeFile: fmp.VendorCodeFile = Obj.GenCapsuleSubItem() if fmp.Certificate_Guid: ExternalTool, ExternalOption = FindExtendTool([], GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid) CmdOption = '' CapInputFile = fmp.ImageFile if not os.path.isabs(fmp.ImageFile): CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, fmp.ImageFile) CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.tmp' if ExternalTool is None: EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % fmp.Certificate_Guid) else: CmdOption += ExternalTool if ExternalOption: CmdOption = CmdOption + ' ' + ExternalOption CmdOption += ' -e ' + ' --monotonic-count ' + str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile CmdList = CmdOption.split() GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate FMP auth capsule") if uuid.UUID(fmp.Certificate_Guid) == EFI_CERT_TYPE_PKCS7_GUID: dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) - os.path.getsize(CapInputFile) else: dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256 fmp.ImageFile = CapOutputTmp AuthData = [fmp.MonotonicCount, dwLength, WIN_CERT_REVISION, WIN_CERT_TYPE_EFI_GUID, fmp.Certificate_Guid] fmp.Buffer = fmp.GenCapsuleSubItem(AuthData) else: fmp.Buffer = fmp.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue()) Header.write(pack('=I', HdrSize + BodySize)) # # The real capsule header structure is 28 bytes # Header.write('\x00'*(HdrSize-28)) Header.write(FwMgrHdr.getvalue()) Header.write(Content.getvalue()) # # Generate FMP capsule file # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.Cap' SaveFileOnChange(CapOutputFile, Header.getvalue(), True) return CapOutputFile ## Generate capsule # # @param self The object pointer # @retval string Generated Capsule file path # def GenCapsule(self):
## Generate inf file for capsule # # @param self The object pointer # @retval file inf file object # def GenCapInf(self): self.CapInfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') CapInfFile.writelines("[options]" + TAB_LINE_BREAK) for Item in self.TokensDict: CapInfFile.writelines("EFI_" + \ Item + \ ' = ' + \ self.TokensDict[Item] + \ TAB_LINE_BREAK) return CapInfFile
if self.UiCapsuleName.upper() + 'cap' in GenFdsGlobalVariable.ImageBinDict: return GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] GenFdsGlobalVariable.InfLogger( "\nGenerate %s Capsule" %self.UiCapsuleName) if ('CAPSULE_GUID' in self.TokensDict and uuid.UUID(self.TokensDict['CAPSULE_GUID']) == uuid.UUID('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')): return self.GenFmpCapsule() CapInfFile = self.GenCapInf() CapInfFile.writelines("[files]" + TAB_LINE_BREAK) CapFileList = [] for CapsuleDataObj in self.CapsuleDataList: CapsuleDataObj.CapsuleName = self.CapsuleName FileName = CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName = None CapFileList.append(FileName) CapInfFile.writelines("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) CapInfFile.close() # # Call GenFv tool to generate capsule # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) CapOutputFile = CapOutputFile + '.Cap' GenFdsGlobalVariable.GenerateFirmwareVolume( CapOutputFile, [self.CapInfFileName], Capsule=True, FfsList=CapFileList ) GenFdsGlobalVariable.VerboseLogger( "\nGenerate %s Capsule Successfully" %self.UiCapsuleName) GenFdsGlobalVariable.SharpCounter = 0 GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] = CapOutputFile return CapOutputFile
identifier_body
Capsule.py
## @file # generate capsule # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # from __future__ import absolute_import from .GenFdsGlobalVariable import GenFdsGlobalVariable, FindExtendTool from CommonDataClass.FdfClass import CapsuleClassObject import Common.LongFilePathOs as os from io import BytesIO from Common.Misc import SaveFileOnChange, PackRegistryFormatGuid import uuid from struct import pack from Common import EdkLogger from Common.BuildToolError import GENFDS_ERROR from Common.DataType import TAB_LINE_BREAK WIN_CERT_REVISION = 0x0200 WIN_CERT_TYPE_EFI_GUID = 0x0EF1 EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}') ## create inf file describes what goes into capsule and call GenFv to generate capsule # # class Capsule (CapsuleClassObject): ## The constructor # # @param self The object pointer # def
(self): CapsuleClassObject.__init__(self) # For GenFv self.BlockSize = None # For GenFv self.BlockNum = None self.CapsuleName = None ## Generate FMP capsule # # @retval string Generated Capsule file path # def GenFmpCapsule(self): # # Generate capsule header # typedef struct { # EFI_GUID CapsuleGuid; # UINT32 HeaderSize; # UINT32 Flags; # UINT32 CapsuleImageSize; # } EFI_CAPSULE_HEADER; # Header = BytesIO() # # Use FMP capsule GUID: 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A # Header.write(PackRegistryFormatGuid('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')) HdrSize = 0 if 'CAPSULE_HEADER_SIZE' in self.TokensDict: Header.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16))) HdrSize = int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16) else: Header.write(pack('=I', 0x20)) HdrSize = 0x20 Flags = 0 if 'CAPSULE_FLAGS' in self.TokensDict: for flag in self.TokensDict['CAPSULE_FLAGS'].split(','): flag = flag.strip() if flag == 'PopulateSystemTable': Flags |= 0x00010000 | 0x00020000 elif flag == 'PersistAcrossReset': Flags |= 0x00010000 elif flag == 'InitiateReset': Flags |= 0x00040000 Header.write(pack('=I', Flags)) # # typedef struct { # UINT32 Version; # UINT16 EmbeddedDriverCount; # UINT16 PayloadItemCount; # // UINT64 ItemOffsetList[]; # } EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER; # FwMgrHdr = BytesIO() if 'CAPSULE_HEADER_INIT_VERSION' in self.TokensDict: FwMgrHdr.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_INIT_VERSION'], 16))) else: FwMgrHdr.write(pack('=I', 0x00000001)) FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList), len(self.FmpPayloadList))) FwMgrHdrSize = 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList)) # # typedef struct _WIN_CERTIFICATE { # UINT32 dwLength; # UINT16 wRevision; # UINT16 wCertificateType; # //UINT8 bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE; # # typedef struct _WIN_CERTIFICATE_UEFI_GUID { # WIN_CERTIFICATE Hdr; # EFI_GUID CertType; # //UINT8 CertData[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE_UEFI_GUID; # # typedef struct { # UINT64 MonotonicCount; # WIN_CERTIFICATE_UEFI_GUID AuthInfo; # } EFI_FIRMWARE_IMAGE_AUTHENTICATION; # # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 { # EFI_GUID HashType; # UINT8 PublicKey[256]; # UINT8 Signature[256]; # } EFI_CERT_BLOCK_RSA_2048_SHA256; # PreSize = FwMgrHdrSize Content = BytesIO() for driver in self.CapsuleDataList: FileName = driver.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += os.path.getsize(FileName) File = open(FileName, 'rb') Content.write(File.read()) File.close() for fmp in self.FmpPayloadList: if fmp.Existed: FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) continue if fmp.ImageFile: for Obj in fmp.ImageFile: fmp.ImageFile = Obj.GenCapsuleSubItem() if fmp.VendorCodeFile: for Obj in fmp.VendorCodeFile: fmp.VendorCodeFile = Obj.GenCapsuleSubItem() if fmp.Certificate_Guid: ExternalTool, ExternalOption = FindExtendTool([], GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid) CmdOption = '' CapInputFile = fmp.ImageFile if not os.path.isabs(fmp.ImageFile): CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, fmp.ImageFile) CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.tmp' if ExternalTool is None: EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % fmp.Certificate_Guid) else: CmdOption += ExternalTool if ExternalOption: CmdOption = CmdOption + ' ' + ExternalOption CmdOption += ' -e ' + ' --monotonic-count ' + str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile CmdList = CmdOption.split() GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate FMP auth capsule") if uuid.UUID(fmp.Certificate_Guid) == EFI_CERT_TYPE_PKCS7_GUID: dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) - os.path.getsize(CapInputFile) else: dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256 fmp.ImageFile = CapOutputTmp AuthData = [fmp.MonotonicCount, dwLength, WIN_CERT_REVISION, WIN_CERT_TYPE_EFI_GUID, fmp.Certificate_Guid] fmp.Buffer = fmp.GenCapsuleSubItem(AuthData) else: fmp.Buffer = fmp.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue()) Header.write(pack('=I', HdrSize + BodySize)) # # The real capsule header structure is 28 bytes # Header.write('\x00'*(HdrSize-28)) Header.write(FwMgrHdr.getvalue()) Header.write(Content.getvalue()) # # Generate FMP capsule file # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.Cap' SaveFileOnChange(CapOutputFile, Header.getvalue(), True) return CapOutputFile ## Generate capsule # # @param self The object pointer # @retval string Generated Capsule file path # def GenCapsule(self): if self.UiCapsuleName.upper() + 'cap' in GenFdsGlobalVariable.ImageBinDict: return GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] GenFdsGlobalVariable.InfLogger( "\nGenerate %s Capsule" %self.UiCapsuleName) if ('CAPSULE_GUID' in self.TokensDict and uuid.UUID(self.TokensDict['CAPSULE_GUID']) == uuid.UUID('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')): return self.GenFmpCapsule() CapInfFile = self.GenCapInf() CapInfFile.writelines("[files]" + TAB_LINE_BREAK) CapFileList = [] for CapsuleDataObj in self.CapsuleDataList: CapsuleDataObj.CapsuleName = self.CapsuleName FileName = CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName = None CapFileList.append(FileName) CapInfFile.writelines("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) CapInfFile.close() # # Call GenFv tool to generate capsule # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) CapOutputFile = CapOutputFile + '.Cap' GenFdsGlobalVariable.GenerateFirmwareVolume( CapOutputFile, [self.CapInfFileName], Capsule=True, FfsList=CapFileList ) GenFdsGlobalVariable.VerboseLogger( "\nGenerate %s Capsule Successfully" %self.UiCapsuleName) GenFdsGlobalVariable.SharpCounter = 0 GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] = CapOutputFile return CapOutputFile ## Generate inf file for capsule # # @param self The object pointer # @retval file inf file object # def GenCapInf(self): self.CapInfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') CapInfFile.writelines("[options]" + TAB_LINE_BREAK) for Item in self.TokensDict: CapInfFile.writelines("EFI_" + \ Item + \ ' = ' + \ self.TokensDict[Item] + \ TAB_LINE_BREAK) return CapInfFile
__init__
identifier_name
Capsule.py
## @file # generate capsule # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR> # # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## # Import Modules # from __future__ import absolute_import from .GenFdsGlobalVariable import GenFdsGlobalVariable, FindExtendTool from CommonDataClass.FdfClass import CapsuleClassObject import Common.LongFilePathOs as os from io import BytesIO from Common.Misc import SaveFileOnChange, PackRegistryFormatGuid import uuid from struct import pack from Common import EdkLogger from Common.BuildToolError import GENFDS_ERROR from Common.DataType import TAB_LINE_BREAK WIN_CERT_REVISION = 0x0200 WIN_CERT_TYPE_EFI_GUID = 0x0EF1 EFI_CERT_TYPE_PKCS7_GUID = uuid.UUID('{4aafd29d-68df-49ee-8aa9-347d375665a7}') EFI_CERT_TYPE_RSA2048_SHA256_GUID = uuid.UUID('{a7717414-c616-4977-9420-844712a735bf}') ## create inf file describes what goes into capsule and call GenFv to generate capsule # # class Capsule (CapsuleClassObject): ## The constructor # # @param self The object pointer # def __init__(self): CapsuleClassObject.__init__(self) # For GenFv self.BlockSize = None # For GenFv self.BlockNum = None self.CapsuleName = None ## Generate FMP capsule # # @retval string Generated Capsule file path # def GenFmpCapsule(self): # # Generate capsule header # typedef struct { # EFI_GUID CapsuleGuid; # UINT32 HeaderSize; # UINT32 Flags; # UINT32 CapsuleImageSize; # } EFI_CAPSULE_HEADER; # Header = BytesIO() # # Use FMP capsule GUID: 6DCBD5ED-E82D-4C44-BDA1-7194199AD92A # Header.write(PackRegistryFormatGuid('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')) HdrSize = 0 if 'CAPSULE_HEADER_SIZE' in self.TokensDict: Header.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16))) HdrSize = int(self.TokensDict['CAPSULE_HEADER_SIZE'], 16) else: Header.write(pack('=I', 0x20)) HdrSize = 0x20 Flags = 0 if 'CAPSULE_FLAGS' in self.TokensDict: for flag in self.TokensDict['CAPSULE_FLAGS'].split(','): flag = flag.strip() if flag == 'PopulateSystemTable': Flags |= 0x00010000 | 0x00020000 elif flag == 'PersistAcrossReset': Flags |= 0x00010000 elif flag == 'InitiateReset': Flags |= 0x00040000 Header.write(pack('=I', Flags)) # # typedef struct { # UINT32 Version; # UINT16 EmbeddedDriverCount; # UINT16 PayloadItemCount; # // UINT64 ItemOffsetList[]; # } EFI_FIRMWARE_MANAGEMENT_CAPSULE_HEADER; # FwMgrHdr = BytesIO() if 'CAPSULE_HEADER_INIT_VERSION' in self.TokensDict: FwMgrHdr.write(pack('=I', int(self.TokensDict['CAPSULE_HEADER_INIT_VERSION'], 16))) else: FwMgrHdr.write(pack('=I', 0x00000001)) FwMgrHdr.write(pack('=HH', len(self.CapsuleDataList), len(self.FmpPayloadList)))
# UINT16 wRevision; # UINT16 wCertificateType; # //UINT8 bCertificate[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE; # # typedef struct _WIN_CERTIFICATE_UEFI_GUID { # WIN_CERTIFICATE Hdr; # EFI_GUID CertType; # //UINT8 CertData[ANYSIZE_ARRAY]; # } WIN_CERTIFICATE_UEFI_GUID; # # typedef struct { # UINT64 MonotonicCount; # WIN_CERTIFICATE_UEFI_GUID AuthInfo; # } EFI_FIRMWARE_IMAGE_AUTHENTICATION; # # typedef struct _EFI_CERT_BLOCK_RSA_2048_SHA256 { # EFI_GUID HashType; # UINT8 PublicKey[256]; # UINT8 Signature[256]; # } EFI_CERT_BLOCK_RSA_2048_SHA256; # PreSize = FwMgrHdrSize Content = BytesIO() for driver in self.CapsuleDataList: FileName = driver.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += os.path.getsize(FileName) File = open(FileName, 'rb') Content.write(File.read()) File.close() for fmp in self.FmpPayloadList: if fmp.Existed: FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) continue if fmp.ImageFile: for Obj in fmp.ImageFile: fmp.ImageFile = Obj.GenCapsuleSubItem() if fmp.VendorCodeFile: for Obj in fmp.VendorCodeFile: fmp.VendorCodeFile = Obj.GenCapsuleSubItem() if fmp.Certificate_Guid: ExternalTool, ExternalOption = FindExtendTool([], GenFdsGlobalVariable.ArchList, fmp.Certificate_Guid) CmdOption = '' CapInputFile = fmp.ImageFile if not os.path.isabs(fmp.ImageFile): CapInputFile = os.path.join(GenFdsGlobalVariable.WorkSpaceDir, fmp.ImageFile) CapOutputTmp = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.tmp' if ExternalTool is None: EdkLogger.error("GenFds", GENFDS_ERROR, "No tool found with GUID %s" % fmp.Certificate_Guid) else: CmdOption += ExternalTool if ExternalOption: CmdOption = CmdOption + ' ' + ExternalOption CmdOption += ' -e ' + ' --monotonic-count ' + str(fmp.MonotonicCount) + ' -o ' + CapOutputTmp + ' ' + CapInputFile CmdList = CmdOption.split() GenFdsGlobalVariable.CallExternalTool(CmdList, "Failed to generate FMP auth capsule") if uuid.UUID(fmp.Certificate_Guid) == EFI_CERT_TYPE_PKCS7_GUID: dwLength = 4 + 2 + 2 + 16 + os.path.getsize(CapOutputTmp) - os.path.getsize(CapInputFile) else: dwLength = 4 + 2 + 2 + 16 + 16 + 256 + 256 fmp.ImageFile = CapOutputTmp AuthData = [fmp.MonotonicCount, dwLength, WIN_CERT_REVISION, WIN_CERT_TYPE_EFI_GUID, fmp.Certificate_Guid] fmp.Buffer = fmp.GenCapsuleSubItem(AuthData) else: fmp.Buffer = fmp.GenCapsuleSubItem() FwMgrHdr.write(pack('=Q', PreSize)) PreSize += len(fmp.Buffer) Content.write(fmp.Buffer) BodySize = len(FwMgrHdr.getvalue()) + len(Content.getvalue()) Header.write(pack('=I', HdrSize + BodySize)) # # The real capsule header structure is 28 bytes # Header.write('\x00'*(HdrSize-28)) Header.write(FwMgrHdr.getvalue()) Header.write(Content.getvalue()) # # Generate FMP capsule file # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) + '.Cap' SaveFileOnChange(CapOutputFile, Header.getvalue(), True) return CapOutputFile ## Generate capsule # # @param self The object pointer # @retval string Generated Capsule file path # def GenCapsule(self): if self.UiCapsuleName.upper() + 'cap' in GenFdsGlobalVariable.ImageBinDict: return GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] GenFdsGlobalVariable.InfLogger( "\nGenerate %s Capsule" %self.UiCapsuleName) if ('CAPSULE_GUID' in self.TokensDict and uuid.UUID(self.TokensDict['CAPSULE_GUID']) == uuid.UUID('6DCBD5ED-E82D-4C44-BDA1-7194199AD92A')): return self.GenFmpCapsule() CapInfFile = self.GenCapInf() CapInfFile.writelines("[files]" + TAB_LINE_BREAK) CapFileList = [] for CapsuleDataObj in self.CapsuleDataList: CapsuleDataObj.CapsuleName = self.CapsuleName FileName = CapsuleDataObj.GenCapsuleSubItem() CapsuleDataObj.CapsuleName = None CapFileList.append(FileName) CapInfFile.writelines("EFI_FILE_NAME = " + \ FileName + \ TAB_LINE_BREAK) SaveFileOnChange(self.CapInfFileName, CapInfFile.getvalue(), False) CapInfFile.close() # # Call GenFv tool to generate capsule # CapOutputFile = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName) CapOutputFile = CapOutputFile + '.Cap' GenFdsGlobalVariable.GenerateFirmwareVolume( CapOutputFile, [self.CapInfFileName], Capsule=True, FfsList=CapFileList ) GenFdsGlobalVariable.VerboseLogger( "\nGenerate %s Capsule Successfully" %self.UiCapsuleName) GenFdsGlobalVariable.SharpCounter = 0 GenFdsGlobalVariable.ImageBinDict[self.UiCapsuleName.upper() + 'cap'] = CapOutputFile return CapOutputFile ## Generate inf file for capsule # # @param self The object pointer # @retval file inf file object # def GenCapInf(self): self.CapInfFileName = os.path.join(GenFdsGlobalVariable.FvDir, self.UiCapsuleName + "_Cap" + '.inf') CapInfFile = BytesIO() #open (self.CapInfFileName , 'w+') CapInfFile.writelines("[options]" + TAB_LINE_BREAK) for Item in self.TokensDict: CapInfFile.writelines("EFI_" + \ Item + \ ' = ' + \ self.TokensDict[Item] + \ TAB_LINE_BREAK) return CapInfFile
FwMgrHdrSize = 4+2+2+8*(len(self.CapsuleDataList)+len(self.FmpPayloadList)) # # typedef struct _WIN_CERTIFICATE { # UINT32 dwLength;
random_line_split
controllers.js
angular.module('starter.controllers', []) // A simple controller that fetches a list of data from a service .controller('PetIndexCtrl', function($scope, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pets = PetService.all(); }) // A simple controller that shows a tapped item's data .controller('PetDetailCtrl', function($scope, $stateParams, PetService) { // "Pets" is a service returning mock data (services.js) $scope.pet = PetService.get($stateParams.petId); }) // getting fake favor data .controller('FavorIndexCtrl', function($scope, FavorService) { $scope.favors = FavorService.all(); }) // A simple controller that shows a tapped item's data .controller('FavorDetailCtrl', function($scope, $stateParams, FavorService) { // "Pets" is a service returning mock data (services.js) $scope.favor = FavorService.get($stateParams.favorId);
});
random_line_split
about.tsx
import '../src/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/styles'; import Link from 'next/link'; const useStyles = makeStyles(theme => ({ root: { textAlign: 'center', paddingTop: theme.spacing.unit * 20, }, })); function About() { const classes = useStyles({}); return ( <div className={classes.root}> <Typography variant="h4" gutterBottom> Material-UI </Typography> <Typography variant="subtitle1" gutterBottom> about page </Typography>
</Typography> <Button variant="contained" color="primary"> Do nothing button </Button> </div> ); } export default About;
<Typography gutterBottom> <Link href="/"> <a>Go to the main page</a> </Link>
random_line_split
about.tsx
import '../src/bootstrap'; // --- Post bootstrap ----- import React from 'react'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import { makeStyles } from '@material-ui/styles'; import Link from 'next/link'; const useStyles = makeStyles(theme => ({ root: { textAlign: 'center', paddingTop: theme.spacing.unit * 20, }, })); function
() { const classes = useStyles({}); return ( <div className={classes.root}> <Typography variant="h4" gutterBottom> Material-UI </Typography> <Typography variant="subtitle1" gutterBottom> about page </Typography> <Typography gutterBottom> <Link href="/"> <a>Go to the main page</a> </Link> </Typography> <Button variant="contained" color="primary"> Do nothing button </Button> </div> ); } export default About;
About
identifier_name